~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_smart.py

  • Committer: Martin Pool
  • Date: 2005-08-24 08:59:32 UTC
  • Revision ID: mbp@sourcefrog.net-20050824085932-c61f1f1f1c930e13
- Add a simple UIFactory 

  The idea of this is to let a client of bzrlib set some 
  policy about how output is displayed.

  In this revision all that's done is that progress bars
  are constructed by a policy established by the application
  rather than being randomly constructed in the library 
  or passed down the calls.  This avoids progress bars
  popping up while running the test suite and cleans up
  some code.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 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
 
from cStringIO import StringIO
29
 
import tarfile
30
 
 
31
 
from bzrlib import (
32
 
    bencode,
33
 
    branch as _mod_branch,
34
 
    bzrdir,
35
 
    errors,
36
 
    pack,
37
 
    tests,
38
 
    transport,
39
 
    urlutils,
40
 
    versionedfile,
41
 
    )
42
 
from bzrlib.smart import (
43
 
    branch as smart_branch,
44
 
    bzrdir as smart_dir,
45
 
    repository as smart_repo,
46
 
    packrepository as smart_packrepo,
47
 
    request as smart_req,
48
 
    server,
49
 
    vfs,
50
 
    )
51
 
from bzrlib.tests import test_server
52
 
from bzrlib.transport import (
53
 
    chroot,
54
 
    memory,
55
 
    )
56
 
 
57
 
 
58
 
def load_tests(standard_tests, module, loader):
59
 
    """Multiply tests version and protocol consistency."""
60
 
    # FindRepository tests.
61
 
    scenarios = [
62
 
        ("find_repository", {
63
 
            "_request_class": smart_dir.SmartServerRequestFindRepositoryV1}),
64
 
        ("find_repositoryV2", {
65
 
            "_request_class": smart_dir.SmartServerRequestFindRepositoryV2}),
66
 
        ("find_repositoryV3", {
67
 
            "_request_class": smart_dir.SmartServerRequestFindRepositoryV3}),
68
 
        ]
69
 
    to_adapt, result = tests.split_suite_by_re(standard_tests,
70
 
        "TestSmartServerRequestFindRepository")
71
 
    v2_only, v1_and_2 = tests.split_suite_by_re(to_adapt,
72
 
        "_v2")
73
 
    tests.multiply_tests(v1_and_2, scenarios, result)
74
 
    # The first scenario is only applicable to v1 protocols, it is deleted
75
 
    # since.
76
 
    tests.multiply_tests(v2_only, scenarios[1:], result)
77
 
    return result
78
 
 
79
 
 
80
 
class TestCaseWithChrootedTransport(tests.TestCaseWithTransport):
81
 
 
82
 
    def setUp(self):
83
 
        self.vfs_transport_factory = memory.MemoryServer
84
 
        tests.TestCaseWithTransport.setUp(self)
85
 
        self._chroot_server = None
86
 
 
87
 
    def get_transport(self, relpath=None):
88
 
        if self._chroot_server is None:
89
 
            backing_transport = tests.TestCaseWithTransport.get_transport(self)
90
 
            self._chroot_server = chroot.ChrootServer(backing_transport)
91
 
            self.start_server(self._chroot_server)
92
 
        t = transport.get_transport(self._chroot_server.get_url())
93
 
        if relpath is not None:
94
 
            t = t.clone(relpath)
95
 
        return t
96
 
 
97
 
 
98
 
class TestCaseWithSmartMedium(tests.TestCaseWithMemoryTransport):
99
 
 
100
 
    def setUp(self):
101
 
        super(TestCaseWithSmartMedium, self).setUp()
102
 
        # We're allowed to set  the transport class here, so that we don't use
103
 
        # the default or a parameterized class, but rather use the
104
 
        # TestCaseWithTransport infrastructure to set up a smart server and
105
 
        # transport.
106
 
        self.transport_server = self.make_transport_server
107
 
 
108
 
    def make_transport_server(self):
109
 
        return test_server.SmartTCPServer_for_testing('-' + self.id())
110
 
 
111
 
    def get_smart_medium(self):
112
 
        """Get a smart medium to use in tests."""
113
 
        return self.get_transport().get_smart_medium()
114
 
 
115
 
 
116
 
class TestByteStreamToStream(tests.TestCase):
117
 
 
118
 
    def test_repeated_substreams_same_kind_are_one_stream(self):
119
 
        # Make a stream - an iterable of bytestrings.
120
 
        stream = [('text', [versionedfile.FulltextContentFactory(('k1',), None,
121
 
            None, 'foo')]),('text', [
122
 
            versionedfile.FulltextContentFactory(('k2',), None, None, 'bar')])]
123
 
        fmt = bzrdir.format_registry.get('pack-0.92')().repository_format
124
 
        bytes = smart_repo._stream_to_byte_stream(stream, fmt)
125
 
        streams = []
126
 
        # Iterate the resulting iterable; checking that we get only one stream
127
 
        # out.
128
 
        fmt, stream = smart_repo._byte_stream_to_stream(bytes)
129
 
        for kind, substream in stream:
130
 
            streams.append((kind, list(substream)))
131
 
        self.assertLength(1, streams)
132
 
        self.assertLength(2, streams[0][1])
133
 
 
134
 
 
135
 
class TestSmartServerResponse(tests.TestCase):
136
 
 
137
 
    def test__eq__(self):
138
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', )),
139
 
            smart_req.SmartServerResponse(('ok', )))
140
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'body'),
141
 
            smart_req.SmartServerResponse(('ok', ), 'body'))
142
 
        self.assertNotEqual(smart_req.SmartServerResponse(('ok', )),
143
 
            smart_req.SmartServerResponse(('notok', )))
144
 
        self.assertNotEqual(smart_req.SmartServerResponse(('ok', ), 'body'),
145
 
            smart_req.SmartServerResponse(('ok', )))
146
 
        self.assertNotEqual(None,
147
 
            smart_req.SmartServerResponse(('ok', )))
148
 
 
149
 
    def test__str__(self):
150
 
        """SmartServerResponses can be stringified."""
151
 
        self.assertEqual(
152
 
            "<SuccessfulSmartServerResponse args=('args',) body='body'>",
153
 
            str(smart_req.SuccessfulSmartServerResponse(('args',), 'body')))
154
 
        self.assertEqual(
155
 
            "<FailedSmartServerResponse args=('args',) body='body'>",
156
 
            str(smart_req.FailedSmartServerResponse(('args',), 'body')))
157
 
 
158
 
 
159
 
class TestSmartServerRequest(tests.TestCaseWithMemoryTransport):
160
 
 
161
 
    def test_translate_client_path(self):
162
 
        transport = self.get_transport()
163
 
        request = smart_req.SmartServerRequest(transport, 'foo/')
164
 
        self.assertEqual('./', request.translate_client_path('foo/'))
165
 
        self.assertRaises(
166
 
            errors.InvalidURLJoin, request.translate_client_path, 'foo/..')
167
 
        self.assertRaises(
168
 
            errors.PathNotChild, request.translate_client_path, '/')
169
 
        self.assertRaises(
170
 
            errors.PathNotChild, request.translate_client_path, 'bar/')
171
 
        self.assertEqual('./baz', request.translate_client_path('foo/baz'))
172
 
        e_acute = u'\N{LATIN SMALL LETTER E WITH ACUTE}'.encode('utf-8')
173
 
        self.assertEqual('./' + urlutils.escape(e_acute),
174
 
                         request.translate_client_path('foo/' + e_acute))
175
 
 
176
 
    def test_translate_client_path_vfs(self):
177
 
        """VfsRequests receive escaped paths rather than raw UTF-8."""
178
 
        transport = self.get_transport()
179
 
        request = vfs.VfsRequest(transport, 'foo/')
180
 
        e_acute = u'\N{LATIN SMALL LETTER E WITH ACUTE}'.encode('utf-8')
181
 
        escaped = urlutils.escape('foo/' + e_acute)
182
 
        self.assertEqual('./' + urlutils.escape(e_acute),
183
 
                         request.translate_client_path(escaped))
184
 
 
185
 
    def test_transport_from_client_path(self):
186
 
        transport = self.get_transport()
187
 
        request = smart_req.SmartServerRequest(transport, 'foo/')
188
 
        self.assertEqual(
189
 
            transport.base,
190
 
            request.transport_from_client_path('foo/').base)
191
 
 
192
 
 
193
 
class TestSmartServerBzrDirRequestCloningMetaDir(
194
 
    tests.TestCaseWithMemoryTransport):
195
 
    """Tests for BzrDir.cloning_metadir."""
196
 
 
197
 
    def test_cloning_metadir(self):
198
 
        """When there is a bzrdir present, the call succeeds."""
199
 
        backing = self.get_transport()
200
 
        dir = self.make_bzrdir('.')
201
 
        local_result = dir.cloning_metadir()
202
 
        request_class = smart_dir.SmartServerBzrDirRequestCloningMetaDir
203
 
        request = request_class(backing)
204
 
        expected = smart_req.SuccessfulSmartServerResponse(
205
 
            (local_result.network_name(),
206
 
            local_result.repository_format.network_name(),
207
 
            ('branch', local_result.get_branch_format().network_name())))
208
 
        self.assertEqual(expected, request.execute('', 'False'))
209
 
 
210
 
    def test_cloning_metadir_reference(self):
211
 
        """The request fails when bzrdir contains a branch reference."""
212
 
        backing = self.get_transport()
213
 
        referenced_branch = self.make_branch('referenced')
214
 
        dir = self.make_bzrdir('.')
215
 
        local_result = dir.cloning_metadir()
216
 
        reference = _mod_branch.BranchReferenceFormat().initialize(
217
 
            dir, target_branch=referenced_branch)
218
 
        reference_url = _mod_branch.BranchReferenceFormat().get_reference(dir)
219
 
        # The server shouldn't try to follow the branch reference, so it's fine
220
 
        # if the referenced branch isn't reachable.
221
 
        backing.rename('referenced', 'moved')
222
 
        request_class = smart_dir.SmartServerBzrDirRequestCloningMetaDir
223
 
        request = request_class(backing)
224
 
        expected = smart_req.FailedSmartServerResponse(('BranchReference',))
225
 
        self.assertEqual(expected, request.execute('', 'False'))
226
 
 
227
 
 
228
 
class TestSmartServerRequestCreateRepository(tests.TestCaseWithMemoryTransport):
229
 
    """Tests for BzrDir.create_repository."""
230
 
 
231
 
    def test_makes_repository(self):
232
 
        """When there is a bzrdir present, the call succeeds."""
233
 
        backing = self.get_transport()
234
 
        self.make_bzrdir('.')
235
 
        request_class = smart_dir.SmartServerRequestCreateRepository
236
 
        request = request_class(backing)
237
 
        reference_bzrdir_format = bzrdir.format_registry.get('pack-0.92')()
238
 
        reference_format = reference_bzrdir_format.repository_format
239
 
        network_name = reference_format.network_name()
240
 
        expected = smart_req.SuccessfulSmartServerResponse(
241
 
            ('ok', 'no', 'no', 'no', network_name))
242
 
        self.assertEqual(expected, request.execute('', network_name, 'True'))
243
 
 
244
 
 
245
 
class TestSmartServerRequestFindRepository(tests.TestCaseWithMemoryTransport):
246
 
    """Tests for BzrDir.find_repository."""
247
 
 
248
 
    def test_no_repository(self):
