/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 breezy/tests/test_smart.py

  • Committer: Jelmer Vernooij
  • Date: 2017-07-23 15:59:57 UTC
  • mto: This revision was merged to the branch mainline in revision 6740.
  • Revision ID: jelmer@jelmer.uk-20170723155957-rw4kqurf44fqx4x0
Move AlreadyBuilding/NotBuilding errors.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2012, 2016 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Tests for the smart wire/domain protocol.
 
18
 
 
19
This module contains tests for the domain-level smart requests and responses,
 
20
such as the 'Branch.lock_write' request. Many of these use specific disk
 
21
formats to exercise calls that only make sense for formats with specific
 
22
properties.
 
23
 
 
24
Tests for low-level protocol encoding are found in test_smart_transport.
 
25
"""
 
26
 
 
27
import bz2
 
28
import zlib
 
29
 
 
30
from breezy import (
 
31
    bencode,
 
32
    branch as _mod_branch,
 
33
    controldir,
 
34
    errors,
 
35
    gpg,
 
36
    tests,
 
37
    transport,
 
38
    urlutils,
 
39
    )
 
40
from breezy.bzr import (
 
41
    branch as _mod_bzrbranch,
 
42
    inventory_delta,
 
43
    versionedfile,
 
44
    )
 
45
from breezy.bzr.smart import (
 
46
    branch as smart_branch,
 
47
    bzrdir as smart_dir,
 
48
    repository as smart_repo,
 
49
    packrepository as smart_packrepo,
 
50
    request as smart_req,
 
51
    server,
 
52
    vfs,
 
53
    )
 
54
from breezy.testament import Testament
 
55
from breezy.tests import test_server
 
56
from breezy.transport import (
 
57
    chroot,
 
58
    memory,
 
59
    )
 
60
 
 
61
 
 
62
def load_tests(loader, standard_tests, pattern):
 
63
    """Multiply tests version and protocol consistency."""
 
64
    # FindRepository tests.
 
65
    scenarios = [
 
66
        ("find_repository", {
 
67
            "_request_class": smart_dir.SmartServerRequestFindRepositoryV1}),
 
68
        ("find_repositoryV2", {
 
69
            "_request_class": smart_dir.SmartServerRequestFindRepositoryV2}),
 
70
        ("find_repositoryV3", {
 
71
            "_request_class": smart_dir.SmartServerRequestFindRepositoryV3}),
 
72
        ]
 
73
    to_adapt, result = tests.split_suite_by_re(standard_tests,
 
74
        "TestSmartServerRequestFindRepository")
 
75
    v2_only, v1_and_2 = tests.split_suite_by_re(to_adapt,
 
76
        "_v2")
 
77
    tests.multiply_tests(v1_and_2, scenarios, result)
 
78
    # The first scenario is only applicable to v1 protocols, it is deleted
 
79
    # since.
 
80
    tests.multiply_tests(v2_only, scenarios[1:], result)
 
81
    return result
 
82
 
 
83
 
 
84
class TestCaseWithChrootedTransport(tests.TestCaseWithTransport):
 
85
 
 
86
    def setUp(self):
 
87
        self.vfs_transport_factory = memory.MemoryServer
 
88
        super(TestCaseWithChrootedTransport, self).setUp()
 
89
        self._chroot_server = None
 
90
 
 
91
    def get_transport(self, relpath=None):
 
92
        if self._chroot_server is None:
 
93
            backing_transport = tests.TestCaseWithTransport.get_transport(self)
 
94
            self._chroot_server = chroot.ChrootServer(backing_transport)
 
95
            self.start_server(self._chroot_server)
 
96
        t = transport.get_transport_from_url(self._chroot_server.get_url())
 
97
        if relpath is not None:
 
98
            t = t.clone(relpath)
 
99
        return t
 
100
 
 
101
 
 
102
class TestCaseWithSmartMedium(tests.TestCaseWithMemoryTransport):
 
103
 
 
104
    def setUp(self):
 
105
        super(TestCaseWithSmartMedium, self).setUp()
 
106
        # We're allowed to set  the transport class here, so that we don't use
 
107
        # the default or a parameterized class, but rather use the
 
108
        # TestCaseWithTransport infrastructure to set up a smart server and
 
109
        # transport.
 
110
        self.overrideAttr(self, "transport_server", self.make_transport_server)
 
111
 
 
112
    def make_transport_server(self):
 
113
        return test_server.SmartTCPServer_for_testing('-' + self.id())
 
114
 
 
115
    def get_smart_medium(self):
 
116
        """Get a smart medium to use in tests."""
 
117
        return self.get_transport().get_smart_medium()
 
118
 
 
119
 
 
120
class TestByteStreamToStream(tests.TestCase):
 
121
 
 
122
    def test_repeated_substreams_same_kind_are_one_stream(self):
 
123
        # Make a stream - an iterable of bytestrings.
 
124
        stream = [('text', [versionedfile.FulltextContentFactory(('k1',), None,
 
125
            None, 'foo')]),('text', [
 
126
            versionedfile.FulltextContentFactory(('k2',), None, None, 'bar')])]
 
127
        fmt = controldir.format_registry.get('pack-0.92')().repository_format
 
128
        bytes = smart_repo._stream_to_byte_stream(stream, fmt)
 
129
        streams = []
 
130
        # Iterate the resulting iterable; checking that we get only one stream
 
131
        # out.
 
132
        fmt, stream = smart_repo._byte_stream_to_stream(bytes)
 
133
        for kind, substream in stream:
 
134
            streams.append((kind, list(substream)))
 
135
        self.assertLength(1, streams)
 
136
        self.assertLength(2, streams[0][1])
 
137
 
 
138
 
 
139
class TestSmartServerResponse(tests.TestCase):
 
140
 
 
141
    def test__eq__(self):
 
142
        self.assertEqual(smart_req.SmartServerResponse(('ok', )),
 
143
            smart_req.SmartServerResponse(('ok', )))
 
144
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'body'),
 
145
            smart_req.SmartServerResponse(('ok', ), 'body'))
 
146
        self.assertNotEqual(smart_req.SmartServerResponse(('ok', )),
 
147
            smart_req.SmartServerResponse(('notok', )))
 
148
        self.assertNotEqual(smart_req.SmartServerResponse(('ok', ), 'body'),
 
149
            smart_req.SmartServerResponse(('ok', )))
 
150
        self.assertNotEqual(None,
 
151
            smart_req.SmartServerResponse(('ok', )))
 
152
 
 
153
    def test__str__(self):
 
154
        """SmartServerResponses can be stringified."""
 
155
        self.assertEqual(
 
156
            "<SuccessfulSmartServerResponse args=('args',) body='body'>",
 
157
            str(smart_req.SuccessfulSmartServerResponse(('args',), 'body')))
 
158
        self.assertEqual(
 
159
            "<FailedSmartServerResponse args=('args',) body='body'>",
 
160
            str(smart_req.FailedSmartServerResponse(('args',), 'body')))
 
161
 
 
162
 
 
163
class TestSmartServerRequest(tests.TestCaseWithMemoryTransport):
 
164
 
 
165
    def test_translate_client_path(self):
 
166
        transport = self.get_transport()
 
167
        request = smart_req.SmartServerRequest(transport, 'foo/')
 
168
        self.assertEqual('./', request.translate_client_path('foo/'))
 
169
        self.assertRaises(
 
170
            errors.InvalidURLJoin, request.translate_client_path, 'foo/..')
 
171
        self.assertRaises(
 
172
            errors.PathNotChild, request.translate_client_path, '/')
 
173
        self.assertRaises(
 
174
            errors.PathNotChild, request.translate_client_path, 'bar/')
 
175
        self.assertEqual('./baz', request.translate_client_path('foo/baz'))
 
176
        e_acute = u'\N{LATIN SMALL LETTER E WITH ACUTE}'.encode('utf-8')
 
177
        self.assertEqual('./' + urlutils.escape(e_acute),
 
178
                         request.translate_client_path('foo/' + e_acute))
 
179
 
 
180
    def test_translate_client_path_vfs(self):
 
181
        """VfsRequests receive escaped paths rather than raw UTF-8."""
 
182
        transport = self.get_transport()
 
183
        request = vfs.VfsRequest(transport, 'foo/')
 
184
        e_acute = u'\N{LATIN SMALL LETTER E WITH ACUTE}'.encode('utf-8')
 
185
        escaped = urlutils.escape('foo/' + e_acute)
 
186
        self.assertEqual('./' + urlutils.escape(e_acute),
 
187
                         request.translate_client_path(escaped))
 
188
 
 
189
    def test_transport_from_client_path(self):
 
190
        transport = self.get_transport()
 
191
        request = smart_req.SmartServerRequest(transport, 'foo/')
 
192
        self.assertEqual(
 
193
            transport.base,
 
194
            request.transport_from_client_path('foo/').base)
 
195
 
 
196
 
 
197
class TestSmartServerBzrDirRequestCloningMetaDir(
 
198
    tests.TestCaseWithMemoryTransport):
 
199
    """Tests for BzrDir.cloning_metadir."""
 
200
 
 
201
    def test_cloning_metadir(self):
 
202
        """When there is a bzrdir present, the call succeeds."""
 
203
        backing = self.get_transport()
 
204
        dir = self.make_controldir('.')
 
205
        local_result = dir.cloning_metadir()
 
206
        request_class = smart_dir.SmartServerBzrDirRequestCloningMetaDir
 
207
        request = request_class(backing)
 
208
        expected = smart_req.SuccessfulSmartServerResponse(
 
209
            (local_result.network_name(),
 
210
            local_result.repository_format.network_name(),
 
211
            ('branch', local_result.get_branch_format().network_name())))
 
212
        self.assertEqual(expected, request.execute('', 'False'))
 
213
 
 
214
    def test_cloning_metadir_reference(self):
 
215
        """The request fails when bzrdir contains a branch reference."""
 
216
        backing = self.get_transport()
 
217
        referenced_branch = self.make_branch('referenced')
 
218
        dir = self.make_controldir('.')
 
219
        local_result = dir.cloning_metadir()
 
220
        reference = _mod_bzrbranch.BranchReferenceFormat().initialize(
 
221
            dir, target_branch=referenced_branch)
 
222
        reference_url = _mod_bzrbranch.BranchReferenceFormat().get_reference(dir)
 
223
        # The server shouldn't try to follow the branch reference, so it's fine
 
224
        # if the referenced branch isn't reachable.
 
225
        backing.rename('referenced', 'moved')
 
226
        request_class = smart_dir.SmartServerBzrDirRequestCloningMetaDir
 
227
        request = request_class(backing)
 
228
        expected = smart_req.FailedSmartServerResponse(('BranchReference',))
 
229
        self.assertEqual(expected, request.execute('', 'False'))
 
230
 
 
231
 
 
232
class TestSmartServerBzrDirRequestCloningMetaDir(
 
233
    tests.TestCaseWithMemoryTransport):
 
234
    """Tests for BzrDir.checkout_metadir."""
 
235
 
 
236
    def test_checkout_metadir(self):
 
237
        backing = self.get_transport()
 
238
        request = smart_dir.SmartServerBzrDirRequestCheckoutMetaDir(
 
239
            backing)
 
240
        branch = self.make_branch('.', format='2a')
 
241
        response = request.execute('')
 
242
        self.assertEqual(
 
243
            smart_req.SmartServerResponse(
 
244
                ('Bazaar-NG meta directory, format 1\n',
 
245
                 'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
 
246
                 'Bazaar Branch Format 7 (needs bzr 1.6)\n')),
 
247
            response)
 
248
 
 
249
 
 
250
class TestSmartServerBzrDirRequestDestroyBranch(
 
251
    tests.TestCaseWithMemoryTransport):
 
252
    """Tests for BzrDir.destroy_branch."""
 
253
 
 
254
    def test_destroy_branch_default(self):
 
255
        """The default branch can be removed."""
 
256
        backing = self.get_transport()
 
257
        dir = self.make_branch('.').controldir
 
258
        request_class = smart_dir.SmartServerBzrDirRequestDestroyBranch
 
259
        request = request_class(backing)
 
260
        expected = smart_req.SuccessfulSmartServerResponse(('ok',))
 
261
        self.assertEqual(expected, request.execute('', None))
 
262
 
 
263
    def test_destroy_branch_named(self):
 
264
        """A named branch can be removed."""
 
265
        backing = self.get_transport()
 
266
        dir = self.make_repository('.', format="development-colo").controldir
 
267
        dir.create_branch(name="branchname")
 
268
        request_class = smart_dir.SmartServerBzrDirRequestDestroyBranch
 
269
        request = request_class(backing)
 
270
        expected = smart_req.SuccessfulSmartServerResponse(('ok',))
 
271
        self.assertEqual(expected, request.execute('', "branchname"))
 
272
 
 
273
    def test_destroy_branch_missing(self):
 
274
        """An error is raised if the branch didn't exist."""
 
275
        backing = self.get_transport()
 
276
        dir = self.make_controldir('.', format="development-colo")
 
277
        request_class = smart_dir.SmartServerBzrDirRequestDestroyBranch
 
278
        request = request_class(backing)
 
279
        expected = smart_req.FailedSmartServerResponse(('nobranch',), None)
 
280
        self.assertEqual(expected, request.execute('', "branchname"))
 
281
 
 
282
 
 
283
class TestSmartServerBzrDirRequestHasWorkingTree(
 
284
    tests.TestCaseWithTransport):
 
285
    """Tests for BzrDir.has_workingtree."""
 
286
 
 
287
    def test_has_workingtree_yes(self):
 
288
        """A working tree is present."""
 
289
        backing = self.get_transport()
 
290
        dir = self.make_branch_and_tree('.').controldir
 
291
        request_class = smart_dir.SmartServerBzrDirRequestHasWorkingTree
 
292
        request = request_class(backing)
 
293
        expected = smart_req.SuccessfulSmartServerResponse(('yes',))
 
294
        self.assertEqual(expected, request.execute(''))
 
295
 
 
296
    def test_has_workingtree_no(self):
 
297
        """A working tree is missing."""
 
298
        backing = self.get_transport()
 
299
        dir = self.make_controldir('.')
 
300
        request_class = smart_dir.SmartServerBzrDirRequestHasWorkingTree
 
301
        request = request_class(backing)
 
302
        expected = smart_req.SuccessfulSmartServerResponse(('no',))
 
303
        self.assertEqual(expected, request.execute(''))
 
304
 
 
305
 
 
306
class TestSmartServerBzrDirRequestDestroyRepository(
 
307
    tests.TestCaseWithMemoryTransport):
 
308
    """Tests for BzrDir.destroy_repository."""
 
309
 
 
310
    def test_destroy_repository_default(self):
 
311
        """The repository can be removed."""
 
312
        backing = self.get_transport()
 
313
        dir = self.make_repository('.').controldir
 
314
        request_class = smart_dir.SmartServerBzrDirRequestDestroyRepository
 
315
        request = request_class(backing)
 
316
        expected = smart_req.SuccessfulSmartServerResponse(('ok',))
 
317
        self.assertEqual(expected, request.execute(''))
 
318
 
 
319
    def test_destroy_repository_missing(self):
 
320
        """An error is raised if the repository didn't exist."""
 
321
        backing = self.get_transport()
 
322
        dir = self.make_controldir('.')
 
323
        request_class = smart_dir.SmartServerBzrDirRequestDestroyRepository
 
324
        request = request_class(backing)
 
325
        expected = smart_req.FailedSmartServerResponse(
 
326
            ('norepository',), None)
 
327
        self.assertEqual(expected, request.execute(''))
 
328
 
 
329
 
 
330
class TestSmartServerRequestCreateRepository(tests.TestCaseWithMemoryTransport):
 
331
    """Tests for BzrDir.create_repository."""
 
332
 
 
333
    def test_makes_repository(self):
 
334
        """When there is a bzrdir present, the call succeeds."""
 
335
        backing = self.get_transport()
 
336
        self.make_controldir('.')
 
337
        request_class = smart_dir.SmartServerRequestCreateRepository
 
338
        request = request_class(backing)
 
339
        reference_bzrdir_format = controldir.format_registry.get('pack-0.92')()
 
340
        reference_format = reference_bzrdir_format.repository_format
 
341
        network_name = reference_format.network_name()
 
342
        expected = smart_req.SuccessfulSmartServerResponse(
 
343
            ('ok', 'no', 'no', 'no', network_name))
 
344
        self.assertEqual(expected, request.execute('', network_name, 'True'))
 
345
 
 
346
 
 
347
class TestSmartServerRequestFindRepository(tests.TestCaseWithMemoryTransport):
 
348
    """Tests for BzrDir.find_repository."""
 
349
 
 
350
    def test_no_repository(self):
 
351
        """When there is no repository to be found, ('norepository', ) is returned."""
 
