1
# Copyright (C) 2006-2011 Canonical Ltd
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.
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.
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
17
"""Tests for the smart wire/domain protocol.
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
24
Tests for low-level protocol encoding are found in test_smart_transport.
30
branch as _mod_branch,
39
from bzrlib.smart import (
40
branch as smart_branch,
42
repository as smart_repo,
43
packrepository as smart_packrepo,
48
from bzrlib.tests import test_server
49
from bzrlib.transport import (
55
def load_tests(standard_tests, module, loader):
56
"""Multiply tests version and protocol consistency."""
57
# FindRepository tests.
60
"_request_class": smart_dir.SmartServerRequestFindRepositoryV1}),
61
("find_repositoryV2", {
62
"_request_class": smart_dir.SmartServerRequestFindRepositoryV2}),
63
("find_repositoryV3", {
64
"_request_class": smart_dir.SmartServerRequestFindRepositoryV3}),
66
to_adapt, result = tests.split_suite_by_re(standard_tests,
67
"TestSmartServerRequestFindRepository")
68
v2_only, v1_and_2 = tests.split_suite_by_re(to_adapt,
70
tests.multiply_tests(v1_and_2, scenarios, result)
71
# The first scenario is only applicable to v1 protocols, it is deleted
73
tests.multiply_tests(v2_only, scenarios[1:], result)
77
class TestCaseWithChrootedTransport(tests.TestCaseWithTransport):
80
self.vfs_transport_factory = memory.MemoryServer
81
tests.TestCaseWithTransport.setUp(self)
82
self._chroot_server = None
84
def get_transport(self, relpath=None):
85
if self._chroot_server is None:
86
backing_transport = tests.TestCaseWithTransport.get_transport(self)
87
self._chroot_server = chroot.ChrootServer(backing_transport)
88
self.start_server(self._chroot_server)
89
t = transport.get_transport_from_url(self._chroot_server.get_url())
90
if relpath is not None:
95
class TestCaseWithSmartMedium(tests.TestCaseWithMemoryTransport):
98
super(TestCaseWithSmartMedium, self).setUp()
99
# We're allowed to set the transport class here, so that we don't use
100
# the default or a parameterized class, but rather use the
101
# TestCaseWithTransport infrastructure to set up a smart server and
103
self.overrideAttr(self, "transport_server", self.make_transport_server)
105
def make_transport_server(self):
106
return test_server.SmartTCPServer_for_testing('-' + self.id())
108
def get_smart_medium(self):
109
"""Get a smart medium to use in tests."""
110
return self.get_transport().get_smart_medium()
113
class TestByteStreamToStream(tests.TestCase):
115
def test_repeated_substreams_same_kind_are_one_stream(self):
116
# Make a stream - an iterable of bytestrings.
117
stream = [('text', [versionedfile.FulltextContentFactory(('k1',), None,
118
None, 'foo')]),('text', [
119
versionedfile.FulltextContentFactory(('k2',), None, None, 'bar')])]
120
fmt = bzrdir.format_registry.get('pack-0.92')().repository_format
121
bytes = smart_repo._stream_to_byte_stream(stream, fmt)
123
# Iterate the resulting iterable; checking that we get only one stream
125
fmt, stream = smart_repo._byte_stream_to_stream(bytes)
126
for kind, substream in stream:
127
streams.append((kind, list(substream)))
128
self.assertLength(1, streams)
129
self.assertLength(2, streams[0][1])
132
class TestSmartServerResponse(tests.TestCase):
134
def test__eq__(self):
135
self.assertEqual(smart_req.SmartServerResponse(('ok', )),
136
smart_req.SmartServerResponse(('ok', )))
137
self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'body'),
138
smart_req.SmartServerResponse(('ok', ), 'body'))
139
self.assertNotEqual(smart_req.SmartServerResponse(('ok', )),
140
smart_req.SmartServerResponse(('notok', )))
141
self.assertNotEqual(smart_req.SmartServerResponse(('ok', ), 'body'),
142
smart_req.SmartServerResponse(('ok', )))
143
self.assertNotEqual(None,
144
smart_req.SmartServerResponse(('ok', )))
146
def test__str__(self):
147
"""SmartServerResponses can be stringified."""
149
"<SuccessfulSmartServerResponse args=('args',) body='body'>",
150
str(smart_req.SuccessfulSmartServerResponse(('args',), 'body')))
152
"<FailedSmartServerResponse args=('args',) body='body'>",
153
str(smart_req.FailedSmartServerResponse(('args',), 'body')))
156
class TestSmartServerRequest(tests.TestCaseWithMemoryTransport):
158
def test_translate_client_path(self):
159
transport = self.get_transport()
160
request = smart_req.SmartServerRequest(transport, 'foo/')
161
self.assertEqual('./', request.translate_client_path('foo/'))
163
errors.InvalidURLJoin, request.translate_client_path, 'foo/..')
165
errors.PathNotChild, request.translate_client_path, '/')
167
errors.PathNotChild, request.translate_client_path, 'bar/')
168
self.assertEqual('./baz', request.translate_client_path('foo/baz'))
169
e_acute = u'\N{LATIN SMALL LETTER E WITH ACUTE}'.encode('utf-8')
170
self.assertEqual('./' + urlutils.escape(e_acute),
171
request.translate_client_path('foo/' + e_acute))
173
def test_translate_client_path_vfs(self):
174
"""VfsRequests receive escaped paths rather than raw UTF-8."""
175
transport = self.get_transport()
176
request = vfs.VfsRequest(transport, 'foo/')
177
e_acute = u'\N{LATIN SMALL LETTER E WITH ACUTE}'.encode('utf-8')
178
escaped = urlutils.escape('foo/' + e_acute)
179
self.assertEqual('./' + urlutils.escape(e_acute),
180
request.translate_client_path(escaped))
182
def test_transport_from_client_path(self):
183
transport = self.get_transport()
184
request = smart_req.SmartServerRequest(transport, 'foo/')
187
request.transport_from_client_path('foo/').base)
190
class TestSmartServerBzrDirRequestCloningMetaDir(
191
tests.TestCaseWithMemoryTransport):
192
"""Tests for BzrDir.cloning_metadir."""
194
def test_cloning_metadir(self):
195
"""When there is a bzrdir present, the call succeeds."""
196
backing = self.get_transport()
197
dir = self.make_bzrdir('.')
198
local_result = dir.cloning_metadir()
199
request_class = smart_dir.SmartServerBzrDirRequestCloningMetaDir
200
request = request_class(backing)
201
expected = smart_req.SuccessfulSmartServerResponse(
202
(local_result.network_name(),
203
local_result.repository_format.network_name(),
204
('branch', local_result.get_branch_format().network_name())))
205
self.assertEqual(expected, request.execute('', 'False'))
207
def test_cloning_metadir_reference(self):
208
"""The request fails when bzrdir contains a branch reference."""
209
backing = self.get_transport()
210
referenced_branch = self.make_branch('referenced')
211
dir = self.make_bzrdir('.')
212
local_result = dir.cloning_metadir()
213
reference = _mod_branch.BranchReferenceFormat().initialize(
214
dir, target_branch=referenced_branch)
215
reference_url = _mod_branch.BranchReferenceFormat().get_reference(dir)
216
# The server shouldn't try to follow the branch reference, so it's fine
217
# if the referenced branch isn't reachable.
218
backing.rename('referenced', 'moved')
219
request_class = smart_dir.SmartServerBzrDirRequestCloningMetaDir
220
request = request_class(backing)
221
expected = smart_req.FailedSmartServerResponse(('BranchReference',))
222
self.assertEqual(expected, request.execute('', 'False'))
225
class TestSmartServerBzrDirRequestDestroyBranch(
226
tests.TestCaseWithMemoryTransport):
227
"""Tests for BzrDir.destroy_branch."""
229
def test_destroy_branch_default(self):
230
"""The default branch can be removed."""
231
backing = self.get_transport()
232
dir = self.make_branch('.').bzrdir
233
request_class = smart_dir.SmartServerBzrDirRequestDestroyBranch
234
request = request_class(backing)
235
expected = smart_req.SuccessfulSmartServerResponse(('ok',))
236
self.assertEqual(expected, request.execute('', None))
238
def test_destroy_branch_named(self):
239
"""A named branch can be removed."""
240
backing = self.get_transport()
241
dir = self.make_repository('.', format="development-colo").bzrdir
242
dir.create_branch(name="branchname")
243
request_class = smart_dir.SmartServerBzrDirRequestDestroyBranch
244
request = request_class(backing)
245
expected = smart_req.SuccessfulSmartServerResponse(('ok',))
246
self.assertEqual(expected, request.execute('', "branchname"))
248
def test_destroy_branch_missing(self):
249
"""An error is raised if the branch didn't exist."""
250
backing = self.get_transport()
251
dir = self.make_bzrdir('.', format="development-colo")
252
request_class = smart_dir.SmartServerBzrDirRequestDestroyBranch
253
request = request_class(backing)
254
expected = smart_req.FailedSmartServerResponse(('nobranch',), None)
255
self.assertEqual(expected, request.execute('', "branchname"))
258
class TestSmartServerBzrDirRequestHasWorkingTree(
259
tests.TestCaseWithTransport):
260
"""Tests for BzrDir.has_workingtree."""
262
def test_has_workingtree_yes(self):
263
"""A working tree is present."""
264
backing = self.get_transport()
265
dir = self.make_branch_and_tree('.').bzrdir
266
request_class = smart_dir.SmartServerBzrDirRequestHasWorkingTree
267
request = request_class(backing)
268
expected = smart_req.SuccessfulSmartServerResponse(('yes',))
269
self.assertEqual(expected, request.execute(''))
271
def test_has_workingtree_no(self):
272
"""A working tree is missing."""
273
backing = self.get_transport()
274
dir = self.make_bzrdir('.')
275
request_class = smart_dir.SmartServerBzrDirRequestHasWorkingTree
276
request = request_class(backing)
277
expected = smart_req.SuccessfulSmartServerResponse(('no',))
278
self.assertEqual(expected, request.execute(''))
281
class TestSmartServerBzrDirRequestDestroyRepository(
282
tests.TestCaseWithMemoryTransport):
283
"""Tests for BzrDir.destroy_repository."""
285
def test_destroy_repository_default(self):
286
"""The repository can be removed."""
287
backing = self.get_transport()
288
dir = self.make_repository('.').bzrdir
289
request_class = smart_dir.SmartServerBzrDirRequestDestroyRepository
290
request = request_class(backing)
291
expected = smart_req.SuccessfulSmartServerResponse(('ok',))
292
self.assertEqual(expected, request.execute(''))
294
def test_destroy_repository_missing(self):
295
"""An error is raised if the repository didn't exist."""
296
backing = self.get_transport()
297
dir = self.make_bzrdir('.')
298
request_class = smart_dir.SmartServerBzrDirRequestDestroyRepository
299
request = request_class(backing)
300
expected = smart_req.FailedSmartServerResponse(
301
('norepository',), None)
302
self.assertEqual(expected, request.execute(''))
305
class TestSmartServerRequestCreateRepository(tests.TestCaseWithMemoryTransport):
306
"""Tests for BzrDir.create_repository."""
308
def test_makes_repository(self):
309
"""When there is a bzrdir present, the call succeeds."""
310
backing = self.get_transport()
311
self.make_bzrdir('.')
312
request_class = smart_dir.SmartServerRequestCreateRepository
313
request = request_class(backing)
314
reference_bzrdir_format = bzrdir.format_registry.get('pack-0.92')()
315
reference_format = reference_bzrdir_format.repository_format
316
network_name = reference_format.network_name()
317
expected = smart_req.SuccessfulSmartServerResponse(
318
('ok', 'no', 'no', 'no', network_name))
319
self.assertEqual(expected, request.execute('', network_name, 'True'))
322
class TestSmartServerRequestFindRepository(tests.TestCaseWithMemoryTransport):
323
"""Tests for BzrDir.find_repository."""
325
def test_no_repository(self):
326
"""When there is no repository to be found, ('norepository', ) is returned."""
327
backing = self.get_transport()
328
request = self._request_class(backing)
329
self.make_bzrdir('.')
330
self.assertEqual(smart_req.SmartServerResponse(('norepository', )),
333
def test_nonshared_repository(self):
334
# nonshared repositorys only allow 'find' to return a handle when the
335
# path the repository is being searched on is the same as that that
336
# the repository is at.
337
backing = self.get_transport()
338
request = self._request_class(backing)
339
result = self._make_repository_and_result()
340
self.assertEqual(result, request.execute(''))
341
self.make_bzrdir('subdir')
342
self.assertEqual(smart_req.SmartServerResponse(('norepository', )),
343
request.execute('subdir'))
345
def _make_repository_and_result(self, shared=False, format=None):
346
"""Convenience function to setup a repository.
348
:result: The SmartServerResponse to expect when opening it.
350
repo = self.make_repository('.', shared=shared, format=format)
351
if repo.supports_rich_root():
355
if repo._format.supports_tree_reference:
359
if repo._format.supports_external_lookups:
363
if (smart_dir.SmartServerRequestFindRepositoryV3 ==
364
self._request_class):
365
return smart_req.SuccessfulSmartServerResponse(
366
('ok', '', rich_root, subtrees, external,
367
repo._format.network_name()))
368
elif (smart_dir.SmartServerRequestFindRepositoryV2 ==
369
self._request_class):
370
# All tests so far are on formats, and for non-external
372
return smart_req.SuccessfulSmartServerResponse(
373
('ok', '', rich_root, subtrees, external))
375
return smart_req.SuccessfulSmartServerResponse(
376
('ok', '', rich_root, subtrees))
378
def test_shared_repository(self):
379
"""When there is a shared repository, we get 'ok', 'relpath-to-repo'."""
380
backing = self.get_transport()
381
request = self._request_class(backing)
382
result = self._make_repository_and_result(shared=True)
383
self.assertEqual(result, request.execute(''))
384
self.make_bzrdir('subdir')
385
result2 = smart_req.SmartServerResponse(
386
result.args[0:1] + ('..', ) + result.args[2:])
387
self.assertEqual(result2,
388
request.execute('subdir'))
389
self.make_bzrdir('subdir/deeper')
390
result3 = smart_req.SmartServerResponse(
391
result.args[0:1] + ('../..', ) + result.args[2:])
392
self.assertEqual(result3,
393
request.execute('subdir/deeper'))
395
def test_rich_root_and_subtree_encoding(self):
396
"""Test for the format attributes for rich root and subtree support."""
397
backing = self.get_transport()
398
request = self._request_class(backing)
399
result = self._make_repository_and_result(
400
format='dirstate-with-subtree')
401
# check the test will be valid
402
self.assertEqual('yes', result.args[2])
403
self.assertEqual('yes', result.args[3])
404
self.assertEqual(result, request.execute(''))
406
def test_supports_external_lookups_no_v2(self):
407
"""Test for the supports_external_lookups attribute."""
408
backing = self.get_transport()
409
request = self._request_class(backing)
410
result = self._make_repository_and_result(
411
format='dirstate-with-subtree')
412
# check the test will be valid
413
self.assertEqual('no', result.args[4])
414
self.assertEqual(result, request.execute(''))
417
class TestSmartServerBzrDirRequestGetConfigFile(
418
tests.TestCaseWithMemoryTransport):
419
"""Tests for BzrDir.get_config_file."""
421
def test_present(self):
422
backing = self.get_transport()
423
dir = self.make_bzrdir('.')
424
dir.get_config().set_default_stack_on("/")
425
local_result = dir._get_config()._get_config_file().read()
426
request_class = smart_dir.SmartServerBzrDirRequestConfigFile
427
request = request_class(backing)
428
expected = smart_req.SuccessfulSmartServerResponse((), local_result)
429
self.assertEqual(expected, request.execute(''))
431
def test_missing(self):
432
backing = self.get_transport()
433
dir = self.make_bzrdir('.')
434
request_class = smart_dir.SmartServerBzrDirRequestConfigFile
435
request = request_class(backing)
436
expected = smart_req.SuccessfulSmartServerResponse((), '')
437
self.assertEqual(expected, request.execute(''))
440
class TestSmartServerRequestInitializeBzrDir(tests.TestCaseWithMemoryTransport):
442
def test_empty_dir(self):
443
"""Initializing an empty dir should succeed and do it."""
444
backing = self.get_transport()
445
request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
446
self.assertEqual(smart_req.SmartServerResponse(('ok', )),
448
made_dir = bzrdir.BzrDir.open_from_transport(backing)
449
# no branch, tree or repository is expected with the current
451
self.assertRaises(errors.NoWorkingTree, made_dir.open_workingtree)
452
self.assertRaises(errors.NotBranchError, made_dir.open_branch)
453
self.assertRaises(errors.NoRepositoryPresent, made_dir.open_repository)
455
def test_missing_dir(self):
456
"""Initializing a missing directory should fail like the bzrdir api."""
457
backing = self.get_transport()
458
request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
459
self.assertRaises(errors.NoSuchFile,
460
request.execute, 'subdir')
462
def test_initialized_dir(self):
463
"""Initializing an extant bzrdir should fail like the bzrdir api."""
464
backing = self.get_transport()
465
request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
466
self.make_bzrdir('subdir')
467
self.assertRaises(errors.FileExists,
468
request.execute, 'subdir')
471
class TestSmartServerRequestBzrDirInitializeEx(
472
tests.TestCaseWithMemoryTransport):
473
"""Basic tests for BzrDir.initialize_ex_1.16 in the smart server.
475
The main unit tests in test_bzrdir exercise the API comprehensively.
478
def test_empty_dir(self):
479
"""Initializing an empty dir should succeed and do it."""
480
backing = self.get_transport()
481
name = self.make_bzrdir('reference')._format.network_name()
482
request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
484
smart_req.SmartServerResponse(('', '', '', '', '', '', name,
485
'False', '', '', '')),
486
request.execute(name, '', 'True', 'False', 'False', '', '', '', '',
488
made_dir = bzrdir.BzrDir.open_from_transport(backing)
489
# no branch, tree or repository is expected with the current
491
self.assertRaises(errors.NoWorkingTree, made_dir.open_workingtree)
492
self.assertRaises(errors.NotBranchError, made_dir.open_branch)
493
self.assertRaises(errors.NoRepositoryPresent, made_dir.open_repository)
495
def test_missing_dir(self):
496
"""Initializing a missing directory should fail like the bzrdir api."""
497
backing = self.get_transport()
498
name = self.make_bzrdir('reference')._format.network_name()
499
request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
500
self.assertRaises(errors.NoSuchFile, request.execute, name,
501
'subdir/dir', 'False', 'False', 'False', '', '', '', '', 'False')
503
def test_initialized_dir(self):
504
"""Initializing an extant directory should fail like the bzrdir api."""
505
backing = self.get_transport()
506
name = self.make_bzrdir('reference')._format.network_name()
507
request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
508
self.make_bzrdir('subdir')
509
self.assertRaises(errors.FileExists, request.execute, name, 'subdir',
510
'False', 'False', 'False', '', '', '', '', 'False')
513
class TestSmartServerRequestOpenBzrDir(tests.TestCaseWithMemoryTransport):
515
def test_no_directory(self):
516
backing = self.get_transport()
517
request = smart_dir.SmartServerRequestOpenBzrDir(backing)
518
self.assertEqual(smart_req.SmartServerResponse(('no', )),
519
request.execute('does-not-exist'))
521
def test_empty_directory(self):
522
backing = self.get_transport()
523
backing.mkdir('empty')
524
request = smart_dir.SmartServerRequestOpenBzrDir(backing)
525
self.assertEqual(smart_req.SmartServerResponse(('no', )),
526
request.execute('empty'))
528
def test_outside_root_client_path(self):
529
backing = self.get_transport()
530
request = smart_dir.SmartServerRequestOpenBzrDir(backing,
531
root_client_path='root')
532
self.assertEqual(smart_req.SmartServerResponse(('no', )),
533
request.execute('not-root'))
536
class TestSmartServerRequestOpenBzrDir_2_1(tests.TestCaseWithMemoryTransport):
538
def test_no_directory(self):
539
backing = self.get_transport()
540
request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
541
self.assertEqual(smart_req.SmartServerResponse(('no', )),
542
request.execute('does-not-exist'))
544
def test_empty_directory(self):
545
backing = self.get_transport()
546
backing.mkdir('empty')
547
request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
548
self.assertEqual(smart_req.SmartServerResponse(('no', )),
549
request.execute('empty'))
551
def test_present_without_workingtree(self):
552
backing = self.get_transport()
553
request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
554
self.make_bzrdir('.')
555
self.assertEqual(smart_req.SmartServerResponse(('yes', 'no')),
558
def test_outside_root_client_path(self):
559
backing = self.get_transport()
560
request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing,
561
root_client_path='root')
562
self.assertEqual(smart_req.SmartServerResponse(('no',)),
563
request.execute('not-root'))
566
class TestSmartServerRequestOpenBzrDir_2_1_disk(TestCaseWithChrootedTransport):
568
def test_present_with_workingtree(self):
569
self.vfs_transport_factory = test_server.LocalURLServer
570
backing = self.get_transport()
571
request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
572
bd = self.make_bzrdir('.')
573
bd.create_repository()
575
bd.create_workingtree()
576
self.assertEqual(smart_req.SmartServerResponse(('yes', 'yes')),
580
class TestSmartServerRequestOpenBranch(TestCaseWithChrootedTransport):
582
def test_no_branch(self):
583
"""When there is no branch, ('nobranch', ) is returned."""
584
backing = self.get_transport()
585
request = smart_dir.SmartServerRequestOpenBranch(backing)
586
self.make_bzrdir('.')
587
self.assertEqual(smart_req.SmartServerResponse(('nobranch', )),
590
def test_branch(self):
591
"""When there is a branch, 'ok' is returned."""
592
backing = self.get_transport()
593
request = smart_dir.SmartServerRequestOpenBranch(backing)
594
self.make_branch('.')
595
self.assertEqual(smart_req.SmartServerResponse(('ok', '')),
598
def test_branch_reference(self):
599
"""When there is a branch reference, the reference URL is returned."""
600
self.vfs_transport_factory = test_server.LocalURLServer
601
backing = self.get_transport()
602
request = smart_dir.SmartServerRequestOpenBranch(backing)
603
branch = self.make_branch('branch')
604
checkout = branch.create_checkout('reference',lightweight=True)
605
reference_url = _mod_branch.BranchReferenceFormat().get_reference(
607
self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
608
self.assertEqual(smart_req.SmartServerResponse(('ok', reference_url)),
609
request.execute('reference'))
611
def test_notification_on_branch_from_repository(self):
612
"""When there is a repository, the error should return details."""
613
backing = self.get_transport()
614
request = smart_dir.SmartServerRequestOpenBranch(backing)
615
repo = self.make_repository('.')
616
self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
620
class TestSmartServerRequestOpenBranchV2(TestCaseWithChrootedTransport):
622
def test_no_branch(self):
623
"""When there is no branch, ('nobranch', ) is returned."""
624
backing = self.get_transport()
625
self.make_bzrdir('.')
626
request = smart_dir.SmartServerRequestOpenBranchV2(backing)
627
self.assertEqual(smart_req.SmartServerResponse(('nobranch', )),
630
def test_branch(self):
631
"""When there is a branch, 'ok' is returned."""
632
backing = self.get_transport()
633
expected = self.make_branch('.')._format.network_name()
634
request = smart_dir.SmartServerRequestOpenBranchV2(backing)
635
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
636
('branch', expected)),
639
def test_branch_reference(self):
640
"""When there is a branch reference, the reference URL is returned."""
641
self.vfs_transport_factory = test_server.LocalURLServer
642
backing = self.get_transport()
643
request = smart_dir.SmartServerRequestOpenBranchV2(backing)
644
branch = self.make_branch('branch')
645
checkout = branch.create_checkout('reference',lightweight=True)
646
reference_url = _mod_branch.BranchReferenceFormat().get_reference(
648
self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
649
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
650
('ref', reference_url)),
651
request.execute('reference'))
653
def test_stacked_branch(self):
654
"""Opening a stacked branch does not open the stacked-on branch."""
655
trunk = self.make_branch('trunk')
656
feature = self.make_branch('feature')
657
feature.set_stacked_on_url(trunk.base)
659
_mod_branch.Branch.hooks.install_named_hook(
660
'open', opened_branches.append, None)
661
backing = self.get_transport()
662
request = smart_dir.SmartServerRequestOpenBranchV2(backing)
665
response = request.execute('feature')
667
request.teardown_jail()
668
expected_format = feature._format.network_name()
669
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
670
('branch', expected_format)),
672
self.assertLength(1, opened_branches)
674
def test_notification_on_branch_from_repository(self):
675
"""When there is a repository, the error should return details."""
676
backing = self.get_transport()
677
request = smart_dir.SmartServerRequestOpenBranchV2(backing)
678
repo = self.make_repository('.')
679
self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
683
class TestSmartServerRequestOpenBranchV3(TestCaseWithChrootedTransport):
685
def test_no_branch(self):
686
"""When there is no branch, ('nobranch', ) is returned."""
687
backing = self.get_transport()
688
self.make_bzrdir('.')
689
request = smart_dir.SmartServerRequestOpenBranchV3(backing)
690
self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
693
def test_branch(self):
694
"""When there is a branch, 'ok' is returned."""
695
backing = self.get_transport()
696
expected = self.make_branch('.')._format.network_name()
697
request = smart_dir.SmartServerRequestOpenBranchV3(backing)
698
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
699
('branch', expected)),
702
def test_branch_reference(self):
703
"""When there is a branch reference, the reference URL is returned."""
704
self.vfs_transport_factory = test_server.LocalURLServer
705
backing = self.get_transport()
706
request = smart_dir.SmartServerRequestOpenBranchV3(backing)
707
branch = self.make_branch('branch')
708
checkout = branch.create_checkout('reference',lightweight=True)
709
reference_url = _mod_branch.BranchReferenceFormat().get_reference(
711
self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
712
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
713
('ref', reference_url)),
714
request.execute('reference'))
716
def test_stacked_branch(self):
717
"""Opening a stacked branch does not open the stacked-on branch."""
718
trunk = self.make_branch('trunk')
719
feature = self.make_branch('feature')
720
feature.set_stacked_on_url(trunk.base)
722
_mod_branch.Branch.hooks.install_named_hook(
723
'open', opened_branches.append, None)
724
backing = self.get_transport()
725
request = smart_dir.SmartServerRequestOpenBranchV3(backing)
728
response = request.execute('feature')
730
request.teardown_jail()
731
expected_format = feature._format.network_name()
732
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
733
('branch', expected_format)),
735
self.assertLength(1, opened_branches)
737
def test_notification_on_branch_from_repository(self):
738
"""When there is a repository, the error should return details."""
739
backing = self.get_transport()
740
request = smart_dir.SmartServerRequestOpenBranchV3(backing)
741
repo = self.make_repository('.')
742
self.assertEqual(smart_req.SmartServerResponse(
743
('nobranch', 'location is a repository')),
747
class TestSmartServerRequestRevisionHistory(tests.TestCaseWithMemoryTransport):
749
def test_empty(self):
750
"""For an empty branch, the body is empty."""
751
backing = self.get_transport()
752
request = smart_branch.SmartServerRequestRevisionHistory(backing)
753
self.make_branch('.')
754
self.assertEqual(smart_req.SmartServerResponse(('ok', ), ''),
757
def test_not_empty(self):
758
"""For a non-empty branch, the body is empty."""
759
backing = self.get_transport()
760
request = smart_branch.SmartServerRequestRevisionHistory(backing)
761
tree = self.make_branch_and_memory_tree('.')
764
r1 = tree.commit('1st commit')
765
r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
768
smart_req.SmartServerResponse(('ok', ), ('\x00'.join([r1, r2]))),
772
class TestSmartServerBranchRequest(tests.TestCaseWithMemoryTransport):
774
def test_no_branch(self):
775
"""When there is a bzrdir and no branch, NotBranchError is raised."""
776
backing = self.get_transport()
777
request = smart_branch.SmartServerBranchRequest(backing)
778
self.make_bzrdir('.')
779
self.assertRaises(errors.NotBranchError,
782
def test_branch_reference(self):
783
"""When there is a branch reference, NotBranchError is raised."""
784
backing = self.get_transport()
785
request = smart_branch.SmartServerBranchRequest(backing)
786
branch = self.make_branch('branch')
787
checkout = branch.create_checkout('reference',lightweight=True)
788
self.assertRaises(errors.NotBranchError,
789
request.execute, 'checkout')
792
class TestSmartServerBranchRequestLastRevisionInfo(
793
tests.TestCaseWithMemoryTransport):
795
def test_empty(self):
796
"""For an empty branch, the result is ('ok', '0', 'null:')."""
797
backing = self.get_transport()
798
request = smart_branch.SmartServerBranchRequestLastRevisionInfo(backing)
799
self.make_branch('.')
800
self.assertEqual(smart_req.SmartServerResponse(('ok', '0', 'null:')),
803
def test_not_empty(self):
804
"""For a non-empty branch, the result is ('ok', 'revno', 'revid')."""
805
backing = self.get_transport()
806
request = smart_branch.SmartServerBranchRequestLastRevisionInfo(backing)
807
tree = self.make_branch_and_memory_tree('.')
810
rev_id_utf8 = u'\xc8'.encode('utf-8')
811
r1 = tree.commit('1st commit')
812
r2 = tree.commit('2nd commit', rev_id=rev_id_utf8)
815
smart_req.SmartServerResponse(('ok', '2', rev_id_utf8)),
819
class TestSmartServerBranchRequestRevisionIdToRevno(
820
tests.TestCaseWithMemoryTransport):
823
backing = self.get_transport()
824
request = smart_branch.SmartServerBranchRequestRevisionIdToRevno(
826
self.make_branch('.')
827
self.assertEqual(smart_req.SmartServerResponse(('ok', '0')),
828
request.execute('', 'null:'))
830
def test_simple(self):
831
backing = self.get_transport()
832
request = smart_branch.SmartServerBranchRequestRevisionIdToRevno(
834
tree = self.make_branch_and_memory_tree('.')
837
r1 = tree.commit('1st commit')
840
smart_req.SmartServerResponse(('ok', '1')),
841
request.execute('', r1))
843
def test_not_found(self):
844
backing = self.get_transport()
845
request = smart_branch.SmartServerBranchRequestRevisionIdToRevno(
847
branch = self.make_branch('.')
849
smart_req.FailedSmartServerResponse(
850
('NoSuchRevision', 'idontexist')),
851
request.execute('', 'idontexist'))
854
class TestSmartServerBranchRequestGetConfigFile(
855
tests.TestCaseWithMemoryTransport):
857
def test_default(self):
858
"""With no file, we get empty content."""
859
backing = self.get_transport()
860
request = smart_branch.SmartServerBranchGetConfigFile(backing)
861
branch = self.make_branch('.')
862
# there should be no file by default
864
self.assertEqual(smart_req.SmartServerResponse(('ok', ), content),
867
def test_with_content(self):
868
# SmartServerBranchGetConfigFile should return the content from
869
# branch.control_files.get('branch.conf') for now - in the future it may
870
# perform more complex processing.
871
backing = self.get_transport()
872
request = smart_branch.SmartServerBranchGetConfigFile(backing)
873
branch = self.make_branch('.')
874
branch._transport.put_bytes('branch.conf', 'foo bar baz')
875
self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'foo bar baz'),
879
class TestLockedBranch(tests.TestCaseWithMemoryTransport):
881
def get_lock_tokens(self, branch):
882
branch_token = branch.lock_write().branch_token
883
repo_token = branch.repository.lock_write().repository_token
884
branch.repository.unlock()
885
return branch_token, repo_token
888
class TestSmartServerBranchRequestPutConfigFile(TestLockedBranch):
890
def test_with_content(self):
891
backing = self.get_transport()
892
request = smart_branch.SmartServerBranchPutConfigFile(backing)
893
branch = self.make_branch('.')
894
branch_token, repo_token = self.get_lock_tokens(branch)
895
self.assertIs(None, request.execute('', branch_token, repo_token))
897
smart_req.SmartServerResponse(('ok', )),
898
request.do_body('foo bar baz'))
900
branch.control_transport.get_bytes('branch.conf'),
905
class TestSmartServerBranchRequestSetConfigOption(TestLockedBranch):
907
def test_value_name(self):
908
branch = self.make_branch('.')
909
request = smart_branch.SmartServerBranchRequestSetConfigOption(
910
branch.bzrdir.root_transport)
911
branch_token, repo_token = self.get_lock_tokens(branch)
912
config = branch._get_config()
913
result = request.execute('', branch_token, repo_token, 'bar', 'foo',
915
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
916
self.assertEqual('bar', config.get_option('foo'))
920
def test_value_name_section(self):
921
branch = self.make_branch('.')
922
request = smart_branch.SmartServerBranchRequestSetConfigOption(
923
branch.bzrdir.root_transport)
924
branch_token, repo_token = self.get_lock_tokens(branch)
925
config = branch._get_config()
926
result = request.execute('', branch_token, repo_token, 'bar', 'foo',
928
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
929
self.assertEqual('bar', config.get_option('foo', 'gam'))
934
class TestSmartServerBranchRequestSetConfigOptionDict(TestLockedBranch):
937
TestLockedBranch.setUp(self)
938
# A dict with non-ascii keys and values to exercise unicode
940
self.encoded_value_dict = (
941
'd5:ascii1:a11:unicode \xe2\x8c\x9a3:\xe2\x80\xbde')
943
'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'}
945
def test_value_name(self):
946
branch = self.make_branch('.')
947
request = smart_branch.SmartServerBranchRequestSetConfigOptionDict(
948
branch.bzrdir.root_transport)
949
branch_token, repo_token = self.get_lock_tokens(branch)
950
config = branch._get_config()
951
result = request.execute('', branch_token, repo_token,
952
self.encoded_value_dict, 'foo', '')
953
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
954
self.assertEqual(self.value_dict, config.get_option('foo'))
958
def test_value_name_section(self):
959
branch = self.make_branch('.')
960
request = smart_branch.SmartServerBranchRequestSetConfigOptionDict(
961
branch.bzrdir.root_transport)
962
branch_token, repo_token = self.get_lock_tokens(branch)
963
config = branch._get_config()
964
result = request.execute('', branch_token, repo_token,
965
self.encoded_value_dict, 'foo', 'gam')
966
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
967
self.assertEqual(self.value_dict, config.get_option('foo', 'gam'))
972
class TestSmartServerBranchRequestSetTagsBytes(TestLockedBranch):
973
# Only called when the branch format and tags match [yay factory
974
# methods] so only need to test straight forward cases.
976
def test_set_bytes(self):
977
base_branch = self.make_branch('base')
978
tag_bytes = base_branch._get_tags_bytes()
979
# get_lock_tokens takes out a lock.
980
branch_token, repo_token = self.get_lock_tokens(base_branch)
981
request = smart_branch.SmartServerBranchSetTagsBytes(
982
self.get_transport())
983
response = request.execute('base', branch_token, repo_token)
984
self.assertEqual(None, response)
985
response = request.do_chunk(tag_bytes)
986
self.assertEqual(None, response)
987
response = request.do_end()
989
smart_req.SuccessfulSmartServerResponse(()), response)
992
def test_lock_failed(self):
993
base_branch = self.make_branch('base')
994
base_branch.lock_write()
995
tag_bytes = base_branch._get_tags_bytes()
996
request = smart_branch.SmartServerBranchSetTagsBytes(
997
self.get_transport())
998
self.assertRaises(errors.TokenMismatch, request.execute,
999
'base', 'wrong token', 'wrong token')
1000
# The request handler will keep processing the message parts, so even
1001
# if the request fails immediately do_chunk and do_end are still
1003
request.do_chunk(tag_bytes)
1005
base_branch.unlock()
1009
class SetLastRevisionTestBase(TestLockedBranch):
1010
"""Base test case for verbs that implement set_last_revision."""
1013
tests.TestCaseWithMemoryTransport.setUp(self)
1014
backing_transport = self.get_transport()
1015
self.request = self.request_class(backing_transport)
1016
self.tree = self.make_branch_and_memory_tree('.')
1018
def lock_branch(self):
1019
return self.get_lock_tokens(self.tree.branch)
1021
def unlock_branch(self):
1022
self.tree.branch.unlock()
1024
def set_last_revision(self, revision_id, revno):
1025
branch_token, repo_token = self.lock_branch()
1026
response = self._set_last_revision(
1027
revision_id, revno, branch_token, repo_token)
1028
self.unlock_branch()
1031
def assertRequestSucceeds(self, revision_id, revno):
1032
response = self.set_last_revision(revision_id, revno)
1033
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
1037
class TestSetLastRevisionVerbMixin(object):
1038
"""Mixin test case for verbs that implement set_last_revision."""
1040
def test_set_null_to_null(self):
1041
"""An empty branch can have its last revision set to 'null:'."""
1042
self.assertRequestSucceeds('null:', 0)
1044
def test_NoSuchRevision(self):
1045
"""If the revision_id is not present, the verb returns NoSuchRevision.
1047
revision_id = 'non-existent revision'
1048
self.assertEqual(smart_req.FailedSmartServerResponse(('NoSuchRevision',
1050
self.set_last_revision(revision_id, 1))
1052
def make_tree_with_two_commits(self):
1053
self.tree.lock_write()
1055
rev_id_utf8 = u'\xc8'.encode('utf-8')
1056
r1 = self.tree.commit('1st commit', rev_id=rev_id_utf8)
1057
r2 = self.tree.commit('2nd commit', rev_id='rev-2')
1060
def test_branch_last_revision_info_is_updated(self):
1061
"""A branch's tip can be set to a revision that is present in its
1064
# Make a branch with an empty revision history, but two revisions in
1066
self.make_tree_with_two_commits()
1067
rev_id_utf8 = u'\xc8'.encode('utf-8')
1068
self.tree.branch.set_last_revision_info(0, 'null:')
1070
(0, 'null:'), self.tree.branch.last_revision_info())
1071
# We can update the branch to a revision that is present in the
1073
self.assertRequestSucceeds(rev_id_utf8, 1)
1075
(1, rev_id_utf8), self.tree.branch.last_revision_info())
1077
def test_branch_last_revision_info_rewind(self):
1078
"""A branch's tip can be set to a revision that is an ancestor of the
1081
self.make_tree_with_two_commits()
1082
rev_id_utf8 = u'\xc8'.encode('utf-8')
1084
(2, 'rev-2'), self.tree.branch.last_revision_info())
1085
self.assertRequestSucceeds(rev_id_utf8, 1)
1087
(1, rev_id_utf8), self.tree.branch.last_revision_info())
1089
def test_TipChangeRejected(self):
1090
"""If a pre_change_branch_tip hook raises TipChangeRejected, the verb
1091
returns TipChangeRejected.
1093
rejection_message = u'rejection message\N{INTERROBANG}'
1094
def hook_that_rejects(params):
1095
raise errors.TipChangeRejected(rejection_message)
1096
_mod_branch.Branch.hooks.install_named_hook(
1097
'pre_change_branch_tip', hook_that_rejects, None)
1099
smart_req.FailedSmartServerResponse(
1100
('TipChangeRejected', rejection_message.encode('utf-8'))),
1101
self.set_last_revision('null:', 0))
1104
class TestSmartServerBranchRequestSetLastRevision(
1105
SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
1106
"""Tests for Branch.set_last_revision verb."""
1108
request_class = smart_branch.SmartServerBranchRequestSetLastRevision
1110
def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
1111
return self.request.execute(
1112
'', branch_token, repo_token, revision_id)
1115
class TestSmartServerBranchRequestSetLastRevisionInfo(
1116
SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
1117
"""Tests for Branch.set_last_revision_info verb."""
1119
request_class = smart_branch.SmartServerBranchRequestSetLastRevisionInfo
1121
def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
1122
return self.request.execute(
1123
'', branch_token, repo_token, revno, revision_id)
1125
def test_NoSuchRevision(self):
1126
"""Branch.set_last_revision_info does not have to return
1127
NoSuchRevision if the revision_id is absent.
1129
raise tests.TestNotApplicable()
1132
class TestSmartServerBranchRequestSetLastRevisionEx(
1133
SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
1134
"""Tests for Branch.set_last_revision_ex verb."""
1136
request_class = smart_branch.SmartServerBranchRequestSetLastRevisionEx
1138
def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
1139
return self.request.execute(
1140
'', branch_token, repo_token, revision_id, 0, 0)
1142
def assertRequestSucceeds(self, revision_id, revno):
1143
response = self.set_last_revision(revision_id, revno)
1145
smart_req.SuccessfulSmartServerResponse(('ok', revno, revision_id)),
1148
def test_branch_last_revision_info_rewind(self):
1149
"""A branch's tip can be set to a revision that is an ancestor of the
1150
current tip, but only if allow_overwrite_descendant is passed.
1152
self.make_tree_with_two_commits()
1153
rev_id_utf8 = u'\xc8'.encode('utf-8')
1155
(2, 'rev-2'), self.tree.branch.last_revision_info())
1156
# If allow_overwrite_descendant flag is 0, then trying to set the tip
1157
# to an older revision ID has no effect.
1158
branch_token, repo_token = self.lock_branch()
1159
response = self.request.execute(
1160
'', branch_token, repo_token, rev_id_utf8, 0, 0)
1162
smart_req.SuccessfulSmartServerResponse(('ok', 2, 'rev-2')),
1165
(2, 'rev-2'), self.tree.branch.last_revision_info())
1167
# If allow_overwrite_descendant flag is 1, then setting the tip to an
1169
response = self.request.execute(
1170
'', branch_token, repo_token, rev_id_utf8, 0, 1)
1172
smart_req.SuccessfulSmartServerResponse(('ok', 1, rev_id_utf8)),
1174
self.unlock_branch()
1176
(1, rev_id_utf8), self.tree.branch.last_revision_info())
1178
def make_branch_with_divergent_history(self):
1179
"""Make a branch with divergent history in its repo.
1181
The branch's tip will be 'child-2', and the repo will also contain
1182
'child-1', which diverges from a common base revision.
1184
self.tree.lock_write()
1186
r1 = self.tree.commit('1st commit')
1187
revno_1, revid_1 = self.tree.branch.last_revision_info()
1188
r2 = self.tree.commit('2nd commit', rev_id='child-1')
1189
# Undo the second commit
1190
self.tree.branch.set_last_revision_info(revno_1, revid_1)
1191
self.tree.set_parent_ids([revid_1])
1192
# Make a new second commit, child-2. child-2 has diverged from
1194
new_r2 = self.tree.commit('2nd commit', rev_id='child-2')
1197
def test_not_allow_diverged(self):
1198
"""If allow_diverged is not passed, then setting a divergent history
1199
returns a Diverged error.
1201
self.make_branch_with_divergent_history()
1203
smart_req.FailedSmartServerResponse(('Diverged',)),
1204
self.set_last_revision('child-1', 2))
1205
# The branch tip was not changed.
1206
self.assertEqual('child-2', self.tree.branch.last_revision())
1208
def test_allow_diverged(self):
1209
"""If allow_diverged is passed, then setting a divergent history
1212
self.make_branch_with_divergent_history()
1213
branch_token, repo_token = self.lock_branch()
1214
response = self.request.execute(
1215
'', branch_token, repo_token, 'child-1', 1, 0)
1217
smart_req.SuccessfulSmartServerResponse(('ok', 2, 'child-1')),
1219
self.unlock_branch()
1220
# The branch tip was changed.
1221
self.assertEqual('child-1', self.tree.branch.last_revision())
1224
class TestSmartServerBranchBreakLock(tests.TestCaseWithMemoryTransport):
1226
def test_lock_to_break(self):
1227
base_branch = self.make_branch('base')
1228
request = smart_branch.SmartServerBranchBreakLock(
1229
self.get_transport())
1230
base_branch.lock_write()
1232
smart_req.SuccessfulSmartServerResponse(('ok', ), None),
1233
request.execute('base'))
1235
def test_nothing_to_break(self):
1236
base_branch = self.make_branch('base')
1237
request = smart_branch.SmartServerBranchBreakLock(
1238
self.get_transport())
1240
smart_req.SuccessfulSmartServerResponse(('ok', ), None),
1241
request.execute('base'))
1244
class TestSmartServerBranchRequestGetParent(tests.TestCaseWithMemoryTransport):
1246
def test_get_parent_none(self):
1247
base_branch = self.make_branch('base')
1248
request = smart_branch.SmartServerBranchGetParent(self.get_transport())
1249
response = request.execute('base')
1251
smart_req.SuccessfulSmartServerResponse(('',)), response)
1253
def test_get_parent_something(self):
1254
base_branch = self.make_branch('base')
1255
base_branch.set_parent(self.get_url('foo'))
1256
request = smart_branch.SmartServerBranchGetParent(self.get_transport())
1257
response = request.execute('base')
1259
smart_req.SuccessfulSmartServerResponse(("../foo",)),
1263
class TestSmartServerBranchRequestSetParent(TestLockedBranch):
1265
def test_set_parent_none(self):
1266
branch = self.make_branch('base', format="1.9")
1268
branch._set_parent_location('foo')
1270
request = smart_branch.SmartServerBranchRequestSetParentLocation(
1271
self.get_transport())
1272
branch_token, repo_token = self.get_lock_tokens(branch)
1274
response = request.execute('base', branch_token, repo_token, '')
1277
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), response)
1278
self.assertEqual(None, branch.get_parent())
1280
def test_set_parent_something(self):
1281
branch = self.make_branch('base', format="1.9")
1282
request = smart_branch.SmartServerBranchRequestSetParentLocation(
1283
self.get_transport())
1284
branch_token, repo_token = self.get_lock_tokens(branch)
1286
response = request.execute('base', branch_token, repo_token,
1290
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), response)
1291
self.assertEqual('http://bar/', branch.get_parent())
1294
class TestSmartServerBranchRequestGetTagsBytes(
1295
tests.TestCaseWithMemoryTransport):
1296
# Only called when the branch format and tags match [yay factory
1297
# methods] so only need to test straight forward cases.
1299
def test_get_bytes(self):
1300
base_branch = self.make_branch('base')
1301
request = smart_branch.SmartServerBranchGetTagsBytes(
1302
self.get_transport())
1303
response = request.execute('base')
1305
smart_req.SuccessfulSmartServerResponse(('',)), response)
1308
class TestSmartServerBranchRequestGetStackedOnURL(tests.TestCaseWithMemoryTransport):
1310
def test_get_stacked_on_url(self):
1311
base_branch = self.make_branch('base', format='1.6')
1312
stacked_branch = self.make_branch('stacked', format='1.6')
1313
# typically should be relative
1314
stacked_branch.set_stacked_on_url('../base')
1315
request = smart_branch.SmartServerBranchRequestGetStackedOnURL(
1316
self.get_transport())
1317
response = request.execute('stacked')
1319
smart_req.SmartServerResponse(('ok', '../base')),
1323
class TestSmartServerBranchRequestLockWrite(TestLockedBranch):
1326
tests.TestCaseWithMemoryTransport.setUp(self)
1328
def test_lock_write_on_unlocked_branch(self):
1329
backing = self.get_transport()
1330
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1331
branch = self.make_branch('.', format='knit')
1332
repository = branch.repository
1333
response = request.execute('')
1334
branch_nonce = branch.control_files._lock.peek().get('nonce')
1335
repository_nonce = repository.control_files._lock.peek().get('nonce')
1336
self.assertEqual(smart_req.SmartServerResponse(
1337
('ok', branch_nonce, repository_nonce)),
1339
# The branch (and associated repository) is now locked. Verify that
1340
# with a new branch object.
1341
new_branch = repository.bzrdir.open_branch()
1342
self.assertRaises(errors.LockContention, new_branch.lock_write)
1344
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1345
response = request.execute('', branch_nonce, repository_nonce)
1347
def test_lock_write_on_locked_branch(self):
1348
backing = self.get_transport()
1349
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1350
branch = self.make_branch('.')
1351
branch_token = branch.lock_write().branch_token
1352
branch.leave_lock_in_place()
1354
response = request.execute('')
1356
smart_req.SmartServerResponse(('LockContention',)), response)
1358
branch.lock_write(branch_token)
1359
branch.dont_leave_lock_in_place()
1362
def test_lock_write_with_tokens_on_locked_branch(self):
1363
backing = self.get_transport()
1364
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1365
branch = self.make_branch('.', format='knit')
1366
branch_token, repo_token = self.get_lock_tokens(branch)
1367
branch.leave_lock_in_place()
1368
branch.repository.leave_lock_in_place()
1370
response = request.execute('',
1371
branch_token, repo_token)
1373
smart_req.SmartServerResponse(('ok', branch_token, repo_token)),
1376
branch.repository.lock_write(repo_token)
1377
branch.repository.dont_leave_lock_in_place()
1378
branch.repository.unlock()
1379
branch.lock_write(branch_token)
1380
branch.dont_leave_lock_in_place()
1383
def test_lock_write_with_mismatched_tokens_on_locked_branch(self):
1384
backing = self.get_transport()
1385
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1386
branch = self.make_branch('.', format='knit')
1387
branch_token, repo_token = self.get_lock_tokens(branch)
1388
branch.leave_lock_in_place()
1389
branch.repository.leave_lock_in_place()
1391
response = request.execute('',
1392
branch_token+'xxx', repo_token)
1394
smart_req.SmartServerResponse(('TokenMismatch',)), response)
1396
branch.repository.lock_write(repo_token)
1397
branch.repository.dont_leave_lock_in_place()
1398
branch.repository.unlock()
1399
branch.lock_write(branch_token)
1400
branch.dont_leave_lock_in_place()
1403
def test_lock_write_on_locked_repo(self):
1404
backing = self.get_transport()
1405
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1406
branch = self.make_branch('.', format='knit')
1407
repo = branch.repository
1408
repo_token = repo.lock_write().repository_token
1409
repo.leave_lock_in_place()
1411
response = request.execute('')
1413
smart_req.SmartServerResponse(('LockContention',)), response)
1415
repo.lock_write(repo_token)
1416
repo.dont_leave_lock_in_place()
1419
def test_lock_write_on_readonly_transport(self):
1420
backing = self.get_readonly_transport()
1421
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1422
branch = self.make_branch('.')
1423
root = self.get_transport().clone('/')
1424
path = urlutils.relative_url(root.base, self.get_transport().base)
1425
response = request.execute(path)
1426
error_name, lock_str, why_str = response.args
1427
self.assertFalse(response.is_successful())
1428
self.assertEqual('LockFailed', error_name)
1431
class TestSmartServerBranchRequestGetPhysicalLockStatus(TestLockedBranch):
1434
tests.TestCaseWithMemoryTransport.setUp(self)
1436
def test_true(self):
1437
backing = self.get_transport()
1438
request = smart_branch.SmartServerBranchRequestGetPhysicalLockStatus(
1440
branch = self.make_branch('.')
1441
branch_token, repo_token = self.get_lock_tokens(branch)
1442
self.assertEquals(True, branch.get_physical_lock_status())
1443
response = request.execute('')
1445
smart_req.SmartServerResponse(('yes',)), response)
1448
def test_false(self):
1449
backing = self.get_transport()
1450
request = smart_branch.SmartServerBranchRequestGetPhysicalLockStatus(
1452
branch = self.make_branch('.')
1453
self.assertEquals(False, branch.get_physical_lock_status())
1454
response = request.execute('')
1456
smart_req.SmartServerResponse(('no',)), response)
1459
class TestSmartServerBranchRequestUnlock(TestLockedBranch):
1462
tests.TestCaseWithMemoryTransport.setUp(self)
1464
def test_unlock_on_locked_branch_and_repo(self):
1465
backing = self.get_transport()
1466
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1467
branch = self.make_branch('.', format='knit')
1469
branch_token, repo_token = self.get_lock_tokens(branch)
1470
# Unlock the branch (and repo) object, leaving the physical locks
1472
branch.leave_lock_in_place()
1473
branch.repository.leave_lock_in_place()
1475
response = request.execute('',
1476
branch_token, repo_token)
1478
smart_req.SmartServerResponse(('ok',)), response)
1479
# The branch is now unlocked. Verify that with a new branch
1481
new_branch = branch.bzrdir.open_branch()
1482
new_branch.lock_write()
1485
def test_unlock_on_unlocked_branch_unlocked_repo(self):
1486
backing = self.get_transport()
1487
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1488
branch = self.make_branch('.', format='knit')
1489
response = request.execute(
1490
'', 'branch token', 'repo token')
1492
smart_req.SmartServerResponse(('TokenMismatch',)), response)
1494
def test_unlock_on_unlocked_branch_locked_repo(self):
1495
backing = self.get_transport()
1496
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1497
branch = self.make_branch('.', format='knit')
1498
# Lock the repository.
1499
repo_token = branch.repository.lock_write().repository_token
1500
branch.repository.leave_lock_in_place()
1501
branch.repository.unlock()
1502
# Issue branch lock_write request on the unlocked branch (with locked
1504
response = request.execute('', 'branch token', repo_token)
1506
smart_req.SmartServerResponse(('TokenMismatch',)), response)
1508
branch.repository.lock_write(repo_token)
1509
branch.repository.dont_leave_lock_in_place()
1510
branch.repository.unlock()
1513
class TestSmartServerRepositoryRequest(tests.TestCaseWithMemoryTransport):
1515
def test_no_repository(self):
1516
"""Raise NoRepositoryPresent when there is a bzrdir and no repo."""
1517
# we test this using a shared repository above the named path,
1518
# thus checking the right search logic is used - that is, that
1519
# its the exact path being looked at and the server is not
1521
backing = self.get_transport()
1522
request = smart_repo.SmartServerRepositoryRequest(backing)
1523
self.make_repository('.', shared=True)
1524
self.make_bzrdir('subdir')
1525
self.assertRaises(errors.NoRepositoryPresent,
1526
request.execute, 'subdir')
1529
class TestSmartServerRepositoryAddSignatureText(tests.TestCaseWithMemoryTransport):
1531
def test_add_text(self):
1532
backing = self.get_transport()
1533
request = smart_repo.SmartServerRepositoryAddSignatureText(backing)
1534
tree = self.make_branch_and_memory_tree('.')
1535
write_token = tree.lock_write()
1536
self.addCleanup(tree.unlock)
1538
tree.commit("Message", rev_id='rev1')
1539
tree.branch.repository.start_write_group()
1540
write_group_tokens = tree.branch.repository.suspend_write_group()
1541
self.assertEqual(None, request.execute('', write_token,
1542
write_group_tokens, 'rev1'))
1543
response = request.do_body('somesignature')
1544
self.assertTrue(response.is_successful())
1545
self.assertEqual(response.args[0], 'ok')
1546
write_group_tokens = response.args[1:]
1547
tree.branch.repository.resume_write_group(write_group_tokens)
1548
tree.branch.repository.commit_write_group()
1550
self.assertEqual("somesignature",
1551
tree.branch.repository.get_signature_text("rev1"))
1554
class TestSmartServerRepositoryAllRevisionIds(
1555
tests.TestCaseWithMemoryTransport):
1557
def test_empty(self):
1558
"""An empty body should be returned for an empty repository."""
1559
backing = self.get_transport()
1560
request = smart_repo.SmartServerRepositoryAllRevisionIds(backing)
1561
self.make_repository('.')
1563
smart_req.SuccessfulSmartServerResponse(("ok", ), ""),
1564
request.execute(''))
1566
def test_some_revisions(self):
1567
"""An empty body should be returned for an empty repository."""
1568
backing = self.get_transport()
1569
request = smart_repo.SmartServerRepositoryAllRevisionIds(backing)
1570
tree = self.make_branch_and_memory_tree('.')
1573
tree.commit(rev_id='origineel', message="message")
1574
tree.commit(rev_id='nog-een-revisie', message="message")
1577
smart_req.SuccessfulSmartServerResponse(("ok", ),
1578
"origineel\nnog-een-revisie"),
1579
request.execute(''))
1582
class TestSmartServerRepositoryBreakLock(tests.TestCaseWithMemoryTransport):
1584
def test_lock_to_break(self):
1585
backing = self.get_transport()
1586
request = smart_repo.SmartServerRepositoryBreakLock(backing)
1587
tree = self.make_branch_and_memory_tree('.')
1588
tree.branch.repository.lock_write()
1590
smart_req.SuccessfulSmartServerResponse(('ok', ), None),
1591
request.execute(''))
1593
def test_nothing_to_break(self):
1594
backing = self.get_transport()
1595
request = smart_repo.SmartServerRepositoryBreakLock(backing)
1596
tree = self.make_branch_and_memory_tree('.')
1598
smart_req.SuccessfulSmartServerResponse(('ok', ), None),
1599
request.execute(''))
1602
class TestSmartServerRepositoryGetParentMap(tests.TestCaseWithMemoryTransport):
1604
def test_trivial_bzipped(self):
1605
# This tests that the wire encoding is actually bzipped
1606
backing = self.get_transport()
1607
request = smart_repo.SmartServerRepositoryGetParentMap(backing)
1608
tree = self.make_branch_and_memory_tree('.')
1610
self.assertEqual(None,
1611
request.execute('', 'missing-id'))
1612
# Note that it returns a body that is bzipped.
1614
smart_req.SuccessfulSmartServerResponse(('ok', ), bz2.compress('')),
1615
request.do_body('\n\n0\n'))
1617
def test_trivial_include_missing(self):
1618
backing = self.get_transport()
1619
request = smart_repo.SmartServerRepositoryGetParentMap(backing)
1620
tree = self.make_branch_and_memory_tree('.')
1622
self.assertEqual(None,
1623
request.execute('', 'missing-id', 'include-missing:'))
1625
smart_req.SuccessfulSmartServerResponse(('ok', ),
1626
bz2.compress('missing:missing-id')),
1627
request.do_body('\n\n0\n'))
1630
class TestSmartServerRepositoryGetRevisionGraph(
1631
tests.TestCaseWithMemoryTransport):
1633
def test_none_argument(self):
1634
backing = self.get_transport()
1635
request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1636
tree = self.make_branch_and_memory_tree('.')
1639
r1 = tree.commit('1st commit')
1640
r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1643
# the lines of revision_id->revision_parent_list has no guaranteed
1644
# order coming out of a dict, so sort both our test and response
1645
lines = sorted([' '.join([r2, r1]), r1])
1646
response = request.execute('', '')
1647
response.body = '\n'.join(sorted(response.body.split('\n')))
1650
smart_req.SmartServerResponse(('ok', ), '\n'.join(lines)), response)
1652
def test_specific_revision_argument(self):
1653
backing = self.get_transport()
1654
request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1655
tree = self.make_branch_and_memory_tree('.')
1658
rev_id_utf8 = u'\xc9'.encode('utf-8')
1659
r1 = tree.commit('1st commit', rev_id=rev_id_utf8)
1660
r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1663
self.assertEqual(smart_req.SmartServerResponse(('ok', ), rev_id_utf8),
1664
request.execute('', rev_id_utf8))
1666
def test_no_such_revision(self):
1667
backing = self.get_transport()
1668
request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1669
tree = self.make_branch_and_memory_tree('.')
1672
r1 = tree.commit('1st commit')
1675
# Note that it still returns body (of zero bytes).
1676
self.assertEqual(smart_req.SmartServerResponse(
1677
('nosuchrevision', 'missingrevision', ), ''),
1678
request.execute('', 'missingrevision'))
1681
class TestSmartServerRepositoryGetRevIdForRevno(
1682
tests.TestCaseWithMemoryTransport):
1684
def test_revno_found(self):
1685
backing = self.get_transport()
1686
request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1687
tree = self.make_branch_and_memory_tree('.')
1690
rev1_id_utf8 = u'\xc8'.encode('utf-8')
1691
rev2_id_utf8 = u'\xc9'.encode('utf-8')
1692
tree.commit('1st commit', rev_id=rev1_id_utf8)
1693
tree.commit('2nd commit', rev_id=rev2_id_utf8)
1696
self.assertEqual(smart_req.SmartServerResponse(('ok', rev1_id_utf8)),
1697
request.execute('', 1, (2, rev2_id_utf8)))
1699
def test_known_revid_missing(self):
1700
backing = self.get_transport()
1701
request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1702
repo = self.make_repository('.')
1704
smart_req.FailedSmartServerResponse(('nosuchrevision', 'ghost')),
1705
request.execute('', 1, (2, 'ghost')))
1707
def test_history_incomplete(self):
1708
backing = self.get_transport()
1709
request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1710
parent = self.make_branch_and_memory_tree('parent', format='1.9')
1712
parent.add([''], ['TREE_ROOT'])
1713
r1 = parent.commit(message='first commit')
1714
r2 = parent.commit(message='second commit')
1716
local = self.make_branch_and_memory_tree('local', format='1.9')
1717
local.branch.pull(parent.branch)
1718
local.set_parent_ids([r2])
1719
r3 = local.commit(message='local commit')
1720
local.branch.create_clone_on_transport(
1721
self.get_transport('stacked'), stacked_on=self.get_url('parent'))
1723
smart_req.SmartServerResponse(('history-incomplete', 2, r2)),
1724
request.execute('stacked', 1, (3, r3)))
1727
class GetStreamTestBase(tests.TestCaseWithMemoryTransport):
1729
def make_two_commit_repo(self):
1730
tree = self.make_branch_and_memory_tree('.')
1733
r1 = tree.commit('1st commit')
1734
r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1736
repo = tree.branch.repository
1740
class TestSmartServerRepositoryGetStream(GetStreamTestBase):
1742
def test_ancestry_of(self):
1743
"""The search argument may be a 'ancestry-of' some heads'."""
1744
backing = self.get_transport()
1745
request = smart_repo.SmartServerRepositoryGetStream(backing)
1746
repo, r1, r2 = self.make_two_commit_repo()
1747
fetch_spec = ['ancestry-of', r2]
1748
lines = '\n'.join(fetch_spec)
1749
request.execute('', repo._format.network_name())
1750
response = request.do_body(lines)
1751
self.assertEqual(('ok',), response.args)
1752
stream_bytes = ''.join(response.body_stream)
1753
self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
1755
def test_search(self):
1756
"""The search argument may be a 'search' of some explicit keys."""
1757
backing = self.get_transport()
1758
request = smart_repo.SmartServerRepositoryGetStream(backing)
1759
repo, r1, r2 = self.make_two_commit_repo()
1760
fetch_spec = ['search', '%s %s' % (r1, r2), 'null:', '2']
1761
lines = '\n'.join(fetch_spec)
1762
request.execute('', repo._format.network_name())
1763
response = request.do_body(lines)
1764
self.assertEqual(('ok',), response.args)
1765
stream_bytes = ''.join(response.body_stream)
1766
self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
1768
def test_search_everything(self):
1769
"""A search of 'everything' returns a stream."""
1770
backing = self.get_transport()
1771
request = smart_repo.SmartServerRepositoryGetStream_1_19(backing)
1772
repo, r1, r2 = self.make_two_commit_repo()
1773
serialised_fetch_spec = 'everything'
1774
request.execute('', repo._format.network_name())
1775
response = request.do_body(serialised_fetch_spec)
1776
self.assertEqual(('ok',), response.args)
1777
stream_bytes = ''.join(response.body_stream)
1778
self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
1781
class TestSmartServerRequestHasRevision(tests.TestCaseWithMemoryTransport):
1783
def test_missing_revision(self):
1784
"""For a missing revision, ('no', ) is returned."""
1785
backing = self.get_transport()
1786
request = smart_repo.SmartServerRequestHasRevision(backing)
1787
self.make_repository('.')
1788
self.assertEqual(smart_req.SmartServerResponse(('no', )),
1789
request.execute('', 'revid'))
1791
def test_present_revision(self):
1792
"""For a present revision, ('yes', ) is returned."""
1793
backing = self.get_transport()
1794
request = smart_repo.SmartServerRequestHasRevision(backing)
1795
tree = self.make_branch_and_memory_tree('.')
1798
rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1799
r1 = tree.commit('a commit', rev_id=rev_id_utf8)
1801
self.assertTrue(tree.branch.repository.has_revision(rev_id_utf8))
1802
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
1803
request.execute('', rev_id_utf8))
1806
class TestSmartServerRequestHasSignatureForRevisionId(
1807
tests.TestCaseWithMemoryTransport):
1809
def test_missing_revision(self):
1810
"""For a missing revision, NoSuchRevision is returned."""
1811
backing = self.get_transport()
1812
request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
1814
self.make_repository('.')
1816
smart_req.FailedSmartServerResponse(
1817
('nosuchrevision', 'revid'), None),
1818
request.execute('', 'revid'))
1820
def test_missing_signature(self):
1821
"""For a missing signature, ('no', ) is returned."""
1822
backing = self.get_transport()
1823
request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
1825
tree = self.make_branch_and_memory_tree('.')
1828
r1 = tree.commit('a commit', rev_id='A')
1830
self.assertTrue(tree.branch.repository.has_revision('A'))
1831
self.assertEqual(smart_req.SmartServerResponse(('no', )),
1832
request.execute('', 'A'))
1834
def test_present_signature(self):
1835
"""For a present signature, ('yes', ) is returned."""
1836
backing = self.get_transport()
1837
request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
1839
strategy = gpg.LoopbackGPGStrategy(None)
1840
tree = self.make_branch_and_memory_tree('.')
1843
r1 = tree.commit('a commit', rev_id='A')
1844
tree.branch.repository.start_write_group()
1845
tree.branch.repository.sign_revision('A', strategy)
1846
tree.branch.repository.commit_write_group()
1848
self.assertTrue(tree.branch.repository.has_revision('A'))
1849
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
1850
request.execute('', 'A'))
1853
class TestSmartServerRepositoryGatherStats(tests.TestCaseWithMemoryTransport):
1855
def test_empty_revid(self):
1856
"""With an empty revid, we get only size an number and revisions"""
1857
backing = self.get_transport()
1858
request = smart_repo.SmartServerRepositoryGatherStats(backing)
1859
repository = self.make_repository('.')
1860
stats = repository.gather_stats()
1861
expected_body = 'revisions: 0\n'
1862
self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
1863
request.execute('', '', 'no'))
1865
def test_revid_with_committers(self):
1866
"""For a revid we get more infos."""
1867
backing = self.get_transport()
1868
rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1869
request = smart_repo.SmartServerRepositoryGatherStats(backing)
1870
tree = self.make_branch_and_memory_tree('.')
1873
# Let's build a predictable result
1874
tree.commit('a commit', timestamp=123456.2, timezone=3600)
1875
tree.commit('a commit', timestamp=654321.4, timezone=0,
1879
stats = tree.branch.repository.gather_stats()
1880
expected_body = ('firstrev: 123456.200 3600\n'
1881
'latestrev: 654321.400 0\n'
1883
self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
1887
def test_not_empty_repository_with_committers(self):
1888
"""For a revid and requesting committers we get the whole thing."""
1889
backing = self.get_transport()
1890
rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1891
request = smart_repo.SmartServerRepositoryGatherStats(backing)
1892
tree = self.make_branch_and_memory_tree('.')
1895
# Let's build a predictable result
1896
tree.commit('a commit', timestamp=123456.2, timezone=3600,
1898
tree.commit('a commit', timestamp=654321.4, timezone=0,
1899
committer='bar', rev_id=rev_id_utf8)
1901
stats = tree.branch.repository.gather_stats()
1903
expected_body = ('committers: 2\n'
1904
'firstrev: 123456.200 3600\n'
1905
'latestrev: 654321.400 0\n'
1907
self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
1909
rev_id_utf8, 'yes'))
1911
def test_unknown_revid(self):
1912
"""An unknown revision id causes a 'nosuchrevision' error."""
1913
backing = self.get_transport()
1914
request = smart_repo.SmartServerRepositoryGatherStats(backing)
1915
repository = self.make_repository('.')
1916
expected_body = 'revisions: 0\n'
1918
smart_req.FailedSmartServerResponse(
1919
('nosuchrevision', 'mia'), None),
1920
request.execute('', 'mia', 'yes'))
1923
class TestSmartServerRepositoryIsShared(tests.TestCaseWithMemoryTransport):
1925
def test_is_shared(self):
1926
"""For a shared repository, ('yes', ) is returned."""
1927
backing = self.get_transport()
1928
request = smart_repo.SmartServerRepositoryIsShared(backing)
1929
self.make_repository('.', shared=True)
1930
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
1931
request.execute('', ))
1933
def test_is_not_shared(self):
1934
"""For a shared repository, ('no', ) is returned."""
1935
backing = self.get_transport()
1936
request = smart_repo.SmartServerRepositoryIsShared(backing)
1937
self.make_repository('.', shared=False)
1938
self.assertEqual(smart_req.SmartServerResponse(('no', )),
1939
request.execute('', ))
1942
class TestSmartServerRepositoryMakeWorkingTrees(
1943
tests.TestCaseWithMemoryTransport):
1945
def test_make_working_trees(self):
1946
"""For a repository with working trees, ('yes', ) is returned."""
1947
backing = self.get_transport()
1948
request = smart_repo.SmartServerRepositoryMakeWorkingTrees(backing)
1949
r = self.make_repository('.')
1950
r.set_make_working_trees(True)
1951
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
1952
request.execute('', ))
1954
def test_is_not_shared(self):
1955
"""For a repository with working trees, ('no', ) is returned."""
1956
backing = self.get_transport()
1957
request = smart_repo.SmartServerRepositoryMakeWorkingTrees(backing)
1958
r = self.make_repository('.')
1959
r.set_make_working_trees(False)
1960
self.assertEqual(smart_req.SmartServerResponse(('no', )),
1961
request.execute('', ))
1964
class TestSmartServerRepositoryLockWrite(tests.TestCaseWithMemoryTransport):
1966
def test_lock_write_on_unlocked_repo(self):
1967
backing = self.get_transport()
1968
request = smart_repo.SmartServerRepositoryLockWrite(backing)
1969
repository = self.make_repository('.', format='knit')
1970
response = request.execute('')
1971
nonce = repository.control_files._lock.peek().get('nonce')
1972
self.assertEqual(smart_req.SmartServerResponse(('ok', nonce)), response)
1973
# The repository is now locked. Verify that with a new repository
1975
new_repo = repository.bzrdir.open_repository()
1976
self.assertRaises(errors.LockContention, new_repo.lock_write)
1978
request = smart_repo.SmartServerRepositoryUnlock(backing)
1979
response = request.execute('', nonce)
1981
def test_lock_write_on_locked_repo(self):
1982
backing = self.get_transport()
1983
request = smart_repo.SmartServerRepositoryLockWrite(backing)
1984
repository = self.make_repository('.', format='knit')
1985
repo_token = repository.lock_write().repository_token
1986
repository.leave_lock_in_place()
1988
response = request.execute('')
1990
smart_req.SmartServerResponse(('LockContention',)), response)
1992
repository.lock_write(repo_token)
1993
repository.dont_leave_lock_in_place()
1996
def test_lock_write_on_readonly_transport(self):
1997
backing = self.get_readonly_transport()
1998
request = smart_repo.SmartServerRepositoryLockWrite(backing)
1999
repository = self.make_repository('.', format='knit')
2000
response = request.execute('')
2001
self.assertFalse(response.is_successful())
2002
self.assertEqual('LockFailed', response.args[0])
2005
class TestInsertStreamBase(tests.TestCaseWithMemoryTransport):
2007
def make_empty_byte_stream(self, repo):
2008
byte_stream = smart_repo._stream_to_byte_stream([], repo._format)
2009
return ''.join(byte_stream)
2012
class TestSmartServerRepositoryInsertStream(TestInsertStreamBase):
2014
def test_insert_stream_empty(self):
2015
backing = self.get_transport()
2016
request = smart_repo.SmartServerRepositoryInsertStream(backing)
2017
repository = self.make_repository('.')
2018
response = request.execute('', '')
2019
self.assertEqual(None, response)
2020
response = request.do_chunk(self.make_empty_byte_stream(repository))
2021
self.assertEqual(None, response)
2022
response = request.do_end()
2023
self.assertEqual(smart_req.SmartServerResponse(('ok', )), response)
2026
class TestSmartServerRepositoryInsertStreamLocked(TestInsertStreamBase):
2028
def test_insert_stream_empty(self):
2029
backing = self.get_transport()
2030
request = smart_repo.SmartServerRepositoryInsertStreamLocked(
2032
repository = self.make_repository('.', format='knit')
2033
lock_token = repository.lock_write().repository_token
2034
response = request.execute('', '', lock_token)
2035
self.assertEqual(None, response)
2036
response = request.do_chunk(self.make_empty_byte_stream(repository))
2037
self.assertEqual(None, response)
2038
response = request.do_end()
2039
self.assertEqual(smart_req.SmartServerResponse(('ok', )), response)
2042
def test_insert_stream_with_wrong_lock_token(self):
2043
backing = self.get_transport()
2044
request = smart_repo.SmartServerRepositoryInsertStreamLocked(
2046
repository = self.make_repository('.', format='knit')
2047
lock_token = repository.lock_write().repository_token
2049
errors.TokenMismatch, request.execute, '', '', 'wrong-token')
2053
class TestSmartServerRepositoryUnlock(tests.TestCaseWithMemoryTransport):
2056
tests.TestCaseWithMemoryTransport.setUp(self)
2058
def test_unlock_on_locked_repo(self):
2059
backing = self.get_transport()
2060
request = smart_repo.SmartServerRepositoryUnlock(backing)
2061
repository = self.make_repository('.', format='knit')
2062
token = repository.lock_write().repository_token
2063
repository.leave_lock_in_place()
2065
response = request.execute('', token)
2067
smart_req.SmartServerResponse(('ok',)), response)
2068
# The repository is now unlocked. Verify that with a new repository
2070
new_repo = repository.bzrdir.open_repository()
2071
new_repo.lock_write()
2074
def test_unlock_on_unlocked_repo(self):
2075
backing = self.get_transport()
2076
request = smart_repo.SmartServerRepositoryUnlock(backing)
2077
repository = self.make_repository('.', format='knit')
2078
response = request.execute('', 'some token')
2080
smart_req.SmartServerResponse(('TokenMismatch',)), response)
2083
class TestSmartServerRepositoryGetPhysicalLockStatus(
2084
tests.TestCaseWithTransport):
2086
def test_with_write_lock(self):
2087
backing = self.get_transport()
2088
repo = self.make_repository('.')
2089
self.addCleanup(repo.lock_write().unlock)
2090
# lock_write() doesn't necessarily actually take a physical
2092
if repo.get_physical_lock_status():
2096
request_class = smart_repo.SmartServerRepositoryGetPhysicalLockStatus
2097
request = request_class(backing)
2098
self.assertEqual(smart_req.SuccessfulSmartServerResponse((expected,)),
2099
request.execute('', ))
2101
def test_without_write_lock(self):
2102
backing = self.get_transport()
2103
repo = self.make_repository('.')
2104
self.assertEquals(False, repo.get_physical_lock_status())
2105
request_class = smart_repo.SmartServerRepositoryGetPhysicalLockStatus
2106
request = request_class(backing)
2107
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('no',)),
2108
request.execute('', ))
2111
class TestSmartServerIsReadonly(tests.TestCaseWithMemoryTransport):
2113
def test_is_readonly_no(self):
2114
backing = self.get_transport()
2115
request = smart_req.SmartServerIsReadonly(backing)
2116
response = request.execute()
2118
smart_req.SmartServerResponse(('no',)), response)
2120
def test_is_readonly_yes(self):
2121
backing = self.get_readonly_transport()
2122
request = smart_req.SmartServerIsReadonly(backing)
2123
response = request.execute()
2125
smart_req.SmartServerResponse(('yes',)), response)
2128
class TestSmartServerRepositorySetMakeWorkingTrees(
2129
tests.TestCaseWithMemoryTransport):
2131
def test_set_false(self):
2132
backing = self.get_transport()
2133
repo = self.make_repository('.', shared=True)
2134
repo.set_make_working_trees(True)
2135
request_class = smart_repo.SmartServerRepositorySetMakeWorkingTrees
2136
request = request_class(backing)
2137
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2138
request.execute('', 'False'))
2139
repo = repo.bzrdir.open_repository()
2140
self.assertFalse(repo.make_working_trees())
2142
def test_set_true(self):
2143
backing = self.get_transport()
2144
repo = self.make_repository('.', shared=True)
2145
repo.set_make_working_trees(False)
2146
request_class = smart_repo.SmartServerRepositorySetMakeWorkingTrees
2147
request = request_class(backing)
2148
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2149
request.execute('', 'True'))
2150
repo = repo.bzrdir.open_repository()
2151
self.assertTrue(repo.make_working_trees())
2154
class TestSmartServerRepositoryGetSerializerFormat(
2155
tests.TestCaseWithMemoryTransport):
2157
def test_get_serializer_format(self):
2158
backing = self.get_transport()
2159
repo = self.make_repository('.', format='2a')
2160
request_class = smart_repo.SmartServerRepositoryGetSerializerFormat
2161
request = request_class(backing)
2163
smart_req.SuccessfulSmartServerResponse(('ok', '10')),
2164
request.execute(''))
2167
class TestSmartServerRepositoryWriteGroup(
2168
tests.TestCaseWithMemoryTransport):
2170
def test_start_write_group(self):
2171
backing = self.get_transport()
2172
repo = self.make_repository('.')
2173
lock_token = repo.lock_write().repository_token
2174
self.addCleanup(repo.unlock)
2175
request_class = smart_repo.SmartServerRepositoryStartWriteGroup
2176
request = request_class(backing)
2177
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok', [])),
2178
request.execute('', lock_token))
2180
def test_start_write_group_unsuspendable(self):
2181
backing = self.get_transport()
2182
repo = self.make_repository('.', format='knit')
2183
lock_token = repo.lock_write().repository_token
2184
self.addCleanup(repo.unlock)
2185
request_class = smart_repo.SmartServerRepositoryStartWriteGroup
2186
request = request_class(backing)
2188
smart_req.FailedSmartServerResponse(('UnsuspendableWriteGroup',)),
2189
request.execute('', lock_token))
2191
def test_commit_write_group(self):
2192
backing = self.get_transport()
2193
repo = self.make_repository('.')
2194
lock_token = repo.lock_write().repository_token
2195
self.addCleanup(repo.unlock)
2196
repo.start_write_group()
2197
tokens = repo.suspend_write_group()
2198
request_class = smart_repo.SmartServerRepositoryCommitWriteGroup
2199
request = request_class(backing)
2200
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2201
request.execute('', lock_token, tokens))
2203
def test_abort_write_group(self):
2204
backing = self.get_transport()
2205
repo = self.make_repository('.')
2206
lock_token = repo.lock_write().repository_token
2207
repo.start_write_group()
2208
tokens = repo.suspend_write_group()
2209
self.addCleanup(repo.unlock)
2210
request_class = smart_repo.SmartServerRepositoryAbortWriteGroup
2211
request = request_class(backing)
2212
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2213
request.execute('', lock_token, tokens))
2215
def test_check_write_group(self):
2216
backing = self.get_transport()
2217
repo = self.make_repository('.')
2218
lock_token = repo.lock_write().repository_token
2219
repo.start_write_group()
2220
tokens = repo.suspend_write_group()
2221
self.addCleanup(repo.unlock)
2222
request_class = smart_repo.SmartServerRepositoryCheckWriteGroup
2223
request = request_class(backing)
2224
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2225
request.execute('', lock_token, tokens))
2227
def test_check_write_group_invalid(self):
2228
backing = self.get_transport()
2229
repo = self.make_repository('.')
2230
lock_token = repo.lock_write().repository_token
2231
self.addCleanup(repo.unlock)
2232
request_class = smart_repo.SmartServerRepositoryCheckWriteGroup
2233
request = request_class(backing)
2234
self.assertEqual(smart_req.FailedSmartServerResponse(
2235
('UnresumableWriteGroup', ['random'],
2236
'Malformed write group token')),
2237
request.execute('', lock_token, ["random"]))
2240
class TestSmartServerPackRepositoryAutopack(tests.TestCaseWithTransport):
2242
def make_repo_needing_autopacking(self, path='.'):
2243
# Make a repo in need of autopacking.
2244
tree = self.make_branch_and_tree('.', format='pack-0.92')
2245
repo = tree.branch.repository
2246
# monkey-patch the pack collection to disable autopacking
2247
repo._pack_collection._max_pack_count = lambda count: count
2249
tree.commit('commit %s' % x)
2250
self.assertEqual(10, len(repo._pack_collection.names()))
2251
del repo._pack_collection._max_pack_count
2254
def test_autopack_needed(self):
2255
repo = self.make_repo_needing_autopacking()
2257
self.addCleanup(repo.unlock)
2258
backing = self.get_transport()
2259
request = smart_packrepo.SmartServerPackRepositoryAutopack(
2261
response = request.execute('')
2262
self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
2263
repo._pack_collection.reload_pack_names()
2264
self.assertEqual(1, len(repo._pack_collection.names()))
2266
def test_autopack_not_needed(self):
2267
tree = self.make_branch_and_tree('.', format='pack-0.92')
2268
repo = tree.branch.repository
2270
self.addCleanup(repo.unlock)
2272
tree.commit('commit %s' % x)
2273
backing = self.get_transport()
2274
request = smart_packrepo.SmartServerPackRepositoryAutopack(
2276
response = request.execute('')
2277
self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
2278
repo._pack_collection.reload_pack_names()
2279
self.assertEqual(9, len(repo._pack_collection.names()))
2281
def test_autopack_on_nonpack_format(self):
2282
"""A request to autopack a non-pack repo is a no-op."""
2283
repo = self.make_repository('.', format='knit')
2284
backing = self.get_transport()
2285
request = smart_packrepo.SmartServerPackRepositoryAutopack(
2287
response = request.execute('')
2288
self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
2291
class TestSmartServerVfsGet(tests.TestCaseWithMemoryTransport):
2293
def test_unicode_path(self):
2294
"""VFS requests expect unicode paths to be escaped."""
2295
filename = u'foo\N{INTERROBANG}'
2296
filename_escaped = urlutils.escape(filename)
2297
backing = self.get_transport()
2298
request = vfs.GetRequest(backing)
2299
backing.put_bytes_non_atomic(filename_escaped, 'contents')
2300
self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'contents'),
2301
request.execute(filename_escaped))
2304
class TestHandlers(tests.TestCase):
2305
"""Tests for the request.request_handlers object."""
2307
def test_all_registrations_exist(self):
2308
"""All registered request_handlers can be found."""
2309
# If there's a typo in a register_lazy call, this loop will fail with
2310
# an AttributeError.
2311
for key, item in smart_req.request_handlers.iteritems():
2314
def assertHandlerEqual(self, verb, handler):
2315
self.assertEqual(smart_req.request_handlers.get(verb), handler)
2317
def test_registered_methods(self):
2318
"""Test that known methods are registered to the correct object."""
2319
self.assertHandlerEqual('Branch.break_lock',
2320
smart_branch.SmartServerBranchBreakLock)
2321
self.assertHandlerEqual('Branch.get_config_file',
2322
smart_branch.SmartServerBranchGetConfigFile)
2323
self.assertHandlerEqual('Branch.put_config_file',
2324
smart_branch.SmartServerBranchPutConfigFile)
2325
self.assertHandlerEqual('Branch.get_parent',
2326
smart_branch.SmartServerBranchGetParent)
2327
self.assertHandlerEqual('Branch.get_physical_lock_status',
2328
smart_branch.SmartServerBranchRequestGetPhysicalLockStatus)
2329
self.assertHandlerEqual('Branch.get_tags_bytes',
2330
smart_branch.SmartServerBranchGetTagsBytes)
2331
self.assertHandlerEqual('Branch.lock_write',
2332
smart_branch.SmartServerBranchRequestLockWrite)
2333
self.assertHandlerEqual('Branch.last_revision_info',
2334
smart_branch.SmartServerBranchRequestLastRevisionInfo)
2335
self.assertHandlerEqual('Branch.revision_history',
2336
smart_branch.SmartServerRequestRevisionHistory)
2337
self.assertHandlerEqual('Branch.revision_id_to_revno',
2338
smart_branch.SmartServerBranchRequestRevisionIdToRevno)
2339
self.assertHandlerEqual('Branch.set_config_option',
2340
smart_branch.SmartServerBranchRequestSetConfigOption)
2341
self.assertHandlerEqual('Branch.set_last_revision',
2342
smart_branch.SmartServerBranchRequestSetLastRevision)
2343
self.assertHandlerEqual('Branch.set_last_revision_info',
2344
smart_branch.SmartServerBranchRequestSetLastRevisionInfo)
2345
self.assertHandlerEqual('Branch.set_last_revision_ex',
2346
smart_branch.SmartServerBranchRequestSetLastRevisionEx)
2347
self.assertHandlerEqual('Branch.set_parent_location',
2348
smart_branch.SmartServerBranchRequestSetParentLocation)
2349
self.assertHandlerEqual('Branch.unlock',
2350
smart_branch.SmartServerBranchRequestUnlock)
2351
self.assertHandlerEqual('BzrDir.destroy_branch',
2352
smart_dir.SmartServerBzrDirRequestDestroyBranch)
2353
self.assertHandlerEqual('BzrDir.find_repository',
2354
smart_dir.SmartServerRequestFindRepositoryV1)
2355
self.assertHandlerEqual('BzrDir.find_repositoryV2',
2356
smart_dir.SmartServerRequestFindRepositoryV2)
2357
self.assertHandlerEqual('BzrDirFormat.initialize',
2358
smart_dir.SmartServerRequestInitializeBzrDir)
2359
self.assertHandlerEqual('BzrDirFormat.initialize_ex_1.16',
2360
smart_dir.SmartServerRequestBzrDirInitializeEx)
2361
self.assertHandlerEqual('BzrDir.cloning_metadir',
2362
smart_dir.SmartServerBzrDirRequestCloningMetaDir)
2363
self.assertHandlerEqual('BzrDir.get_config_file',
2364
smart_dir.SmartServerBzrDirRequestConfigFile)
2365
self.assertHandlerEqual('BzrDir.open_branch',
2366
smart_dir.SmartServerRequestOpenBranch)
2367
self.assertHandlerEqual('BzrDir.open_branchV2',
2368
smart_dir.SmartServerRequestOpenBranchV2)
2369
self.assertHandlerEqual('BzrDir.open_branchV3',
2370
smart_dir.SmartServerRequestOpenBranchV3)
2371
self.assertHandlerEqual('PackRepository.autopack',
2372
smart_packrepo.SmartServerPackRepositoryAutopack)
2373
self.assertHandlerEqual('Repository.add_signature_text',
2374
smart_repo.SmartServerRepositoryAddSignatureText)
2375
self.assertHandlerEqual('Repository.all_revision_ids',
2376
smart_repo.SmartServerRepositoryAllRevisionIds)
2377
self.assertHandlerEqual('Repository.break_lock',
2378
smart_repo.SmartServerRepositoryBreakLock)
2379
self.assertHandlerEqual('Repository.gather_stats',
2380
smart_repo.SmartServerRepositoryGatherStats)
2381
self.assertHandlerEqual('Repository.get_parent_map',
2382
smart_repo.SmartServerRepositoryGetParentMap)
2383
self.assertHandlerEqual('Repository.get_physical_lock_status',
2384
smart_repo.SmartServerRepositoryGetPhysicalLockStatus)
2385
self.assertHandlerEqual('Repository.get_rev_id_for_revno',
2386
smart_repo.SmartServerRepositoryGetRevIdForRevno)
2387
self.assertHandlerEqual('Repository.get_revision_graph',
2388
smart_repo.SmartServerRepositoryGetRevisionGraph)
2389
self.assertHandlerEqual('Repository.get_stream',
2390
smart_repo.SmartServerRepositoryGetStream)
2391
self.assertHandlerEqual('Repository.get_stream_1.19',
2392
smart_repo.SmartServerRepositoryGetStream_1_19)
2393
self.assertHandlerEqual('Repository.has_revision',
2394
smart_repo.SmartServerRequestHasRevision)
2395
self.assertHandlerEqual('Repository.insert_stream',
2396
smart_repo.SmartServerRepositoryInsertStream)
2397
self.assertHandlerEqual('Repository.insert_stream_locked',
2398
smart_repo.SmartServerRepositoryInsertStreamLocked)
2399
self.assertHandlerEqual('Repository.is_shared',
2400
smart_repo.SmartServerRepositoryIsShared)
2401
self.assertHandlerEqual('Repository.lock_write',
2402
smart_repo.SmartServerRepositoryLockWrite)
2403
self.assertHandlerEqual('Repository.make_working_trees',
2404
smart_repo.SmartServerRepositoryMakeWorkingTrees)
2405
self.assertHandlerEqual('Repository.tarball',
2406
smart_repo.SmartServerRepositoryTarball)
2407
self.assertHandlerEqual('Repository.unlock',
2408
smart_repo.SmartServerRepositoryUnlock)
2409
self.assertHandlerEqual('Repository.start_write_group',
2410
smart_repo.SmartServerRepositoryStartWriteGroup)
2411
self.assertHandlerEqual('Repository.check_write_group',
2412
smart_repo.SmartServerRepositoryCheckWriteGroup)
2413
self.assertHandlerEqual('Repository.commit_write_group',
2414
smart_repo.SmartServerRepositoryCommitWriteGroup)
2415
self.assertHandlerEqual('Repository.abort_write_group',
2416
smart_repo.SmartServerRepositoryAbortWriteGroup)
2417
self.assertHandlerEqual('VersionedFileRepository.get_serializer_format',
2418
smart_repo.SmartServerRepositoryGetSerializerFormat)
2419
self.assertHandlerEqual('Transport.is_readonly',
2420
smart_req.SmartServerIsReadonly)
2423
class SmartTCPServerHookTests(tests.TestCaseWithMemoryTransport):
2424
"""Tests for SmartTCPServer hooks."""
2427
super(SmartTCPServerHookTests, self).setUp()
2428
self.server = server.SmartTCPServer(self.get_transport())
2430
def test_run_server_started_hooks(self):
2431
"""Test the server started hooks get fired properly."""
2433
server.SmartTCPServer.hooks.install_named_hook('server_started',
2434
lambda backing_urls, url: started_calls.append((backing_urls, url)),
2436
started_ex_calls = []
2437
server.SmartTCPServer.hooks.install_named_hook('server_started_ex',
2438
lambda backing_urls, url: started_ex_calls.append((backing_urls, url)),
2440
self.server._sockname = ('example.com', 42)
2441
self.server.run_server_started_hooks()
2442
self.assertEquals(started_calls,
2443
[([self.get_transport().base], 'bzr://example.com:42/')])
2444
self.assertEquals(started_ex_calls,
2445
[([self.get_transport().base], self.server)])
2447
def test_run_server_started_hooks_ipv6(self):
2448
"""Test that socknames can contain 4-tuples."""
2449
self.server._sockname = ('::', 42, 0, 0)
2451
server.SmartTCPServer.hooks.install_named_hook('server_started',
2452
lambda backing_urls, url: started_calls.append((backing_urls, url)),
2454
self.server.run_server_started_hooks()
2455
self.assertEquals(started_calls,
2456
[([self.get_transport().base], 'bzr://:::42/')])
2458
def test_run_server_stopped_hooks(self):
2459
"""Test the server stopped hooks."""
2460
self.server._sockname = ('example.com', 42)
2462
server.SmartTCPServer.hooks.install_named_hook('server_stopped',
2463
lambda backing_urls, url: stopped_calls.append((backing_urls, url)),
2465
self.server.run_server_stopped_hooks()
2466
self.assertEquals(stopped_calls,
2467
[([self.get_transport().base], 'bzr://example.com:42/')])