249
 
        """When there is no repository to be found, ('norepository', ) is returned."""
250
 
        backing = self.get_transport()
251
 
        request = self._request_class(backing)
252
 
        self.make_bzrdir('.')
253
 
        self.assertEqual(smart_req.SmartServerResponse(('norepository', )),
254
 
            request.execute(''))
255
 
 
256
 
    def test_nonshared_repository(self):
257
 
        # nonshared repositorys only allow 'find' to return a handle when the
258
 
        # path the repository is being searched on is the same as that that
259
 
        # the repository is at.
260
 
        backing = self.get_transport()
261
 
        request = self._request_class(backing)
262
 
        result = self._make_repository_and_result()
263
 
        self.assertEqual(result, request.execute(''))
264
 
        self.make_bzrdir('subdir')
265
 
        self.assertEqual(smart_req.SmartServerResponse(('norepository', )),
266
 
            request.execute('subdir'))
267
 
 
268
 
    def _make_repository_and_result(self, shared=False, format=None):
269
 
        """Convenience function to setup a repository.
270
 
 
271
 
        :result: The SmartServerResponse to expect when opening it.
272
 
        """
273
 
        repo = self.make_repository('.', shared=shared, format=format)
274
 
        if repo.supports_rich_root():
275
 
            rich_root = 'yes'
276
 
        else:
277
 
            rich_root = 'no'
278
 
        if repo._format.supports_tree_reference:
279
 
            subtrees = 'yes'
280
 
        else:
281
 
            subtrees = 'no'
282
 
        if repo._format.supports_external_lookups:
283
 
            external = 'yes'
284
 
        else:
285
 
            external = 'no'
286
 
        if (smart_dir.SmartServerRequestFindRepositoryV3 ==
287
 
            self._request_class):
288
 
            return smart_req.SuccessfulSmartServerResponse(
289
 
                ('ok', '', rich_root, subtrees, external,
290
 
                 repo._format.network_name()))
291
 
        elif (smart_dir.SmartServerRequestFindRepositoryV2 ==
292
 
            self._request_class):
293
 
            # All tests so far are on formats, and for non-external
294
 
            # repositories.
295
 
            return smart_req.SuccessfulSmartServerResponse(
296
 
                ('ok', '', rich_root, subtrees, external))
297
 
        else:
298
 
            return smart_req.SuccessfulSmartServerResponse(
299
 
                ('ok', '', rich_root, subtrees))
300
 
 
301
 
    def test_shared_repository(self):
302
 
        """When there is a shared repository, we get 'ok', 'relpath-to-repo'."""
303
 
        backing = self.get_transport()
304
 
        request = self._request_class(backing)
305
 
        result = self._make_repository_and_result(shared=True)
306
 
        self.assertEqual(result, request.execute(''))
307
 
        self.make_bzrdir('subdir')
308
 
        result2 = smart_req.SmartServerResponse(
309
 
            result.args[0:1] + ('..', ) + result.args[2:])
310
 
        self.assertEqual(result2,
311
 
            request.execute('subdir'))
312
 
        self.make_bzrdir('subdir/deeper')
313
 
        result3 = smart_req.SmartServerResponse(
314
 
            result.args[0:1] + ('../..', ) + result.args[2:])
315
 
        self.assertEqual(result3,
316
 
            request.execute('subdir/deeper'))
317
 
 
318
 
    def test_rich_root_and_subtree_encoding(self):
319
 
        """Test for the format attributes for rich root and subtree support."""
320
 
        backing = self.get_transport()
321
 
        request = self._request_class(backing)
322
 
        result = self._make_repository_and_result(
323
 
            format='dirstate-with-subtree')
324
 
        # check the test will be valid
325
 
        self.assertEqual('yes', result.args[2])
326
 
        self.assertEqual('yes', result.args[3])
327
 
        self.assertEqual(result, request.execute(''))
328
 
 
329
 
    def test_supports_external_lookups_no_v2(self):
330
 
        """Test for the supports_external_lookups attribute."""
331
 
        backing = self.get_transport()
332
 
        request = self._request_class(backing)
333
 
        result = self._make_repository_and_result(
334
 
            format='dirstate-with-subtree')
335
 
        # check the test will be valid
336
 
        self.assertEqual('no', result.args[4])
337
 
        self.assertEqual(result, request.execute(''))
338
 
 
339
 
 
340
 
class TestSmartServerBzrDirRequestGetConfigFile(
341
 
    tests.TestCaseWithMemoryTransport):
342
 
    """Tests for BzrDir.get_config_file."""
343
 
 
344
 
    def test_present(self):
345
 
        backing = self.get_transport()
346
 
        dir = self.make_bzrdir('.')
347
 
        dir.get_config().set_default_stack_on("/")
348
 
        local_result = dir._get_config()._get_config_file().read()
349
 
        request_class = smart_dir.SmartServerBzrDirRequestConfigFile
350
 
        request = request_class(backing)
351
 
        expected = smart_req.SuccessfulSmartServerResponse((), local_result)
352
 
        self.assertEqual(expected, request.execute(''))
353
 
 
354
 
    def test_missing(self):
355
 
        backing = self.get_transport()
356
 
        dir = self.make_bzrdir('.')
357
 
        request_class = smart_dir.SmartServerBzrDirRequestConfigFile
358
 
        request = request_class(backing)
359
 
        expected = smart_req.SuccessfulSmartServerResponse((), '')
360
 
        self.assertEqual(expected, request.execute(''))
361
 
 
362
 
 
363
 
class TestSmartServerRequestInitializeBzrDir(tests.TestCaseWithMemoryTransport):
364
 
 
365
 
    def test_empty_dir(self):
366
 
        """Initializing an empty dir should succeed and do it."""
367
 
        backing = self.get_transport()
368
 
        request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
369
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', )),
370
 
            request.execute(''))
371
 
        made_dir = bzrdir.BzrDir.open_from_transport(backing)
372
 
        # no branch, tree or repository is expected with the current
373
 
        # default formart.
374
 
        self.assertRaises(errors.NoWorkingTree, made_dir.open_workingtree)
375
 
        self.assertRaises(errors.NotBranchError, made_dir.open_branch)
376
 
        self.assertRaises(errors.NoRepositoryPresent, made_dir.open_repository)
377
 
 
378
 
    def test_missing_dir(self):
379
 
        """Initializing a missing directory should fail like the bzrdir api."""
380
 
        backing = self.get_transport()
381
 
        request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
382
 
        self.assertRaises(errors.NoSuchFile,
383
 
            request.execute, 'subdir')
384
 
 
385
 
    def test_initialized_dir(self):
386
 
        """Initializing an extant bzrdir should fail like the bzrdir api."""
387
 
        backing = self.get_transport()
388
 
        request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
389
 
        self.make_bzrdir('subdir')
390
 
        self.assertRaises(errors.FileExists,
391
 
            request.execute, 'subdir')
392
 
 
393
 
 
394
 
class TestSmartServerRequestBzrDirInitializeEx(
395
 
    tests.TestCaseWithMemoryTransport):
396
 
    """Basic tests for BzrDir.initialize_ex_1.16 in the smart server.
397
 
 
398
 
    The main unit tests in test_bzrdir exercise the API comprehensively.
399
 
    """
400
 
 
401
 
    def test_empty_dir(self):
402
 
        """Initializing an empty dir should succeed and do it."""
403
 
        backing = self.get_transport()
404
 
        name = self.make_bzrdir('reference')._format.network_name()
405
 
        request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
406
 
        self.assertEqual(
407
 
            smart_req.SmartServerResponse(('', '', '', '', '', '', name,
408
 
                                           'False', '', '', '')),
409
 
            request.execute(name, '', 'True', 'False', 'False', '', '', '', '',
410
 
                            'False'))
411
 
        made_dir = bzrdir.BzrDir.open_from_transport(backing)
412
 
        # no branch, tree or repository is expected with the current
413
 
        # default format.
414
 
        self.assertRaises(errors.NoWorkingTree, made_dir.open_workingtree)
415
 
        self.assertRaises(errors.NotBranchError, made_dir.open_branch)
416
 
        self.assertRaises(errors.NoRepositoryPresent, made_dir.open_repository)
417
 
 
418
 
    def test_missing_dir(self):
419
 
        """Initializing a missing directory should fail like the bzrdir api."""
420
 
        backing = self.get_transport()
421
 
        name = self.make_bzrdir('reference')._format.network_name()
422
 
        request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
423
 
        self.assertRaises(errors.NoSuchFile, request.execute, name,
424
 
            'subdir/dir', 'False', 'False', 'False', '', '', '', '', 'False')
425
 
 
426
 
    def test_initialized_dir(self):
427
 
        """Initializing an extant directory should fail like the bzrdir api."""
428
 
        backing = self.get_transport()
429
 
        name = self.make_bzrdir('reference')._format.network_name()
430
 
        request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
431
 
        self.make_bzrdir('subdir')
432
 
        self.assertRaises(errors.FileExists, request.execute, name, 'subdir',
433
 
            'False', 'False', 'False', '', '', '', '', 'False')
434
 
 
435
 
 
436
 
class TestSmartServerRequestOpenBzrDir(tests.TestCaseWithMemoryTransport):
437
 
 
438
 
    def test_no_directory(self):
439
 
        backing = self.get_transport()
440
 
        request = smart_dir.SmartServerRequestOpenBzrDir(backing)
441
 
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
442
 
            request.execute('does-not-exist'))
443
 
 
444
 
    def test_empty_directory(self):
445
 
        backing = self.get_transport()
446
 
        backing.mkdir('empty')
447
 
        request = smart_dir.SmartServerRequestOpenBzrDir(backing)
448
 
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
449
 
            request.execute('empty'))
450
 
 
451
 
    def test_outside_root_client_path(self):
452
 
        backing = self.get_transport()
453
 
        request = smart_dir.SmartServerRequestOpenBzrDir(backing,
454
 
            root_client_path='root')
455
 
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
456
 
            request.execute('not-root'))
457
 
 
458
 
 
459
 
class TestSmartServerRequestOpenBzrDir_2_1(tests.TestCaseWithMemoryTransport):
460
 
 
461
 
    def test_no_directory(self):
462
 
        backing = self.get_transport()
463
 
        request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
464
 
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
465
 
            request.execute('does-not-exist'))
466
 
 
467
 
    def test_empty_directory(self):
468
 
        backing = self.get_transport()
469
 
        backing.mkdir('empty')
470
 
        request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
471
 
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
472
 
            request.execute('empty'))
473
 
 
474
 
    def test_present_without_workingtree(self):
475
 
        backing = self.get_transport()
476
 
        request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
477
 
        self.make_bzrdir('.')
478
 
        self.assertEqual(smart_req.SmartServerResponse(('yes', 'no')),
479
 
            request.execute(''))
480
 
 
481
 
    def test_outside_root_client_path(self):
482
 
        backing = self.get_transport()
483
 
        request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing,
484
 
            root_client_path='root')
485
 
        self.assertEqual(smart_req.SmartServerResponse(('no',)),
486
 
            request.execute('not-root'))
487
 
 
488
 
 
489
 
class TestSmartServerRequestOpenBzrDir_2_1_disk(TestCaseWithChrootedTransport):
490
 
 
491
 
    def test_present_with_workingtree(self):
492
 
        self.vfs_transport_factory = test_server.LocalURLServer
493
 
        backing = self.get_transport()
494
 
        request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
495
 
        bd = self.make_bzrdir('.')