352
        backing = self.get_transport()
 
353
        request = self._request_class(backing)
 
354
        self.make_controldir('.')
 
355
        self.assertEqual(smart_req.SmartServerResponse(('norepository', )),
 
356
            request.execute(''))
 
357
 
 
358
    def test_nonshared_repository(self):
 
359
        # nonshared repositorys only allow 'find' to return a handle when the
 
360
        # path the repository is being searched on is the same as that that
 
361
        # the repository is at.
 
362
        backing = self.get_transport()
 
363
        request = self._request_class(backing)
 
364
        result = self._make_repository_and_result()
 
365
        self.assertEqual(result, request.execute(''))
 
366
        self.make_controldir('subdir')
 
367
        self.assertEqual(smart_req.SmartServerResponse(('norepository', )),
 
368
            request.execute('subdir'))
 
369
 
 
370
    def _make_repository_and_result(self, shared=False, format=None):
 
371
        """Convenience function to setup a repository.
 
372
 
 
373
        :result: The SmartServerResponse to expect when opening it.
 
374
        """
 
375
        repo = self.make_repository('.', shared=shared, format=format)
 
376
        if repo.supports_rich_root():
 
377
            rich_root = 'yes'
 
378
        else:
 
379
            rich_root = 'no'
 
380
        if repo._format.supports_tree_reference:
 
381
            subtrees = 'yes'
 
382
        else:
 
383
            subtrees = 'no'
 
384
        if repo._format.supports_external_lookups:
 
385
            external = 'yes'
 
386
        else:
 
387
            external = 'no'
 
388
        if (smart_dir.SmartServerRequestFindRepositoryV3 ==
 
389
            self._request_class):
 
390
            return smart_req.SuccessfulSmartServerResponse(
 
391
                ('ok', '', rich_root, subtrees, external,
 
392
                 repo._format.network_name()))
 
393
        elif (smart_dir.SmartServerRequestFindRepositoryV2 ==
 
394
            self._request_class):
 
395
            # All tests so far are on formats, and for non-external
 
396
            # repositories.
 
397
            return smart_req.SuccessfulSmartServerResponse(
 
398
                ('ok', '', rich_root, subtrees, external))
 
399
        else:
 
400
            return smart_req.SuccessfulSmartServerResponse(
 
401
                ('ok', '', rich_root, subtrees))
 
402
 
 
403
    def test_shared_repository(self):
 
404
        """When there is a shared repository, we get 'ok', 'relpath-to-repo'."""
 
405
        backing = self.get_transport()
 
406
        request = self._request_class(backing)
 
407
        result = self._make_repository_and_result(shared=True)
 
408
        self.assertEqual(result, request.execute(''))
 
409
        self.make_controldir('subdir')
 
410
        result2 = smart_req.SmartServerResponse(
 
411
            result.args[0:1] + ('..', ) + result.args[2:])
 
412
        self.assertEqual(result2,
 
413
            request.execute('subdir'))
 
414
        self.make_controldir('subdir/deeper')
 
415
        result3 = smart_req.SmartServerResponse(
 
416
            result.args[0:1] + ('../..', ) + result.args[2:])
 
417
        self.assertEqual(result3,
 
418
            request.execute('subdir/deeper'))
 
419
 
 
420
    def test_rich_root_and_subtree_encoding(self):
 
421
        """Test for the format attributes for rich root and subtree support."""
 
422
        backing = self.get_transport()
 
423
        request = self._request_class(backing)
 
424
        result = self._make_repository_and_result(
 
425
            format='development-subtree')
 
426
        # check the test will be valid
 
427
        self.assertEqual('yes', result.args[2])
 
428
        self.assertEqual('yes', result.args[3])
 
429
        self.assertEqual(result, request.execute(''))
 
430
 
 
431
    def test_supports_external_lookups_no_v2(self):
 
432
        """Test for the supports_external_lookups attribute."""
 
433
        backing = self.get_transport()
 
434
        request = self._request_class(backing)
 
435
        result = self._make_repository_and_result(
 
436
            format='development-subtree')
 
437
        # check the test will be valid
 
438
        self.assertEqual('yes', result.args[4])
 
439
        self.assertEqual(result, request.execute(''))
 
440
 
 
441
 
 
442
class TestSmartServerBzrDirRequestGetConfigFile(
 
443
    tests.TestCaseWithMemoryTransport):
 
444
    """Tests for BzrDir.get_config_file."""
 
445
 
 
446
    def test_present(self):
 
447
        backing = self.get_transport()
 
448
        dir = self.make_controldir('.')
 
449
        dir.get_config().set_default_stack_on("/")
 
450
        local_result = dir._get_config()._get_config_file().read()
 
451
        request_class = smart_dir.SmartServerBzrDirRequestConfigFile
 
452
        request = request_class(backing)
 
453
        expected = smart_req.SuccessfulSmartServerResponse((), local_result)
 
454
        self.assertEqual(expected, request.execute(''))
 
455
 
 
456
    def test_missing(self):
 
457
        backing = self.get_transport()
 
458
        dir = self.make_controldir('.')
 
459
        request_class = smart_dir.SmartServerBzrDirRequestConfigFile
 
460
        request = request_class(backing)
 
461
        expected = smart_req.SuccessfulSmartServerResponse((), '')
 
462
        self.assertEqual(expected, request.execute(''))
 
463
 
 
464
 
 
465
class TestSmartServerBzrDirRequestGetBranches(
 
466
    tests.TestCaseWithMemoryTransport):
 
467
    """Tests for BzrDir.get_branches."""
 
468
 
 
469
    def test_simple(self):
 
470
        backing = self.get_transport()
 
471
        branch = self.make_branch('.')
 
472
        request_class = smart_dir.SmartServerBzrDirRequestGetBranches
 
473
        request = request_class(backing)
 
474
        local_result = bencode.bencode(
 
475
            {"": ("branch", branch._format.network_name())})
 
476
        expected = smart_req.SuccessfulSmartServerResponse(
 
477
            ("success", ), local_result)
 
478
        self.assertEqual(expected, request.execute(''))
 
479
 
 
480
    def test_empty(self):
 
481
        backing = self.get_transport()
 
482
        dir = self.make_controldir('.')
 
483
        request_class = smart_dir.SmartServerBzrDirRequestGetBranches
 
484
        request = request_class(backing)
 
485
        local_result = bencode.bencode({})
 
486
        expected = smart_req.SuccessfulSmartServerResponse(
 
487
            ('success',), local_result)
 
488
        self.assertEqual(expected, request.execute(''))
 
489
 
 
490
 
 
491
class TestSmartServerRequestInitializeBzrDir(tests.TestCaseWithMemoryTransport):
 
492
 
 
493
    def test_empty_dir(self):
 
494
        """Initializing an empty dir should succeed and do it."""
 
495
        backing = self.get_transport()
 
496
        request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
 
497
        self.assertEqual(smart_req.SmartServerResponse(('ok', )),
 
498
            request.execute(''))
 
499
        made_dir = controldir.ControlDir.open_from_transport(backing)
 
500
        # no branch, tree or repository is expected with the current
 
501
        # default formart.
 
502
        self.assertRaises(errors.NoWorkingTree, made_dir.open_workingtree)
 
503
        self.assertRaises(errors.NotBranchError, made_dir.open_branch)
 
504
        self.assertRaises(errors.NoRepositoryPresent, made_dir.open_repository)
 
505
 
 
506
    def test_missing_dir(self):
 
507
        """Initializing a missing directory should fail like the bzrdir api."""
 
508
        backing = self.get_transport()
 
509
        request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
 
510
        self.assertRaises(errors.NoSuchFile,
 
511
            request.execute, 'subdir')
 
512
 
 
513
    def test_initialized_dir(self):
 
514
        """Initializing an extant bzrdir should fail like the bzrdir api."""
 
515
        backing = self.get_transport()
 
516
        request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
 
517
        self.make_controldir('subdir')
 
518
        self.assertRaises(errors.AlreadyControlDirError,
 
519
            request.execute, 'subdir')
 
520
 
 
521
 
 
522
class TestSmartServerRequestBzrDirInitializeEx(
 
523
    tests.TestCaseWithMemoryTransport):
 
524
    """Basic tests for BzrDir.initialize_ex_1.16 in the smart server.
 
525
 
 
526
    The main unit tests in test_bzrdir exercise the API comprehensively.
 
527
    """
 
528
 
 
529
    def test_empty_dir(self):
 
530
        """Initializing an empty dir should succeed and do it."""
 
531
        backing = self.get_transport()
 
532
        name = self.make_controldir('reference')._format.network_name()
 
533
        request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
 
534
        self.assertEqual(
 
535
            smart_req.SmartServerResponse(('', '', '', '', '', '', name,
 
536
                                           'False', '', '', '')),
 
537
            request.execute(name, '', 'True', 'False', 'False', '', '', '', '',
 
538
                            'False'))
 
539
        made_dir = controldir.ControlDir.open_from_transport(backing)
 
540
        # no branch, tree or repository is expected with the current
 
541
        # default format.
 
542
        self.assertRaises(errors.NoWorkingTree, made_dir.open_workingtree)
 
543
        self.assertRaises(errors.NotBranchError, made_dir.open_branch)
 
544
        self.assertRaises(errors.NoRepositoryPresent, made_dir.open_repository)
 
545
 
 
546
    def test_missing_dir(self):
 
547
        """Initializing a missing directory should fail like the bzrdir api."""
 
548
        backing = self.get_transport()
 
549
        name = self.make_controldir('reference')._format.network_name()
 
550
        request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
 
551
        self.assertRaises(errors.NoSuchFile, request.execute, name,
 
552
            'subdir/dir', 'False', 'False', 'False', '', '', '', '', 'False')
 
553
 
 
554
    def test_initialized_dir(self):
 
555
        """Initializing an extant directory should fail like the bzrdir api."""
 
556
        backing = self.get_transport()
 
557
        name = self.make_controldir('reference')._format.network_name()
 
558
        request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
 
559
        self.make_controldir('subdir')
 
560
        self.assertRaises(errors.FileExists, request.execute, name, 'subdir',
 
561
            'False', 'False', 'False', '', '', '', '', 'False')
 
562
 
 
563
 
 
564
class TestSmartServerRequestOpenBzrDir(tests.TestCaseWithMemoryTransport):
 
565
 
 
566
    def test_no_directory(self):
 
567
        backing = self.get_transport()
 
568
        request = smart_dir.SmartServerRequestOpenBzrDir(backing)
 
569
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
 
570
            request.execute('does-not-exist'))
 
571
 
 
572
    def test_empty_directory(self):
 
573
        backing = self.get_transport()
 
574
        backing.mkdir('empty')
 
575
        request = smart_dir.SmartServerRequestOpenBzrDir(backing)
 
576
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
 
577
            request.execute('empty'))
 
578
 
 
579
    def test_outside_root_client_path(self):
 
580
        backing = self.get_transport()
 
581
        request = smart_dir.SmartServerRequestOpenBzrDir(backing,
 
582
            root_client_path='root')
 
583
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
 
584
            request.execute('not-root'))
 
585
 
 
586
 
 
587
class TestSmartServerRequestOpenBzrDir_2_1(tests.TestCaseWithMemoryTransport):
 
588
 
 
589
    def test_no_directory(self):
 
590
        backing = self.get_transport()
 
591
        request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
 
592
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
 
593
            request.execute('does-not-exist'))
 
594
 
 
595
    def test_empty_directory(self):
 
596
        backing = self.get_transport()
 
597
        backing.mkdir('empty')
 
598
        request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
 
599
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
 
600
            request.execute('empty'))
 
601
 
 
602
    def test_present_without_workingtree(self):
 
603
        backing = self.get_transport()
 
604
        request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
 
605
        self.make_controldir('.')
 
606
        self.assertEqual(smart_req.SmartServerResponse(('yes', 'no')),
 
607
            request.execute(''))
 
608
 
 
609
    def test_outside_root_client_path(self):
 
610
        backing = self.get_transport()
 
611
        request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing,
 
612
            root_client_path='root')
 
613
        self.assertEqual(smart_req.SmartServerResponse(('no',)),
 
614
            request.execute('not-root'))
 
615
 
 
616
 
 
617
class TestSmartServerRequestOpenBzrDir_2_1_disk(TestCaseWithChrootedTransport):
 
618
 
 
619
    def test_present_with_workingtree(self):
 
620
        self.vfs_transport_factory = test_server.LocalURLServer
 
621
        backing = self.get_transport()
 
622
        request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
 
623
        bd = self.make_controldir('.')
 
624
        bd.create_repository()
 
625
        bd.create_branch()
 
626
        bd.create_workingtree()
 
627
        self.assertEqual(smart_req.SmartServerResponse(('yes', 'yes')),
 
628
            request.execute(''))
 
629
 
 
630
 
 
631
class TestSmartServerRequestOpenBranch(TestCaseWithChrootedTransport):
 
632
 
 
633
    def test_no_branch(self):
 
634
        """When there is no branch, ('nobranch', ) is returned."""
 
635
        backing = self.get_transport()
 
636
        request = smart_dir.SmartServerRequestOpenBranch(backing)
 
637
        self.make_controldir('.')
 
638
        self.assertEqual(smart_req.SmartServerResponse(('nobranch', )),
 
639
            request.execute(''))
 
640
 
 
641
    def test_branch(self):
 
642
        """When there is a branch, 'ok' is returned."""
 
643
        backing = self.get_transport()
 
644
        request = smart_dir.SmartServerRequestOpenBranch(backing)
 
645
        self.make_branch('.')
 
646
        self.assertEqual(smart_req.SmartServerResponse(('ok', '')),
 
647
            request.execute(''))
 
648
 
 
649
    def test_branch_reference(self):
 
650
        """When there is a branch reference, the reference URL is returned."""
 
651
        self.vfs_transport_factory = test_server.LocalURLServer
 
652
        backing = self.get_transport()
 
653
        request = smart_dir.SmartServerRequestOpenBranch(backing)
 
654
        branch = self.make_branch('branch')
 
655
        checkout = branch.create_checkout('reference',lightweight=True)
 
656
        reference_url = _mod_bzrbranch.BranchReferenceFormat().get_reference(
 
657
            checkout.controldir)
 
658
        self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
 
659
        self.assertEqual(smart_req.SmartServerResponse(('ok', reference_url)),
 
660
            request.execute('reference'))
 
661
 
 
662
    def test_notification_on_branch_from_repository(self):
 
663
        """When there is a repository, the error should return details."""
 
664
        backing = self.get_transport()
 
665
        request = smart_dir.SmartServerRequestOpenBranch(backing)
 
666
        repo = self.make_repository('.')
 
667
        self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
 
668
            request.execute(''))
 
669
 
 
670
 
 
671
class TestSmartServerRequestOpenBranchV2(TestCaseWithChrootedTransport):
 
672
 
 
673
    def test_no_branch(self):
 
674
        """When there is no branch, ('nobranch', ) is returned."""
 
675
        backing = self.get_transport()
 
676
        self.make_controldir('.')
 
677
        request = smart_dir.SmartServerRequestOpenBranchV2(backing)
 
678
        self.assertEqual(smart_req.SmartServerResponse(('nobranch', )),
 
679
            request.execute(''))
 
680
 
 
681
    def test_branch(self):
 
682
        """When there is a branch, 'ok' is returned."""
 
683
        backing = self.get_transport()
 
684
        expected = self.make_branch('.')._format.network_name()
 
685
        request = smart_dir.SmartServerRequestOpenBranchV2(backing)
 
686
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
 
687
                ('branch', expected)),
 
688
                         request.execute(''))
 
689
 
 
690
    def test_branch_reference(self):
 
691
        """When there is a branch reference, the reference URL is returned."""
 
692
        self.vfs_transport_factory = test_server.LocalURLServer
 
693
        backing = self.get_transport()
 
694
        request = smart_dir.SmartServerRequestOpenBranchV2(backing)
 
695
        branch = self.make_branch('branch')
 
696
        checkout = branch.create_checkout('reference',lightweight=True)
 
697
        reference_url = _mod_bzrbranch.BranchReferenceFormat().get_reference(
 
698
            checkout.controldir)
 
699
        self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
 
700
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
 
701
                ('ref', reference_url)),
 
702
                         request.execute('reference'))
 
703
 
 
704
    def test_stacked_branch(self):
 
705
        """Opening a stacked branch does not open the stacked-on branch."""
 
706
        trunk = self.make_branch('trunk')
 
707
        feature = self.make_branch('feature')
 
708
        feature.set_stacked_on_url(trunk.base)
 
709
        opened_branches = []
 
710
        _mod_branch.Branch.hooks.install_named_hook(
 
711
            'open', opened_branches.append, None)
 
712
        backing = self.get_transport()
 