496
 
        bd.create_repository()
497
 
        bd.create_branch()
498
 
        bd.create_workingtree()
499
 
        self.assertEqual(smart_req.SmartServerResponse(('yes', 'yes')),
500
 
            request.execute(''))
501
 
 
502
 
 
503
 
class TestSmartServerRequestOpenBranch(TestCaseWithChrootedTransport):
504
 
 
505
 
    def test_no_branch(self):
506
 
        """When there is no branch, ('nobranch', ) is returned."""
507
 
        backing = self.get_transport()
508
 
        request = smart_dir.SmartServerRequestOpenBranch(backing)
509
 
        self.make_bzrdir('.')
510
 
        self.assertEqual(smart_req.SmartServerResponse(('nobranch', )),
511
 
            request.execute(''))
512
 
 
513
 
    def test_branch(self):
514
 
        """When there is a branch, 'ok' is returned."""
515
 
        backing = self.get_transport()
516
 
        request = smart_dir.SmartServerRequestOpenBranch(backing)
517
 
        self.make_branch('.')
518
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', '')),
519
 
            request.execute(''))
520
 
 
521
 
    def test_branch_reference(self):
522
 
        """When there is a branch reference, the reference URL is returned."""
523
 
        self.vfs_transport_factory = test_server.LocalURLServer
524
 
        backing = self.get_transport()
525
 
        request = smart_dir.SmartServerRequestOpenBranch(backing)
526
 
        branch = self.make_branch('branch')
527
 
        checkout = branch.create_checkout('reference',lightweight=True)
528
 
        reference_url = _mod_branch.BranchReferenceFormat().get_reference(
529
 
            checkout.bzrdir)
530
 
        self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
531
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', reference_url)),
532
 
            request.execute('reference'))
533
 
 
534
 
    def test_notification_on_branch_from_repository(self):
535
 
        """When there is a repository, the error should return details."""
536
 
        backing = self.get_transport()
537
 
        request = smart_dir.SmartServerRequestOpenBranch(backing)
538
 
        repo = self.make_repository('.')
539
 
        self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
540
 
            request.execute(''))
541
 
 
542
 
 
543
 
class TestSmartServerRequestOpenBranchV2(TestCaseWithChrootedTransport):
544
 
 
545
 
    def test_no_branch(self):
546
 
        """When there is no branch, ('nobranch', ) is returned."""
547
 
        backing = self.get_transport()
548
 
        self.make_bzrdir('.')
549
 
        request = smart_dir.SmartServerRequestOpenBranchV2(backing)
550
 
        self.assertEqual(smart_req.SmartServerResponse(('nobranch', )),
551
 
            request.execute(''))
552
 
 
553
 
    def test_branch(self):
554
 
        """When there is a branch, 'ok' is returned."""
555
 
        backing = self.get_transport()
556
 
        expected = self.make_branch('.')._format.network_name()
557
 
        request = smart_dir.SmartServerRequestOpenBranchV2(backing)
558
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
559
 
                ('branch', expected)),
560
 
                         request.execute(''))
561
 
 
562
 
    def test_branch_reference(self):
563
 
        """When there is a branch reference, the reference URL is returned."""
564
 
        self.vfs_transport_factory = test_server.LocalURLServer
565
 
        backing = self.get_transport()
566
 
        request = smart_dir.SmartServerRequestOpenBranchV2(backing)
567
 
        branch = self.make_branch('branch')
568
 
        checkout = branch.create_checkout('reference',lightweight=True)
569
 
        reference_url = _mod_branch.BranchReferenceFormat().get_reference(
570
 
            checkout.bzrdir)
571
 
        self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
572
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
573
 
                ('ref', reference_url)),
574
 
                         request.execute('reference'))
575
 
 
576
 
    def test_stacked_branch(self):
577
 
        """Opening a stacked branch does not open the stacked-on branch."""
578
 
        trunk = self.make_branch('trunk')
579
 
        feature = self.make_branch('feature')
580
 
        feature.set_stacked_on_url(trunk.base)
581
 
        opened_branches = []
582
 
        _mod_branch.Branch.hooks.install_named_hook(
583
 
            'open', opened_branches.append, None)
584
 
        backing = self.get_transport()
585
 
        request = smart_dir.SmartServerRequestOpenBranchV2(backing)
586
 
        request.setup_jail()
587
 
        try:
588
 
            response = request.execute('feature')
589
 
        finally:
590
 
            request.teardown_jail()
591
 
        expected_format = feature._format.network_name()
592
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
593
 
                ('branch', expected_format)),
594
 
                         response)
595
 
        self.assertLength(1, opened_branches)
596
 
 
597
 
    def test_notification_on_branch_from_repository(self):
598
 
        """When there is a repository, the error should return details."""
599
 
        backing = self.get_transport()
600
 
        request = smart_dir.SmartServerRequestOpenBranchV2(backing)
601
 
        repo = self.make_repository('.')
602
 
        self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
603
 
            request.execute(''))
604
 
 
605
 
 
606
 
class TestSmartServerRequestOpenBranchV3(TestCaseWithChrootedTransport):
607
 
 
608
 
    def test_no_branch(self):
609
 
        """When there is no branch, ('nobranch', ) is returned."""
610
 
        backing = self.get_transport()
611
 
        self.make_bzrdir('.')
612
 
        request = smart_dir.SmartServerRequestOpenBranchV3(backing)
613
 
        self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
614
 
            request.execute(''))
615
 
 
616
 
    def test_branch(self):
617
 
        """When there is a branch, 'ok' is returned."""
618
 
        backing = self.get_transport()
619
 
        expected = self.make_branch('.')._format.network_name()
620
 
        request = smart_dir.SmartServerRequestOpenBranchV3(backing)
621
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
622
 
                ('branch', expected)),
623
 
                         request.execute(''))
624
 
 
625
 
    def test_branch_reference(self):
626
 
        """When there is a branch reference, the reference URL is returned."""
627
 
        self.vfs_transport_factory = test_server.LocalURLServer
628
 
        backing = self.get_transport()
629
 
        request = smart_dir.SmartServerRequestOpenBranchV3(backing)
630
 
        branch = self.make_branch('branch')
631
 
        checkout = branch.create_checkout('reference',lightweight=True)
632
 
        reference_url = _mod_branch.BranchReferenceFormat().get_reference(
633
 
            checkout.bzrdir)
634
 
        self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
635
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
636
 
                ('ref', reference_url)),
637
 
                         request.execute('reference'))
638
 
 
639
 
    def test_stacked_branch(self):
640
 
        """Opening a stacked branch does not open the stacked-on branch."""
641
 
        trunk = self.make_branch('trunk')
642
 
        feature = self.make_branch('feature')
643
 
        feature.set_stacked_on_url(trunk.base)
644
 
        opened_branches = []
645
 
        _mod_branch.Branch.hooks.install_named_hook(
646
 
            'open', opened_branches.append, None)
647
 
        backing = self.get_transport()
648
 
        request = smart_dir.SmartServerRequestOpenBranchV3(backing)
649
 
        request.setup_jail()
650
 
        try:
651
 
            response = request.execute('feature')
652
 
        finally:
653
 
            request.teardown_jail()
654
 
        expected_format = feature._format.network_name()
655
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(
656
 
                ('branch', expected_format)),
657
 
                         response)
658
 
        self.assertLength(1, opened_branches)
659
 
 
660
 
    def test_notification_on_branch_from_repository(self):
661
 
        """When there is a repository, the error should return details."""
662
 
        backing = self.get_transport()
663
 
        request = smart_dir.SmartServerRequestOpenBranchV3(backing)
664
 
        repo = self.make_repository('.')
665
 
        self.assertEqual(smart_req.SmartServerResponse(
666
 
                ('nobranch', 'location is a repository')),
667
 
                         request.execute(''))
668
 
 
669
 
 
670
 
class TestSmartServerRequestRevisionHistory(tests.TestCaseWithMemoryTransport):
671
 
 
672
 
    def test_empty(self):
673
 
        """For an empty branch, the body is empty."""
674
 
        backing = self.get_transport()
675
 
        request = smart_branch.SmartServerRequestRevisionHistory(backing)
676
 
        self.make_branch('.')
677
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), ''),
678
 
            request.execute(''))
679
 
 
680
 
    def test_not_empty(self):
681
 
        """For a non-empty branch, the body is empty."""
682
 
        backing = self.get_transport()
683
 
        request = smart_branch.SmartServerRequestRevisionHistory(backing)
684
 
        tree = self.make_branch_and_memory_tree('.')
685
 
        tree.lock_write()
686
 
        tree.add('')
687
 
        r1 = tree.commit('1st commit')
688
 
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
689
 
        tree.unlock()
690
 
        self.assertEqual(
691
 
            smart_req.SmartServerResponse(('ok', ), ('\x00'.join([r1, r2]))),
692
 
            request.execute(''))
693
 
 
694
 
 
695
 
class TestSmartServerBranchRequest(tests.TestCaseWithMemoryTransport):
696
 
 
697
 
    def test_no_branch(self):
698
 
        """When there is a bzrdir and no branch, NotBranchError is raised."""
699
 
        backing = self.get_transport()
700
 
        request = smart_branch.SmartServerBranchRequest(backing)
701
 
        self.make_bzrdir('.')
702
 
        self.assertRaises(errors.NotBranchError,
703
 
            request.execute, '')
704
 
 
705
 
    def test_branch_reference(self):
706
 
        """When there is a branch reference, NotBranchError is raised."""
707
 
        backing = self.get_transport()
708
 
        request = smart_branch.SmartServerBranchRequest(backing)
709
 
        branch = self.make_branch('branch')
710
 
        checkout = branch.create_checkout('reference',lightweight=True)
711
 
        self.assertRaises(errors.NotBranchError,
712
 
            request.execute, 'checkout')
713
 
 
714
 
 
715
 
class TestSmartServerBranchRequestLastRevisionInfo(
716
 
    tests.TestCaseWithMemoryTransport):
717
 
 
718
 
    def test_empty(self):
719
 
        """For an empty branch, the result is ('ok', '0', 'null:')."""
720
 
        backing = self.get_transport()
721
 
        request = smart_branch.SmartServerBranchRequestLastRevisionInfo(backing)
722
 
        self.make_branch('.')
723
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', '0', 'null:')),
724
 
            request.execute(''))
725
 
 
726
 
    def test_not_empty(self):
727
 
        """For a non-empty branch, the result is ('ok', 'revno', 'revid')."""
728
 
        backing = self.get_transport()
729
 
        request = smart_branch.SmartServerBranchRequestLastRevisionInfo(backing)
730
 
        tree = self.make_branch_and_memory_tree('.')
731
 
        tree.lock_write()
732
 
        tree.add('')
733
 
        rev_id_utf8 = u'\xc8'.encode('utf-8')
734
 
        r1 = tree.commit('1st commit')
735
 
        r2 = tree.commit('2nd commit', rev_id=rev_id_utf8)
736
 
        tree.unlock()
737
 
        self.assertEqual(
738
 
            smart_req.SmartServerResponse(('ok', '2', rev_id_utf8)),
739
 
            request.execute(''))
740
 
 
741
 
 
742
 
class TestSmartServerBranchRequestGetConfigFile(
743
 
    tests.TestCaseWithMemoryTransport):
744
 
 
745
 
    def test_default(self):
746
 
        """With no file, we get empty content."""
747
 
        backing = self.get_transport()