713
        request = smart_dir.SmartServerRequestOpenBranchV2(backing)
 
714
        request.setup_jail()
 
715
        try:
 
716
            response = request.execute('feature')
 
717
        finally:
 
718
            request.teardown_jail()
 
719
        expected_format = feature._format.network_name()
 
720
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
 
721
                ('branch', expected_format)),
 
722
                         response)
 
723
        self.assertLength(1, opened_branches)
 
724
 
 
725
    def test_notification_on_branch_from_repository(self):
 
726
        """When there is a repository, the error should return details."""
 
727
        backing = self.get_transport()
 
728
        request = smart_dir.SmartServerRequestOpenBranchV2(backing)
 
729
        repo = self.make_repository('.')
 
730
        self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
 
731
            request.execute(''))
 
732
 
 
733
 
 
734
class TestSmartServerRequestOpenBranchV3(TestCaseWithChrootedTransport):
 
735
 
 
736
    def test_no_branch(self):
 
737
        """When there is no branch, ('nobranch', ) is returned."""
 
738
        backing = self.get_transport()
 
739
        self.make_controldir('.')
 
740
        request = smart_dir.SmartServerRequestOpenBranchV3(backing)
 
741
        self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
 
742
            request.execute(''))
 
743
 
 
744
    def test_branch(self):
 
745
        """When there is a branch, 'ok' is returned."""
 
746
        backing = self.get_transport()
 
747
        expected = self.make_branch('.')._format.network_name()
 
748
        request = smart_dir.SmartServerRequestOpenBranchV3(backing)
 
749
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
 
750
                ('branch', expected)),
 
751
                         request.execute(''))
 
752
 
 
753
    def test_branch_reference(self):
 
754
        """When there is a branch reference, the reference URL is returned."""
 
755
        self.vfs_transport_factory = test_server.LocalURLServer
 
756
        backing = self.get_transport()
 
757
        request = smart_dir.SmartServerRequestOpenBranchV3(backing)
 
758
        branch = self.make_branch('branch')
 
759
        checkout = branch.create_checkout('reference',lightweight=True)
 
760
        reference_url = _mod_bzrbranch.BranchReferenceFormat().get_reference(
 
761
            checkout.controldir)
 
762
        self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
 
763
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
 
764
                ('ref', reference_url)),
 
765
                         request.execute('reference'))
 
766
 
 
767
    def test_stacked_branch(self):
 
768
        """Opening a stacked branch does not open the stacked-on branch."""
 
769
        trunk = self.make_branch('trunk')
 
770
        feature = self.make_branch('feature')
 
771
        feature.set_stacked_on_url(trunk.base)
 
772
        opened_branches = []
 
773
        _mod_branch.Branch.hooks.install_named_hook(
 
774
            'open', opened_branches.append, None)
 
775
        backing = self.get_transport()
 
776
        request = smart_dir.SmartServerRequestOpenBranchV3(backing)
 
777
        request.setup_jail()
 
778
        try:
 
779
            response = request.execute('feature')
 
780
        finally:
 
781
            request.teardown_jail()
 
782
        expected_format = feature._format.network_name()
 
783
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
 
784
                ('branch', expected_format)),
 
785
                         response)
 
786
        self.assertLength(1, opened_branches)
 
787
 
 
788
    def test_notification_on_branch_from_repository(self):
 
789
        """When there is a repository, the error should return details."""
 
790
        backing = self.get_transport()
 
791
        request = smart_dir.SmartServerRequestOpenBranchV3(backing)
 
792
        repo = self.make_repository('.')
 
793
        self.assertEqual(smart_req.SmartServerResponse(
 
794
                ('nobranch', 'location is a repository')),
 
795
                         request.execute(''))
 
796
 
 
797
 
 
798
class TestSmartServerRequestRevisionHistory(tests.TestCaseWithMemoryTransport):
 
799
 
 
800
    def test_empty(self):
 
801
        """For an empty branch, the body is empty."""
 
802
        backing = self.get_transport()
 
803
        request = smart_branch.SmartServerRequestRevisionHistory(backing)
 
804
        self.make_branch('.')
 
805
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), ''),
 
806
            request.execute(''))
 
807
 
 
808
    def test_not_empty(self):
 
809
        """For a non-empty branch, the body is empty."""
 
810
        backing = self.get_transport()
 
811
        request = smart_branch.SmartServerRequestRevisionHistory(backing)
 
812
        tree = self.make_branch_and_memory_tree('.')
 
813
        tree.lock_write()
 
814
        tree.add('')
 
815
        r1 = tree.commit('1st commit')
 
816
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
 
817
        tree.unlock()
 
818
        self.assertEqual(
 
819
            smart_req.SmartServerResponse(('ok', ), ('\x00'.join([r1, r2]))),
 
820
            request.execute(''))
 
821
 
 
822
 
 
823
class TestSmartServerBranchRequest(tests.TestCaseWithMemoryTransport):
 
824
 
 
825
    def test_no_branch(self):
 
826
        """When there is a bzrdir and no branch, NotBranchError is raised."""
 
827
        backing = self.get_transport()
 
828
        request = smart_branch.SmartServerBranchRequest(backing)
 
829
        self.make_controldir('.')
 
830
        self.assertRaises(errors.NotBranchError,
 
831
            request.execute, '')
 
832
 
 
833
    def test_branch_reference(self):
 
834
        """When there is a branch reference, NotBranchError is raised."""
 
835
        backing = self.get_transport()
 
836
        request = smart_branch.SmartServerBranchRequest(backing)
 
837
        branch = self.make_branch('branch')
 
838
        checkout = branch.create_checkout('reference',lightweight=True)
 
839
        self.assertRaises(errors.NotBranchError,
 
840
            request.execute, 'checkout')
 
841
 
 
842
 
 
843
class TestSmartServerBranchRequestLastRevisionInfo(
 
844
    tests.TestCaseWithMemoryTransport):
 
845
 
 
846
    def test_empty(self):
 
847
        """For an empty branch, the result is ('ok', '0', 'null:')."""
 
848
        backing = self.get_transport()
 
849
        request = smart_branch.SmartServerBranchRequestLastRevisionInfo(backing)
 
850
        self.make_branch('.')
 
851
        self.assertEqual(smart_req.SmartServerResponse(('ok', '0', 'null:')),
 
852
            request.execute(''))
 
853
 
 
854
    def test_not_empty(self):
 
855
        """For a non-empty branch, the result is ('ok', 'revno', 'revid')."""
 
856
        backing = self.get_transport()
 
857
        request = smart_branch.SmartServerBranchRequestLastRevisionInfo(backing)
 
858
        tree = self.make_branch_and_memory_tree('.')
 
859
        tree.lock_write()
 
860
        tree.add('')
 
861
        rev_id_utf8 = u'\xc8'.encode('utf-8')
 
862
        r1 = tree.commit('1st commit')
 
863
        r2 = tree.commit('2nd commit', rev_id=rev_id_utf8)
 
864
        tree.unlock()
 
865
        self.assertEqual(
 
866
            smart_req.SmartServerResponse(('ok', '2', rev_id_utf8)),
 
867
            request.execute(''))
 
868
 
 
869
 
 
870
class TestSmartServerBranchRequestRevisionIdToRevno(
 
871
    tests.TestCaseWithMemoryTransport):
 
872
 
 
873
    def test_null(self):
 
874
        backing = self.get_transport()
 
875
        request = smart_branch.SmartServerBranchRequestRevisionIdToRevno(
 
876
            backing)
 
877
        self.make_branch('.')
 
878
        self.assertEqual(smart_req.SmartServerResponse(('ok', '0')),
 
879
            request.execute('', 'null:'))
 
880
 
 
881
    def test_simple(self):
 
882
        backing = self.get_transport()
 
883
        request = smart_branch.SmartServerBranchRequestRevisionIdToRevno(
 
884
            backing)
 
885
        tree = self.make_branch_and_memory_tree('.')
 
886
        tree.lock_write()
 
887
        tree.add('')
 
888
        r1 = tree.commit('1st commit')
 
889
        tree.unlock()
 
890
        self.assertEqual(
 
891
            smart_req.SmartServerResponse(('ok', '1')),
 
892
            request.execute('', r1))
 
893
 
 
894
    def test_not_found(self):
 
895
        backing = self.get_transport()
 
896
        request = smart_branch.SmartServerBranchRequestRevisionIdToRevno(
 
897
            backing)
 
898
        branch = self.make_branch('.')
 
899
        self.assertEqual(
 
900
            smart_req.FailedSmartServerResponse(
 
901
                ('NoSuchRevision', 'idontexist')),
 
902
            request.execute('', 'idontexist'))
 
903
 
 
904
 
 
905
class TestSmartServerBranchRequestGetConfigFile(
 
906
    tests.TestCaseWithMemoryTransport):
 
907
 
 
908
    def test_default(self):
 
909
        """With no file, we get empty content."""
 
910
        backing = self.get_transport()
 
911
        request = smart_branch.SmartServerBranchGetConfigFile(backing)
 
912
        branch = self.make_branch('.')
 
913
        # there should be no file by default
 
914
        content = ''
 
915
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), content),
 
916
            request.execute(''))
 
917
 
 
918
    def test_with_content(self):
 
919
        # SmartServerBranchGetConfigFile should return the content from
 
920
        # branch.control_files.get('branch.conf') for now - in the future it may
 
921
        # perform more complex processing.
 
922
        backing = self.get_transport()
 
923
        request = smart_branch.SmartServerBranchGetConfigFile(backing)
 
924
        branch = self.make_branch('.')
 
925
        branch._transport.put_bytes('branch.conf', 'foo bar baz')
 
926
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'foo bar baz'),
 
927
            request.execute(''))
 
928
 
 
929
 
 
930
class TestLockedBranch(tests.TestCaseWithMemoryTransport):
 
931
 
 
932
    def get_lock_tokens(self, branch):
 
933
        branch_token = branch.lock_write().branch_token
 
934
        repo_token = branch.repository.lock_write().repository_token
 
935
        branch.repository.unlock()
 
936
        return branch_token, repo_token
 
937
 
 
938
 
 
939
class TestSmartServerBranchRequestPutConfigFile(TestLockedBranch):
 
940
 
 
941
    def test_with_content(self):
 
942
        backing = self.get_transport()
 
943
        request = smart_branch.SmartServerBranchPutConfigFile(backing)
 
944
        branch = self.make_branch('.')
 
945
        branch_token, repo_token = self.get_lock_tokens(branch)
 
946
        self.assertIs(None, request.execute('', branch_token, repo_token))
 
947
        self.assertEqual(
 
948
            smart_req.SmartServerResponse(('ok', )),
 
949
            request.do_body('foo bar baz'))
 
950
        self.assertEqual(
 
951
            branch.control_transport.get_bytes('branch.conf'),
 
952
            'foo bar baz')
 
953
        branch.unlock()
 
954
 
 
955
 
 
956
class TestSmartServerBranchRequestSetConfigOption(TestLockedBranch):
 
957
 
 
958
    def test_value_name(self):
 
959
        branch = self.make_branch('.')
 
960
        request = smart_branch.SmartServerBranchRequestSetConfigOption(
 
961
            branch.controldir.root_transport)
 
962
        branch_token, repo_token = self.get_lock_tokens(branch)
 
963
        config = branch._get_config()
 
964
        result = request.execute('', branch_token, repo_token, 'bar', 'foo',
 
965
            '')
 
966
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
 
967
        self.assertEqual('bar', config.get_option('foo'))
 
968
        # Cleanup
 
969
        branch.unlock()
 
970
 
 
971
    def test_value_name_section(self):
 
972
        branch = self.make_branch('.')
 
973
        request = smart_branch.SmartServerBranchRequestSetConfigOption(
 
974
            branch.controldir.root_transport)
 
975
        branch_token, repo_token = self.get_lock_tokens(branch)
 
976
        config = branch._get_config()
 
977
        result = request.execute('', branch_token, repo_token, 'bar', 'foo',
 
978
            'gam')
 
979
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
 
980
        self.assertEqual('bar', config.get_option('foo', 'gam'))
 
981
        # Cleanup
 
982
        branch.unlock()
 
983
 
 
984
 
 
985
class TestSmartServerBranchRequestSetConfigOptionDict(TestLockedBranch):
 
986
 
 
987
    def setUp(self):
 
988
        TestLockedBranch.setUp(self)
 
989
        # A dict with non-ascii keys and values to exercise unicode
 
990
        # roundtripping.
 
991
        self.encoded_value_dict = (
 
992
            'd5:ascii1:a11:unicode \xe2\x8c\x9a3:\xe2\x80\xbde')
 
993
        self.value_dict = {
 
994
            'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'}
 
995
 
 
996
    def test_value_name(self):
 
997
        branch = self.make_branch('.')
 
998
        request = smart_branch.SmartServerBranchRequestSetConfigOptionDict(
 
999
            branch.controldir.root_transport)
 
1000
        branch_token, repo_token = self.get_lock_tokens(branch)
 
1001
        config = branch._get_config()
 
1002
        result = request.execute('', branch_token, repo_token,
 
1003
            self.encoded_value_dict, 'foo', '')
 
1004
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
 
1005
        self.assertEqual(self.value_dict, config.get_option('foo'))
 
1006
        # Cleanup
 
1007
        branch.unlock()
 
1008
 
 
1009
    def test_value_name_section(self):
 
1010
        branch = self.make_branch('.')
 
1011
        request = smart_branch.SmartServerBranchRequestSetConfigOptionDict(
 
1012
            branch.controldir.root_transport)
 
1013
        branch_token, repo_token = self.get_lock_tokens(branch)
 
1014
        config = branch._get_config()
 
1015
        result = request.execute('', branch_token, repo_token,
 
1016
            self.encoded_value_dict, 'foo', 'gam')
 
1017
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
 
1018
        self.assertEqual(self.value_dict, config.get_option('foo', 'gam'))
 
1019
        # Cleanup
 
1020
        branch.unlock()
 
1021
 
 
1022
 
 
1023
class TestSmartServerBranchRequestSetTagsBytes(TestLockedBranch):
 
1024
    # Only called when the branch format and tags match [yay factory
 
1025
    # methods] so only need to test straight forward cases.
 
1026
 
 
1027
    def test_set_bytes(self):
 
1028
        base_branch = self.make_branch('base')
 
1029
        tag_bytes = base_branch._get_tags_bytes()
 
1030
        # get_lock_tokens takes out a lock.
 
1031
        branch_token, repo_token = self.get_lock_tokens(base_branch)
 
1032
        request = smart_branch.SmartServerBranchSetTagsBytes(
 
1033
            self.get_transport())
 
1034
        response = request.execute('base', branch_token, repo_token)
 
1035
        self.assertEqual(None, response)
 
1036
        response = request.do_chunk(tag_bytes)
 
1037
        self.assertEqual(None, response)
 
1038
        response = request.do_end()
 
1039
        self.assertEqual(
 
1040
            smart_req.SuccessfulSmartServerResponse(()), response)
 
1041
        base_branch.unlock()
 
1042
 
 
1043
    def test_lock_failed(self):
 
1044
        base_branch = self.make_branch('base')
 
1045
        base_branch.lock_write()
 
1046
        tag_bytes = base_branch._get_tags_bytes()
 
1047
        request = smart_branch.SmartServerBranchSetTagsBytes(
 
1048
            self.get_transport())
 
1049
        self.assertRaises(errors.TokenMismatch, request.execute,
 
1050
            'base', 'wrong token', 'wrong token')
 
1051
        # The request handler will keep processing the message parts, so even
 
1052
        # if the request fails immediately do_chunk and do_end are still
 
1053
        # called.
 
1054
        request.do_chunk(tag_bytes)
 
1055
        request.do_end()
 
1056
        base_branch.unlock()
 
1057
 
 
1058
 
 
1059
 
 
1060
class SetLastRevisionTestBase(TestLockedBranch):
 
1061
    """Base test case for verbs that implement set_last_revision."""
 
1062
 
 
1063
    def setUp(self):
 
1064
        super(SetLastRevisionTestBase, self).setUp()
 
1065
        backing_transport = self.get_transport()
 
1066
        self.request = self.request_class(backing_transport)
 
1067
        self.tree = self.make_branch_and_memory_tree('.')
 
1068
 
 
1069
    def lock_branch(self):
 
1070
        return self.get_lock_tokens(self.tree.branch)
 
1071
 
 
1072
    def unlock_branch(self):
 
1073
        self.tree.branch.unlock()
 
1074
 
 
1075
    def set_last_revision(self, revision_id, revno):
 
1076
        branch_token, repo_token = self.lock_branch()
 
1077
        response = self._set_last_revision(
 
1078
            revision_id, revno, branch_token, repo_token)
 
1079
        self.unlock_branch()
 
1080
        return response
 