748
 
        request = smart_branch.SmartServerBranchGetConfigFile(backing)
749
 
        branch = self.make_branch('.')
750
 
        # there should be no file by default
751
 
        content = ''
752
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), content),
753
 
            request.execute(''))
754
 
 
755
 
    def test_with_content(self):
756
 
        # SmartServerBranchGetConfigFile should return the content from
757
 
        # branch.control_files.get('branch.conf') for now - in the future it may
758
 
        # perform more complex processing.
759
 
        backing = self.get_transport()
760
 
        request = smart_branch.SmartServerBranchGetConfigFile(backing)
761
 
        branch = self.make_branch('.')
762
 
        branch._transport.put_bytes('branch.conf', 'foo bar baz')
763
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'foo bar baz'),
764
 
            request.execute(''))
765
 
 
766
 
 
767
 
class TestLockedBranch(tests.TestCaseWithMemoryTransport):
768
 
 
769
 
    def get_lock_tokens(self, branch):
770
 
        branch_token = branch.lock_write().branch_token
771
 
        repo_token = branch.repository.lock_write().repository_token
772
 
        branch.repository.unlock()
773
 
        return branch_token, repo_token
774
 
 
775
 
 
776
 
class TestSmartServerBranchRequestSetConfigOption(TestLockedBranch):
777
 
 
778
 
    def test_value_name(self):
779
 
        branch = self.make_branch('.')
780
 
        request = smart_branch.SmartServerBranchRequestSetConfigOption(
781
 
            branch.bzrdir.root_transport)
782
 
        branch_token, repo_token = self.get_lock_tokens(branch)
783
 
        config = branch._get_config()
784
 
        result = request.execute('', branch_token, repo_token, 'bar', 'foo',
785
 
            '')
786
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
787
 
        self.assertEqual('bar', config.get_option('foo'))
788
 
        # Cleanup
789
 
        branch.unlock()
790
 
 
791
 
    def test_value_name_section(self):
792
 
        branch = self.make_branch('.')
793
 
        request = smart_branch.SmartServerBranchRequestSetConfigOption(
794
 
            branch.bzrdir.root_transport)
795
 
        branch_token, repo_token = self.get_lock_tokens(branch)
796
 
        config = branch._get_config()
797
 
        result = request.execute('', branch_token, repo_token, 'bar', 'foo',
798
 
            'gam')
799
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
800
 
        self.assertEqual('bar', config.get_option('foo', 'gam'))
801
 
        # Cleanup
802
 
        branch.unlock()
803
 
 
804
 
 
805
 
class TestSmartServerBranchRequestSetTagsBytes(TestLockedBranch):
806
 
    # Only called when the branch format and tags match [yay factory
807
 
    # methods] so only need to test straight forward cases.
808
 
 
809
 
    def test_set_bytes(self):
810
 
        base_branch = self.make_branch('base')
811
 
        tag_bytes = base_branch._get_tags_bytes()
812
 
        # get_lock_tokens takes out a lock.
813
 
        branch_token, repo_token = self.get_lock_tokens(base_branch)
814
 
        request = smart_branch.SmartServerBranchSetTagsBytes(
815
 
            self.get_transport())
816
 
        response = request.execute('base', branch_token, repo_token)
817
 
        self.assertEqual(None, response)
818
 
        response = request.do_chunk(tag_bytes)
819
 
        self.assertEqual(None, response)
820
 
        response = request.do_end()
821
 
        self.assertEquals(
822
 
            smart_req.SuccessfulSmartServerResponse(()), response)
823
 
        base_branch.unlock()
824
 
 
825
 
    def test_lock_failed(self):
826
 
        base_branch = self.make_branch('base')
827
 
        base_branch.lock_write()
828
 
        tag_bytes = base_branch._get_tags_bytes()
829
 
        request = smart_branch.SmartServerBranchSetTagsBytes(
830
 
            self.get_transport())
831
 
        self.assertRaises(errors.TokenMismatch, request.execute,
832
 
            'base', 'wrong token', 'wrong token')
833
 
        # The request handler will keep processing the message parts, so even
834
 
        # if the request fails immediately do_chunk and do_end are still
835
 
        # called.
836
 
        request.do_chunk(tag_bytes)
837
 
        request.do_end()
838
 
        base_branch.unlock()
839
 
 
840
 
 
841
 
 
842
 
class SetLastRevisionTestBase(TestLockedBranch):
843
 
    """Base test case for verbs that implement set_last_revision."""
844
 
 
845
 
    def setUp(self):
846
 
        tests.TestCaseWithMemoryTransport.setUp(self)
847
 
        backing_transport = self.get_transport()
848
 
        self.request = self.request_class(backing_transport)
849
 
        self.tree = self.make_branch_and_memory_tree('.')
850
 
 
851
 
    def lock_branch(self):
852
 
        return self.get_lock_tokens(self.tree.branch)
853
 
 
854
 
    def unlock_branch(self):
855
 
        self.tree.branch.unlock()
856
 
 
857
 
    def set_last_revision(self, revision_id, revno):
858
 
        branch_token, repo_token = self.lock_branch()
859
 
        response = self._set_last_revision(
860
 
            revision_id, revno, branch_token, repo_token)
861
 
        self.unlock_branch()
862
 
        return response
863
 
 
864
 
    def assertRequestSucceeds(self, revision_id, revno):
865
 
        response = self.set_last_revision(revision_id, revno)
866
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
867
 
                         response)
868
 
 
869
 
 
870
 
class TestSetLastRevisionVerbMixin(object):
871
 
    """Mixin test case for verbs that implement set_last_revision."""
872
 
 
873
 
    def test_set_null_to_null(self):
874
 
        """An empty branch can have its last revision set to 'null:'."""
875
 
        self.assertRequestSucceeds('null:', 0)
876
 
 
877
 
    def test_NoSuchRevision(self):
878
 
        """If the revision_id is not present, the verb returns NoSuchRevision.
879
 
        """
880
 
        revision_id = 'non-existent revision'
881
 
        self.assertEqual(smart_req.FailedSmartServerResponse(('NoSuchRevision',
882
 
                                                              revision_id)),
883
 
                         self.set_last_revision(revision_id, 1))
884
 
 
885
 
    def make_tree_with_two_commits(self):
886
 
        self.tree.lock_write()
887
 
        self.tree.add('')
888
 
        rev_id_utf8 = u'\xc8'.encode('utf-8')
889
 
        r1 = self.tree.commit('1st commit', rev_id=rev_id_utf8)
890
 
        r2 = self.tree.commit('2nd commit', rev_id='rev-2')
891
 
        self.tree.unlock()
892
 
 
893
 
    def test_branch_last_revision_info_is_updated(self):
894
 
        """A branch's tip can be set to a revision that is present in its
895
 
        repository.
896
 
        """
897
 
        # Make a branch with an empty revision history, but two revisions in
898
 
        # its repository.
899
 
        self.make_tree_with_two_commits()
900
 
        rev_id_utf8 = u'\xc8'.encode('utf-8')
901
 
        self.tree.branch.set_revision_history([])
902
 
        self.assertEqual(
903
 
            (0, 'null:'), self.tree.branch.last_revision_info())
904
 
        # We can update the branch to a revision that is present in the
905
 
        # repository.
906
 
        self.assertRequestSucceeds(rev_id_utf8, 1)
907
 
        self.assertEqual(
908
 
            (1, rev_id_utf8), self.tree.branch.last_revision_info())
909
 
 
910
 
    def test_branch_last_revision_info_rewind(self):
911
 
        """A branch's tip can be set to a revision that is an ancestor of the
912
 
        current tip.
913
 
        """
914
 
        self.make_tree_with_two_commits()
915
 
        rev_id_utf8 = u'\xc8'.encode('utf-8')
916
 
        self.assertEqual(
917
 
            (2, 'rev-2'), self.tree.branch.last_revision_info())
918
 
        self.assertRequestSucceeds(rev_id_utf8, 1)
919
 
        self.assertEqual(
920
 
            (1, rev_id_utf8), self.tree.branch.last_revision_info())
921
 
 
922
 
    def test_TipChangeRejected(self):
923
 
        """If a pre_change_branch_tip hook raises TipChangeRejected, the verb
924
 
        returns TipChangeRejected.
925
 
        """
926
 
        rejection_message = u'rejection message\N{INTERROBANG}'
927
 
        def hook_that_rejects(params):
928
 
            raise errors.TipChangeRejected(rejection_message)
929
 
        _mod_branch.Branch.hooks.install_named_hook(
930
 
            'pre_change_branch_tip', hook_that_rejects, None)
931
 
        self.assertEqual(
932
 
            smart_req.FailedSmartServerResponse(
933
 
                ('TipChangeRejected', rejection_message.encode('utf-8'))),
934
 
            self.set_last_revision('null:', 0))
935
 
 
936
 
 
937
 
class TestSmartServerBranchRequestSetLastRevision(
938
 
        SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
939
 
    """Tests for Branch.set_last_revision verb."""
940
 
 
941
 
    request_class = smart_branch.SmartServerBranchRequestSetLastRevision
942
 
 
943
 
    def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
944
 
        return self.request.execute(
945
 
            '', branch_token, repo_token, revision_id)
946
 
 
947
 
 
948
 
class TestSmartServerBranchRequestSetLastRevisionInfo(
949
 
        SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
950
 
    """Tests for Branch.set_last_revision_info verb."""
951
 
 
952
 
    request_class = smart_branch.SmartServerBranchRequestSetLastRevisionInfo
953
 
 
954
 
    def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
955
 
        return self.request.execute(
956
 
            '', branch_token, repo_token, revno, revision_id)
957
 
 
958
 
    def test_NoSuchRevision(self):
959
 
        """Branch.set_last_revision_info does not have to return
960
 
        NoSuchRevision if the revision_id is absent.
961
 
        """
962
 
        raise tests.TestNotApplicable()
963
 
 
964
 
 
965
 
class TestSmartServerBranchRequestSetLastRevisionEx(
966
 
        SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
967
 
    """Tests for Branch.set_last_revision_ex verb."""
968
 
 
969
 
    request_class = smart_branch.SmartServerBranchRequestSetLastRevisionEx
970
 
 
971
 
    def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
972
 
        return self.request.execute(
973
 
            '', branch_token, repo_token, revision_id, 0, 0)
974
 
 
975
 
    def assertRequestSucceeds(self, revision_id, revno):
976
 
        response = self.set_last_revision(revision_id, revno)
977
 
        self.assertEqual(
978
 
            smart_req.SuccessfulSmartServerResponse(('ok', revno, revision_id)),
979
 
            response)
980
 
 
981
 
    def test_branch_last_revision_info_rewind(self):
982
 
        """A branch's tip can be set to a revision that is an ancestor of the
983
 
        current tip, but only if allow_overwrite_descendant is passed.
984
 
        """
985
 
        self.make_tree_with_two_commits()
986
 
        rev_id_utf8 = u'\xc8'.encode('utf-8')
987
 
        self.assertEqual(
988
 
            (2, 'rev-2'), self.tree.branch.last_revision_info())
989
 
        # If allow_overwrite_descendant flag is 0, then trying to set the tip
990
 
        # to an older revision ID has no effect.
991
 
        branch_token, repo_token = self.lock_branch()
992
 
        response = self.request.execute(
993
 
            '', branch_token, repo_token, rev_id_utf8, 0, 0)
994
 
        self.assertEqual(
995
 
            smart_req.SuccessfulSmartServerResponse(('ok', 2, 'rev-2')),
996
 
            response)
997
 
        self.assertEqual(
998
 
            (2, 'rev-2'), self.tree.branch.last_revision_info())
999
 
 
1000
 
        # If allow_overwrite_descendant flag is 1, then setting the tip to an
1001
 
        # ancestor works.
1002
 
        response = self.request.execute(
1003
 
            '', branch_token, repo_token, rev_id_utf8, 0, 1)
1004
 
        self.assertEqual(
1005
 
            smart_req.SuccessfulSmartServerResponse(('ok', 1, rev_id_utf8)),
1006
 
            response)
1007
 
        self.unlock_branch()
1008
 
        self.assertEqual(
1009
 
            (1, rev_id_utf8), self.tree.branch.last_revision_info())
1010
 
 
1011
 
    def make_branch_with_divergent_history(self):
1012
 
        """Make a branch with divergent history in its repo.
1013
 
 
1014
 
        The branch's tip will be 'child-2', and the repo will also contain
1015
 
        'child-1', which diverges from a common base revision.
1016
 
        """
1017
 
        self.tree.lock_write()
1018
 
        self.tree.add('')
1019
 
        r1 = self.tree.commit('1st commit')
1020
 
        revno_1, revid_1 = self.tree.branch.last_revision_info()
1021
 
        r2 = self.tree.commit('2nd commit', rev_id='child-1')
1022
 
        # Undo the second commit
1023
 
        self.tree.branch.set_last_revision_info(revno_1, revid_1)
1024
 
        self.tree.set_parent_ids([revid_1])
1025
 
        # Make a new second commit, child-2.  child-2 has diverged from
1026
 
        # child-1.
1027
 
        new_r2 = self.tree.commit('2nd commit', rev_id='child-2')
1028
 
        self.tree.unlock()
1029
 
 
1030
 
    def test_not_allow_diverged(self):
1031
 
        """If allow_diverged is not passed, then setting a divergent history
1032
 
        returns a Diverged error.
1033
 
        """
1034
 
        self.make_branch_with_divergent_history()
1035
 
        self.assertEqual(
1036
 
            smart_req.FailedSmartServerResponse(('Diverged',)),
1037
 
            self.set_last_revision('child-1', 2))
1038
 
        # The branch tip was not changed.
1039
 
        self.assertEqual('child-2', self.tree.branch.last_revision())
1040
 
 
1041
 
    def test_allow_diverged(self):
1042
 
        """If allow_diverged is passed, then setting a divergent history
1043
 
        succeeds.
1044
 
        """
1045
 
        self.make_branch_with_divergent_history()
1046
 
        branch_token, repo_token = self.lock_branch()
1047
 
        response = self.request.execute(
1048
 
            '', branch_token, repo_token, 'child-1', 1, 0)
1049
 
        self.assertEqual(
1050
 
            smart_req.SuccessfulSmartServerResponse(('ok', 2, 'child-1')),
1051
 
            response)
1052
 
        self.unlock_branch()
1053
 
        # The branch tip was changed.
1054
 
        self.assertEqual('child-1', self.tree.branch.last_revision())
1055
 
 
1056
 
 
1057
 
class TestSmartServerBranchRequestGetParent(tests.TestCaseWithMemoryTransport):
1058
 
 
1059
 
    def test_get_parent_none(self):
1060
 
        base_branch = self.make_branch('base')
1061
 
        request = smart_branch.SmartServerBranchGetParent(self.get_transport())
1062
 
        response = request.execute('base')
1063
 
        self.assertEquals(
1064
 
            smart_req.SuccessfulSmartServerResponse(('',)), response)
1065
 
 
1066
 
    def test_get_parent_something(self):
1067
 
        base_branch = self.make_branch('base')
1068
 
        base_branch.set_parent(self.get_url('foo'))
1069
 
        request = smart_branch.SmartServerBranchGetParent(self.get_transport())
1070
 
        response = request.execute('base')
1071
 
        self.assertEquals(
1072
 
            smart_req.SuccessfulSmartServerResponse(("../foo",)),
1073
 
            response)
1074
 
 
1075
 
 
1076
 
class TestSmartServerBranchRequestSetParent(TestLockedBranch):
1077
 
 
1078
 
    def test_set_parent_none(self):
1079
 
        branch = self.make_branch('base', format="1.9")
1080
 
        branch.lock_write()
1081
 
        branch._set_parent_location('foo')
1082
 
        branch.unlock()
1083
 
        request = smart_branch.SmartServerBranchRequestSetParentLocation(
1084
 
            self.get_transport())
1085
 
        branch_token, repo_token = self.get_lock_tokens(branch)
1086
 
        try:
1087
 
            response = request.execute('base', branch_token, repo_token, '')
1088
 
        finally:
1089
 
            branch.unlock()
1090
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), response)
1091
 
        self.assertEqual(None, branch.get_parent())
1092
 
 
1093
 
    def test_set_parent_something(self):
1094
 
        branch = self.make_branch('base', format="1.9")
1095
 
        request = smart_branch.SmartServerBranchRequestSetParentLocation(
1096
 
            self.get_transport())
1097
 
        branch_token, repo_token = self.get_lock_tokens(branch)
1098
 
        try:
1099
 
            response = request.execute('base', branch_token, repo_token,
1100
 
            'http://bar/')
1101
 
        finally:
1102
 
            branch.unlock()
1103
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), response)
1104
 
        self.assertEqual('http://bar/', branch.get_parent())
1105
 
 
1106
 
 
1107
 
class TestSmartServerBranchRequestGetTagsBytes(
1108
 
    tests.TestCaseWithMemoryTransport):
1109
 
    # Only called when the branch format and tags match [yay factory
1110
 
    # methods] so only need to test straight forward cases.
1111
 
 
1112
 
    def test_get_bytes(self):
1113
 
        base_branch = self.make_branch('base')
1114
 
        request = smart_branch.SmartServerBranchGetTagsBytes(
1115
 
            self.get_transport())
1116
 
        response = request.execute('base')
1117
 
        self.assertEquals(
1118
 
            smart_req.SuccessfulSmartServerResponse(('',)), response)
1119
 
 
1120
 
 
1121
 
class TestSmartServerBranchRequestGetStackedOnURL(tests.TestCaseWithMemoryTransport):
1122
 
 
1123
 
    def test_get_stacked_on_url(self):
1124
 
        base_branch = self.make_branch('base', format='1.6')
1125
 
        stacked_branch = self.make_branch('stacked', format='1.6')
1126
 
        # typically should be relative
1127
 
        stacked_branch.set_stacked_on_url('../base')
1128
 
        request = smart_branch.SmartServerBranchRequestGetStackedOnURL(
1129
 
            self.get_transport())
1130
 
        response = request.execute('stacked')
1131
 
        self.assertEquals(
1132
 
            smart_req.SmartServerResponse(('ok', '../base')),
1133
 
            response)
1134
 
 
1135
 
 
1136
 
class TestSmartServerBranchRequestLockWrite(TestLockedBranch):
1137
 
 
1138
 
    def setUp(self):
1139
 
        tests.TestCaseWithMemoryTransport.setUp(self)
1140
 
 
1141
 
    def test_lock_write_on_unlocked_branch(self):
1142
 
        backing = self.get_transport()
1143
 
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1144
 
        branch = self.make_branch('.', format='knit')
1145
 
        repository = branch.repository
1146
 
        response = request.execute('')
1147
 
        branch_nonce = branch.control_files._lock.peek().get('nonce')
1148
 
        repository_nonce = repository.control_files._lock.peek().get('nonce')
1149
 
        self.assertEqual(smart_req.SmartServerResponse(
1150
 
                ('ok', branch_nonce, repository_nonce)),
1151
 
                         response)
1152
 
        # The branch (and associated repository) is now locked.  Verify that
1153
 
        # with a new branch object.
1154
 
        new_branch = repository.bzrdir.open_branch()
1155
 
        self.assertRaises(errors.LockContention, new_branch.lock_write)
1156
 
        # Cleanup
1157
 
        request = smart_branch.SmartServerBranchRequestUnlock(backing)
1158
 
        response = request.execute('', branch_nonce, repository_nonce)
1159
 
 
1160
 
    def test_lock_write_on_locked_branch(self):
1161
 
        backing = self.get_transport()
1162
 
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1163
 
        branch = self.make_branch('.')
1164
 
        branch_token = branch.lock_write().branch_token
1165
 
        branch.leave_lock_in_place()
1166
 
        branch.unlock()
1167
 
        response = request.execute('')
1168
 
        self.assertEqual(
1169
 
            smart_req.SmartServerResponse(('LockContention',)), response)
1170
 
        # Cleanup
1171
 
        branch.lock_write(branch_token)
1172
 
        branch.dont_leave_lock_in_place()
1173
 
        branch.unlock()
1174
 
 
1175
 
    def test_lock_write_with_tokens_on_locked_branch(self):
1176
 
        backing = self.get_transport()
1177
 
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1178
 
        branch = self.make_branch('.', format='knit')
1179
 
        branch_token, repo_token = self.get_lock_tokens(branch)
1180
 
        branch.leave_lock_in_place()
1181
 
        branch.repository.leave_lock_in_place()
1182
 
        branch.unlock()
1183
 
        response = request.execute('',
1184
 
                                   branch_token, repo_token)
1185
 
        self.assertEqual(
1186
 
            smart_req.SmartServerResponse(('ok', branch_token, repo_token)),
1187
 
            response)
1188
 
        # Cleanup
1189
 
        branch.repository.lock_write(repo_token)
1190
 
        branch.repository.dont_leave_lock_in_place()
1191
 
        branch.repository.unlock()
1192
 
        branch.lock_write(branch_token)
1193
 
        branch.dont_leave_lock_in_place()
1194
 
        branch.unlock()
1195
 
 
1196
 
    def test_lock_write_with_mismatched_tokens_on_locked_branch(self):
1197
 
        backing = self.get_transport()
1198
 
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1199
 
        branch = self.make_branch('.', format='knit')
1200
 
        branch_token, repo_token = self.get_lock_tokens(branch)
1201
 
        branch.leave_lock_in_place()
1202
 
        branch.repository.leave_lock_in_place()
1203
 
        branch.unlock()
1204
 
        response = request.execute('',
1205
 
                                   branch_token+'xxx', repo_token)
1206
 
        self.assertEqual(
1207
 
            smart_req.SmartServerResponse(('TokenMismatch',)), response)
1208
 
        # Cleanup
1209
 
        branch.repository.lock_write(repo_token)
1210
 
        branch.repository.dont_leave_lock_in_place()
1211
 
        branch.repository.unlock()
1212
 
        branch.lock_write(branch_token)
1213
 
        branch.dont_leave_lock_in_place()
1214
 
        branch.unlock()
1215
 
 
1216
 
    def test_lock_write_on_locked_repo(self):
1217
 
        backing = self.get_transport()
1218
 
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1219
 
        branch = self.make_branch('.', format='knit')
1220
 
        repo = branch.repository
1221
 
        repo_token = repo.lock_write().repository_token
1222
 
        repo.leave_lock_in_place()
1223
 
        repo.unlock()
1224
 
        response = request.execute('')
1225
 
        self.assertEqual(
1226
 
            smart_req.SmartServerResponse(('LockContention',)), response)
1227
 
        # Cleanup
1228
 
        repo.lock_write(repo_token)
1229
 
        repo.dont_leave_lock_in_place()