1081
 
 
1082
    def assertRequestSucceeds(self, revision_id, revno):
 
1083
        response = self.set_last_revision(revision_id, revno)
 
1084
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
 
1085
                         response)
 
1086
 
 
1087
 
 
1088
class TestSetLastRevisionVerbMixin(object):
 
1089
    """Mixin test case for verbs that implement set_last_revision."""
 
1090
 
 
1091
    def test_set_null_to_null(self):
 
1092
        """An empty branch can have its last revision set to 'null:'."""
 
1093
        self.assertRequestSucceeds('null:', 0)
 
1094
 
 
1095
    def test_NoSuchRevision(self):
 
1096
        """If the revision_id is not present, the verb returns NoSuchRevision.
 
1097
        """
 
1098
        revision_id = 'non-existent revision'
 
1099
        self.assertEqual(smart_req.FailedSmartServerResponse(('NoSuchRevision',
 
1100
                                                              revision_id)),
 
1101
                         self.set_last_revision(revision_id, 1))
 
1102
 
 
1103
    def make_tree_with_two_commits(self):
 
1104
        self.tree.lock_write()
 
1105
        self.tree.add('')
 
1106
        rev_id_utf8 = u'\xc8'.encode('utf-8')
 
1107
        r1 = self.tree.commit('1st commit', rev_id=rev_id_utf8)
 
1108
        r2 = self.tree.commit('2nd commit', rev_id='rev-2')
 
1109
        self.tree.unlock()
 
1110
 
 
1111
    def test_branch_last_revision_info_is_updated(self):
 
1112
        """A branch's tip can be set to a revision that is present in its
 
1113
        repository.
 
1114
        """
 
1115
        # Make a branch with an empty revision history, but two revisions in
 
1116
        # its repository.
 
1117
        self.make_tree_with_two_commits()
 
1118
        rev_id_utf8 = u'\xc8'.encode('utf-8')
 
1119
        self.tree.branch.set_last_revision_info(0, 'null:')
 
1120
        self.assertEqual(
 
1121
            (0, 'null:'), self.tree.branch.last_revision_info())
 
1122
        # We can update the branch to a revision that is present in the
 
1123
        # repository.
 
1124
        self.assertRequestSucceeds(rev_id_utf8, 1)
 
1125
        self.assertEqual(
 
1126
            (1, rev_id_utf8), self.tree.branch.last_revision_info())
 
1127
 
 
1128
    def test_branch_last_revision_info_rewind(self):
 
1129
        """A branch's tip can be set to a revision that is an ancestor of the
 
1130
        current tip.
 
1131
        """
 
1132
        self.make_tree_with_two_commits()
 
1133
        rev_id_utf8 = u'\xc8'.encode('utf-8')
 
1134
        self.assertEqual(
 
1135
            (2, 'rev-2'), self.tree.branch.last_revision_info())
 
1136
        self.assertRequestSucceeds(rev_id_utf8, 1)
 
1137
        self.assertEqual(
 
1138
            (1, rev_id_utf8), self.tree.branch.last_revision_info())
 
1139
 
 
1140
    def test_TipChangeRejected(self):
 
1141
        """If a pre_change_branch_tip hook raises TipChangeRejected, the verb
 
1142
        returns TipChangeRejected.
 
1143
        """
 
1144
        rejection_message = u'rejection message\N{INTERROBANG}'
 
1145
        def hook_that_rejects(params):
 
1146
            raise errors.TipChangeRejected(rejection_message)
 
1147
        _mod_branch.Branch.hooks.install_named_hook(
 
1148
            'pre_change_branch_tip', hook_that_rejects, None)
 
1149
        self.assertEqual(
 
1150
            smart_req.FailedSmartServerResponse(
 
1151
                ('TipChangeRejected', rejection_message.encode('utf-8'))),
 
1152
            self.set_last_revision('null:', 0))
 
1153
 
 
1154
 
 
1155
class TestSmartServerBranchRequestSetLastRevision(
 
1156
        SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
 
1157
    """Tests for Branch.set_last_revision verb."""
 
1158
 
 
1159
    request_class = smart_branch.SmartServerBranchRequestSetLastRevision
 
1160
 
 
1161
    def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
 
1162
        return self.request.execute(
 
1163
            '', branch_token, repo_token, revision_id)
 
1164
 
 
1165
 
 
1166
class TestSmartServerBranchRequestSetLastRevisionInfo(
 
1167
        SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
 
1168
    """Tests for Branch.set_last_revision_info verb."""
 
1169
 
 
1170
    request_class = smart_branch.SmartServerBranchRequestSetLastRevisionInfo
 
1171
 
 
1172
    def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
 
1173
        return self.request.execute(
 
1174
            '', branch_token, repo_token, revno, revision_id)
 
1175
 
 
1176
    def test_NoSuchRevision(self):
 
1177
        """Branch.set_last_revision_info does not have to return
 
1178
        NoSuchRevision if the revision_id is absent.
 
1179
        """
 
1180
        raise tests.TestNotApplicable()
 
1181
 
 
1182
 
 
1183
class TestSmartServerBranchRequestSetLastRevisionEx(
 
1184
        SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
 
1185
    """Tests for Branch.set_last_revision_ex verb."""
 
1186
 
 
1187
    request_class = smart_branch.SmartServerBranchRequestSetLastRevisionEx
 
1188
 
 
1189
    def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
 
1190
        return self.request.execute(
 
1191
            '', branch_token, repo_token, revision_id, 0, 0)
 
1192
 
 
1193
    def assertRequestSucceeds(self, revision_id, revno):
 
1194
        response = self.set_last_revision(revision_id, revno)
 
1195
        self.assertEqual(
 
1196
            smart_req.SuccessfulSmartServerResponse(('ok', revno, revision_id)),
 
1197
            response)
 
1198
 
 
1199
    def test_branch_last_revision_info_rewind(self):
 
1200
        """A branch's tip can be set to a revision that is an ancestor of the
 
1201
        current tip, but only if allow_overwrite_descendant is passed.
 
1202
        """
 
1203
        self.make_tree_with_two_commits()
 
1204
        rev_id_utf8 = u'\xc8'.encode('utf-8')
 
1205
        self.assertEqual(
 
1206
            (2, 'rev-2'), self.tree.branch.last_revision_info())
 
1207
        # If allow_overwrite_descendant flag is 0, then trying to set the tip
 
1208
        # to an older revision ID has no effect.
 
1209
        branch_token, repo_token = self.lock_branch()
 
1210
        response = self.request.execute(
 
1211
            '', branch_token, repo_token, rev_id_utf8, 0, 0)
 
1212
        self.assertEqual(
 
1213
            smart_req.SuccessfulSmartServerResponse(('ok', 2, 'rev-2')),
 
1214
            response)
 
1215
        self.assertEqual(
 
1216
            (2, 'rev-2'), self.tree.branch.last_revision_info())
 
1217
 
 
1218
        # If allow_overwrite_descendant flag is 1, then setting the tip to an
 
1219
        # ancestor works.
 
1220
        response = self.request.execute(
 
1221
            '', branch_token, repo_token, rev_id_utf8, 0, 1)
 
1222
        self.assertEqual(
 
1223
            smart_req.SuccessfulSmartServerResponse(('ok', 1, rev_id_utf8)),
 
1224
            response)
 
1225
        self.unlock_branch()
 
1226
        self.assertEqual(
 
1227
            (1, rev_id_utf8), self.tree.branch.last_revision_info())
 
1228
 
 
1229
    def make_branch_with_divergent_history(self):
 
1230
        """Make a branch with divergent history in its repo.
 
1231
 
 
1232
        The branch's tip will be 'child-2', and the repo will also contain
 
1233
        'child-1', which diverges from a common base revision.
 
1234
        """
 
1235
        self.tree.lock_write()
 
1236
        self.tree.add('')
 
1237
        r1 = self.tree.commit('1st commit')
 
1238
        revno_1, revid_1 = self.tree.branch.last_revision_info()
 
1239
        r2 = self.tree.commit('2nd commit', rev_id='child-1')
 
1240
        # Undo the second commit
 
1241
        self.tree.branch.set_last_revision_info(revno_1, revid_1)
 
1242
        self.tree.set_parent_ids([revid_1])
 
1243
        # Make a new second commit, child-2.  child-2 has diverged from
 
1244
        # child-1.
 
1245
        new_r2 = self.tree.commit('2nd commit', rev_id='child-2')
 
1246
        self.tree.unlock()
 
1247
 
 
1248
    def test_not_allow_diverged(self):
 
1249
        """If allow_diverged is not passed, then setting a divergent history
 
1250
        returns a Diverged error.
 
1251
        """
 
1252
        self.make_branch_with_divergent_history()
 
1253
        self.assertEqual(
 
1254
            smart_req.FailedSmartServerResponse(('Diverged',)),
 
1255
            self.set_last_revision('child-1', 2))
 
1256
        # The branch tip was not changed.
 
1257
        self.assertEqual('child-2', self.tree.branch.last_revision())
 
1258
 
 
1259
    def test_allow_diverged(self):
 
1260
        """If allow_diverged is passed, then setting a divergent history
 
1261
        succeeds.
 
1262
        """
 
1263
        self.make_branch_with_divergent_history()
 
1264
        branch_token, repo_token = self.lock_branch()
 
1265
        response = self.request.execute(
 
1266
            '', branch_token, repo_token, 'child-1', 1, 0)
 
1267
        self.assertEqual(
 
1268
            smart_req.SuccessfulSmartServerResponse(('ok', 2, 'child-1')),
 
1269
            response)
 
1270
        self.unlock_branch()
 
1271
        # The branch tip was changed.
 
1272
        self.assertEqual('child-1', self.tree.branch.last_revision())
 
1273
 
 
1274
 
 
1275
class TestSmartServerBranchBreakLock(tests.TestCaseWithMemoryTransport):
 
1276
 
 
1277
    def test_lock_to_break(self):
 
1278
        base_branch = self.make_branch('base')
 
1279
        request = smart_branch.SmartServerBranchBreakLock(
 
1280
            self.get_transport())
 
1281
        base_branch.lock_write()
 
1282
        self.assertEqual(
 
1283
            smart_req.SuccessfulSmartServerResponse(('ok', ), None),
 
1284
            request.execute('base'))
 
1285
 
 
1286
    def test_nothing_to_break(self):
 
1287
        base_branch = self.make_branch('base')
 
1288
        request = smart_branch.SmartServerBranchBreakLock(
 
1289
            self.get_transport())
 
1290
        self.assertEqual(
 
1291
            smart_req.SuccessfulSmartServerResponse(('ok', ), None),
 
1292
            request.execute('base'))
 
1293
 
 
1294
 
 
1295
class TestSmartServerBranchRequestGetParent(tests.TestCaseWithMemoryTransport):
 
1296
 
 
1297
    def test_get_parent_none(self):
 
1298
        base_branch = self.make_branch('base')
 
1299
        request = smart_branch.SmartServerBranchGetParent(self.get_transport())
 
1300
        response = request.execute('base')
 
1301
        self.assertEqual(
 
1302
            smart_req.SuccessfulSmartServerResponse(('',)), response)
 
1303
 
 
1304
    def test_get_parent_something(self):
 
1305
        base_branch = self.make_branch('base')
 
1306
        base_branch.set_parent(self.get_url('foo'))
 
1307
        request = smart_branch.SmartServerBranchGetParent(self.get_transport())
 
1308
        response = request.execute('base')
 
1309
        self.assertEqual(
 
1310
            smart_req.SuccessfulSmartServerResponse(("../foo",)),
 
1311
            response)
 
1312
 
 
1313
 
 
1314
class TestSmartServerBranchRequestSetParent(TestLockedBranch):
 
1315
 
 
1316
    def test_set_parent_none(self):
 
1317
        branch = self.make_branch('base', format="1.9")
 
1318
        branch.lock_write()
 
1319
        branch._set_parent_location('foo')
 
1320
        branch.unlock()
 
1321
        request = smart_branch.SmartServerBranchRequestSetParentLocation(
 
1322
            self.get_transport())
 
1323
        branch_token, repo_token = self.get_lock_tokens(branch)
 
1324
        try:
 
1325
            response = request.execute('base', branch_token, repo_token, '')
 
1326
        finally:
 
1327
            branch.unlock()
 
1328
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), response)
 
1329
        # Refresh branch as SetParentLocation modified it
 
1330
        branch = branch.controldir.open_branch()
 
1331
        self.assertEqual(None, branch.get_parent())
 
1332
 
 
1333
    def test_set_parent_something(self):
 
1334
        branch = self.make_branch('base', format="1.9")
 
1335
        request = smart_branch.SmartServerBranchRequestSetParentLocation(
 
1336
            self.get_transport())
 
1337
        branch_token, repo_token = self.get_lock_tokens(branch)
 
1338
        try:
 
1339
            response = request.execute('base', branch_token, repo_token,
 
1340
                                       'http://bar/')
 
1341
        finally:
 
1342
            branch.unlock()
 
1343
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), response)
 
1344
        refreshed = _mod_branch.Branch.open(branch.base)
 
1345
        self.assertEqual('http://bar/', refreshed.get_parent())
 
1346
 
 
1347
 
 
1348
class TestSmartServerBranchRequestGetTagsBytes(
 
1349
    tests.TestCaseWithMemoryTransport):
 
1350
    # Only called when the branch format and tags match [yay factory
 
1351
    # methods] so only need to test straight forward cases.
 
1352
 
 
1353
    def test_get_bytes(self):
 
1354
        base_branch = self.make_branch('base')
 
1355
        request = smart_branch.SmartServerBranchGetTagsBytes(
 
1356
            self.get_transport())
 
1357
        response = request.execute('base')
 
1358
        self.assertEqual(
 
1359
            smart_req.SuccessfulSmartServerResponse(('',)), response)
 
1360
 
 
1361
 
 
1362
class TestSmartServerBranchRequestGetStackedOnURL(tests.TestCaseWithMemoryTransport):
 
1363
 
 
1364
    def test_get_stacked_on_url(self):
 
1365
        base_branch = self.make_branch('base', format='1.6')
 
1366
        stacked_branch = self.make_branch('stacked', format='1.6')
 
1367
        # typically should be relative
 
1368
        stacked_branch.set_stacked_on_url('../base')
 
1369
        request = smart_branch.SmartServerBranchRequestGetStackedOnURL(
 
1370
            self.get_transport())
 
1371
        response = request.execute('stacked')
 
1372
        self.assertEqual(
 
1373
            smart_req.SmartServerResponse(('ok', '../base')),
 
1374
            response)
 
1375
 
 
1376
 
 
1377
class TestSmartServerBranchRequestLockWrite(TestLockedBranch):
 
1378
 
 
1379
    def test_lock_write_on_unlocked_branch(self):
 
1380
        backing = self.get_transport()
 
1381
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
 
1382
        branch = self.make_branch('.', format='knit')
 
1383
        repository = branch.repository
 
1384
        response = request.execute('')
 
1385
        branch_nonce = branch.control_files._lock.peek().get('nonce')
 
1386
        repository_nonce = repository.control_files._lock.peek().get('nonce')
 
1387
        self.assertEqual(smart_req.SmartServerResponse(
 
1388
                ('ok', branch_nonce, repository_nonce)),
 
1389
                         response)
 
1390
        # The branch (and associated repository) is now locked.  Verify that
 
1391
        # with a new branch object.
 
1392
        new_branch = repository.controldir.open_branch()
 
1393
        self.assertRaises(errors.LockContention, new_branch.lock_write)
 
1394
        # Cleanup
 
1395
        request = smart_branch.SmartServerBranchRequestUnlock(backing)
 
1396
        response = request.execute('', branch_nonce, repository_nonce)
 
1397
 
 
1398
    def test_lock_write_on_locked_branch(self):
 
1399
        backing = self.get_transport()
 
1400
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
 
1401
        branch = self.make_branch('.')
 
1402
        branch_token = branch.lock_write().branch_token
 
1403
        branch.leave_lock_in_place()
 
1404
        branch.unlock()
 
1405
        response = request.execute('')
 
1406
        self.assertEqual(
 
1407
            smart_req.SmartServerResponse(('LockContention',)), response)
 
1408
        # Cleanup
 
1409
        branch.lock_write(branch_token)
 
1410
        branch.dont_leave_lock_in_place()
 
1411
        branch.unlock()
 
1412
 
 
1413
    def test_lock_write_with_tokens_on_locked_branch(self):
 
1414
        backing = self.get_transport()
 
1415
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
 
1416
        branch = self.make_branch('.', format='knit')
 
1417
        branch_token, repo_token = self.get_lock_tokens(branch)
 
1418
        branch.leave_lock_in_place()
 
1419
        branch.repository.leave_lock_in_place()
 
1420
        branch.unlock()
 
1421
        response = request.execute('',
 
1422
                                   branch_token, repo_token)
 
1423
        self.assertEqual(
 
1424
            smart_req.SmartServerResponse(('ok', branch_token, repo_token)),
 
1425
            response)
 
1426
        # Cleanup
 
1427
        branch.repository.lock_write(repo_token)
 
1428
        branch.repository.dont_leave_lock_in_place()
 
1429
        branch.repository.unlock()
 
1430
        branch.lock_write(branch_token)
 
1431
        branch.dont_leave_lock_in_place()
 
1432
        branch.unlock()
 
1433
 
 
1434
    def test_lock_write_with_mismatched_tokens_on_locked_branch(self):
 
1435
        backing = self.get_transport()
 
1436
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
 
1437
        branch = self.make_branch('.', format='knit')
 
1438
        branch_token, repo_token = self.get_lock_tokens(branch)
 
1439
        branch.leave_lock_in_place()
 
1440
        branch.repository.leave_lock_in_place()
 
1441
        branch.unlock()
 
1442
        response = request.execute('',
 
1443
                                   branch_token+'xxx', repo_token)
 
1444
        self.assertEqual(
 
1445
            smart_req.SmartServerResponse(('TokenMismatch',)), response)
 
1446
        # Cleanup
 
1447
        branch.repository.lock_write(repo_token)
 
1448
        branch.repository.dont_leave_lock_in_place()
 
1449
        branch.repository.unlock()
 
1450
        branch.lock_write(branch_token)
 
1451
        branch.dont_leave_lock_in_place()
 
1452
        branch.unlock()
 
1453
 
 
1454
    def test_lock_write_on_locked_repo(self):
 
1455
        backing = self.get_transport()
 
1456
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
 
1457
        branch = self.make_branch('.', format='knit')
 
1458
        repo = branch.repository
 
1459
        repo_token = repo.lock_write().repository_token
 
1460
        repo.leave_lock_in_place()
 
1461
        repo.unlock()
 
1462
        response = request.execute('')
 
1463
        self.assertEqual(
 
1464
            smart_req.SmartServerResponse(('LockContention',)), response)
 
1465
        # Cleanup
 
1466
        repo.lock_write(repo_token)
 
1467
        repo.dont_leave_lock_in_place()
 
1468
        repo.unlock()
 
1469
 
 
1470
    def test_lock_write_on_readonly_transport(self):
 
1471
        backing = self.get_readonly_transport()
 
1472
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
 
1473
        branch = self.make_branch('.')
 
1474
        root = self.get_transport().clone('/')
 
1475
        path = urlutils.relative_url(root.base, self.get_transport().base)
 
1476
        response = request.execute(path)
 
1477
        error_name, lock_str, why_str = response.args
 
1478
        self.assertFalse(response.is_successful())
 
1479
        self.assertEqual('LockFailed', error_name)
 
1480
 
 
1481
 
 
1482
class TestSmartServerBranchRequestGetPhysicalLockStatus(TestLockedBranch):
 
1483
 
 
1484
    def test_true(self):
 
1485
        backing = self.get_transport()
 
1486
        request = smart_branch.SmartServerBranchRequestGetPhysicalLockStatus(
 
1487
            backing)
 
1488
        branch = self.make_branch('.')
 
1489
        branch_token, repo_token = self.get_lock_tokens(branch)
 
1490
        self.assertEqual(True, branch.get_physical_lock_status())
 
1491
        response = request.execute('')
 
1492
        self.assertEqual(
 
1493
            smart_req.SmartServerResponse(('yes',)), response)
 
1494
        branch.unlock()
 
1495
 
 
1496
    def test_false(self):
 
1497
        backing = self.get_transport()
 
1498
        request = smart_branch.SmartServerBranchRequestGetPhysicalLockStatus(
 
1499
            backing)
 
1500
        branch = self.make_branch('.')
 
1501
        self.assertEqual(False, branch.get_physical_lock_status())
 
1502
        response = request.execute('')
 
1503
        self.assertEqual(
 
1504
            smart_req.SmartServerResponse(('no',)), response)
 
1505
 
 
1506
 
 
1507
class TestSmartServerBranchRequestUnlock(TestLockedBranch):
 
1508
 
 
1509
    def test_unlock_on_locked_branch_and_repo(self):
 
1510
        backing = self.get_transport()
 
1511
        request = smart_branch.SmartServerBranchRequestUnlock(backing)
 
1512
        branch = self.make_branch('.', format='knit')
 
1513
        # Lock the branch
 
1514
        branch_token, repo_token = self.get_lock_tokens(branch)
 
1515
        # Unlock the branch (and repo) object, leaving the physical locks
 
1516
        # in place.
 
1517
        branch.leave_lock_in_place()
 
1518
        branch.repository.leave_lock_in_place()
 
1519
        branch.unlock()
 
1520
        response = request.execute('',
 
1521
                                   branch_token, repo_token)
 
1522
        self.assertEqual(
 
1523
            smart_req.SmartServerResponse(('ok',)), response)
 
1524
        # The branch is now unlocked.  Verify that with a new branch
 
1525
        # object.
 
1526
        new_branch = branch.controldir.open_branch()
 
1527
        new_branch.lock_write()
 
1528
        new_branch.unlock()
 
1529
 
 
1530
    def test_unlock_on_unlocked_branch_unlocked_repo(self):
 
1531
        backing = self.get_transport()
 
1532
        request = smart_branch.SmartServerBranchRequestUnlock(backing)
 
1533
        branch = self.make_branch('.', format='knit')
 
1534
        response = request.execute(
 
1535
            '', 'branch token', 'repo token')
 
1536
        self.assertEqual(
 
1537
            smart_req.SmartServerResponse(('TokenMismatch',)), response)
 
1538
 
 
1539
    def test_unlock_on_unlocked_branch_locked_repo(self):
 
1540
        backing = self.get_transport()
 
1541
        request = smart_branch.SmartServerBranchRequestUnlock(backing)
 
1542
        branch = self.make_branch('.', format='knit')
 
1543
        # Lock the repository.
 
1544
        repo_token = branch.repository.lock_write().repository_token
 
1545
        branch.repository.leave_lock_in_place()
 
1546
        branch.repository.unlock()
 
1547
        # Issue branch lock_write request on the unlocked branch (with locked
 
1548
        # repo).
 
1549
        response = request.execute('', 'branch token', repo_token)
 
1550
        self.assertEqual(
 
1551
            smart_req.SmartServerResponse(('TokenMismatch',)), response)
 
1552
        # Cleanup
 
1553
        branch.repository.lock_write(repo_token)
 
1554
        branch.repository.dont_leave_lock_in_place()
 
1555
        branch.repository.unlock()
 
1556
 
 
1557
 
 
1558
class TestSmartServerRepositoryRequest(tests.TestCaseWithMemoryTransport):
 
1559
 
 
1560
    def test_no_repository(self):
 
1561
        """Raise NoRepositoryPresent when there is a bzrdir and no repo."""
 
1562
        # we test this using a shared repository above the named path,
 
1563
        # thus checking the right search logic is used - that is, that
 
1564
        # its the exact path being looked at and the server is not
 
1565
        # searching.
 
1566
        backing = self.get_transport()
 
1567
        request = smart_repo.SmartServerRepositoryRequest(backing)
 
1568
        self.make_repository('.', shared=True)
 
1569
        self.make_controldir('subdir')
 
1570
        self.assertRaises(errors.NoRepositoryPresent,
 
1571
            request.execute, 'subdir')
 
1572
 
 
1573
 
 
1574
class TestSmartServerRepositoryAddSignatureText(tests.TestCaseWithMemoryTransport):
 
1575
 
 
1576
    def test_add_text(self):
 
1577
        backing = self.get_transport()
 
1578
        request = smart_repo.SmartServerRepositoryAddSignatureText(backing)
 
1579
        tree = self.make_branch_and_memory_tree('.')
 
1580
        write_token = tree.lock_write()
 
1581
        self.addCleanup(tree.unlock)
 
1582
        tree.add('')
 
1583
        tree.commit("Message", rev_id='rev1')
 
1584
        tree.branch.repository.start_write_group()
 
1585
        write_group_tokens = tree.branch.repository.suspend_write_group()
 
1586
        self.assertEqual(None, request.execute('', write_token,
 
1587
            'rev1', *write_group_tokens))
 
1588
        response = request.do_body('somesignature')
 
1589
        self.assertTrue(response.is_successful())
 
1590
        self.assertEqual(response.args[0], 'ok')
 
1591
        write_group_tokens = response.args[1:]
 
1592
        tree.branch.repository.resume_write_group(write_group_tokens)
 
1593
        tree.branch.repository.commit_write_group()
 
1594
        tree.unlock()
 
1595
        self.assertEqual("somesignature",
 
1596
            tree.branch.repository.get_signature_text("rev1"))
 
1597
 
 
1598
 
 
1599
class TestSmartServerRepositoryAllRevisionIds(
 
1600
    tests.TestCaseWithMemoryTransport):
 
1601
 
 
1602
    def test_empty(self):
 
1603
        """An empty body should be returned for an empty repository."""
 
1604
        backing = self.get_transport()
 
1605
        request = smart_repo.SmartServerRepositoryAllRevisionIds(backing)
 
1606
        self.make_repository('.')
 
1607
        self.assertEqual(
 
1608
            smart_req.SuccessfulSmartServerResponse(("ok", ), ""),
 
1609
            request.execute(''))
 
1610
 
 
1611
    def test_some_revisions(self):
 
1612
        """An empty body should be returned for an empty repository."""
 
1613
        backing = self.get_transport()
 
1614
        request = smart_repo.SmartServerRepositoryAllRevisionIds(backing)
 
1615
        tree = self.make_branch_and_memory_tree('.')
 
1616
        tree.lock_write()
 
1617
        tree.add('')
 
1618
        tree.commit(rev_id='origineel', message="message")
 
1619
        tree.commit(rev_id='nog-een-revisie', message="message")
 
1620
        tree.unlock()
 
1621
        self.assertEqual(
 
1622
            smart_req.SuccessfulSmartServerResponse(("ok", ),
 
1623
                "origineel\nnog-een-revisie"),
 
1624
            request.execute(''))
 
1625
 
 
1626
 
 
1627
class TestSmartServerRepositoryBreakLock(tests.TestCaseWithMemoryTransport):
 
1628
 
 
1629
    def test_lock_to_break(self):
 
1630
        backing = self.get_transport()
 
1631
        request = smart_repo.SmartServerRepositoryBreakLock(backing)
 
1632
        tree = self.make_branch_and_memory_tree('.')
 
1633
        tree.branch.repository.lock_write()
 
1634
        self.assertEqual(
 
1635
            smart_req.SuccessfulSmartServerResponse(('ok', ), None),
 
1636
            request.execute(''))
 
1637
 
 
1638
    def test_nothing_to_break(self):
 
1639
        backing = self.get_transport()
 
1640
        request = smart_repo.SmartServerRepositoryBreakLock(backing)
 
1641
        tree = self.make_branch_and_memory_tree('.')
 
1642
        self.assertEqual(
 
1643
            smart_req.SuccessfulSmartServerResponse(('ok', ), None),
 
1644
            request.execute(''))
 
1645
 
 
1646
 
 
1647
class TestSmartServerRepositoryGetParentMap(tests.TestCaseWithMemoryTransport):
 
1648
 
 
1649
    def test_trivial_bzipped(self):
 
1650
        # This tests that the wire encoding is actually bzipped
 
1651
        backing = self.get_transport()
 
1652
        request = smart_repo.SmartServerRepositoryGetParentMap(backing)
 
1653
        tree = self.make_branch_and_memory_tree('.')
 
1654
 
 
1655
        self.assertEqual(None,
 
1656
            request.execute('', 'missing-id'))
 
1657
        # Note that it returns a body that is bzipped.
 
1658
        self.assertEqual(
 
1659
            smart_req.SuccessfulSmartServerResponse(('ok', ), bz2.compress('')),
 
1660
            request.do_body('\n\n0\n'))
 
1661
 
 
1662
    def test_trivial_include_missing(self):
 
1663
        backing = self.get_transport()
 
1664
        request = smart_repo.SmartServerRepositoryGetParentMap(backing)
 
1665
        tree = self.make_branch_and_memory_tree('.')
 
1666
 
 
1667
        self.assertEqual(None,
 
1668
            request.execute('', 'missing-id', 'include-missing:'))
 
1669
        self.assertEqual(
 
1670
            smart_req.SuccessfulSmartServerResponse(('ok', ),
 
1671
                bz2.compress('missing:missing-id')),
 
1672
            request.do_body('\n\n0\n'))
 
1673
 
 
1674
 
 
1675
class TestSmartServerRepositoryGetRevisionGraph(
 
1676
    tests.TestCaseWithMemoryTransport):
 
1677
 
 
1678
    def test_none_argument(self):
 
1679
        backing = self.get_transport()
 
1680
        request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
 
1681
        tree = self.make_branch_and_memory_tree('.')
 
1682
        tree.lock_write()
 
1683
        tree.add('')
 
1684
        r1 = tree.commit('1st commit')
 
1685
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
 
1686
        tree.unlock()
 
1687
 
 
1688
        # the lines of revision_id->revision_parent_list has no guaranteed
 
1689
        # order coming out of a dict, so sort both our test and response
 
1690
        lines = sorted([' '.join([r2, r1]), r1])
 
1691
        response = request.execute('', '')
 
1692
        response.body = '\n'.join(sorted(response.body.split('\n')))
 
1693
 
 
1694
        self.assertEqual(
 
1695
            smart_req.SmartServerResponse(('ok', ), '\n'.join(lines)), response)
 
1696
 
 
1697
    def test_specific_revision_argument(self):
 
1698
        backing = self.get_transport()
 
1699
        request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
 
1700
        tree = self.make_branch_and_memory_tree('.')
 
1701
        tree.lock_write()
 
1702
        tree.add('')
 
1703
        rev_id_utf8 = u'\xc9'.encode('utf-8')
 
1704
        r1 = tree.commit('1st commit', rev_id=rev_id_utf8)
 
1705
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
 
1706
        tree.unlock()
 
1707
 
 
1708
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), rev_id_utf8),
 
1709
            request.execute('', rev_id_utf8))
 
1710
 
 
1711
    def test_no_such_revision(self):
 
1712
        backing = self.get_transport()
 
1713
        request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
 
1714
        tree = self.make_branch_and_memory_tree('.')
 
1715
        tree.lock_write()
 
1716
        tree.add('')
 
1717
        r1 = tree.commit('1st commit')
 
1718
        tree.unlock()
 
1719
 
 
1720
        # Note that it still returns body (of zero bytes).
 
1721
        self.assertEqual(smart_req.SmartServerResponse(
 
1722
                ('nosuchrevision', 'missingrevision', ), ''),
 
1723
                         request.execute('', 'missingrevision'))
 
1724
 
 
1725
 
 
1726
class TestSmartServerRepositoryGetRevIdForRevno(
 
1727
    tests.TestCaseWithMemoryTransport):
 
1728
 
 
1729
    def test_revno_found(self):
 
1730
        backing = self.get_transport()
 
1731
        request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
 
1732
        tree = self.make_branch_and_memory_tree('.')
 
1733
        tree.lock_write()
 
1734
        tree.add('')
 
1735
        rev1_id_utf8 = u'\xc8'.encode('utf-8')
 
1736
        rev2_id_utf8 = u'\xc9'.encode('utf-8')
 
1737
        tree.commit('1st commit', rev_id=rev1_id_utf8)
 
1738
        tree.commit('2nd commit', rev_id=rev2_id_utf8)
 
1739
        tree.unlock()
 
1740
 
 
1741
        self.assertEqual(smart_req.SmartServerResponse(('ok', rev1_id_utf8)),
 
1742
            request.execute('', 1, (2, rev2_id_utf8)))
 
1743
 
 
1744
    def test_known_revid_missing(self):
 
1745
        backing = self.get_transport()
 
1746
        request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
 
1747
        repo = self.make_repository('.')
 
1748
        self.assertEqual(
 
1749
            smart_req.FailedSmartServerResponse(('nosuchrevision', 'ghost')),
 
1750
            request.execute('', 1, (2, 'ghost')))
 
1751
 
 
1752
    def test_history_incomplete(self):
 
1753
        backing = self.get_transport()
 
1754
        request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
 
1755
        parent = self.make_branch_and_memory_tree('parent', format='1.9')
 
1756
        parent.lock_write()
 
1757
        parent.add([''], ['TREE_ROOT'])
 
1758
        r1 = parent.commit(message='first commit')
 
1759
        r2 = parent.commit(message='second commit')
 
1760
        parent.unlock()
 
1761
        local = self.make_branch_and_memory_tree('local', format='1.9')
 