1230
 
        repo.unlock()
1231
 
 
1232
 
    def test_lock_write_on_readonly_transport(self):
1233
 
        backing = self.get_readonly_transport()
1234
 
        request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1235
 
        branch = self.make_branch('.')
1236
 
        root = self.get_transport().clone('/')
1237
 
        path = urlutils.relative_url(root.base, self.get_transport().base)
1238
 
        response = request.execute(path)
1239
 
        error_name, lock_str, why_str = response.args
1240
 
        self.assertFalse(response.is_successful())
1241
 
        self.assertEqual('LockFailed', error_name)
1242
 
 
1243
 
 
1244
 
class TestSmartServerBranchRequestUnlock(TestLockedBranch):
1245
 
 
1246
 
    def setUp(self):
1247
 
        tests.TestCaseWithMemoryTransport.setUp(self)
1248
 
 
1249
 
    def test_unlock_on_locked_branch_and_repo(self):
1250
 
        backing = self.get_transport()
1251
 
        request = smart_branch.SmartServerBranchRequestUnlock(backing)
1252
 
        branch = self.make_branch('.', format='knit')
1253
 
        # Lock the branch
1254
 
        branch_token, repo_token = self.get_lock_tokens(branch)
1255
 
        # Unlock the branch (and repo) object, leaving the physical locks
1256
 
        # in place.
1257
 
        branch.leave_lock_in_place()
1258
 
        branch.repository.leave_lock_in_place()
1259
 
        branch.unlock()
1260
 
        response = request.execute('',
1261
 
                                   branch_token, repo_token)
1262
 
        self.assertEqual(
1263
 
            smart_req.SmartServerResponse(('ok',)), response)
1264
 
        # The branch is now unlocked.  Verify that with a new branch
1265
 
        # object.
1266
 
        new_branch = branch.bzrdir.open_branch()
1267
 
        new_branch.lock_write()
1268
 
        new_branch.unlock()
1269
 
 
1270
 
    def test_unlock_on_unlocked_branch_unlocked_repo(self):
1271
 
        backing = self.get_transport()
1272
 
        request = smart_branch.SmartServerBranchRequestUnlock(backing)
1273
 
        branch = self.make_branch('.', format='knit')
1274
 
        response = request.execute(
1275
 
            '', 'branch token', 'repo token')
1276
 
        self.assertEqual(
1277
 
            smart_req.SmartServerResponse(('TokenMismatch',)), response)
1278
 
 
1279
 
    def test_unlock_on_unlocked_branch_locked_repo(self):
1280
 
        backing = self.get_transport()
1281
 
        request = smart_branch.SmartServerBranchRequestUnlock(backing)
1282
 
        branch = self.make_branch('.', format='knit')
1283
 
        # Lock the repository.
1284
 
        repo_token = branch.repository.lock_write().repository_token
1285
 
        branch.repository.leave_lock_in_place()
1286
 
        branch.repository.unlock()
1287
 
        # Issue branch lock_write request on the unlocked branch (with locked
1288
 
        # repo).
1289
 
        response = request.execute('', 'branch token', repo_token)
1290
 
        self.assertEqual(
1291
 
            smart_req.SmartServerResponse(('TokenMismatch',)), response)
1292
 
        # Cleanup
1293
 
        branch.repository.lock_write(repo_token)
1294
 
        branch.repository.dont_leave_lock_in_place()
1295
 
        branch.repository.unlock()
1296
 
 
1297
 
 
1298
 
class TestSmartServerRepositoryRequest(tests.TestCaseWithMemoryTransport):
1299
 
 
1300
 
    def test_no_repository(self):
1301
 
        """Raise NoRepositoryPresent when there is a bzrdir and no repo."""
1302
 
        # we test this using a shared repository above the named path,
1303
 
        # thus checking the right search logic is used - that is, that
1304
 
        # its the exact path being looked at and the server is not
1305
 
        # searching.
1306
 
        backing = self.get_transport()
1307
 
        request = smart_repo.SmartServerRepositoryRequest(backing)
1308
 
        self.make_repository('.', shared=True)
1309
 
        self.make_bzrdir('subdir')
1310
 
        self.assertRaises(errors.NoRepositoryPresent,
1311
 
            request.execute, 'subdir')
1312
 
 
1313
 
 
1314
 
class TestSmartServerRepositoryGetParentMap(tests.TestCaseWithMemoryTransport):
1315
 
 
1316
 
    def test_trivial_bzipped(self):
1317
 
        # This tests that the wire encoding is actually bzipped
1318
 
        backing = self.get_transport()
1319
 
        request = smart_repo.SmartServerRepositoryGetParentMap(backing)
1320
 
        tree = self.make_branch_and_memory_tree('.')
1321
 
 
1322
 
        self.assertEqual(None,
1323
 
            request.execute('', 'missing-id'))
1324
 
        # Note that it returns a body that is bzipped.
1325
 
        self.assertEqual(
1326
 
            smart_req.SuccessfulSmartServerResponse(('ok', ), bz2.compress('')),
1327
 
            request.do_body('\n\n0\n'))
1328
 
 
1329
 
    def test_trivial_include_missing(self):
1330
 
        backing = self.get_transport()
1331
 
        request = smart_repo.SmartServerRepositoryGetParentMap(backing)
1332
 
        tree = self.make_branch_and_memory_tree('.')
1333
 
 
1334
 
        self.assertEqual(None,
1335
 
            request.execute('', 'missing-id', 'include-missing:'))
1336
 
        self.assertEqual(
1337
 
            smart_req.SuccessfulSmartServerResponse(('ok', ),
1338
 
                bz2.compress('missing:missing-id')),
1339
 
            request.do_body('\n\n0\n'))
1340
 
 
1341
 
 
1342
 
class TestSmartServerRepositoryGetRevisionGraph(
1343
 
    tests.TestCaseWithMemoryTransport):
1344
 
 
1345
 
    def test_none_argument(self):
1346
 
        backing = self.get_transport()
1347
 
        request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1348
 
        tree = self.make_branch_and_memory_tree('.')
1349
 
        tree.lock_write()
1350
 
        tree.add('')
1351
 
        r1 = tree.commit('1st commit')
1352
 
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1353
 
        tree.unlock()
1354
 
 
1355
 
        # the lines of revision_id->revision_parent_list has no guaranteed
1356
 
        # order coming out of a dict, so sort both our test and response
1357
 
        lines = sorted([' '.join([r2, r1]), r1])
1358
 
        response = request.execute('', '')
1359
 
        response.body = '\n'.join(sorted(response.body.split('\n')))
1360
 
 
1361
 
        self.assertEqual(
1362
 
            smart_req.SmartServerResponse(('ok', ), '\n'.join(lines)), response)
1363
 
 
1364
 
    def test_specific_revision_argument(self):
1365
 
        backing = self.get_transport()
1366
 
        request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1367
 
        tree = self.make_branch_and_memory_tree('.')
1368
 
        tree.lock_write()
1369
 
        tree.add('')
1370
 
        rev_id_utf8 = u'\xc9'.encode('utf-8')
1371
 
        r1 = tree.commit('1st commit', rev_id=rev_id_utf8)
1372
 
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1373
 
        tree.unlock()
1374
 
 
1375
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), rev_id_utf8),
1376
 
            request.execute('', rev_id_utf8))
1377
 
 
1378
 
    def test_no_such_revision(self):
1379
 
        backing = self.get_transport()
1380
 
        request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1381
 
        tree = self.make_branch_and_memory_tree('.')
1382
 
        tree.lock_write()
1383
 
        tree.add('')
1384
 
        r1 = tree.commit('1st commit')
1385
 
        tree.unlock()
1386
 
 
1387
 
        # Note that it still returns body (of zero bytes).
1388
 
        self.assertEqual(smart_req.SmartServerResponse(
1389
 
                ('nosuchrevision', 'missingrevision', ), ''),
1390
 
                         request.execute('', 'missingrevision'))
1391
 
 
1392
 
 
1393
 
class TestSmartServerRepositoryGetRevIdForRevno(
1394
 
    tests.TestCaseWithMemoryTransport):
1395
 
 
1396
 
    def test_revno_found(self):
1397
 
        backing = self.get_transport()
1398
 
        request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1399
 
        tree = self.make_branch_and_memory_tree('.')
1400
 
        tree.lock_write()
1401
 
        tree.add('')
1402
 
        rev1_id_utf8 = u'\xc8'.encode('utf-8')
1403
 
        rev2_id_utf8 = u'\xc9'.encode('utf-8')
1404
 
        tree.commit('1st commit', rev_id=rev1_id_utf8)
1405
 
        tree.commit('2nd commit', rev_id=rev2_id_utf8)
1406
 
        tree.unlock()
1407
 
 
1408
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', rev1_id_utf8)),
1409
 
            request.execute('', 1, (2, rev2_id_utf8)))
1410
 
 
1411
 
    def test_known_revid_missing(self):
1412
 
        backing = self.get_transport()
1413
 
        request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1414
 
        repo = self.make_repository('.')
1415
 
        self.assertEqual(
1416
 
            smart_req.FailedSmartServerResponse(('nosuchrevision', 'ghost')),
1417
 
            request.execute('', 1, (2, 'ghost')))
1418
 
 
1419
 
    def test_history_incomplete(self):
1420
 
        backing = self.get_transport()
1421
 
        request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1422
 
        parent = self.make_branch_and_memory_tree('parent', format='1.9')
1423
 
        parent.lock_write()
1424
 
        parent.add([''], ['TREE_ROOT'])
1425
 
        r1 = parent.commit(message='first commit')
1426
 
        r2 = parent.commit(message='second commit')
1427
 
        parent.unlock()
1428
 
        local = self.make_branch_and_memory_tree('local', format='1.9')
1429
 
        local.branch.pull(parent.branch)
1430
 
        local.set_parent_ids([r2])
1431
 
        r3 = local.commit(message='local commit')
1432
 
        local.branch.create_clone_on_transport(
1433
 
            self.get_transport('stacked'), stacked_on=self.get_url('parent'))
1434
 
        self.assertEqual(
1435
 
            smart_req.SmartServerResponse(('history-incomplete', 2, r2)),
1436
 
            request.execute('stacked', 1, (3, r3)))
1437
 
 
1438
 
 
1439
 
class TestSmartServerRepositoryGetStream(tests.TestCaseWithMemoryTransport):
1440
 
 
1441
 
    def make_two_commit_repo(self):
1442
 
        tree = self.make_branch_and_memory_tree('.')
1443
 
        tree.lock_write()
1444
 
        tree.add('')
1445
 
        r1 = tree.commit('1st commit')
1446
 
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1447
 
        tree.unlock()
1448
 
        repo = tree.branch.repository
1449
 
        return repo, r1, r2
1450
 
 
1451
 
    def test_ancestry_of(self):
1452
 
        """The search argument may be a 'ancestry-of' some heads'."""
1453
 
        backing = self.get_transport()
1454
 
        request = smart_repo.SmartServerRepositoryGetStream(backing)
1455
 
        repo, r1, r2 = self.make_two_commit_repo()
1456
 
        fetch_spec = ['ancestry-of', r2]
1457
 
        lines = '\n'.join(fetch_spec)
1458
 
        request.execute('', repo._format.network_name())
1459
 
        response = request.do_body(lines)
1460
 
        self.assertEqual(('ok',), response.args)
1461
 
        stream_bytes = ''.join(response.body_stream)