1762
        local.branch.pull(parent.branch)
 
1763
        local.set_parent_ids([r2])
 
1764
        r3 = local.commit(message='local commit')
 
1765
        local.branch.create_clone_on_transport(
 
1766
            self.get_transport('stacked'), stacked_on=self.get_url('parent'))
 
1767
        self.assertEqual(
 
1768
            smart_req.SmartServerResponse(('history-incomplete', 2, r2)),
 
1769
            request.execute('stacked', 1, (3, r3)))
 
1770
 
 
1771
 
 
1772
class TestSmartServerRepositoryIterRevisions(
 
1773
    tests.TestCaseWithMemoryTransport):
 
1774
 
 
1775
    def test_basic(self):
 
1776
        backing = self.get_transport()
 
1777
        request = smart_repo.SmartServerRepositoryIterRevisions(backing)
 
1778
        tree = self.make_branch_and_memory_tree('.', format='2a')
 
1779
        tree.lock_write()
 
1780
        tree.add('')
 
1781
        tree.commit('1st commit', rev_id="rev1")
 
1782
        tree.commit('2nd commit', rev_id="rev2")
 
1783
        tree.unlock()
 
1784
 
 
1785
        self.assertIs(None, request.execute(''))
 
1786
        response = request.do_body("rev1\nrev2")
 
1787
        self.assertTrue(response.is_successful())
 
1788
        # Format 2a uses serializer format 10
 
1789
        self.assertEqual(response.args, ("ok", "10"))
 
1790
 
 
1791
        self.addCleanup(tree.branch.lock_read().unlock)
 
1792
        entries = [zlib.compress(record.get_bytes_as("fulltext")) for record in
 
1793
            tree.branch.repository.revisions.get_record_stream(
 
1794
            [("rev1", ), ("rev2", )], "unordered", True)]
 
1795
 
 
1796
        contents = "".join(response.body_stream)
 
1797
        self.assertTrue(contents in (
 
1798
            "".join([entries[0], entries[1]]),
 
1799
            "".join([entries[1], entries[0]])))
 
1800
 
 
1801
    def test_missing(self):
 
1802
        backing = self.get_transport()
 
1803
        request = smart_repo.SmartServerRepositoryIterRevisions(backing)
 
1804
        tree = self.make_branch_and_memory_tree('.', format='2a')
 
1805
 
 
1806
        self.assertIs(None, request.execute(''))
 
1807
        response = request.do_body("rev1\nrev2")
 
1808
        self.assertTrue(response.is_successful())
 
1809
        # Format 2a uses serializer format 10
 
1810
        self.assertEqual(response.args, ("ok", "10"))
 
1811
 
 
1812
        contents = "".join(response.body_stream)
 
1813
        self.assertEqual(contents, "")
 
1814
 
 
1815
 
 
1816
class GetStreamTestBase(tests.TestCaseWithMemoryTransport):
 
1817
 
 
1818
    def make_two_commit_repo(self):
 
1819
        tree = self.make_branch_and_memory_tree('.')
 
1820
        tree.lock_write()
 
1821
        tree.add('')
 
1822
        r1 = tree.commit('1st commit')
 
1823
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
 
1824
        tree.unlock()
 
1825
        repo = tree.branch.repository
 
1826
        return repo, r1, r2
 
1827
 
 
1828
 
 
1829
class TestSmartServerRepositoryGetStream(GetStreamTestBase):
 
1830
 
 
1831
    def test_ancestry_of(self):
 
1832
        """The search argument may be a 'ancestry-of' some heads'."""
 
1833
        backing = self.get_transport()
 
1834
        request = smart_repo.SmartServerRepositoryGetStream(backing)
 
1835
        repo, r1, r2 = self.make_two_commit_repo()
 
1836
        fetch_spec = ['ancestry-of', r2]
 
1837
        lines = '\n'.join(fetch_spec)
 
1838
        request.execute('', repo._format.network_name())
 
1839
        response = request.do_body(lines)
 
1840
        self.assertEqual(('ok',), response.args)
 
1841
        stream_bytes = ''.join(response.body_stream)
 
1842
        self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
 
1843
 
 
1844
    def test_search(self):
 
1845
        """The search argument may be a 'search' of some explicit keys."""
 
1846
        backing = self.get_transport()
 
1847
        request = smart_repo.SmartServerRepositoryGetStream(backing)
 
1848
        repo, r1, r2 = self.make_two_commit_repo()
 
1849
        fetch_spec = ['search', '%s %s' % (r1, r2), 'null:', '2']
 
1850
        lines = '\n'.join(fetch_spec)
 
1851
        request.execute('', repo._format.network_name())
 
1852
        response = request.do_body(lines)
 
1853
        self.assertEqual(('ok',), response.args)
 
1854
        stream_bytes = ''.join(response.body_stream)
 
1855
        self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
 
1856
 
 
1857
    def test_search_everything(self):
 
1858
        """A search of 'everything' returns a stream."""
 
1859
        backing = self.get_transport()
 
1860
        request = smart_repo.SmartServerRepositoryGetStream_1_19(backing)
 
1861
        repo, r1, r2 = self.make_two_commit_repo()
 
1862
        serialised_fetch_spec = 'everything'
 
1863
        request.execute('', repo._format.network_name())
 
1864
        response = request.do_body(serialised_fetch_spec)
 
1865
        self.assertEqual(('ok',), response.args)
 
1866
        stream_bytes = ''.join(response.body_stream)
 
1867
        self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
 
1868
 
 
1869
 
 
1870
class TestSmartServerRequestHasRevision(tests.TestCaseWithMemoryTransport):
 
1871
 
 
1872
    def test_missing_revision(self):
 
1873
        """For a missing revision, ('no', ) is returned."""
 
1874
        backing = self.get_transport()
 
1875
        request = smart_repo.SmartServerRequestHasRevision(backing)
 
1876
        self.make_repository('.')
 
1877
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
 
1878
            request.execute('', 'revid'))
 
1879
 
 
1880
    def test_present_revision(self):
 
1881
        """For a present revision, ('yes', ) is returned."""
 
1882
        backing = self.get_transport()
 
1883
        request = smart_repo.SmartServerRequestHasRevision(backing)
 
1884
        tree = self.make_branch_and_memory_tree('.')
 
1885
        tree.lock_write()
 
1886
        tree.add('')
 
1887
        rev_id_utf8 = u'\xc8abc'.encode('utf-8')
 
1888
        r1 = tree.commit('a commit', rev_id=rev_id_utf8)
 
1889
        tree.unlock()
 
1890
        self.assertTrue(tree.branch.repository.has_revision(rev_id_utf8))
 
1891
        self.assertEqual(smart_req.SmartServerResponse(('yes', )),
 
1892
            request.execute('', rev_id_utf8))
 
1893
 
 
1894
 
 
1895
class TestSmartServerRepositoryIterFilesBytes(tests.TestCaseWithTransport):
 
1896
 
 
1897
    def test_single(self):
 
1898
        backing = self.get_transport()
 
1899
        request = smart_repo.SmartServerRepositoryIterFilesBytes(backing)
 
1900
        t = self.make_branch_and_tree('.')
 
1901
        self.addCleanup(t.lock_write().unlock)
 
1902
        self.build_tree_contents([("file", "somecontents")])
 
1903
        t.add(["file"], ["thefileid"])
 
1904
        t.commit(rev_id='somerev', message="add file")
 
1905
        self.assertIs(None, request.execute(''))
 
1906
        response = request.do_body("thefileid\0somerev\n")
 
1907
        self.assertTrue(response.is_successful())
 
1908
        self.assertEqual(response.args, ("ok", ))
 
1909
        self.assertEqual("".join(response.body_stream),
 
1910
            "ok\x000\n" + zlib.compress("somecontents"))
 
1911
 
 
1912
    def test_missing(self):
 
1913
        backing = self.get_transport()
 
1914
        request = smart_repo.SmartServerRepositoryIterFilesBytes(backing)
 
1915
        t = self.make_branch_and_tree('.')
 
1916
        self.addCleanup(t.lock_write().unlock)
 
1917
        self.assertIs(None, request.execute(''))
 
1918
        response = request.do_body("thefileid\0revision\n")
 
1919
        self.assertTrue(response.is_successful())
 
1920
        self.assertEqual(response.args, ("ok", ))
 
1921
        self.assertEqual("".join(response.body_stream),
 
1922
            "absent\x00thefileid\x00revision\x000\n")
 
1923
 
 
1924
 
 
1925
class TestSmartServerRequestHasSignatureForRevisionId(
 
1926
        tests.TestCaseWithMemoryTransport):
 
1927
 
 
1928
    def test_missing_revision(self):
 
1929
        """For a missing revision, NoSuchRevision is returned."""
 
1930
        backing = self.get_transport()
 
1931
        request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
 
1932
            backing)
 
1933
        self.make_repository('.')
 
1934
        self.assertEqual(
 
1935
            smart_req.FailedSmartServerResponse(
 
1936
                ('nosuchrevision', 'revid'), None),
 
1937
            request.execute('', 'revid'))
 
1938
 
 
1939
    def test_missing_signature(self):
 
1940
        """For a missing signature, ('no', ) is returned."""
 
1941
        backing = self.get_transport()
 
1942
        request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
 
1943
            backing)
 
1944
        tree = self.make_branch_and_memory_tree('.')
 
1945
        tree.lock_write()
 
1946
        tree.add('')
 
1947
        r1 = tree.commit('a commit', rev_id='A')
 
1948
        tree.unlock()
 
1949
        self.assertTrue(tree.branch.repository.has_revision('A'))
 
1950
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
 
1951
            request.execute('', 'A'))
 
1952
 
 
1953
    def test_present_signature(self):
 
1954
        """For a present signature, ('yes', ) is returned."""
 
1955
        backing = self.get_transport()
 
1956
        request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
 
1957
            backing)
 
1958
        strategy = gpg.LoopbackGPGStrategy(None)
 
1959
        tree = self.make_branch_and_memory_tree('.')
 
1960
        tree.lock_write()
 
1961
        tree.add('')
 
1962
        r1 = tree.commit('a commit', rev_id='A')
 
1963
        tree.branch.repository.start_write_group()
 
1964
        tree.branch.repository.sign_revision('A', strategy)
 
1965
        tree.branch.repository.commit_write_group()
 
1966
        tree.unlock()
 
1967
        self.assertTrue(tree.branch.repository.has_revision('A'))
 
1968
        self.assertEqual(smart_req.SmartServerResponse(('yes', )),
 
1969
            request.execute('', 'A'))
 
1970
 
 
1971
 
 
1972
class TestSmartServerRepositoryGatherStats(tests.TestCaseWithMemoryTransport):
 
1973
 
 
1974
    def test_empty_revid(self):
 
1975
        """With an empty revid, we get only size an number and revisions"""
 
1976
        backing = self.get_transport()
 
1977
        request = smart_repo.SmartServerRepositoryGatherStats(backing)
 
1978
        repository = self.make_repository('.')
 
1979
        stats = repository.gather_stats()
 
1980
        expected_body = 'revisions: 0\n'
 
1981
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
 
1982
                         request.execute('', '', 'no'))
 
1983
 
 
1984
    def test_revid_with_committers(self):
 
1985
        """For a revid we get more infos."""
 
1986
        backing = self.get_transport()
 
1987
        rev_id_utf8 = u'\xc8abc'.encode('utf-8')
 
1988
        request = smart_repo.SmartServerRepositoryGatherStats(backing)
 
1989
        tree = self.make_branch_and_memory_tree('.')
 
1990
        tree.lock_write()
 
1991
        tree.add('')
 
1992
        # Let's build a predictable result
 
1993
        tree.commit('a commit', timestamp=123456.2, timezone=3600)
 
1994
        tree.commit('a commit', timestamp=654321.4, timezone=0,
 
1995
                    rev_id=rev_id_utf8)
 
1996
        tree.unlock()
 
1997
 
 
1998
        stats = tree.branch.repository.gather_stats()
 
1999
        expected_body = ('firstrev: 123456.200 3600\n'
 
2000
                         'latestrev: 654321.400 0\n'
 
2001
                         'revisions: 2\n')
 
2002
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
 
2003
                         request.execute('',
 
2004
                                         rev_id_utf8, 'no'))
 
2005
 
 
2006
    def test_not_empty_repository_with_committers(self):
 
2007
        """For a revid and requesting committers we get the whole thing."""
 
2008
        backing = self.get_transport()
 
2009
        rev_id_utf8 = u'\xc8abc'.encode('utf-8')
 
2010
        request = smart_repo.SmartServerRepositoryGatherStats(backing)
 
2011
        tree = self.make_branch_and_memory_tree('.')
 
2012
        tree.lock_write()
 
2013
        tree.add('')
 
2014
        # Let's build a predictable result
 
2015
        tree.commit('a commit', timestamp=123456.2, timezone=3600,
 
2016
                    committer='foo')
 
2017
        tree.commit('a commit', timestamp=654321.4, timezone=0,
 
2018
                    committer='bar', rev_id=rev_id_utf8)
 
2019
        tree.unlock()
 
2020
        stats = tree.branch.repository.gather_stats()
 
2021
 
 
2022
        expected_body = ('committers: 2\n'
 
2023
                         'firstrev: 123456.200 3600\n'
 
2024
                         'latestrev: 654321.400 0\n'
 
2025
                         'revisions: 2\n')
 
2026
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
 
2027
                         request.execute('',
 
2028
                                         rev_id_utf8, 'yes'))
 
2029
 
 
2030
    def test_unknown_revid(self):
 
2031
        """An unknown revision id causes a 'nosuchrevision' error."""
 
2032
        backing = self.get_transport()
 
2033
        request = smart_repo.SmartServerRepositoryGatherStats(backing)
 
2034
        repository = self.make_repository('.')
 
2035
        expected_body = 'revisions: 0\n'
 
2036
        self.assertEqual(
 
2037
            smart_req.FailedSmartServerResponse(
 
2038
                ('nosuchrevision', 'mia'), None),
 
2039
            request.execute('', 'mia', 'yes'))
 
2040
 
 
2041
 
 
2042
class TestSmartServerRepositoryIsShared(tests.TestCaseWithMemoryTransport):
 
2043
 
 
2044
    def test_is_shared(self):
 
2045
        """For a shared repository, ('yes', ) is returned."""
 
2046
        backing = self.get_transport()
 
2047
        request = smart_repo.SmartServerRepositoryIsShared(backing)
 
2048
        self.make_repository('.', shared=True)
 
2049
        self.assertEqual(smart_req.SmartServerResponse(('yes', )),
 
2050
            request.execute('', ))
 
2051
 
 
2052
    def test_is_not_shared(self):
 
2053
        """For a shared repository, ('no', ) is returned."""
 
2054
        backing = self.get_transport()
 
2055
        request = smart_repo.SmartServerRepositoryIsShared(backing)
 
2056
        self.make_repository('.', shared=False)
 
2057
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
 
2058
            request.execute('', ))
 
2059
 
 
2060
 
 
2061
class TestSmartServerRepositoryGetRevisionSignatureText(
 
2062
        tests.TestCaseWithMemoryTransport):
 
2063
 
 
2064
    def test_get_signature(self):
 
2065
        backing = self.get_transport()
 
2066
        request = smart_repo.SmartServerRepositoryGetRevisionSignatureText(
 
2067
            backing)
 
2068
        bb = self.make_branch_builder('.')
 
2069
        bb.build_commit(rev_id='A')
 
2070
        repo = bb.get_branch().repository
 
2071
        strategy = gpg.LoopbackGPGStrategy(None)
 
2072
        self.addCleanup(repo.lock_write().unlock)
 
2073
        repo.start_write_group()
 
2074
        repo.sign_revision('A', strategy)
 
2075
        repo.commit_write_group()
 
2076
        expected_body = (
 
2077
            '-----BEGIN PSEUDO-SIGNED CONTENT-----\n' +
 
2078
            Testament.from_revision(repo, 'A').as_short_text() +
 
2079
            '-----END PSEUDO-SIGNED CONTENT-----\n')
 
2080
        self.assertEqual(
 
2081
            smart_req.SmartServerResponse(('ok', ), expected_body),
 
2082
            request.execute('', 'A'))
 
2083
 
 
2084
 
 
2085
class TestSmartServerRepositoryMakeWorkingTrees(
 
2086
        tests.TestCaseWithMemoryTransport):
 
2087
 
 
2088
    def test_make_working_trees(self):
 
2089
        """For a repository with working trees, ('yes', ) is returned."""
 
2090
        backing = self.get_transport()
 
2091
        request = smart_repo.SmartServerRepositoryMakeWorkingTrees(backing)
 
2092
        r = self.make_repository('.')
 
2093
        r.set_make_working_trees(True)
 
2094
        self.assertEqual(smart_req.SmartServerResponse(('yes', )),
 
2095
            request.execute('', ))
 
2096
 
 
2097
    def test_is_not_shared(self):
 
2098
        """For a repository with working trees, ('no', ) is returned."""
 
2099
        backing = self.get_transport()
 
2100
        request = smart_repo.SmartServerRepositoryMakeWorkingTrees(backing)
 
2101
        r = self.make_repository('.')
 
2102
        r.set_make_working_trees(False)
 
2103
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
 
2104
            request.execute('', ))
 
2105
 
 
2106
 
 
2107
class TestSmartServerRepositoryLockWrite(tests.TestCaseWithMemoryTransport):
 
2108
 
 
2109
    def test_lock_write_on_unlocked_repo(self):
 
2110
        backing = self.get_transport()
 
2111
        request = smart_repo.SmartServerRepositoryLockWrite(backing)
 
2112
        repository = self.make_repository('.', format='knit')
 
2113
        response = request.execute('')
 
2114
        nonce = repository.control_files._lock.peek().get('nonce')
 
2115
        self.assertEqual(smart_req.SmartServerResponse(('ok', nonce)), response)
 
2116
        # The repository is now locked.  Verify that with a new repository
 
2117
        # object.
 
2118
        new_repo = repository.controldir.open_repository()
 
2119
        self.assertRaises(errors.LockContention, new_repo.lock_write)
 
2120
        # Cleanup
 
2121
        request = smart_repo.SmartServerRepositoryUnlock(backing)
 
2122
        response = request.execute('', nonce)
 
2123
 
 
2124
    def test_lock_write_on_locked_repo(self):
 
2125
        backing = self.get_transport()
 
2126
        request = smart_repo.SmartServerRepositoryLockWrite(backing)
 
2127
        repository = self.make_repository('.', format='knit')
 
2128
        repo_token = repository.lock_write().repository_token
 
2129
        repository.leave_lock_in_place()
 
2130
        repository.unlock()
 
2131
        response = request.execute('')
 
2132
        self.assertEqual(
 
2133
            smart_req.SmartServerResponse(('LockContention',)), response)
 
2134
        # Cleanup
 
2135
        repository.lock_write(repo_token)
 
2136
        repository.dont_leave_lock_in_place()
 
2137
        repository.unlock()
 
2138
 
 
2139
    def test_lock_write_on_readonly_transport(self):
 
2140
        backing = self.get_readonly_transport()
 
2141
        request = smart_repo.SmartServerRepositoryLockWrite(backing)
 
2142
        repository = self.make_repository('.', format='knit')
 
2143
        response = request.execute('')
 
2144
        self.assertFalse(response.is_successful())
 
2145
        self.assertEqual('LockFailed', response.args[0])
 
2146
 
 
2147
 
 
2148
class TestInsertStreamBase(tests.TestCaseWithMemoryTransport):
 
2149
 
 
2150
    def make_empty_byte_stream(self, repo):
 
2151
        byte_stream = smart_repo._stream_to_byte_stream([], repo._format)
 
2152
        return ''.join(byte_stream)
 
2153
 
 
2154
 
 
2155
class TestSmartServerRepositoryInsertStream(TestInsertStreamBase):
 
2156
 
 
2157
    def test_insert_stream_empty(self):
 
2158
        backing = self.get_transport()
 
2159
        request = smart_repo.SmartServerRepositoryInsertStream(backing)
 
2160
        repository = self.make_repository('.')
 
2161
        response = request.execute('', '')
 
2162
        self.assertEqual(None, response)
 
2163
        response = request.do_chunk(self.make_empty_byte_stream(repository))
 
2164
        self.assertEqual(None, response)
 
2165
        response = request.do_end()
 
2166
        self.assertEqual(smart_req.SmartServerResponse(('ok', )), response)
 
2167
 
 
2168
 
 
2169
class TestSmartServerRepositoryInsertStreamLocked(TestInsertStreamBase):
 
2170
 
 
2171
    def test_insert_stream_empty(self):
 
2172
        backing = self.get_transport()
 
2173
        request = smart_repo.SmartServerRepositoryInsertStreamLocked(
 
2174
            backing)
 
2175
        repository = self.make_repository('.', format='knit')
 
2176
        lock_token = repository.lock_write().repository_token
 
2177
        response = request.execute('', '', lock_token)
 
2178
        self.assertEqual(None, response)
 
2179
        response = request.do_chunk(self.make_empty_byte_stream(repository))
 
2180
        self.assertEqual(None, response)
 
2181
        response = request.do_end()
 
2182
        self.assertEqual(smart_req.SmartServerResponse(('ok', )), response)
 
2183
        repository.unlock()
 
2184
 
 
2185
    def test_insert_stream_with_wrong_lock_token(self):
 
2186
        backing = self.get_transport()
 
2187
        request = smart_repo.SmartServerRepositoryInsertStreamLocked(
 
2188
            backing)
 
2189
        repository = self.make_repository('.', format='knit')
 
2190
        lock_token = repository.lock_write().repository_token
 
2191
        self.assertRaises(
 
2192
            errors.TokenMismatch, request.execute, '', '', 'wrong-token')
 
2193
        repository.unlock()
 
2194
 
 
2195
 
 
2196
class TestSmartServerRepositoryUnlock(tests.TestCaseWithMemoryTransport):
 
2197
 
 
2198
    def test_unlock_on_locked_repo(self):
 
2199
        backing = self.get_transport()
 
2200
        request = smart_repo.SmartServerRepositoryUnlock(backing)
 
2201
        repository = self.make_repository('.', format='knit')
 
2202
        token = repository.lock_write().repository_token
 
2203
        repository.leave_lock_in_place()
 
2204
        repository.unlock()
 
2205
        response = request.execute('', token)
 
2206
        self.assertEqual(
 
2207
            smart_req.SmartServerResponse(('ok',)), response)
 
2208
        # The repository is now unlocked.  Verify that with a new repository
 
2209
        # object.
 
2210
        new_repo = repository.controldir.open_repository()
 
2211
        new_repo.lock_write()
 
2212
        new_repo.unlock()
 
2213
 
 
2214
    def test_unlock_on_unlocked_repo(self):
 
2215
        backing = self.get_transport()
 
2216
        request = smart_repo.SmartServerRepositoryUnlock(backing)
 
2217
        repository = self.make_repository('.', format='knit')
 
2218
        response = request.execute('', 'some token')
 
2219
        self.assertEqual(
 
2220
            smart_req.SmartServerResponse(('TokenMismatch',)), response)
 
2221
 
 
2222
 
 
2223
class TestSmartServerRepositoryGetPhysicalLockStatus(
 
2224
    tests.TestCaseWithTransport):
 
2225
 
 
2226
    def test_with_write_lock(self):
 
2227
        backing = self.get_transport()
 
2228
        repo = self.make_repository('.')
 
2229
        self.addCleanup(repo.lock_write().unlock)
 
2230
        # lock_write() doesn't necessarily actually take a physical
 
2231
        # lock out.
 
2232
        if repo.get_physical_lock_status():
 
2233
            expected = 'yes'
 
2234
        else:
 
2235
            expected = 'no'
 
2236
        request_class = smart_repo.SmartServerRepositoryGetPhysicalLockStatus
 
2237
        request = request_class(backing)
 
2238
        self.assertEqual(smart_req.SuccessfulSmartServerResponse((expected,)),
 
2239
            request.execute('', ))
 
2240
 
 
2241
    def test_without_write_lock(self):
 
2242
        backing = self.get_transport()
 
2243
        repo = self.make_repository('.')
 
2244
        self.assertEqual(False, repo.get_physical_lock_status())
 
2245
        request_class = smart_repo.SmartServerRepositoryGetPhysicalLockStatus
 
2246
        request = request_class(backing)
 
2247
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(('no',)),
 
2248
            request.execute('', ))
 
2249
 
 
2250
 
 
2251
class TestSmartServerRepositoryReconcile(tests.TestCaseWithTransport):
 
2252
 
 
2253
    def test_reconcile(self):
 
2254
        backing = self.get_transport()
 
2255
        repo = self.make_repository('.')
 
2256
        token = repo.lock_write().repository_token
 
2257
        self.addCleanup(repo.unlock)
 
2258
        request_class = smart_repo.SmartServerRepositoryReconcile
 
2259
        request = request_class(backing)
 
2260
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
 
2261
            ('ok', ),
 
2262
             'garbage_inventories: 0\n'
 
2263
             'inconsistent_parents: 0\n'),
 
2264
            request.execute('', token))
 
2265
 
 
2266
 
 
2267
class TestSmartServerIsReadonly(tests.TestCaseWithMemoryTransport):
 
2268
 
 
2269
    def test_is_readonly_no(self):
 
2270
        backing = self.get_transport()
 
2271
        request = smart_req.SmartServerIsReadonly(backing)
 
2272
        response = request.execute()
 
2273
        self.assertEqual(
 
2274
            smart_req.SmartServerResponse(('no',)), response)
 
2275
 
 
2276
    def test_is_readonly_yes(self):
 
2277
        backing = self.get_readonly_transport()
 
2278
        request = smart_req.SmartServerIsReadonly(backing)
 
2279
        response = request.execute()
 
2280
        self.assertEqual(
 
2281
            smart_req.SmartServerResponse(('yes',)), response)
 
2282
 
 
2283
 
 
2284
class TestSmartServerRepositorySetMakeWorkingTrees(
 
2285
    tests.TestCaseWithMemoryTransport):
 
2286
 
 
2287
    def test_set_false(self):
 
2288
        backing = self.get_transport()
 
2289
        repo = self.make_repository('.', shared=True)
 
2290
        repo.set_make_working_trees(True)
 
2291
        request_class = smart_repo.SmartServerRepositorySetMakeWorkingTrees
 
2292
        request = request_class(backing)
 
2293
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
 
2294
            request.execute('', 'False'))
 
2295
        repo = repo.controldir.open_repository()
 
2296
        self.assertFalse(repo.make_working_trees())
 
2297
 
 
2298
    def test_set_true(self):
 
2299
        backing = self.get_transport()
 
2300
        repo = self.make_repository('.', shared=True)
 
2301
        repo.set_make_working_trees(False)
 
2302
        request_class = smart_repo.SmartServerRepositorySetMakeWorkingTrees
 
2303
        request = request_class(backing)
 
2304
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
 
2305
            request.execute('', 'True'))
 
2306
        repo = repo.controldir.open_repository()
 
2307
        self.assertTrue(repo.make_working_trees())
 
2308
 
 
2309
 
 
2310
class TestSmartServerRepositoryGetSerializerFormat(
 
2311
    tests.TestCaseWithMemoryTransport):
 
2312
 
 
2313
    def test_get_serializer_format(self):
 
2314
        backing = self.get_transport()
 
2315
        repo = self.make_repository('.', format='2a')
 
2316
        request_class = smart_repo.SmartServerRepositoryGetSerializerFormat
 
2317
        request = request_class(backing)
 
2318
        self.assertEqual(
 
2319
            smart_req.SuccessfulSmartServerResponse(('ok', '10')),
 
2320
            request.execute(''))
 
2321
 
 
2322
 
 
2323
class TestSmartServerRepositoryWriteGroup(
 
2324
    tests.TestCaseWithMemoryTransport):
 
2325
 
 
2326
    def test_start_write_group(self):
 
2327
        backing = self.get_transport()
 
2328
        repo = self.make_repository('.')
 
2329
        lock_token = repo.lock_write().repository_token
 
2330
        self.addCleanup(repo.unlock)
 
2331
        request_class = smart_repo.SmartServerRepositoryStartWriteGroup
 
2332
        request = request_class(backing)
 
2333
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok', [])),
 
2334
            request.execute('', lock_token))
 
2335
 
 
2336
    def test_start_write_group_unsuspendable(self):
 
2337
        backing = self.get_transport()
 
2338
        repo = self.make_repository('.', format='knit')
 
2339
        lock_token = repo.lock_write().repository_token
 
2340
        self.addCleanup(repo.unlock)
 
2341
        request_class = smart_repo.SmartServerRepositoryStartWriteGroup
 
2342
        request = request_class(backing)
 
2343
        self.assertEqual(
 
2344
            smart_req.FailedSmartServerResponse(('UnsuspendableWriteGroup',)),
 
2345
            request.execute('', lock_token))
 
2346
 
 
2347
    def test_commit_write_group(self):
 
2348
        backing = self.get_transport()
 
2349
        repo = self.make_repository('.')
 
2350
        lock_token = repo.lock_write().repository_token
 
2351
        self.addCleanup(repo.unlock)
 
2352
        repo.start_write_group()
 
2353
        tokens = repo.suspend_write_group()
 
2354
        request_class = smart_repo.SmartServerRepositoryCommitWriteGroup
 
2355
        request = request_class(backing)
 
2356
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
 
2357
            request.execute('', lock_token, tokens))
 
2358
 
 
2359
    def test_abort_write_group(self):
 
2360
        backing = self.get_transport()
 
2361
        repo = self.make_repository('.')
 
2362
        lock_token = repo.lock_write().repository_token
 
2363
        repo.start_write_group()
 
2364
        tokens = repo.suspend_write_group()
 
2365
        self.addCleanup(repo.unlock)
 
2366
        request_class = smart_repo.SmartServerRepositoryAbortWriteGroup
 
2367
        request = request_class(backing)
 
2368
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
 
2369
            request.execute('', lock_token, tokens))
 
2370
 
 
2371
    def test_check_write_group(self):
 
2372
        backing = self.get_transport()
 
2373
        repo = self.make_repository('.')
 
2374
        lock_token = repo.lock_write().repository_token
 
2375
        repo.start_write_group()
 
2376
        tokens = repo.suspend_write_group()
 
2377
        self.addCleanup(repo.unlock)
 
2378
        request_class = smart_repo.SmartServerRepositoryCheckWriteGroup
 
2379
        request = request_class(backing)
 
2380
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
 
2381
            request.execute('', lock_token, tokens))
 
2382
 
 
2383
    def test_check_write_group_invalid(self):
 
2384
        backing = self.get_transport()
 
2385
        repo = self.make_repository('.')
 
2386
        lock_token = repo.lock_write().repository_token
 
2387
        self.addCleanup(repo.unlock)
 
2388
        request_class = smart_repo.SmartServerRepositoryCheckWriteGroup
 
2389
        request = request_class(backing)
 
2390
        self.assertEqual(smart_req.FailedSmartServerResponse(
 
2391
            ('UnresumableWriteGroup', ['random'],
 
2392
                'Malformed write group token')),
 
2393
            request.execute('', lock_token, ["random"]))
 
2394
 
 
2395
 
 
2396
class TestSmartServerPackRepositoryAutopack(tests.TestCaseWithTransport):
 
2397
 
 
2398
    def make_repo_needing_autopacking(self, path='.'):
 
2399
        # Make a repo in need of autopacking.
 
2400
        tree = self.make_branch_and_tree('.', format='pack-0.92')
 
2401
        repo = tree.branch.repository
 
2402
        # monkey-patch the pack collection to disable autopacking
 
2403
        repo._pack_collection._max_pack_count = lambda count: count
 
2404
        for x in range(10):
 
2405
            tree.commit('commit %s' % x)
 
2406
        self.assertEqual(10, len(repo._pack_collection.names()))
 
2407
        del repo._pack_collection._max_pack_count
 
2408
        return repo
 
2409
 
 
2410
    def test_autopack_needed(self):
 
2411
        repo = self.make_repo_needing_autopacking()
 
2412
        repo.lock_write()
 
2413
        self.addCleanup(repo.unlock)
 
2414
        backing = self.get_transport()
 
2415
        request = smart_packrepo.SmartServerPackRepositoryAutopack(
 
2416
            backing)
 
2417
        response = request.execute('')
 
2418
        self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
 
2419
        repo._pack_collection.reload_pack_names()
 
2420
        self.assertEqual(1, len(repo._pack_collection.names()))
 
2421
 
 
2422
    def test_autopack_not_needed(self):
 
2423
        tree = self.make_branch_and_tree('.', format='pack-0.92')
 
2424
        repo = tree.branch.repository
 
2425
        repo.lock_write()
 
2426
        self.addCleanup(repo.unlock)
 
2427
        for x in range(9):
 
2428
            tree.commit('commit %s' % x)
 
2429
        backing = self.get_transport()
 
2430
        request = smart_packrepo.SmartServerPackRepositoryAutopack(
 
2431
            backing)
 
2432
        response = request.execute('')
 
2433
        self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
 
2434
        repo._pack_collection.reload_pack_names()
 
2435
        self.assertEqual(9, len(repo._pack_collection.names()))
 
2436
 
 
2437
    def test_autopack_on_nonpack_format(self):
 
2438
        """A request to autopack a non-pack repo is a no-op."""
 