1462
 
        self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
1463
 
 
1464
 
    def test_search(self):
1465
 
        """The search argument may be a 'search' of some explicit keys."""
1466
 
        backing = self.get_transport()
1467
 
        request = smart_repo.SmartServerRepositoryGetStream(backing)
1468
 
        repo, r1, r2 = self.make_two_commit_repo()
1469
 
        fetch_spec = ['search', '%s %s' % (r1, r2), 'null:', '2']
1470
 
        lines = '\n'.join(fetch_spec)
1471
 
        request.execute('', repo._format.network_name())
1472
 
        response = request.do_body(lines)
1473
 
        self.assertEqual(('ok',), response.args)
1474
 
        stream_bytes = ''.join(response.body_stream)
1475
 
        self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
1476
 
 
1477
 
 
1478
 
class TestSmartServerRequestHasRevision(tests.TestCaseWithMemoryTransport):
1479
 
 
1480
 
    def test_missing_revision(self):
1481
 
        """For a missing revision, ('no', ) is returned."""
1482
 
        backing = self.get_transport()
1483
 
        request = smart_repo.SmartServerRequestHasRevision(backing)
1484
 
        self.make_repository('.')
1485
 
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
1486
 
            request.execute('', 'revid'))
1487
 
 
1488
 
    def test_present_revision(self):
1489
 
        """For a present revision, ('yes', ) is returned."""
1490
 
        backing = self.get_transport()
1491
 
        request = smart_repo.SmartServerRequestHasRevision(backing)
1492
 
        tree = self.make_branch_and_memory_tree('.')
1493
 
        tree.lock_write()
1494
 
        tree.add('')
1495
 
        rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1496
 
        r1 = tree.commit('a commit', rev_id=rev_id_utf8)
1497
 
        tree.unlock()
1498
 
        self.assertTrue(tree.branch.repository.has_revision(rev_id_utf8))
1499
 
        self.assertEqual(smart_req.SmartServerResponse(('yes', )),
1500
 
            request.execute('', rev_id_utf8))
1501
 
 
1502
 
 
1503
 
class TestSmartServerRepositoryGatherStats(tests.TestCaseWithMemoryTransport):
1504
 
 
1505
 
    def test_empty_revid(self):
1506
 
        """With an empty revid, we get only size an number and revisions"""
1507
 
        backing = self.get_transport()
1508
 
        request = smart_repo.SmartServerRepositoryGatherStats(backing)
1509
 
        repository = self.make_repository('.')
1510
 
        stats = repository.gather_stats()
1511
 
        expected_body = 'revisions: 0\n'
1512
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
1513
 
                         request.execute('', '', 'no'))
1514
 
 
1515
 
    def test_revid_with_committers(self):
1516
 
        """For a revid we get more infos."""
1517
 
        backing = self.get_transport()
1518
 
        rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1519
 
        request = smart_repo.SmartServerRepositoryGatherStats(backing)
1520
 
        tree = self.make_branch_and_memory_tree('.')
1521
 
        tree.lock_write()
1522
 
        tree.add('')
1523
 
        # Let's build a predictable result
1524
 
        tree.commit('a commit', timestamp=123456.2, timezone=3600)
1525
 
        tree.commit('a commit', timestamp=654321.4, timezone=0,
1526
 
                    rev_id=rev_id_utf8)
1527
 
        tree.unlock()
1528
 
 
1529
 
        stats = tree.branch.repository.gather_stats()
1530
 
        expected_body = ('firstrev: 123456.200 3600\n'
1531
 
                         'latestrev: 654321.400 0\n'
1532
 
                         'revisions: 2\n')
1533
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
1534
 
                         request.execute('',
1535
 
                                         rev_id_utf8, 'no'))
1536
 
 
1537
 
    def test_not_empty_repository_with_committers(self):
1538
 
        """For a revid and requesting committers we get the whole thing."""
1539
 
        backing = self.get_transport()
1540
 
        rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1541
 
        request = smart_repo.SmartServerRepositoryGatherStats(backing)
1542
 
        tree = self.make_branch_and_memory_tree('.')
1543
 
        tree.lock_write()
1544
 
        tree.add('')
1545
 
        # Let's build a predictable result
1546
 
        tree.commit('a commit', timestamp=123456.2, timezone=3600,
1547
 
                    committer='foo')
1548
 
        tree.commit('a commit', timestamp=654321.4, timezone=0,
1549
 
                    committer='bar', rev_id=rev_id_utf8)
1550
 
        tree.unlock()
1551
 
        stats = tree.branch.repository.gather_stats()
1552
 
 
1553
 
        expected_body = ('committers: 2\n'
1554
 
                         'firstrev: 123456.200 3600\n'
1555
 
                         'latestrev: 654321.400 0\n'
1556
 
                         'revisions: 2\n')
1557
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
1558
 
                         request.execute('',
1559
 
                                         rev_id_utf8, 'yes'))
1560
 
 
1561
 
 
1562
 
class TestSmartServerRepositoryIsShared(tests.TestCaseWithMemoryTransport):
1563
 
 
1564
 
    def test_is_shared(self):
1565
 
        """For a shared repository, ('yes', ) is returned."""
1566
 
        backing = self.get_transport()
1567
 
        request = smart_repo.SmartServerRepositoryIsShared(backing)
1568
 
        self.make_repository('.', shared=True)
1569
 
        self.assertEqual(smart_req.SmartServerResponse(('yes', )),
1570
 
            request.execute('', ))
1571
 
 
1572
 
    def test_is_not_shared(self):
1573
 
        """For a shared repository, ('no', ) is returned."""
1574
 
        backing = self.get_transport()
1575
 
        request = smart_repo.SmartServerRepositoryIsShared(backing)
1576
 
        self.make_repository('.', shared=False)
1577
 
        self.assertEqual(smart_req.SmartServerResponse(('no', )),
1578
 
            request.execute('', ))
1579
 
 
1580
 
 
1581
 
class TestSmartServerRepositoryLockWrite(tests.TestCaseWithMemoryTransport):
1582
 
 
1583
 
    def test_lock_write_on_unlocked_repo(self):
1584
 
        backing = self.get_transport()
1585
 
        request = smart_repo.SmartServerRepositoryLockWrite(backing)
1586
 
        repository = self.make_repository('.', format='knit')
1587
 
        response = request.execute('')
1588
 
        nonce = repository.control_files._lock.peek().get('nonce')
1589
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', nonce)), response)
1590
 
        # The repository is now locked.  Verify that with a new repository
1591
 
        # object.
1592
 
        new_repo = repository.bzrdir.open_repository()
1593
 
        self.assertRaises(errors.LockContention, new_repo.lock_write)
1594
 
        # Cleanup
1595
 
        request = smart_repo.SmartServerRepositoryUnlock(backing)
1596
 
        response = request.execute('', nonce)
1597
 
 
1598
 
    def test_lock_write_on_locked_repo(self):
1599
 
        backing = self.get_transport()
1600
 
        request = smart_repo.SmartServerRepositoryLockWrite(backing)
1601
 
        repository = self.make_repository('.', format='knit')
1602
 
        repo_token = repository.lock_write().repository_token
1603
 
        repository.leave_lock_in_place()
1604
 
        repository.unlock()
1605
 
        response = request.execute('')
1606
 
        self.assertEqual(
1607
 
            smart_req.SmartServerResponse(('LockContention',)), response)
1608
 
        # Cleanup
1609
 
        repository.lock_write(repo_token)
1610
 
        repository.dont_leave_lock_in_place()
1611
 
        repository.unlock()
1612
 
 
1613
 
    def test_lock_write_on_readonly_transport(self):
1614
 
        backing = self.get_readonly_transport()
1615
 
        request = smart_repo.SmartServerRepositoryLockWrite(backing)
1616
 
        repository = self.make_repository('.', format='knit')
1617
 
        response = request.execute('')
1618
 
        self.assertFalse(response.is_successful())
1619
 
        self.assertEqual('LockFailed', response.args[0])
1620
 
 
1621
 
 
1622
 
class TestInsertStreamBase(tests.TestCaseWithMemoryTransport):
1623
 
 
1624
 
    def make_empty_byte_stream(self, repo):
1625
 
        byte_stream = smart_repo._stream_to_byte_stream([], repo._format)
1626
 
        return ''.join(byte_stream)
1627
 
 
1628
 
 
1629
 
class TestSmartServerRepositoryInsertStream(TestInsertStreamBase):
1630
 
 
1631
 
    def test_insert_stream_empty(self):
1632
 
        backing = self.get_transport()
1633
 
        request = smart_repo.SmartServerRepositoryInsertStream(backing)
1634
 
        repository = self.make_repository('.')
1635
 
        response = request.execute('', '')
1636
 
        self.assertEqual(None, response)
1637
 
        response = request.do_chunk(self.make_empty_byte_stream(repository))
1638
 
        self.assertEqual(None, response)
1639
 
        response = request.do_end()
1640
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', )), response)
1641
 
 
1642
 
 
1643
 
class TestSmartServerRepositoryInsertStreamLocked(TestInsertStreamBase):
1644
 
 
1645
 
    def test_insert_stream_empty(self):
1646
 
        backing = self.get_transport()
1647
 
        request = smart_repo.SmartServerRepositoryInsertStreamLocked(
1648
 
            backing)
1649
 
        repository = self.make_repository('.', format='knit')
1650
 
        lock_token = repository.lock_write().repository_token
1651
 
        response = request.execute('', '', lock_token)
1652
 
        self.assertEqual(None, response)
1653
 
        response = request.do_chunk(self.make_empty_byte_stream(repository))
1654
 
        self.assertEqual(None, response)
1655
 
        response = request.do_end()
1656
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', )), response)
1657
 
        repository.unlock()
1658
 
 
1659
 
    def test_insert_stream_with_wrong_lock_token(self):
1660
 
        backing = self.get_transport()
1661
 
        request = smart_repo.SmartServerRepositoryInsertStreamLocked(
1662
 
            backing)
1663
 
        repository = self.make_repository('.', format='knit')
1664
 
        lock_token = repository.lock_write().repository_token
1665
 
        self.assertRaises(
1666
 
            errors.TokenMismatch, request.execute, '', '', 'wrong-token')
1667
 
        repository.unlock()
1668
 
 
1669
 
 
1670
 
class TestSmartServerRepositoryUnlock(tests.TestCaseWithMemoryTransport):
1671
 
 
1672
 
    def setUp(self):
1673
 
        tests.TestCaseWithMemoryTransport.setUp(self)
1674
 
 
1675
 
    def test_unlock_on_locked_repo(self):
1676
 
        backing = self.get_transport()
1677
 
        request = smart_repo.SmartServerRepositoryUnlock(backing)
1678
 
        repository = self.make_repository('.', format='knit')
1679
 
        token = repository.lock_write().repository_token
1680
 
        repository.leave_lock_in_place()
1681
 
        repository.unlock()
1682
 
        response = request.execute('', token)
1683
 
        self.assertEqual(
1684
 
            smart_req.SmartServerResponse(('ok',)), response)
1685
 
        # The repository is now unlocked.  Verify that with a new repository
1686
 
        # object.
1687
 
        new_repo = repository.bzrdir.open_repository()
1688
 
        new_repo.lock_write()
1689
 
        new_repo.unlock()
1690
 
 
1691
 
    def test_unlock_on_unlocked_repo(self):
1692
 
        backing = self.get_transport()