2439
        repo = self.make_repository('.', format='knit')
 
2440
        backing = self.get_transport()
 
2441
        request = smart_packrepo.SmartServerPackRepositoryAutopack(
 
2442
            backing)
 
2443
        response = request.execute('')
 
2444
        self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
 
2445
 
 
2446
 
 
2447
class TestSmartServerVfsGet(tests.TestCaseWithMemoryTransport):
 
2448
 
 
2449
    def test_unicode_path(self):
 
2450
        """VFS requests expect unicode paths to be escaped."""
 
2451
        filename = u'foo\N{INTERROBANG}'
 
2452
        filename_escaped = urlutils.escape(filename)
 
2453
        backing = self.get_transport()
 
2454
        request = vfs.GetRequest(backing)
 
2455
        backing.put_bytes_non_atomic(filename_escaped, 'contents')
 
2456
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'contents'),
 
2457
            request.execute(filename_escaped))
 
2458
 
 
2459
 
 
2460
class TestHandlers(tests.TestCase):
 
2461
    """Tests for the request.request_handlers object."""
 
2462
 
 
2463
    def test_all_registrations_exist(self):
 
2464
        """All registered request_handlers can be found."""
 
2465
        # If there's a typo in a register_lazy call, this loop will fail with
 
2466
        # an AttributeError.
 
2467
        for key in smart_req.request_handlers.keys():
 
2468
            try:
 
2469
                item = smart_req.request_handlers.get(key)
 
2470
            except AttributeError as e:
 
2471
                raise AttributeError('failed to get %s: %s' % (key, e))
 
2472
 
 
2473
    def assertHandlerEqual(self, verb, handler):
 
2474
        self.assertEqual(smart_req.request_handlers.get(verb), handler)
 
2475
 
 
2476
    def test_registered_methods(self):
 
2477
        """Test that known methods are registered to the correct object."""
 
2478
        self.assertHandlerEqual('Branch.break_lock',
 
2479
            smart_branch.SmartServerBranchBreakLock)
 
2480
        self.assertHandlerEqual('Branch.get_config_file',
 
2481
            smart_branch.SmartServerBranchGetConfigFile)
 
2482
        self.assertHandlerEqual('Branch.put_config_file',
 
2483
            smart_branch.SmartServerBranchPutConfigFile)
 
2484
        self.assertHandlerEqual('Branch.get_parent',
 
2485
            smart_branch.SmartServerBranchGetParent)
 
2486
        self.assertHandlerEqual('Branch.get_physical_lock_status',
 
2487
            smart_branch.SmartServerBranchRequestGetPhysicalLockStatus)
 
2488
        self.assertHandlerEqual('Branch.get_tags_bytes',
 
2489
            smart_branch.SmartServerBranchGetTagsBytes)
 
2490
        self.assertHandlerEqual('Branch.lock_write',
 
2491
            smart_branch.SmartServerBranchRequestLockWrite)
 
2492
        self.assertHandlerEqual('Branch.last_revision_info',
 
2493
            smart_branch.SmartServerBranchRequestLastRevisionInfo)
 
2494
        self.assertHandlerEqual('Branch.revision_history',
 
2495
            smart_branch.SmartServerRequestRevisionHistory)
 
2496
        self.assertHandlerEqual('Branch.revision_id_to_revno',
 
2497
            smart_branch.SmartServerBranchRequestRevisionIdToRevno)
 
2498
        self.assertHandlerEqual('Branch.set_config_option',
 
2499
            smart_branch.SmartServerBranchRequestSetConfigOption)
 
2500
        self.assertHandlerEqual('Branch.set_last_revision',
 
2501
            smart_branch.SmartServerBranchRequestSetLastRevision)
 
2502
        self.assertHandlerEqual('Branch.set_last_revision_info',
 
2503
            smart_branch.SmartServerBranchRequestSetLastRevisionInfo)
 
2504
        self.assertHandlerEqual('Branch.set_last_revision_ex',
 
2505
            smart_branch.SmartServerBranchRequestSetLastRevisionEx)
 
2506
        self.assertHandlerEqual('Branch.set_parent_location',
 
2507
            smart_branch.SmartServerBranchRequestSetParentLocation)
 
2508
        self.assertHandlerEqual('Branch.unlock',
 
2509
            smart_branch.SmartServerBranchRequestUnlock)
 
2510
        self.assertHandlerEqual('BzrDir.destroy_branch',
 
2511
            smart_dir.SmartServerBzrDirRequestDestroyBranch)
 
2512
        self.assertHandlerEqual('BzrDir.find_repository',
 
2513
            smart_dir.SmartServerRequestFindRepositoryV1)
 
2514
        self.assertHandlerEqual('BzrDir.find_repositoryV2',
 
2515
            smart_dir.SmartServerRequestFindRepositoryV2)
 
2516
        self.assertHandlerEqual('BzrDirFormat.initialize',
 
2517
            smart_dir.SmartServerRequestInitializeBzrDir)
 
2518
        self.assertHandlerEqual('BzrDirFormat.initialize_ex_1.16',
 
2519
            smart_dir.SmartServerRequestBzrDirInitializeEx)
 
2520
        self.assertHandlerEqual('BzrDir.checkout_metadir',
 
2521
            smart_dir.SmartServerBzrDirRequestCheckoutMetaDir)
 
2522
        self.assertHandlerEqual('BzrDir.cloning_metadir',
 
2523
            smart_dir.SmartServerBzrDirRequestCloningMetaDir)
 
2524
        self.assertHandlerEqual('BzrDir.get_branches',
 
2525
            smart_dir.SmartServerBzrDirRequestGetBranches)
 
2526
        self.assertHandlerEqual('BzrDir.get_config_file',
 
2527
            smart_dir.SmartServerBzrDirRequestConfigFile)
 
2528
        self.assertHandlerEqual('BzrDir.open_branch',
 
2529
            smart_dir.SmartServerRequestOpenBranch)
 
2530
        self.assertHandlerEqual('BzrDir.open_branchV2',
 
2531
            smart_dir.SmartServerRequestOpenBranchV2)
 
2532
        self.assertHandlerEqual('BzrDir.open_branchV3',
 
2533
            smart_dir.SmartServerRequestOpenBranchV3)
 
2534
        self.assertHandlerEqual('PackRepository.autopack',
 
2535
            smart_packrepo.SmartServerPackRepositoryAutopack)
 
2536
        self.assertHandlerEqual('Repository.add_signature_text',
 
2537
            smart_repo.SmartServerRepositoryAddSignatureText)
 
2538
        self.assertHandlerEqual('Repository.all_revision_ids',
 
2539
            smart_repo.SmartServerRepositoryAllRevisionIds)
 
2540
        self.assertHandlerEqual('Repository.break_lock',
 
2541
            smart_repo.SmartServerRepositoryBreakLock)
 
2542
        self.assertHandlerEqual('Repository.gather_stats',
 
2543
            smart_repo.SmartServerRepositoryGatherStats)
 
2544
        self.assertHandlerEqual('Repository.get_parent_map',
 
2545
            smart_repo.SmartServerRepositoryGetParentMap)
 
2546
        self.assertHandlerEqual('Repository.get_physical_lock_status',
 
2547
            smart_repo.SmartServerRepositoryGetPhysicalLockStatus)
 
2548
        self.assertHandlerEqual('Repository.get_rev_id_for_revno',
 
2549
            smart_repo.SmartServerRepositoryGetRevIdForRevno)
 
2550
        self.assertHandlerEqual('Repository.get_revision_graph',
 
2551
            smart_repo.SmartServerRepositoryGetRevisionGraph)
 
2552
        self.assertHandlerEqual('Repository.get_revision_signature_text',
 
2553
            smart_repo.SmartServerRepositoryGetRevisionSignatureText)
 
2554
        self.assertHandlerEqual('Repository.get_stream',
 
2555
            smart_repo.SmartServerRepositoryGetStream)
 
2556
        self.assertHandlerEqual('Repository.get_stream_1.19',
 
2557
            smart_repo.SmartServerRepositoryGetStream_1_19)
 
2558
        self.assertHandlerEqual('Repository.iter_revisions',
 
2559
            smart_repo.SmartServerRepositoryIterRevisions)
 
2560
        self.assertHandlerEqual('Repository.has_revision',
 
2561
            smart_repo.SmartServerRequestHasRevision)
 
2562
        self.assertHandlerEqual('Repository.insert_stream',
 
2563
            smart_repo.SmartServerRepositoryInsertStream)
 
2564
        self.assertHandlerEqual('Repository.insert_stream_locked',
 
2565
            smart_repo.SmartServerRepositoryInsertStreamLocked)
 
2566
        self.assertHandlerEqual('Repository.is_shared',
 
2567
            smart_repo.SmartServerRepositoryIsShared)
 
2568
        self.assertHandlerEqual('Repository.iter_files_bytes',
 
2569
            smart_repo.SmartServerRepositoryIterFilesBytes)
 
2570
        self.assertHandlerEqual('Repository.lock_write',
 
2571
            smart_repo.SmartServerRepositoryLockWrite)
 
2572
        self.assertHandlerEqual('Repository.make_working_trees',
 
2573
            smart_repo.SmartServerRepositoryMakeWorkingTrees)
 
2574
        self.assertHandlerEqual('Repository.pack',
 
2575
            smart_repo.SmartServerRepositoryPack)
 
2576
        self.assertHandlerEqual('Repository.reconcile',
 
2577
            smart_repo.SmartServerRepositoryReconcile)
 
2578
        self.assertHandlerEqual('Repository.tarball',
 
2579
            smart_repo.SmartServerRepositoryTarball)
 
2580
        self.assertHandlerEqual('Repository.unlock',
 
2581
            smart_repo.SmartServerRepositoryUnlock)
 
2582
        self.assertHandlerEqual('Repository.start_write_group',
 
2583
            smart_repo.SmartServerRepositoryStartWriteGroup)
 
2584
        self.assertHandlerEqual('Repository.check_write_group',
 
2585
            smart_repo.SmartServerRepositoryCheckWriteGroup)
 
2586
        self.assertHandlerEqual('Repository.commit_write_group',
 
2587
            smart_repo.SmartServerRepositoryCommitWriteGroup)
 
2588
        self.assertHandlerEqual('Repository.abort_write_group',
 
2589
            smart_repo.SmartServerRepositoryAbortWriteGroup)
 
2590
        self.assertHandlerEqual('VersionedFileRepository.get_serializer_format',
 
2591
            smart_repo.SmartServerRepositoryGetSerializerFormat)
 
2592
        self.assertHandlerEqual('VersionedFileRepository.get_inventories',
 
2593
            smart_repo.SmartServerRepositoryGetInventories)
 
2594
        self.assertHandlerEqual('Transport.is_readonly',
 
2595
            smart_req.SmartServerIsReadonly)
 
2596
 
 
2597
 
 
2598
class SmartTCPServerHookTests(tests.TestCaseWithMemoryTransport):
 
2599
    """Tests for SmartTCPServer hooks."""
 
2600
 
 
2601
    def setUp(self):
 
2602
        super(SmartTCPServerHookTests, self).setUp()
 
2603
        self.server = server.SmartTCPServer(self.get_transport())
 
2604
 
 
2605
    def test_run_server_started_hooks(self):
 
2606
        """Test the server started hooks get fired properly."""
 
2607
        started_calls = []
 
2608
        server.SmartTCPServer.hooks.install_named_hook('server_started',
 
2609
            lambda backing_urls, url: started_calls.append((backing_urls, url)),
 
2610
            None)
 
2611
        started_ex_calls = []
 
2612
        server.SmartTCPServer.hooks.install_named_hook('server_started_ex',
 
2613
            lambda backing_urls, url: started_ex_calls.append((backing_urls, url)),
 
2614
            None)
 
2615
        self.server._sockname = ('example.com', 42)
 
2616
        self.server.run_server_started_hooks()
 
2617
        self.assertEqual(started_calls,
 
2618
            [([self.get_transport().base], 'bzr://example.com:42/')])
 
2619
        self.assertEqual(started_ex_calls,
 
2620
            [([self.get_transport().base], self.server)])
 
2621
 
 
2622
    def test_run_server_started_hooks_ipv6(self):
 
2623
        """Test that socknames can contain 4-tuples."""
 
2624
        self.server._sockname = ('::', 42, 0, 0)
 
2625
        started_calls = []
 
2626
        server.SmartTCPServer.hooks.install_named_hook('server_started',
 
2627
            lambda backing_urls, url: started_calls.append((backing_urls, url)),
 
2628
            None)
 
2629
        self.server.run_server_started_hooks()
 
2630
        self.assertEqual(started_calls,
 
2631
                [([self.get_transport().base], 'bzr://:::42/')])
 
2632
 
 
2633
    def test_run_server_stopped_hooks(self):
 
2634
        """Test the server stopped hooks."""
 
2635
        self.server._sockname = ('example.com', 42)
 
2636
        stopped_calls = []
 
2637
        server.SmartTCPServer.hooks.install_named_hook('server_stopped',
 
2638
            lambda backing_urls, url: stopped_calls.append((backing_urls, url)),
 
2639
            None)
 
2640
        self.server.run_server_stopped_hooks()
 
2641
        self.assertEqual(stopped_calls,
 
2642
            [([self.get_transport().base], 'bzr://example.com:42/')])
 
2643
 
 
2644
 
 
2645
class TestSmartServerRepositoryPack(tests.TestCaseWithMemoryTransport):
 
2646
 
 
2647
    def test_pack(self):
 
2648
        backing = self.get_transport()
 
2649
        request = smart_repo.SmartServerRepositoryPack(backing)
 
2650
        tree = self.make_branch_and_memory_tree('.')
 
2651
        repo_token = tree.branch.repository.lock_write().repository_token
 
2652
 
 
2653
        self.assertIs(None, request.execute('', repo_token, False))
 
2654
 
 
2655
        self.assertEqual(
 
2656
            smart_req.SuccessfulSmartServerResponse(('ok', ), ),
 
2657
            request.do_body(''))
 
2658
 
 
2659
 
 
2660
class TestSmartServerRepositoryGetInventories(tests.TestCaseWithTransport):
 
2661
 
 
2662
    def _get_serialized_inventory_delta(self, repository, base_revid, revid):
 
2663
        base_inv = repository.revision_tree(base_revid).root_inventory
 
2664
        inv = repository.revision_tree(revid).root_inventory
 
2665
        inv_delta = inv._make_delta(base_inv)
 
2666
        serializer = inventory_delta.InventoryDeltaSerializer(True, False)
 
2667
        return "".join(serializer.delta_to_lines(base_revid, revid, inv_delta))
 
2668
 
 
2669
    def test_single(self):
 
2670
        backing = self.get_transport()
 
2671
        request = smart_repo.SmartServerRepositoryGetInventories(backing)
 
2672
        t = self.make_branch_and_tree('.', format='2a')
 
2673
        self.addCleanup(t.lock_write().unlock)
 
2674
        self.build_tree_contents([("file", "somecontents")])
 
2675
        t.add(["file"], ["thefileid"])
 
2676
        t.commit(rev_id='somerev', message="add file")
 
2677
        self.assertIs(None, request.execute('', 'unordered'))
 
2678
        response = request.do_body("somerev\n")
 
2679
        self.assertTrue(response.is_successful())
 
2680
        self.assertEqual(response.args, ("ok", ))
 
2681
        stream = [('inventory-deltas', [
 
2682
            versionedfile.FulltextContentFactory('somerev', None, None,
 
2683
                self._get_serialized_inventory_delta(
 
2684
                    t.branch.repository, 'null:', 'somerev'))])]
 
2685
        fmt = controldir.format_registry.get('2a')().repository_format
 
2686
        self.assertEqual(
 
2687
            "".join(response.body_stream),
 
2688
            "".join(smart_repo._stream_to_byte_stream(stream, fmt)))
 
2689
 
 
2690
    def test_empty(self):
 
2691
        backing = self.get_transport()
 
2692
        request = smart_repo.SmartServerRepositoryGetInventories(backing)
 
2693
        t = self.make_branch_and_tree('.', format='2a')
 
2694
        self.addCleanup(t.lock_write().unlock)
 
2695
        self.build_tree_contents([("file", "somecontents")])
 
2696
        t.add(["file"], ["thefileid"])
 
2697
        t.commit(rev_id='somerev', message="add file")
 
2698
        self.assertIs(None, request.execute('', 'unordered'))
 
2699
        response = request.do_body("")
 
2700
        self.assertTrue(response.is_successful())
 
2701
        self.assertEqual(response.args, ("ok", ))
 
2702
        self.assertEqual("".join(response.body_stream),
 
2703
            "Bazaar pack format 1 (introduced in 0.18)\nB54\n\nBazaar repository format 2a (needs bzr 1.16 or later)\nE")