1693
 
        request = smart_repo.SmartServerRepositoryUnlock(backing)
1694
 
        repository = self.make_repository('.', format='knit')
1695
 
        response = request.execute('', 'some token')
1696
 
        self.assertEqual(
1697
 
            smart_req.SmartServerResponse(('TokenMismatch',)), response)
1698
 
 
1699
 
 
1700
 
class TestSmartServerIsReadonly(tests.TestCaseWithMemoryTransport):
1701
 
 
1702
 
    def test_is_readonly_no(self):
1703
 
        backing = self.get_transport()
1704
 
        request = smart_req.SmartServerIsReadonly(backing)
1705
 
        response = request.execute()
1706
 
        self.assertEqual(
1707
 
            smart_req.SmartServerResponse(('no',)), response)
1708
 
 
1709
 
    def test_is_readonly_yes(self):
1710
 
        backing = self.get_readonly_transport()
1711
 
        request = smart_req.SmartServerIsReadonly(backing)
1712
 
        response = request.execute()
1713
 
        self.assertEqual(
1714
 
            smart_req.SmartServerResponse(('yes',)), response)
1715
 
 
1716
 
 
1717
 
class TestSmartServerRepositorySetMakeWorkingTrees(
1718
 
    tests.TestCaseWithMemoryTransport):
1719
 
 
1720
 
    def test_set_false(self):
1721
 
        backing = self.get_transport()
1722
 
        repo = self.make_repository('.', shared=True)
1723
 
        repo.set_make_working_trees(True)
1724
 
        request_class = smart_repo.SmartServerRepositorySetMakeWorkingTrees
1725
 
        request = request_class(backing)
1726
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
1727
 
            request.execute('', 'False'))
1728
 
        repo = repo.bzrdir.open_repository()
1729
 
        self.assertFalse(repo.make_working_trees())
1730
 
 
1731
 
    def test_set_true(self):
1732
 
        backing = self.get_transport()
1733
 
        repo = self.make_repository('.', shared=True)
1734
 
        repo.set_make_working_trees(False)
1735
 
        request_class = smart_repo.SmartServerRepositorySetMakeWorkingTrees
1736
 
        request = request_class(backing)
1737
 
        self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
1738
 
            request.execute('', 'True'))
1739
 
        repo = repo.bzrdir.open_repository()
1740
 
        self.assertTrue(repo.make_working_trees())
1741
 
 
1742
 
 
1743
 
class TestSmartServerPackRepositoryAutopack(tests.TestCaseWithTransport):
1744
 
 
1745
 
    def make_repo_needing_autopacking(self, path='.'):
1746
 
        # Make a repo in need of autopacking.
1747
 
        tree = self.make_branch_and_tree('.', format='pack-0.92')
1748
 
        repo = tree.branch.repository
1749
 
        # monkey-patch the pack collection to disable autopacking
1750
 
        repo._pack_collection._max_pack_count = lambda count: count
1751
 
        for x in range(10):
1752
 
            tree.commit('commit %s' % x)
1753
 
        self.assertEqual(10, len(repo._pack_collection.names()))
1754
 
        del repo._pack_collection._max_pack_count
1755
 
        return repo
1756
 
 
1757
 
    def test_autopack_needed(self):
1758
 
        repo = self.make_repo_needing_autopacking()
1759
 
        repo.lock_write()
1760
 
        self.addCleanup(repo.unlock)
1761
 
        backing = self.get_transport()
1762
 
        request = smart_packrepo.SmartServerPackRepositoryAutopack(
1763
 
            backing)
1764
 
        response = request.execute('')
1765
 
        self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
1766
 
        repo._pack_collection.reload_pack_names()
1767
 
        self.assertEqual(1, len(repo._pack_collection.names()))
1768
 
 
1769
 
    def test_autopack_not_needed(self):
1770
 
        tree = self.make_branch_and_tree('.', format='pack-0.92')
1771
 
        repo = tree.branch.repository
1772
 
        repo.lock_write()
1773
 
        self.addCleanup(repo.unlock)
1774
 
        for x in range(9):
1775
 
            tree.commit('commit %s' % x)
1776
 
        backing = self.get_transport()
1777
 
        request = smart_packrepo.SmartServerPackRepositoryAutopack(
1778
 
            backing)
1779
 
        response = request.execute('')
1780
 
        self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
1781
 
        repo._pack_collection.reload_pack_names()
1782
 
        self.assertEqual(9, len(repo._pack_collection.names()))
1783
 
 
1784
 
    def test_autopack_on_nonpack_format(self):
1785
 
        """A request to autopack a non-pack repo is a no-op."""
1786
 
        repo = self.make_repository('.', format='knit')
1787
 
        backing = self.get_transport()
1788
 
        request = smart_packrepo.SmartServerPackRepositoryAutopack(
1789
 
            backing)
1790
 
        response = request.execute('')
1791
 
        self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
1792
 
 
1793
 
 
1794
 
class TestSmartServerVfsGet(tests.TestCaseWithMemoryTransport):
1795
 
 
1796
 
    def test_unicode_path(self):
1797
 
        """VFS requests expect unicode paths to be escaped."""
1798
 
        filename = u'foo\N{INTERROBANG}'
1799
 
        filename_escaped = urlutils.escape(filename)
1800
 
        backing = self.get_transport()
1801
 
        request = vfs.GetRequest(backing)
1802
 
        backing.put_bytes_non_atomic(filename_escaped, 'contents')
1803
 
        self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'contents'),
1804
 
            request.execute(filename_escaped))
1805
 
 
1806
 
 
1807
 
class TestHandlers(tests.TestCase):
1808
 
    """Tests for the request.request_handlers object."""
1809
 
 
1810
 
    def test_all_registrations_exist(self):
1811
 
        """All registered request_handlers can be found."""
1812
 
        # If there's a typo in a register_lazy call, this loop will fail with
1813
 
        # an AttributeError.
1814
 
        for key, item in smart_req.request_handlers.iteritems():
1815
 
            pass
1816
 
 
1817
 
    def assertHandlerEqual(self, verb, handler):
1818
 
        self.assertEqual(smart_req.request_handlers.get(verb), handler)
1819
 
 
1820
 
    def test_registered_methods(self):
1821
 
        """Test that known methods are registered to the correct object."""
1822
 
        self.assertHandlerEqual('Branch.get_config_file',
1823
 
            smart_branch.SmartServerBranchGetConfigFile)
1824
 
        self.assertHandlerEqual('Branch.get_parent',
1825
 
            smart_branch.SmartServerBranchGetParent)
1826
 
        self.assertHandlerEqual('Branch.get_tags_bytes',
1827
 
            smart_branch.SmartServerBranchGetTagsBytes)
1828
 
        self.assertHandlerEqual('Branch.lock_write',
1829
 
            smart_branch.SmartServerBranchRequestLockWrite)
1830
 
        self.assertHandlerEqual('Branch.last_revision_info',
1831
 
            smart_branch.SmartServerBranchRequestLastRevisionInfo)
1832
 
        self.assertHandlerEqual('Branch.revision_history',
1833
 
            smart_branch.SmartServerRequestRevisionHistory)
1834
 
        self.assertHandlerEqual('Branch.set_config_option',
1835
 
            smart_branch.SmartServerBranchRequestSetConfigOption)
1836
 
        self.assertHandlerEqual('Branch.set_last_revision',
1837
 
            smart_branch.SmartServerBranchRequestSetLastRevision)
1838
 
        self.assertHandlerEqual('Branch.set_last_revision_info',
1839
 
            smart_branch.SmartServerBranchRequestSetLastRevisionInfo)
1840
 
        self.assertHandlerEqual('Branch.set_last_revision_ex',
1841
 
            smart_branch.SmartServerBranchRequestSetLastRevisionEx)
1842
 
        self.assertHandlerEqual('Branch.set_parent_location',
1843
 
            smart_branch.SmartServerBranchRequestSetParentLocation)
1844
 
        self.assertHandlerEqual('Branch.unlock',
1845
 
            smart_branch.SmartServerBranchRequestUnlock)
1846
 
        self.assertHandlerEqual('BzrDir.find_repository',
1847
 
            smart_dir.SmartServerRequestFindRepositoryV1)
1848
 
        self.assertHandlerEqual('BzrDir.find_repositoryV2',
1849
 
            smart_dir.SmartServerRequestFindRepositoryV2)
1850
 
        self.assertHandlerEqual('BzrDirFormat.initialize',
1851
 
            smart_dir.SmartServerRequestInitializeBzrDir)
1852
 
        self.assertHandlerEqual('BzrDirFormat.initialize_ex_1.16',
1853
 
            smart_dir.SmartServerRequestBzrDirInitializeEx)
1854
 
        self.assertHandlerEqual('BzrDir.cloning_metadir',
1855
 
            smart_dir.SmartServerBzrDirRequestCloningMetaDir)
1856
 
        self.assertHandlerEqual('BzrDir.get_config_file',
1857
 
            smart_dir.SmartServerBzrDirRequestConfigFile)
1858
 
        self.assertHandlerEqual('BzrDir.open_branch',
1859
 
            smart_dir.SmartServerRequestOpenBranch)
1860
 
        self.assertHandlerEqual('BzrDir.open_branchV2',
1861
 
            smart_dir.SmartServerRequestOpenBranchV2)
1862
 
        self.assertHandlerEqual('BzrDir.open_branchV3',
1863
 
            smart_dir.SmartServerRequestOpenBranchV3)
1864
 
        self.assertHandlerEqual('PackRepository.autopack',
1865
 
            smart_packrepo.SmartServerPackRepositoryAutopack)
1866
 
        self.assertHandlerEqual('Repository.gather_stats',
1867
 
            smart_repo.SmartServerRepositoryGatherStats)
1868
 
        self.assertHandlerEqual('Repository.get_parent_map',
1869
 
            smart_repo.SmartServerRepositoryGetParentMap)
1870
 
        self.assertHandlerEqual('Repository.get_rev_id_for_revno',
1871
 
            smart_repo.SmartServerRepositoryGetRevIdForRevno)
1872
 
        self.assertHandlerEqual('Repository.get_revision_graph',
1873
 
            smart_repo.SmartServerRepositoryGetRevisionGraph)
1874
 
        self.assertHandlerEqual('Repository.get_stream',
1875
 
            smart_repo.SmartServerRepositoryGetStream)
1876
 
        self.assertHandlerEqual('Repository.has_revision',
1877
 
            smart_repo.SmartServerRequestHasRevision)
1878
 
        self.assertHandlerEqual('Repository.insert_stream',
1879
 
            smart_repo.SmartServerRepositoryInsertStream)
1880
 
        self.assertHandlerEqual('Repository.insert_stream_locked',
1881
 
            smart_repo.SmartServerRepositoryInsertStreamLocked)
1882
 
        self.assertHandlerEqual('Repository.is_shared',
1883
 
            smart_repo.SmartServerRepositoryIsShared)
1884
 
        self.assertHandlerEqual('Repository.lock_write',
1885
 
            smart_repo.SmartServerRepositoryLockWrite)
1886
 
        self.assertHandlerEqual('Repository.tarball',
1887
 
            smart_repo.SmartServerRepositoryTarball)
1888
 
        self.assertHandlerEqual('Repository.unlock',
1889
 
            smart_repo.SmartServerRepositoryUnlock)
1890
 
        self.assertHandlerEqual('Transport.is_readonly',
1891
 
            smart_req.SmartServerIsReadonly)