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.
31
branch as _mod_branch,
41
from bzrlib.smart import (
42
branch as smart_branch,
44
repository as smart_repo,
45
packrepository as smart_packrepo,
50
from bzrlib.testament import Testament
51
from bzrlib.tests import test_server
52
from bzrlib.transport import (
58
def load_tests(standard_tests, module, loader):
59
"""Multiply tests version and protocol consistency."""
60
# FindRepository tests.
63
"_request_class": smart_dir.SmartServerRequestFindRepositoryV1}),
64
("find_repositoryV2", {
65
"_request_class": smart_dir.SmartServerRequestFindRepositoryV2}),
66
("find_repositoryV3", {
67
"_request_class": smart_dir.SmartServerRequestFindRepositoryV3}),
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,
73
tests.multiply_tests(v1_and_2, scenarios, result)
74
# The first scenario is only applicable to v1 protocols, it is deleted
76
tests.multiply_tests(v2_only, scenarios[1:], result)
80
class TestCaseWithChrootedTransport(tests.TestCaseWithTransport):
83
self.vfs_transport_factory = memory.MemoryServer
84
tests.TestCaseWithTransport.setUp(self)
85
self._chroot_server = None
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_from_url(self._chroot_server.get_url())
93
if relpath is not None:
98
class TestCaseWithSmartMedium(tests.TestCaseWithMemoryTransport):
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
106
self.overrideAttr(self, "transport_server", self.make_transport_server)
108
def make_transport_server(self):
109
return test_server.SmartTCPServer_for_testing('-' + self.id())
111
def get_smart_medium(self):
112
"""Get a smart medium to use in tests."""
113
return self.get_transport().get_smart_medium()
116
class TestByteStreamToStream(tests.TestCase):
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)
126
# Iterate the resulting iterable; checking that we get only one stream
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])
135
class TestSmartServerResponse(tests.TestCase):
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', )))
149
def test__str__(self):
150
"""SmartServerResponses can be stringified."""
152
"<SuccessfulSmartServerResponse args=('args',) body='body'>",
153
str(smart_req.SuccessfulSmartServerResponse(('args',), 'body')))
155
"<FailedSmartServerResponse args=('args',) body='body'>",
156
str(smart_req.FailedSmartServerResponse(('args',), 'body')))
159
class TestSmartServerRequest(tests.TestCaseWithMemoryTransport):
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/'))
166
errors.InvalidURLJoin, request.translate_client_path, 'foo/..')
168
errors.PathNotChild, request.translate_client_path, '/')
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))
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))
185
def test_transport_from_client_path(self):
186
transport = self.get_transport()
187
request = smart_req.SmartServerRequest(transport, 'foo/')
190
request.transport_from_client_path('foo/').base)
193
class TestSmartServerBzrDirRequestCloningMetaDir(
194
tests.TestCaseWithMemoryTransport):
195
"""Tests for BzrDir.cloning_metadir."""
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'))
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'))
228
class TestSmartServerBzrDirRequestCloningMetaDir(
229
tests.TestCaseWithMemoryTransport):
230
"""Tests for BzrDir.checkout_metadir."""
232
def test_checkout_metadir(self):
233
backing = self.get_transport()
234
request = smart_dir.SmartServerBzrDirRequestCheckoutMetaDir(
236
branch = self.make_branch('.', format='2a')
237
response = request.execute('')
239
smart_req.SmartServerResponse(
240
('Bazaar-NG meta directory, format 1\n',
241
'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
242
'Bazaar Branch Format 7 (needs bzr 1.6)\n')),
246
class TestSmartServerBzrDirRequestDestroyBranch(
247
tests.TestCaseWithMemoryTransport):
248
"""Tests for BzrDir.destroy_branch."""
250
def test_destroy_branch_default(self):
251
"""The default branch can be removed."""
252
backing = self.get_transport()
253
dir = self.make_branch('.').bzrdir
254
request_class = smart_dir.SmartServerBzrDirRequestDestroyBranch
255
request = request_class(backing)
256
expected = smart_req.SuccessfulSmartServerResponse(('ok',))
257
self.assertEqual(expected, request.execute('', None))
259
def test_destroy_branch_named(self):
260
"""A named branch can be removed."""
261
backing = self.get_transport()
262
dir = self.make_repository('.', format="development-colo").bzrdir
263
dir.create_branch(name="branchname")
264
request_class = smart_dir.SmartServerBzrDirRequestDestroyBranch
265
request = request_class(backing)
266
expected = smart_req.SuccessfulSmartServerResponse(('ok',))
267
self.assertEqual(expected, request.execute('', "branchname"))
269
def test_destroy_branch_missing(self):
270
"""An error is raised if the branch didn't exist."""
271
backing = self.get_transport()
272
dir = self.make_bzrdir('.', format="development-colo")
273
request_class = smart_dir.SmartServerBzrDirRequestDestroyBranch
274
request = request_class(backing)
275
expected = smart_req.FailedSmartServerResponse(('nobranch',), None)
276
self.assertEqual(expected, request.execute('', "branchname"))
279
class TestSmartServerBzrDirRequestHasWorkingTree(
280
tests.TestCaseWithTransport):
281
"""Tests for BzrDir.has_workingtree."""
283
def test_has_workingtree_yes(self):
284
"""A working tree is present."""
285
backing = self.get_transport()
286
dir = self.make_branch_and_tree('.').bzrdir
287
request_class = smart_dir.SmartServerBzrDirRequestHasWorkingTree
288
request = request_class(backing)
289
expected = smart_req.SuccessfulSmartServerResponse(('yes',))
290
self.assertEqual(expected, request.execute(''))
292
def test_has_workingtree_no(self):
293
"""A working tree is missing."""
294
backing = self.get_transport()
295
dir = self.make_bzrdir('.')
296
request_class = smart_dir.SmartServerBzrDirRequestHasWorkingTree
297
request = request_class(backing)
298
expected = smart_req.SuccessfulSmartServerResponse(('no',))
299
self.assertEqual(expected, request.execute(''))
302
class TestSmartServerBzrDirRequestDestroyRepository(
303
tests.TestCaseWithMemoryTransport):
304
"""Tests for BzrDir.destroy_repository."""
306
def test_destroy_repository_default(self):
307
"""The repository can be removed."""
308
backing = self.get_transport()
309
dir = self.make_repository('.').bzrdir
310
request_class = smart_dir.SmartServerBzrDirRequestDestroyRepository
311
request = request_class(backing)
312
expected = smart_req.SuccessfulSmartServerResponse(('ok',))
313
self.assertEqual(expected, request.execute(''))
315
def test_destroy_repository_missing(self):
316
"""An error is raised if the repository didn't exist."""
317
backing = self.get_transport()
318
dir = self.make_bzrdir('.')
319
request_class = smart_dir.SmartServerBzrDirRequestDestroyRepository
320
request = request_class(backing)
321
expected = smart_req.FailedSmartServerResponse(
322
('norepository',), None)
323
self.assertEqual(expected, request.execute(''))
326
class TestSmartServerRequestCreateRepository(tests.TestCaseWithMemoryTransport):
327
"""Tests for BzrDir.create_repository."""
329
def test_makes_repository(self):
330
"""When there is a bzrdir present, the call succeeds."""
331
backing = self.get_transport()
332
self.make_bzrdir('.')
333
request_class = smart_dir.SmartServerRequestCreateRepository
334
request = request_class(backing)
335
reference_bzrdir_format = bzrdir.format_registry.get('pack-0.92')()
336
reference_format = reference_bzrdir_format.repository_format
337
network_name = reference_format.network_name()
338
expected = smart_req.SuccessfulSmartServerResponse(
339
('ok', 'no', 'no', 'no', network_name))
340
self.assertEqual(expected, request.execute('', network_name, 'True'))
343
class TestSmartServerRequestFindRepository(tests.TestCaseWithMemoryTransport):
344
"""Tests for BzrDir.find_repository."""
346
def test_no_repository(self):
347
"""When there is no repository to be found, ('norepository', ) is returned."""
348
backing = self.get_transport()
349
request = self._request_class(backing)
350
self.make_bzrdir('.')
351
self.assertEqual(smart_req.SmartServerResponse(('norepository', )),
354
def test_nonshared_repository(self):
355
# nonshared repositorys only allow 'find' to return a handle when the
356
# path the repository is being searched on is the same as that that
357
# the repository is at.
358
backing = self.get_transport()
359
request = self._request_class(backing)
360
result = self._make_repository_and_result()
361
self.assertEqual(result, request.execute(''))
362
self.make_bzrdir('subdir')
363
self.assertEqual(smart_req.SmartServerResponse(('norepository', )),
364
request.execute('subdir'))
366
def _make_repository_and_result(self, shared=False, format=None):
367
"""Convenience function to setup a repository.
369
:result: The SmartServerResponse to expect when opening it.
371
repo = self.make_repository('.', shared=shared, format=format)
372
if repo.supports_rich_root():
376
if repo._format.supports_tree_reference:
380
if repo._format.supports_external_lookups:
384
if (smart_dir.SmartServerRequestFindRepositoryV3 ==
385
self._request_class):
386
return smart_req.SuccessfulSmartServerResponse(
387
('ok', '', rich_root, subtrees, external,
388
repo._format.network_name()))
389
elif (smart_dir.SmartServerRequestFindRepositoryV2 ==
390
self._request_class):
391
# All tests so far are on formats, and for non-external
393
return smart_req.SuccessfulSmartServerResponse(
394
('ok', '', rich_root, subtrees, external))
396
return smart_req.SuccessfulSmartServerResponse(
397
('ok', '', rich_root, subtrees))
399
def test_shared_repository(self):
400
"""When there is a shared repository, we get 'ok', 'relpath-to-repo'."""
401
backing = self.get_transport()
402
request = self._request_class(backing)
403
result = self._make_repository_and_result(shared=True)
404
self.assertEqual(result, request.execute(''))
405
self.make_bzrdir('subdir')
406
result2 = smart_req.SmartServerResponse(
407
result.args[0:1] + ('..', ) + result.args[2:])
408
self.assertEqual(result2,
409
request.execute('subdir'))
410
self.make_bzrdir('subdir/deeper')
411
result3 = smart_req.SmartServerResponse(
412
result.args[0:1] + ('../..', ) + result.args[2:])
413
self.assertEqual(result3,
414
request.execute('subdir/deeper'))
416
def test_rich_root_and_subtree_encoding(self):
417
"""Test for the format attributes for rich root and subtree support."""
418
backing = self.get_transport()
419
request = self._request_class(backing)
420
result = self._make_repository_and_result(
421
format='dirstate-with-subtree')
422
# check the test will be valid
423
self.assertEqual('yes', result.args[2])
424
self.assertEqual('yes', result.args[3])
425
self.assertEqual(result, request.execute(''))
427
def test_supports_external_lookups_no_v2(self):
428
"""Test for the supports_external_lookups attribute."""
429
backing = self.get_transport()
430
request = self._request_class(backing)
431
result = self._make_repository_and_result(
432
format='dirstate-with-subtree')
433
# check the test will be valid
434
self.assertEqual('no', result.args[4])
435
self.assertEqual(result, request.execute(''))
438
class TestSmartServerBzrDirRequestGetConfigFile(
439
tests.TestCaseWithMemoryTransport):
440
"""Tests for BzrDir.get_config_file."""
442
def test_present(self):
443
backing = self.get_transport()
444
dir = self.make_bzrdir('.')
445
dir.get_config().set_default_stack_on("/")
446
local_result = dir._get_config()._get_config_file().read()
447
request_class = smart_dir.SmartServerBzrDirRequestConfigFile
448
request = request_class(backing)
449
expected = smart_req.SuccessfulSmartServerResponse((), local_result)
450
self.assertEqual(expected, request.execute(''))
452
def test_missing(self):
453
backing = self.get_transport()
454
dir = self.make_bzrdir('.')
455
request_class = smart_dir.SmartServerBzrDirRequestConfigFile
456
request = request_class(backing)
457
expected = smart_req.SuccessfulSmartServerResponse((), '')
458
self.assertEqual(expected, request.execute(''))
461
class TestSmartServerRequestInitializeBzrDir(tests.TestCaseWithMemoryTransport):
463
def test_empty_dir(self):
464
"""Initializing an empty dir should succeed and do it."""
465
backing = self.get_transport()
466
request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
467
self.assertEqual(smart_req.SmartServerResponse(('ok', )),
469
made_dir = bzrdir.BzrDir.open_from_transport(backing)
470
# no branch, tree or repository is expected with the current
472
self.assertRaises(errors.NoWorkingTree, made_dir.open_workingtree)
473
self.assertRaises(errors.NotBranchError, made_dir.open_branch)
474
self.assertRaises(errors.NoRepositoryPresent, made_dir.open_repository)
476
def test_missing_dir(self):
477
"""Initializing a missing directory should fail like the bzrdir api."""
478
backing = self.get_transport()
479
request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
480
self.assertRaises(errors.NoSuchFile,
481
request.execute, 'subdir')
483
def test_initialized_dir(self):
484
"""Initializing an extant bzrdir should fail like the bzrdir api."""
485
backing = self.get_transport()
486
request = smart_dir.SmartServerRequestInitializeBzrDir(backing)
487
self.make_bzrdir('subdir')
488
self.assertRaises(errors.FileExists,
489
request.execute, 'subdir')
492
class TestSmartServerRequestBzrDirInitializeEx(
493
tests.TestCaseWithMemoryTransport):
494
"""Basic tests for BzrDir.initialize_ex_1.16 in the smart server.
496
The main unit tests in test_bzrdir exercise the API comprehensively.
499
def test_empty_dir(self):
500
"""Initializing an empty dir should succeed and do it."""
501
backing = self.get_transport()
502
name = self.make_bzrdir('reference')._format.network_name()
503
request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
505
smart_req.SmartServerResponse(('', '', '', '', '', '', name,
506
'False', '', '', '')),
507
request.execute(name, '', 'True', 'False', 'False', '', '', '', '',
509
made_dir = bzrdir.BzrDir.open_from_transport(backing)
510
# no branch, tree or repository is expected with the current
512
self.assertRaises(errors.NoWorkingTree, made_dir.open_workingtree)
513
self.assertRaises(errors.NotBranchError, made_dir.open_branch)
514
self.assertRaises(errors.NoRepositoryPresent, made_dir.open_repository)
516
def test_missing_dir(self):
517
"""Initializing a missing directory should fail like the bzrdir api."""
518
backing = self.get_transport()
519
name = self.make_bzrdir('reference')._format.network_name()
520
request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
521
self.assertRaises(errors.NoSuchFile, request.execute, name,
522
'subdir/dir', 'False', 'False', 'False', '', '', '', '', 'False')
524
def test_initialized_dir(self):
525
"""Initializing an extant directory should fail like the bzrdir api."""
526
backing = self.get_transport()
527
name = self.make_bzrdir('reference')._format.network_name()
528
request = smart_dir.SmartServerRequestBzrDirInitializeEx(backing)
529
self.make_bzrdir('subdir')
530
self.assertRaises(errors.FileExists, request.execute, name, 'subdir',
531
'False', 'False', 'False', '', '', '', '', 'False')
534
class TestSmartServerRequestOpenBzrDir(tests.TestCaseWithMemoryTransport):
536
def test_no_directory(self):
537
backing = self.get_transport()
538
request = smart_dir.SmartServerRequestOpenBzrDir(backing)
539
self.assertEqual(smart_req.SmartServerResponse(('no', )),
540
request.execute('does-not-exist'))
542
def test_empty_directory(self):
543
backing = self.get_transport()
544
backing.mkdir('empty')
545
request = smart_dir.SmartServerRequestOpenBzrDir(backing)
546
self.assertEqual(smart_req.SmartServerResponse(('no', )),
547
request.execute('empty'))
549
def test_outside_root_client_path(self):
550
backing = self.get_transport()
551
request = smart_dir.SmartServerRequestOpenBzrDir(backing,
552
root_client_path='root')
553
self.assertEqual(smart_req.SmartServerResponse(('no', )),
554
request.execute('not-root'))
557
class TestSmartServerRequestOpenBzrDir_2_1(tests.TestCaseWithMemoryTransport):
559
def test_no_directory(self):
560
backing = self.get_transport()
561
request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
562
self.assertEqual(smart_req.SmartServerResponse(('no', )),
563
request.execute('does-not-exist'))
565
def test_empty_directory(self):
566
backing = self.get_transport()
567
backing.mkdir('empty')
568
request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
569
self.assertEqual(smart_req.SmartServerResponse(('no', )),
570
request.execute('empty'))
572
def test_present_without_workingtree(self):
573
backing = self.get_transport()
574
request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
575
self.make_bzrdir('.')
576
self.assertEqual(smart_req.SmartServerResponse(('yes', 'no')),
579
def test_outside_root_client_path(self):
580
backing = self.get_transport()
581
request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing,
582
root_client_path='root')
583
self.assertEqual(smart_req.SmartServerResponse(('no',)),
584
request.execute('not-root'))
587
class TestSmartServerRequestOpenBzrDir_2_1_disk(TestCaseWithChrootedTransport):
589
def test_present_with_workingtree(self):
590
self.vfs_transport_factory = test_server.LocalURLServer
591
backing = self.get_transport()
592
request = smart_dir.SmartServerRequestOpenBzrDir_2_1(backing)
593
bd = self.make_bzrdir('.')
594
bd.create_repository()
596
bd.create_workingtree()
597
self.assertEqual(smart_req.SmartServerResponse(('yes', 'yes')),
601
class TestSmartServerRequestOpenBranch(TestCaseWithChrootedTransport):
603
def test_no_branch(self):
604
"""When there is no branch, ('nobranch', ) is returned."""
605
backing = self.get_transport()
606
request = smart_dir.SmartServerRequestOpenBranch(backing)
607
self.make_bzrdir('.')
608
self.assertEqual(smart_req.SmartServerResponse(('nobranch', )),
611
def test_branch(self):
612
"""When there is a branch, 'ok' is returned."""
613
backing = self.get_transport()
614
request = smart_dir.SmartServerRequestOpenBranch(backing)
615
self.make_branch('.')
616
self.assertEqual(smart_req.SmartServerResponse(('ok', '')),
619
def test_branch_reference(self):
620
"""When there is a branch reference, the reference URL is returned."""
621
self.vfs_transport_factory = test_server.LocalURLServer
622
backing = self.get_transport()
623
request = smart_dir.SmartServerRequestOpenBranch(backing)
624
branch = self.make_branch('branch')
625
checkout = branch.create_checkout('reference',lightweight=True)
626
reference_url = _mod_branch.BranchReferenceFormat().get_reference(
628
self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
629
self.assertEqual(smart_req.SmartServerResponse(('ok', reference_url)),
630
request.execute('reference'))
632
def test_notification_on_branch_from_repository(self):
633
"""When there is a repository, the error should return details."""
634
backing = self.get_transport()
635
request = smart_dir.SmartServerRequestOpenBranch(backing)
636
repo = self.make_repository('.')
637
self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
641
class TestSmartServerRequestOpenBranchV2(TestCaseWithChrootedTransport):
643
def test_no_branch(self):
644
"""When there is no branch, ('nobranch', ) is returned."""
645
backing = self.get_transport()
646
self.make_bzrdir('.')
647
request = smart_dir.SmartServerRequestOpenBranchV2(backing)
648
self.assertEqual(smart_req.SmartServerResponse(('nobranch', )),
651
def test_branch(self):
652
"""When there is a branch, 'ok' is returned."""
653
backing = self.get_transport()
654
expected = self.make_branch('.')._format.network_name()
655
request = smart_dir.SmartServerRequestOpenBranchV2(backing)
656
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
657
('branch', expected)),
660
def test_branch_reference(self):
661
"""When there is a branch reference, the reference URL is returned."""
662
self.vfs_transport_factory = test_server.LocalURLServer
663
backing = self.get_transport()
664
request = smart_dir.SmartServerRequestOpenBranchV2(backing)
665
branch = self.make_branch('branch')
666
checkout = branch.create_checkout('reference',lightweight=True)
667
reference_url = _mod_branch.BranchReferenceFormat().get_reference(
669
self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
670
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
671
('ref', reference_url)),
672
request.execute('reference'))
674
def test_stacked_branch(self):
675
"""Opening a stacked branch does not open the stacked-on branch."""
676
trunk = self.make_branch('trunk')
677
feature = self.make_branch('feature')
678
feature.set_stacked_on_url(trunk.base)
680
_mod_branch.Branch.hooks.install_named_hook(
681
'open', opened_branches.append, None)
682
backing = self.get_transport()
683
request = smart_dir.SmartServerRequestOpenBranchV2(backing)
686
response = request.execute('feature')
688
request.teardown_jail()
689
expected_format = feature._format.network_name()
690
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
691
('branch', expected_format)),
693
self.assertLength(1, opened_branches)
695
def test_notification_on_branch_from_repository(self):
696
"""When there is a repository, the error should return details."""
697
backing = self.get_transport()
698
request = smart_dir.SmartServerRequestOpenBranchV2(backing)
699
repo = self.make_repository('.')
700
self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
704
class TestSmartServerRequestOpenBranchV3(TestCaseWithChrootedTransport):
706
def test_no_branch(self):
707
"""When there is no branch, ('nobranch', ) is returned."""
708
backing = self.get_transport()
709
self.make_bzrdir('.')
710
request = smart_dir.SmartServerRequestOpenBranchV3(backing)
711
self.assertEqual(smart_req.SmartServerResponse(('nobranch',)),
714
def test_branch(self):
715
"""When there is a branch, 'ok' is returned."""
716
backing = self.get_transport()
717
expected = self.make_branch('.')._format.network_name()
718
request = smart_dir.SmartServerRequestOpenBranchV3(backing)
719
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
720
('branch', expected)),
723
def test_branch_reference(self):
724
"""When there is a branch reference, the reference URL is returned."""
725
self.vfs_transport_factory = test_server.LocalURLServer
726
backing = self.get_transport()
727
request = smart_dir.SmartServerRequestOpenBranchV3(backing)
728
branch = self.make_branch('branch')
729
checkout = branch.create_checkout('reference',lightweight=True)
730
reference_url = _mod_branch.BranchReferenceFormat().get_reference(
732
self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
733
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
734
('ref', reference_url)),
735
request.execute('reference'))
737
def test_stacked_branch(self):
738
"""Opening a stacked branch does not open the stacked-on branch."""
739
trunk = self.make_branch('trunk')
740
feature = self.make_branch('feature')
741
feature.set_stacked_on_url(trunk.base)
743
_mod_branch.Branch.hooks.install_named_hook(
744
'open', opened_branches.append, None)
745
backing = self.get_transport()
746
request = smart_dir.SmartServerRequestOpenBranchV3(backing)
749
response = request.execute('feature')
751
request.teardown_jail()
752
expected_format = feature._format.network_name()
753
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
754
('branch', expected_format)),
756
self.assertLength(1, opened_branches)
758
def test_notification_on_branch_from_repository(self):
759
"""When there is a repository, the error should return details."""
760
backing = self.get_transport()
761
request = smart_dir.SmartServerRequestOpenBranchV3(backing)
762
repo = self.make_repository('.')
763
self.assertEqual(smart_req.SmartServerResponse(
764
('nobranch', 'location is a repository')),
768
class TestSmartServerRequestRevisionHistory(tests.TestCaseWithMemoryTransport):
770
def test_empty(self):
771
"""For an empty branch, the body is empty."""
772
backing = self.get_transport()
773
request = smart_branch.SmartServerRequestRevisionHistory(backing)
774
self.make_branch('.')
775
self.assertEqual(smart_req.SmartServerResponse(('ok', ), ''),
778
def test_not_empty(self):
779
"""For a non-empty branch, the body is empty."""
780
backing = self.get_transport()
781
request = smart_branch.SmartServerRequestRevisionHistory(backing)
782
tree = self.make_branch_and_memory_tree('.')
785
r1 = tree.commit('1st commit')
786
r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
789
smart_req.SmartServerResponse(('ok', ), ('\x00'.join([r1, r2]))),
793
class TestSmartServerBranchRequest(tests.TestCaseWithMemoryTransport):
795
def test_no_branch(self):
796
"""When there is a bzrdir and no branch, NotBranchError is raised."""
797
backing = self.get_transport()
798
request = smart_branch.SmartServerBranchRequest(backing)
799
self.make_bzrdir('.')
800
self.assertRaises(errors.NotBranchError,
803
def test_branch_reference(self):
804
"""When there is a branch reference, NotBranchError is raised."""
805
backing = self.get_transport()
806
request = smart_branch.SmartServerBranchRequest(backing)
807
branch = self.make_branch('branch')
808
checkout = branch.create_checkout('reference',lightweight=True)
809
self.assertRaises(errors.NotBranchError,
810
request.execute, 'checkout')
813
class TestSmartServerBranchRequestLastRevisionInfo(
814
tests.TestCaseWithMemoryTransport):
816
def test_empty(self):
817
"""For an empty branch, the result is ('ok', '0', 'null:')."""
818
backing = self.get_transport()
819
request = smart_branch.SmartServerBranchRequestLastRevisionInfo(backing)
820
self.make_branch('.')
821
self.assertEqual(smart_req.SmartServerResponse(('ok', '0', 'null:')),
824
def test_not_empty(self):
825
"""For a non-empty branch, the result is ('ok', 'revno', 'revid')."""
826
backing = self.get_transport()
827
request = smart_branch.SmartServerBranchRequestLastRevisionInfo(backing)
828
tree = self.make_branch_and_memory_tree('.')
831
rev_id_utf8 = u'\xc8'.encode('utf-8')
832
r1 = tree.commit('1st commit')
833
r2 = tree.commit('2nd commit', rev_id=rev_id_utf8)
836
smart_req.SmartServerResponse(('ok', '2', rev_id_utf8)),
840
class TestSmartServerBranchRequestRevisionIdToRevno(
841
tests.TestCaseWithMemoryTransport):
844
backing = self.get_transport()
845
request = smart_branch.SmartServerBranchRequestRevisionIdToRevno(
847
self.make_branch('.')
848
self.assertEqual(smart_req.SmartServerResponse(('ok', '0')),
849
request.execute('', 'null:'))
851
def test_simple(self):
852
backing = self.get_transport()
853
request = smart_branch.SmartServerBranchRequestRevisionIdToRevno(
855
tree = self.make_branch_and_memory_tree('.')
858
r1 = tree.commit('1st commit')
861
smart_req.SmartServerResponse(('ok', '1')),
862
request.execute('', r1))
864
def test_not_found(self):
865
backing = self.get_transport()
866
request = smart_branch.SmartServerBranchRequestRevisionIdToRevno(
868
branch = self.make_branch('.')
870
smart_req.FailedSmartServerResponse(
871
('NoSuchRevision', 'idontexist')),
872
request.execute('', 'idontexist'))
875
class TestSmartServerBranchRequestGetConfigFile(
876
tests.TestCaseWithMemoryTransport):
878
def test_default(self):
879
"""With no file, we get empty content."""
880
backing = self.get_transport()
881
request = smart_branch.SmartServerBranchGetConfigFile(backing)
882
branch = self.make_branch('.')
883
# there should be no file by default
885
self.assertEqual(smart_req.SmartServerResponse(('ok', ), content),
888
def test_with_content(self):
889
# SmartServerBranchGetConfigFile should return the content from
890
# branch.control_files.get('branch.conf') for now - in the future it may
891
# perform more complex processing.
892
backing = self.get_transport()
893
request = smart_branch.SmartServerBranchGetConfigFile(backing)
894
branch = self.make_branch('.')
895
branch._transport.put_bytes('branch.conf', 'foo bar baz')
896
self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'foo bar baz'),
900
class TestLockedBranch(tests.TestCaseWithMemoryTransport):
902
def get_lock_tokens(self, branch):
903
branch_token = branch.lock_write().branch_token
904
repo_token = branch.repository.lock_write().repository_token
905
branch.repository.unlock()
906
return branch_token, repo_token
909
class TestSmartServerBranchRequestPutConfigFile(TestLockedBranch):
911
def test_with_content(self):
912
backing = self.get_transport()
913
request = smart_branch.SmartServerBranchPutConfigFile(backing)
914
branch = self.make_branch('.')
915
branch_token, repo_token = self.get_lock_tokens(branch)
916
self.assertIs(None, request.execute('', branch_token, repo_token))
918
smart_req.SmartServerResponse(('ok', )),
919
request.do_body('foo bar baz'))
921
branch.control_transport.get_bytes('branch.conf'),
926
class TestSmartServerBranchRequestSetConfigOption(TestLockedBranch):
928
def test_value_name(self):
929
branch = self.make_branch('.')
930
request = smart_branch.SmartServerBranchRequestSetConfigOption(
931
branch.bzrdir.root_transport)
932
branch_token, repo_token = self.get_lock_tokens(branch)
933
config = branch._get_config()
934
result = request.execute('', branch_token, repo_token, 'bar', 'foo',
936
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
937
self.assertEqual('bar', config.get_option('foo'))
941
def test_value_name_section(self):
942
branch = self.make_branch('.')
943
request = smart_branch.SmartServerBranchRequestSetConfigOption(
944
branch.bzrdir.root_transport)
945
branch_token, repo_token = self.get_lock_tokens(branch)
946
config = branch._get_config()
947
result = request.execute('', branch_token, repo_token, 'bar', 'foo',
949
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
950
self.assertEqual('bar', config.get_option('foo', 'gam'))
955
class TestSmartServerBranchRequestSetConfigOptionDict(TestLockedBranch):
958
TestLockedBranch.setUp(self)
959
# A dict with non-ascii keys and values to exercise unicode
961
self.encoded_value_dict = (
962
'd5:ascii1:a11:unicode \xe2\x8c\x9a3:\xe2\x80\xbde')
964
'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'}
966
def test_value_name(self):
967
branch = self.make_branch('.')
968
request = smart_branch.SmartServerBranchRequestSetConfigOptionDict(
969
branch.bzrdir.root_transport)
970
branch_token, repo_token = self.get_lock_tokens(branch)
971
config = branch._get_config()
972
result = request.execute('', branch_token, repo_token,
973
self.encoded_value_dict, 'foo', '')
974
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
975
self.assertEqual(self.value_dict, config.get_option('foo'))
979
def test_value_name_section(self):
980
branch = self.make_branch('.')
981
request = smart_branch.SmartServerBranchRequestSetConfigOptionDict(
982
branch.bzrdir.root_transport)
983
branch_token, repo_token = self.get_lock_tokens(branch)
984
config = branch._get_config()
985
result = request.execute('', branch_token, repo_token,
986
self.encoded_value_dict, 'foo', 'gam')
987
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), result)
988
self.assertEqual(self.value_dict, config.get_option('foo', 'gam'))
993
class TestSmartServerBranchRequestSetTagsBytes(TestLockedBranch):
994
# Only called when the branch format and tags match [yay factory
995
# methods] so only need to test straight forward cases.
997
def test_set_bytes(self):
998
base_branch = self.make_branch('base')
999
tag_bytes = base_branch._get_tags_bytes()
1000
# get_lock_tokens takes out a lock.
1001
branch_token, repo_token = self.get_lock_tokens(base_branch)
1002
request = smart_branch.SmartServerBranchSetTagsBytes(
1003
self.get_transport())
1004
response = request.execute('base', branch_token, repo_token)
1005
self.assertEqual(None, response)
1006
response = request.do_chunk(tag_bytes)
1007
self.assertEqual(None, response)
1008
response = request.do_end()
1010
smart_req.SuccessfulSmartServerResponse(()), response)
1011
base_branch.unlock()
1013
def test_lock_failed(self):
1014
base_branch = self.make_branch('base')
1015
base_branch.lock_write()
1016
tag_bytes = base_branch._get_tags_bytes()
1017
request = smart_branch.SmartServerBranchSetTagsBytes(
1018
self.get_transport())
1019
self.assertRaises(errors.TokenMismatch, request.execute,
1020
'base', 'wrong token', 'wrong token')
1021
# The request handler will keep processing the message parts, so even
1022
# if the request fails immediately do_chunk and do_end are still
1024
request.do_chunk(tag_bytes)
1026
base_branch.unlock()
1030
class SetLastRevisionTestBase(TestLockedBranch):
1031
"""Base test case for verbs that implement set_last_revision."""
1034
tests.TestCaseWithMemoryTransport.setUp(self)
1035
backing_transport = self.get_transport()
1036
self.request = self.request_class(backing_transport)
1037
self.tree = self.make_branch_and_memory_tree('.')
1039
def lock_branch(self):
1040
return self.get_lock_tokens(self.tree.branch)
1042
def unlock_branch(self):
1043
self.tree.branch.unlock()
1045
def set_last_revision(self, revision_id, revno):
1046
branch_token, repo_token = self.lock_branch()
1047
response = self._set_last_revision(
1048
revision_id, revno, branch_token, repo_token)
1049
self.unlock_branch()
1052
def assertRequestSucceeds(self, revision_id, revno):
1053
response = self.set_last_revision(revision_id, revno)
1054
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
1058
class TestSetLastRevisionVerbMixin(object):
1059
"""Mixin test case for verbs that implement set_last_revision."""
1061
def test_set_null_to_null(self):
1062
"""An empty branch can have its last revision set to 'null:'."""
1063
self.assertRequestSucceeds('null:', 0)
1065
def test_NoSuchRevision(self):
1066
"""If the revision_id is not present, the verb returns NoSuchRevision.
1068
revision_id = 'non-existent revision'
1069
self.assertEqual(smart_req.FailedSmartServerResponse(('NoSuchRevision',
1071
self.set_last_revision(revision_id, 1))
1073
def make_tree_with_two_commits(self):
1074
self.tree.lock_write()
1076
rev_id_utf8 = u'\xc8'.encode('utf-8')
1077
r1 = self.tree.commit('1st commit', rev_id=rev_id_utf8)
1078
r2 = self.tree.commit('2nd commit', rev_id='rev-2')
1081
def test_branch_last_revision_info_is_updated(self):
1082
"""A branch's tip can be set to a revision that is present in its
1085
# Make a branch with an empty revision history, but two revisions in
1087
self.make_tree_with_two_commits()
1088
rev_id_utf8 = u'\xc8'.encode('utf-8')
1089
self.tree.branch.set_last_revision_info(0, 'null:')
1091
(0, 'null:'), self.tree.branch.last_revision_info())
1092
# We can update the branch to a revision that is present in the
1094
self.assertRequestSucceeds(rev_id_utf8, 1)
1096
(1, rev_id_utf8), self.tree.branch.last_revision_info())
1098
def test_branch_last_revision_info_rewind(self):
1099
"""A branch's tip can be set to a revision that is an ancestor of the
1102
self.make_tree_with_two_commits()
1103
rev_id_utf8 = u'\xc8'.encode('utf-8')
1105
(2, 'rev-2'), self.tree.branch.last_revision_info())
1106
self.assertRequestSucceeds(rev_id_utf8, 1)
1108
(1, rev_id_utf8), self.tree.branch.last_revision_info())
1110
def test_TipChangeRejected(self):
1111
"""If a pre_change_branch_tip hook raises TipChangeRejected, the verb
1112
returns TipChangeRejected.
1114
rejection_message = u'rejection message\N{INTERROBANG}'
1115
def hook_that_rejects(params):
1116
raise errors.TipChangeRejected(rejection_message)
1117
_mod_branch.Branch.hooks.install_named_hook(
1118
'pre_change_branch_tip', hook_that_rejects, None)
1120
smart_req.FailedSmartServerResponse(
1121
('TipChangeRejected', rejection_message.encode('utf-8'))),
1122
self.set_last_revision('null:', 0))
1125
class TestSmartServerBranchRequestSetLastRevision(
1126
SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
1127
"""Tests for Branch.set_last_revision verb."""
1129
request_class = smart_branch.SmartServerBranchRequestSetLastRevision
1131
def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
1132
return self.request.execute(
1133
'', branch_token, repo_token, revision_id)
1136
class TestSmartServerBranchRequestSetLastRevisionInfo(
1137
SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
1138
"""Tests for Branch.set_last_revision_info verb."""
1140
request_class = smart_branch.SmartServerBranchRequestSetLastRevisionInfo
1142
def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
1143
return self.request.execute(
1144
'', branch_token, repo_token, revno, revision_id)
1146
def test_NoSuchRevision(self):
1147
"""Branch.set_last_revision_info does not have to return
1148
NoSuchRevision if the revision_id is absent.
1150
raise tests.TestNotApplicable()
1153
class TestSmartServerBranchRequestSetLastRevisionEx(
1154
SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
1155
"""Tests for Branch.set_last_revision_ex verb."""
1157
request_class = smart_branch.SmartServerBranchRequestSetLastRevisionEx
1159
def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
1160
return self.request.execute(
1161
'', branch_token, repo_token, revision_id, 0, 0)
1163
def assertRequestSucceeds(self, revision_id, revno):
1164
response = self.set_last_revision(revision_id, revno)
1166
smart_req.SuccessfulSmartServerResponse(('ok', revno, revision_id)),
1169
def test_branch_last_revision_info_rewind(self):
1170
"""A branch's tip can be set to a revision that is an ancestor of the
1171
current tip, but only if allow_overwrite_descendant is passed.
1173
self.make_tree_with_two_commits()
1174
rev_id_utf8 = u'\xc8'.encode('utf-8')
1176
(2, 'rev-2'), self.tree.branch.last_revision_info())
1177
# If allow_overwrite_descendant flag is 0, then trying to set the tip
1178
# to an older revision ID has no effect.
1179
branch_token, repo_token = self.lock_branch()
1180
response = self.request.execute(
1181
'', branch_token, repo_token, rev_id_utf8, 0, 0)
1183
smart_req.SuccessfulSmartServerResponse(('ok', 2, 'rev-2')),
1186
(2, 'rev-2'), self.tree.branch.last_revision_info())
1188
# If allow_overwrite_descendant flag is 1, then setting the tip to an
1190
response = self.request.execute(
1191
'', branch_token, repo_token, rev_id_utf8, 0, 1)
1193
smart_req.SuccessfulSmartServerResponse(('ok', 1, rev_id_utf8)),
1195
self.unlock_branch()
1197
(1, rev_id_utf8), self.tree.branch.last_revision_info())
1199
def make_branch_with_divergent_history(self):
1200
"""Make a branch with divergent history in its repo.
1202
The branch's tip will be 'child-2', and the repo will also contain
1203
'child-1', which diverges from a common base revision.
1205
self.tree.lock_write()
1207
r1 = self.tree.commit('1st commit')
1208
revno_1, revid_1 = self.tree.branch.last_revision_info()
1209
r2 = self.tree.commit('2nd commit', rev_id='child-1')
1210
# Undo the second commit
1211
self.tree.branch.set_last_revision_info(revno_1, revid_1)
1212
self.tree.set_parent_ids([revid_1])
1213
# Make a new second commit, child-2. child-2 has diverged from
1215
new_r2 = self.tree.commit('2nd commit', rev_id='child-2')
1218
def test_not_allow_diverged(self):
1219
"""If allow_diverged is not passed, then setting a divergent history
1220
returns a Diverged error.
1222
self.make_branch_with_divergent_history()
1224
smart_req.FailedSmartServerResponse(('Diverged',)),
1225
self.set_last_revision('child-1', 2))
1226
# The branch tip was not changed.
1227
self.assertEqual('child-2', self.tree.branch.last_revision())
1229
def test_allow_diverged(self):
1230
"""If allow_diverged is passed, then setting a divergent history
1233
self.make_branch_with_divergent_history()
1234
branch_token, repo_token = self.lock_branch()
1235
response = self.request.execute(
1236
'', branch_token, repo_token, 'child-1', 1, 0)
1238
smart_req.SuccessfulSmartServerResponse(('ok', 2, 'child-1')),
1240
self.unlock_branch()
1241
# The branch tip was changed.
1242
self.assertEqual('child-1', self.tree.branch.last_revision())
1245
class TestSmartServerBranchBreakLock(tests.TestCaseWithMemoryTransport):
1247
def test_lock_to_break(self):
1248
base_branch = self.make_branch('base')
1249
request = smart_branch.SmartServerBranchBreakLock(
1250
self.get_transport())
1251
base_branch.lock_write()
1253
smart_req.SuccessfulSmartServerResponse(('ok', ), None),
1254
request.execute('base'))
1256
def test_nothing_to_break(self):
1257
base_branch = self.make_branch('base')
1258
request = smart_branch.SmartServerBranchBreakLock(
1259
self.get_transport())
1261
smart_req.SuccessfulSmartServerResponse(('ok', ), None),
1262
request.execute('base'))
1265
class TestSmartServerBranchRequestGetParent(tests.TestCaseWithMemoryTransport):
1267
def test_get_parent_none(self):
1268
base_branch = self.make_branch('base')
1269
request = smart_branch.SmartServerBranchGetParent(self.get_transport())
1270
response = request.execute('base')
1272
smart_req.SuccessfulSmartServerResponse(('',)), response)
1274
def test_get_parent_something(self):
1275
base_branch = self.make_branch('base')
1276
base_branch.set_parent(self.get_url('foo'))
1277
request = smart_branch.SmartServerBranchGetParent(self.get_transport())
1278
response = request.execute('base')
1280
smart_req.SuccessfulSmartServerResponse(("../foo",)),
1284
class TestSmartServerBranchRequestSetParent(TestLockedBranch):
1286
def test_set_parent_none(self):
1287
branch = self.make_branch('base', format="1.9")
1289
branch._set_parent_location('foo')
1291
request = smart_branch.SmartServerBranchRequestSetParentLocation(
1292
self.get_transport())
1293
branch_token, repo_token = self.get_lock_tokens(branch)
1295
response = request.execute('base', branch_token, repo_token, '')
1298
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), response)
1299
self.assertEqual(None, branch.get_parent())
1301
def test_set_parent_something(self):
1302
branch = self.make_branch('base', format="1.9")
1303
request = smart_branch.SmartServerBranchRequestSetParentLocation(
1304
self.get_transport())
1305
branch_token, repo_token = self.get_lock_tokens(branch)
1307
response = request.execute('base', branch_token, repo_token,
1311
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), response)
1312
self.assertEqual('http://bar/', branch.get_parent())
1315
class TestSmartServerBranchRequestGetTagsBytes(
1316
tests.TestCaseWithMemoryTransport):
1317
# Only called when the branch format and tags match [yay factory
1318
# methods] so only need to test straight forward cases.
1320
def test_get_bytes(self):
1321
base_branch = self.make_branch('base')
1322
request = smart_branch.SmartServerBranchGetTagsBytes(
1323
self.get_transport())
1324
response = request.execute('base')
1326
smart_req.SuccessfulSmartServerResponse(('',)), response)
1329
class TestSmartServerBranchRequestGetStackedOnURL(tests.TestCaseWithMemoryTransport):
1331
def test_get_stacked_on_url(self):
1332
base_branch = self.make_branch('base', format='1.6')
1333
stacked_branch = self.make_branch('stacked', format='1.6')
1334
# typically should be relative
1335
stacked_branch.set_stacked_on_url('../base')
1336
request = smart_branch.SmartServerBranchRequestGetStackedOnURL(
1337
self.get_transport())
1338
response = request.execute('stacked')
1340
smart_req.SmartServerResponse(('ok', '../base')),
1344
class TestSmartServerBranchRequestLockWrite(TestLockedBranch):
1347
tests.TestCaseWithMemoryTransport.setUp(self)
1349
def test_lock_write_on_unlocked_branch(self):
1350
backing = self.get_transport()
1351
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1352
branch = self.make_branch('.', format='knit')
1353
repository = branch.repository
1354
response = request.execute('')
1355
branch_nonce = branch.control_files._lock.peek().get('nonce')
1356
repository_nonce = repository.control_files._lock.peek().get('nonce')
1357
self.assertEqual(smart_req.SmartServerResponse(
1358
('ok', branch_nonce, repository_nonce)),
1360
# The branch (and associated repository) is now locked. Verify that
1361
# with a new branch object.
1362
new_branch = repository.bzrdir.open_branch()
1363
self.assertRaises(errors.LockContention, new_branch.lock_write)
1365
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1366
response = request.execute('', branch_nonce, repository_nonce)
1368
def test_lock_write_on_locked_branch(self):
1369
backing = self.get_transport()
1370
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1371
branch = self.make_branch('.')
1372
branch_token = branch.lock_write().branch_token
1373
branch.leave_lock_in_place()
1375
response = request.execute('')
1377
smart_req.SmartServerResponse(('LockContention',)), response)
1379
branch.lock_write(branch_token)
1380
branch.dont_leave_lock_in_place()
1383
def test_lock_write_with_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, repo_token)
1394
smart_req.SmartServerResponse(('ok', branch_token, repo_token)),
1397
branch.repository.lock_write(repo_token)
1398
branch.repository.dont_leave_lock_in_place()
1399
branch.repository.unlock()
1400
branch.lock_write(branch_token)
1401
branch.dont_leave_lock_in_place()
1404
def test_lock_write_with_mismatched_tokens_on_locked_branch(self):
1405
backing = self.get_transport()
1406
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1407
branch = self.make_branch('.', format='knit')
1408
branch_token, repo_token = self.get_lock_tokens(branch)
1409
branch.leave_lock_in_place()
1410
branch.repository.leave_lock_in_place()
1412
response = request.execute('',
1413
branch_token+'xxx', repo_token)
1415
smart_req.SmartServerResponse(('TokenMismatch',)), response)
1417
branch.repository.lock_write(repo_token)
1418
branch.repository.dont_leave_lock_in_place()
1419
branch.repository.unlock()
1420
branch.lock_write(branch_token)
1421
branch.dont_leave_lock_in_place()
1424
def test_lock_write_on_locked_repo(self):
1425
backing = self.get_transport()
1426
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1427
branch = self.make_branch('.', format='knit')
1428
repo = branch.repository
1429
repo_token = repo.lock_write().repository_token
1430
repo.leave_lock_in_place()
1432
response = request.execute('')
1434
smart_req.SmartServerResponse(('LockContention',)), response)
1436
repo.lock_write(repo_token)
1437
repo.dont_leave_lock_in_place()
1440
def test_lock_write_on_readonly_transport(self):
1441
backing = self.get_readonly_transport()
1442
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1443
branch = self.make_branch('.')
1444
root = self.get_transport().clone('/')
1445
path = urlutils.relative_url(root.base, self.get_transport().base)
1446
response = request.execute(path)
1447
error_name, lock_str, why_str = response.args
1448
self.assertFalse(response.is_successful())
1449
self.assertEqual('LockFailed', error_name)
1452
class TestSmartServerBranchRequestGetPhysicalLockStatus(TestLockedBranch):
1455
tests.TestCaseWithMemoryTransport.setUp(self)
1457
def test_true(self):
1458
backing = self.get_transport()
1459
request = smart_branch.SmartServerBranchRequestGetPhysicalLockStatus(
1461
branch = self.make_branch('.')
1462
branch_token, repo_token = self.get_lock_tokens(branch)
1463
self.assertEquals(True, branch.get_physical_lock_status())
1464
response = request.execute('')
1466
smart_req.SmartServerResponse(('yes',)), response)
1469
def test_false(self):
1470
backing = self.get_transport()
1471
request = smart_branch.SmartServerBranchRequestGetPhysicalLockStatus(
1473
branch = self.make_branch('.')
1474
self.assertEquals(False, branch.get_physical_lock_status())
1475
response = request.execute('')
1477
smart_req.SmartServerResponse(('no',)), response)
1480
class TestSmartServerBranchRequestUnlock(TestLockedBranch):
1483
tests.TestCaseWithMemoryTransport.setUp(self)
1485
def test_unlock_on_locked_branch_and_repo(self):
1486
backing = self.get_transport()
1487
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1488
branch = self.make_branch('.', format='knit')
1490
branch_token, repo_token = self.get_lock_tokens(branch)
1491
# Unlock the branch (and repo) object, leaving the physical locks
1493
branch.leave_lock_in_place()
1494
branch.repository.leave_lock_in_place()
1496
response = request.execute('',
1497
branch_token, repo_token)
1499
smart_req.SmartServerResponse(('ok',)), response)
1500
# The branch is now unlocked. Verify that with a new branch
1502
new_branch = branch.bzrdir.open_branch()
1503
new_branch.lock_write()
1506
def test_unlock_on_unlocked_branch_unlocked_repo(self):
1507
backing = self.get_transport()
1508
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1509
branch = self.make_branch('.', format='knit')
1510
response = request.execute(
1511
'', 'branch token', 'repo token')
1513
smart_req.SmartServerResponse(('TokenMismatch',)), response)
1515
def test_unlock_on_unlocked_branch_locked_repo(self):
1516
backing = self.get_transport()
1517
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1518
branch = self.make_branch('.', format='knit')
1519
# Lock the repository.
1520
repo_token = branch.repository.lock_write().repository_token
1521
branch.repository.leave_lock_in_place()
1522
branch.repository.unlock()
1523
# Issue branch lock_write request on the unlocked branch (with locked
1525
response = request.execute('', 'branch token', repo_token)
1527
smart_req.SmartServerResponse(('TokenMismatch',)), response)
1529
branch.repository.lock_write(repo_token)
1530
branch.repository.dont_leave_lock_in_place()
1531
branch.repository.unlock()
1534
class TestSmartServerRepositoryRequest(tests.TestCaseWithMemoryTransport):
1536
def test_no_repository(self):
1537
"""Raise NoRepositoryPresent when there is a bzrdir and no repo."""
1538
# we test this using a shared repository above the named path,
1539
# thus checking the right search logic is used - that is, that
1540
# its the exact path being looked at and the server is not
1542
backing = self.get_transport()
1543
request = smart_repo.SmartServerRepositoryRequest(backing)
1544
self.make_repository('.', shared=True)
1545
self.make_bzrdir('subdir')
1546
self.assertRaises(errors.NoRepositoryPresent,
1547
request.execute, 'subdir')
1550
class TestSmartServerRepositoryAddSignatureText(tests.TestCaseWithMemoryTransport):
1552
def test_add_text(self):
1553
backing = self.get_transport()
1554
request = smart_repo.SmartServerRepositoryAddSignatureText(backing)
1555
tree = self.make_branch_and_memory_tree('.')
1556
write_token = tree.lock_write()
1557
self.addCleanup(tree.unlock)
1559
tree.commit("Message", rev_id='rev1')
1560
tree.branch.repository.start_write_group()
1561
write_group_tokens = tree.branch.repository.suspend_write_group()
1562
self.assertEqual(None, request.execute('', write_token,
1563
'rev1', *write_group_tokens))
1564
response = request.do_body('somesignature')
1565
self.assertTrue(response.is_successful())
1566
self.assertEqual(response.args[0], 'ok')
1567
write_group_tokens = response.args[1:]
1568
tree.branch.repository.resume_write_group(write_group_tokens)
1569
tree.branch.repository.commit_write_group()
1571
self.assertEqual("somesignature",
1572
tree.branch.repository.get_signature_text("rev1"))
1575
class TestSmartServerRepositoryAllRevisionIds(
1576
tests.TestCaseWithMemoryTransport):
1578
def test_empty(self):
1579
"""An empty body should be returned for an empty repository."""
1580
backing = self.get_transport()
1581
request = smart_repo.SmartServerRepositoryAllRevisionIds(backing)
1582
self.make_repository('.')
1584
smart_req.SuccessfulSmartServerResponse(("ok", ), ""),
1585
request.execute(''))
1587
def test_some_revisions(self):
1588
"""An empty body should be returned for an empty repository."""
1589
backing = self.get_transport()
1590
request = smart_repo.SmartServerRepositoryAllRevisionIds(backing)
1591
tree = self.make_branch_and_memory_tree('.')
1594
tree.commit(rev_id='origineel', message="message")
1595
tree.commit(rev_id='nog-een-revisie', message="message")
1598
smart_req.SuccessfulSmartServerResponse(("ok", ),
1599
"origineel\nnog-een-revisie"),
1600
request.execute(''))
1603
class TestSmartServerRepositoryBreakLock(tests.TestCaseWithMemoryTransport):
1605
def test_lock_to_break(self):
1606
backing = self.get_transport()
1607
request = smart_repo.SmartServerRepositoryBreakLock(backing)
1608
tree = self.make_branch_and_memory_tree('.')
1609
tree.branch.repository.lock_write()
1611
smart_req.SuccessfulSmartServerResponse(('ok', ), None),
1612
request.execute(''))
1614
def test_nothing_to_break(self):
1615
backing = self.get_transport()
1616
request = smart_repo.SmartServerRepositoryBreakLock(backing)
1617
tree = self.make_branch_and_memory_tree('.')
1619
smart_req.SuccessfulSmartServerResponse(('ok', ), None),
1620
request.execute(''))
1623
class TestSmartServerRepositoryGetParentMap(tests.TestCaseWithMemoryTransport):
1625
def test_trivial_bzipped(self):
1626
# This tests that the wire encoding is actually bzipped
1627
backing = self.get_transport()
1628
request = smart_repo.SmartServerRepositoryGetParentMap(backing)
1629
tree = self.make_branch_and_memory_tree('.')
1631
self.assertEqual(None,
1632
request.execute('', 'missing-id'))
1633
# Note that it returns a body that is bzipped.
1635
smart_req.SuccessfulSmartServerResponse(('ok', ), bz2.compress('')),
1636
request.do_body('\n\n0\n'))
1638
def test_trivial_include_missing(self):
1639
backing = self.get_transport()
1640
request = smart_repo.SmartServerRepositoryGetParentMap(backing)
1641
tree = self.make_branch_and_memory_tree('.')
1643
self.assertEqual(None,
1644
request.execute('', 'missing-id', 'include-missing:'))
1646
smart_req.SuccessfulSmartServerResponse(('ok', ),
1647
bz2.compress('missing:missing-id')),
1648
request.do_body('\n\n0\n'))
1651
class TestSmartServerRepositoryGetRevisionGraph(
1652
tests.TestCaseWithMemoryTransport):
1654
def test_none_argument(self):
1655
backing = self.get_transport()
1656
request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1657
tree = self.make_branch_and_memory_tree('.')
1660
r1 = tree.commit('1st commit')
1661
r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1664
# the lines of revision_id->revision_parent_list has no guaranteed
1665
# order coming out of a dict, so sort both our test and response
1666
lines = sorted([' '.join([r2, r1]), r1])
1667
response = request.execute('', '')
1668
response.body = '\n'.join(sorted(response.body.split('\n')))
1671
smart_req.SmartServerResponse(('ok', ), '\n'.join(lines)), response)
1673
def test_specific_revision_argument(self):
1674
backing = self.get_transport()
1675
request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1676
tree = self.make_branch_and_memory_tree('.')
1679
rev_id_utf8 = u'\xc9'.encode('utf-8')
1680
r1 = tree.commit('1st commit', rev_id=rev_id_utf8)
1681
r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1684
self.assertEqual(smart_req.SmartServerResponse(('ok', ), rev_id_utf8),
1685
request.execute('', rev_id_utf8))
1687
def test_no_such_revision(self):
1688
backing = self.get_transport()
1689
request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1690
tree = self.make_branch_and_memory_tree('.')
1693
r1 = tree.commit('1st commit')
1696
# Note that it still returns body (of zero bytes).
1697
self.assertEqual(smart_req.SmartServerResponse(
1698
('nosuchrevision', 'missingrevision', ), ''),
1699
request.execute('', 'missingrevision'))
1702
class TestSmartServerRepositoryGetRevIdForRevno(
1703
tests.TestCaseWithMemoryTransport):
1705
def test_revno_found(self):
1706
backing = self.get_transport()
1707
request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1708
tree = self.make_branch_and_memory_tree('.')
1711
rev1_id_utf8 = u'\xc8'.encode('utf-8')
1712
rev2_id_utf8 = u'\xc9'.encode('utf-8')
1713
tree.commit('1st commit', rev_id=rev1_id_utf8)
1714
tree.commit('2nd commit', rev_id=rev2_id_utf8)
1717
self.assertEqual(smart_req.SmartServerResponse(('ok', rev1_id_utf8)),
1718
request.execute('', 1, (2, rev2_id_utf8)))
1720
def test_known_revid_missing(self):
1721
backing = self.get_transport()
1722
request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1723
repo = self.make_repository('.')
1725
smart_req.FailedSmartServerResponse(('nosuchrevision', 'ghost')),
1726
request.execute('', 1, (2, 'ghost')))
1728
def test_history_incomplete(self):
1729
backing = self.get_transport()
1730
request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1731
parent = self.make_branch_and_memory_tree('parent', format='1.9')
1733
parent.add([''], ['TREE_ROOT'])
1734
r1 = parent.commit(message='first commit')
1735
r2 = parent.commit(message='second commit')
1737
local = self.make_branch_and_memory_tree('local', format='1.9')
1738
local.branch.pull(parent.branch)
1739
local.set_parent_ids([r2])
1740
r3 = local.commit(message='local commit')
1741
local.branch.create_clone_on_transport(
1742
self.get_transport('stacked'), stacked_on=self.get_url('parent'))
1744
smart_req.SmartServerResponse(('history-incomplete', 2, r2)),
1745
request.execute('stacked', 1, (3, r3)))
1748
class TestSmartServerRepositoryIterRevisions(
1749
tests.TestCaseWithMemoryTransport):
1751
def test_basic(self):
1752
backing = self.get_transport()
1753
request = smart_repo.SmartServerRepositoryIterRevisions(backing)
1754
tree = self.make_branch_and_memory_tree('.', format='2a')
1757
tree.commit('1st commit', rev_id="rev1")
1758
tree.commit('2nd commit', rev_id="rev2")
1761
self.assertIs(None, request.execute(''))
1762
response = request.do_body("rev1\nrev2")
1763
self.assertTrue(response.is_successful())
1764
# Format 2a uses serializer format 10
1765
self.assertEquals(response.args, ("ok", "10"))
1767
self.addCleanup(tree.branch.lock_read().unlock)
1768
entries = [zlib.compress(record.get_bytes_as("fulltext")) for record in
1769
tree.branch.repository.revisions.get_record_stream(
1770
[("rev1", ), ("rev2", )], "unordered", True)]
1772
contents = "".join(response.body_stream)
1773
self.assertTrue(contents in (
1774
"".join([entries[0], entries[1]]),
1775
"".join([entries[1], entries[0]])))
1777
def test_missing(self):
1778
backing = self.get_transport()
1779
request = smart_repo.SmartServerRepositoryIterRevisions(backing)
1780
tree = self.make_branch_and_memory_tree('.', format='2a')
1782
self.assertIs(None, request.execute(''))
1783
response = request.do_body("rev1\nrev2")
1784
self.assertTrue(response.is_successful())
1785
# Format 2a uses serializer format 10
1786
self.assertEquals(response.args, ("ok", "10"))
1788
contents = "".join(response.body_stream)
1789
self.assertEquals(contents, "")
1792
class GetStreamTestBase(tests.TestCaseWithMemoryTransport):
1794
def make_two_commit_repo(self):
1795
tree = self.make_branch_and_memory_tree('.')
1798
r1 = tree.commit('1st commit')
1799
r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1801
repo = tree.branch.repository
1805
class TestSmartServerRepositoryGetStream(GetStreamTestBase):
1807
def test_ancestry_of(self):
1808
"""The search argument may be a 'ancestry-of' some heads'."""
1809
backing = self.get_transport()
1810
request = smart_repo.SmartServerRepositoryGetStream(backing)
1811
repo, r1, r2 = self.make_two_commit_repo()
1812
fetch_spec = ['ancestry-of', r2]
1813
lines = '\n'.join(fetch_spec)
1814
request.execute('', repo._format.network_name())
1815
response = request.do_body(lines)
1816
self.assertEqual(('ok',), response.args)
1817
stream_bytes = ''.join(response.body_stream)
1818
self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
1820
def test_search(self):
1821
"""The search argument may be a 'search' of some explicit keys."""
1822
backing = self.get_transport()
1823
request = smart_repo.SmartServerRepositoryGetStream(backing)
1824
repo, r1, r2 = self.make_two_commit_repo()
1825
fetch_spec = ['search', '%s %s' % (r1, r2), 'null:', '2']
1826
lines = '\n'.join(fetch_spec)
1827
request.execute('', repo._format.network_name())
1828
response = request.do_body(lines)
1829
self.assertEqual(('ok',), response.args)
1830
stream_bytes = ''.join(response.body_stream)
1831
self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
1833
def test_search_everything(self):
1834
"""A search of 'everything' returns a stream."""
1835
backing = self.get_transport()
1836
request = smart_repo.SmartServerRepositoryGetStream_1_19(backing)
1837
repo, r1, r2 = self.make_two_commit_repo()
1838
serialised_fetch_spec = 'everything'
1839
request.execute('', repo._format.network_name())
1840
response = request.do_body(serialised_fetch_spec)
1841
self.assertEqual(('ok',), response.args)
1842
stream_bytes = ''.join(response.body_stream)
1843
self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
1846
class TestSmartServerRequestHasRevision(tests.TestCaseWithMemoryTransport):
1848
def test_missing_revision(self):
1849
"""For a missing revision, ('no', ) is returned."""
1850
backing = self.get_transport()
1851
request = smart_repo.SmartServerRequestHasRevision(backing)
1852
self.make_repository('.')
1853
self.assertEqual(smart_req.SmartServerResponse(('no', )),
1854
request.execute('', 'revid'))
1856
def test_present_revision(self):
1857
"""For a present revision, ('yes', ) is returned."""
1858
backing = self.get_transport()
1859
request = smart_repo.SmartServerRequestHasRevision(backing)
1860
tree = self.make_branch_and_memory_tree('.')
1863
rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1864
r1 = tree.commit('a commit', rev_id=rev_id_utf8)
1866
self.assertTrue(tree.branch.repository.has_revision(rev_id_utf8))
1867
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
1868
request.execute('', rev_id_utf8))
1871
class TestSmartServerRepositoryIterFilesBytes(tests.TestCaseWithTransport):
1873
def test_single(self):
1874
backing = self.get_transport()
1875
request = smart_repo.SmartServerRepositoryIterFilesBytes(backing)
1876
t = self.make_branch_and_tree('.')
1877
self.addCleanup(t.lock_write().unlock)
1878
self.build_tree_contents([("file", "somecontents")])
1879
t.add(["file"], ["thefileid"])
1880
t.commit(rev_id='somerev', message="add file")
1881
self.assertIs(None, request.execute(''))
1882
response = request.do_body("thefileid\0somerev\n")
1883
self.assertTrue(response.is_successful())
1884
self.assertEquals(response.args, ("ok", ))
1885
self.assertEquals("".join(response.body_stream),
1886
"ok\x000\n" + zlib.compress("somecontents"))
1888
def test_missing(self):
1889
backing = self.get_transport()
1890
request = smart_repo.SmartServerRepositoryIterFilesBytes(backing)
1891
t = self.make_branch_and_tree('.')
1892
self.addCleanup(t.lock_write().unlock)
1893
self.assertIs(None, request.execute(''))
1894
response = request.do_body("thefileid\0revision\n")
1895
self.assertTrue(response.is_successful())
1896
self.assertEquals(response.args, ("ok", ))
1897
self.assertEquals("".join(response.body_stream),
1898
"absent\x00thefileid\x00revision\x000\n")
1901
class TestSmartServerRequestHasSignatureForRevisionId(
1902
tests.TestCaseWithMemoryTransport):
1904
def test_missing_revision(self):
1905
"""For a missing revision, NoSuchRevision is returned."""
1906
backing = self.get_transport()
1907
request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
1909
self.make_repository('.')
1911
smart_req.FailedSmartServerResponse(
1912
('nosuchrevision', 'revid'), None),
1913
request.execute('', 'revid'))
1915
def test_missing_signature(self):
1916
"""For a missing signature, ('no', ) is returned."""
1917
backing = self.get_transport()
1918
request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
1920
tree = self.make_branch_and_memory_tree('.')
1923
r1 = tree.commit('a commit', rev_id='A')
1925
self.assertTrue(tree.branch.repository.has_revision('A'))
1926
self.assertEqual(smart_req.SmartServerResponse(('no', )),
1927
request.execute('', 'A'))
1929
def test_present_signature(self):
1930
"""For a present signature, ('yes', ) is returned."""
1931
backing = self.get_transport()
1932
request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
1934
strategy = gpg.LoopbackGPGStrategy(None)
1935
tree = self.make_branch_and_memory_tree('.')
1938
r1 = tree.commit('a commit', rev_id='A')
1939
tree.branch.repository.start_write_group()
1940
tree.branch.repository.sign_revision('A', strategy)
1941
tree.branch.repository.commit_write_group()
1943
self.assertTrue(tree.branch.repository.has_revision('A'))
1944
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
1945
request.execute('', 'A'))
1948
class TestSmartServerRepositoryGatherStats(tests.TestCaseWithMemoryTransport):
1950
def test_empty_revid(self):
1951
"""With an empty revid, we get only size an number and revisions"""
1952
backing = self.get_transport()
1953
request = smart_repo.SmartServerRepositoryGatherStats(backing)
1954
repository = self.make_repository('.')
1955
stats = repository.gather_stats()
1956
expected_body = 'revisions: 0\n'
1957
self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
1958
request.execute('', '', 'no'))
1960
def test_revid_with_committers(self):
1961
"""For a revid we get more infos."""
1962
backing = self.get_transport()
1963
rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1964
request = smart_repo.SmartServerRepositoryGatherStats(backing)
1965
tree = self.make_branch_and_memory_tree('.')
1968
# Let's build a predictable result
1969
tree.commit('a commit', timestamp=123456.2, timezone=3600)
1970
tree.commit('a commit', timestamp=654321.4, timezone=0,
1974
stats = tree.branch.repository.gather_stats()
1975
expected_body = ('firstrev: 123456.200 3600\n'
1976
'latestrev: 654321.400 0\n'
1978
self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
1982
def test_not_empty_repository_with_committers(self):
1983
"""For a revid and requesting committers we get the whole thing."""
1984
backing = self.get_transport()
1985
rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1986
request = smart_repo.SmartServerRepositoryGatherStats(backing)
1987
tree = self.make_branch_and_memory_tree('.')
1990
# Let's build a predictable result
1991
tree.commit('a commit', timestamp=123456.2, timezone=3600,
1993
tree.commit('a commit', timestamp=654321.4, timezone=0,
1994
committer='bar', rev_id=rev_id_utf8)
1996
stats = tree.branch.repository.gather_stats()
1998
expected_body = ('committers: 2\n'
1999
'firstrev: 123456.200 3600\n'
2000
'latestrev: 654321.400 0\n'
2002
self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
2004
rev_id_utf8, 'yes'))
2006
def test_unknown_revid(self):
2007
"""An unknown revision id causes a 'nosuchrevision' error."""
2008
backing = self.get_transport()
2009
request = smart_repo.SmartServerRepositoryGatherStats(backing)
2010
repository = self.make_repository('.')
2011
expected_body = 'revisions: 0\n'
2013
smart_req.FailedSmartServerResponse(
2014
('nosuchrevision', 'mia'), None),
2015
request.execute('', 'mia', 'yes'))
2018
class TestSmartServerRepositoryIsShared(tests.TestCaseWithMemoryTransport):
2020
def test_is_shared(self):
2021
"""For a shared repository, ('yes', ) is returned."""
2022
backing = self.get_transport()
2023
request = smart_repo.SmartServerRepositoryIsShared(backing)
2024
self.make_repository('.', shared=True)
2025
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
2026
request.execute('', ))
2028
def test_is_not_shared(self):
2029
"""For a shared repository, ('no', ) is returned."""
2030
backing = self.get_transport()
2031
request = smart_repo.SmartServerRepositoryIsShared(backing)
2032
self.make_repository('.', shared=False)
2033
self.assertEqual(smart_req.SmartServerResponse(('no', )),
2034
request.execute('', ))
2037
class TestSmartServerRepositoryGetRevisionSignatureText(
2038
tests.TestCaseWithMemoryTransport):
2040
def test_get_signature(self):
2041
backing = self.get_transport()
2042
request = smart_repo.SmartServerRepositoryGetRevisionSignatureText(
2044
bb = self.make_branch_builder('.')
2045
bb.build_commit(rev_id='A')
2046
repo = bb.get_branch().repository
2047
strategy = gpg.LoopbackGPGStrategy(None)
2048
self.addCleanup(repo.lock_write().unlock)
2049
repo.start_write_group()
2050
repo.sign_revision('A', strategy)
2051
repo.commit_write_group()
2053
'-----BEGIN PSEUDO-SIGNED CONTENT-----\n' +
2054
Testament.from_revision(repo, 'A').as_short_text() +
2055
'-----END PSEUDO-SIGNED CONTENT-----\n')
2057
smart_req.SmartServerResponse(('ok', ), expected_body),
2058
request.execute('', 'A'))
2061
class TestSmartServerRepositoryMakeWorkingTrees(
2062
tests.TestCaseWithMemoryTransport):
2064
def test_make_working_trees(self):
2065
"""For a repository with working trees, ('yes', ) is returned."""
2066
backing = self.get_transport()
2067
request = smart_repo.SmartServerRepositoryMakeWorkingTrees(backing)
2068
r = self.make_repository('.')
2069
r.set_make_working_trees(True)
2070
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
2071
request.execute('', ))
2073
def test_is_not_shared(self):
2074
"""For a repository with working trees, ('no', ) is returned."""
2075
backing = self.get_transport()
2076
request = smart_repo.SmartServerRepositoryMakeWorkingTrees(backing)
2077
r = self.make_repository('.')
2078
r.set_make_working_trees(False)
2079
self.assertEqual(smart_req.SmartServerResponse(('no', )),
2080
request.execute('', ))
2083
class TestSmartServerRepositoryLockWrite(tests.TestCaseWithMemoryTransport):
2085
def test_lock_write_on_unlocked_repo(self):
2086
backing = self.get_transport()
2087
request = smart_repo.SmartServerRepositoryLockWrite(backing)
2088
repository = self.make_repository('.', format='knit')
2089
response = request.execute('')
2090
nonce = repository.control_files._lock.peek().get('nonce')
2091
self.assertEqual(smart_req.SmartServerResponse(('ok', nonce)), response)
2092
# The repository is now locked. Verify that with a new repository
2094
new_repo = repository.bzrdir.open_repository()
2095
self.assertRaises(errors.LockContention, new_repo.lock_write)
2097
request = smart_repo.SmartServerRepositoryUnlock(backing)
2098
response = request.execute('', nonce)
2100
def test_lock_write_on_locked_repo(self):
2101
backing = self.get_transport()
2102
request = smart_repo.SmartServerRepositoryLockWrite(backing)
2103
repository = self.make_repository('.', format='knit')
2104
repo_token = repository.lock_write().repository_token
2105
repository.leave_lock_in_place()
2107
response = request.execute('')
2109
smart_req.SmartServerResponse(('LockContention',)), response)
2111
repository.lock_write(repo_token)
2112
repository.dont_leave_lock_in_place()
2115
def test_lock_write_on_readonly_transport(self):
2116
backing = self.get_readonly_transport()
2117
request = smart_repo.SmartServerRepositoryLockWrite(backing)
2118
repository = self.make_repository('.', format='knit')
2119
response = request.execute('')
2120
self.assertFalse(response.is_successful())
2121
self.assertEqual('LockFailed', response.args[0])
2124
class TestInsertStreamBase(tests.TestCaseWithMemoryTransport):
2126
def make_empty_byte_stream(self, repo):
2127
byte_stream = smart_repo._stream_to_byte_stream([], repo._format)
2128
return ''.join(byte_stream)
2131
class TestSmartServerRepositoryInsertStream(TestInsertStreamBase):
2133
def test_insert_stream_empty(self):
2134
backing = self.get_transport()
2135
request = smart_repo.SmartServerRepositoryInsertStream(backing)
2136
repository = self.make_repository('.')
2137
response = request.execute('', '')
2138
self.assertEqual(None, response)
2139
response = request.do_chunk(self.make_empty_byte_stream(repository))
2140
self.assertEqual(None, response)
2141
response = request.do_end()
2142
self.assertEqual(smart_req.SmartServerResponse(('ok', )), response)
2145
class TestSmartServerRepositoryInsertStreamLocked(TestInsertStreamBase):
2147
def test_insert_stream_empty(self):
2148
backing = self.get_transport()
2149
request = smart_repo.SmartServerRepositoryInsertStreamLocked(
2151
repository = self.make_repository('.', format='knit')
2152
lock_token = repository.lock_write().repository_token
2153
response = request.execute('', '', lock_token)
2154
self.assertEqual(None, response)
2155
response = request.do_chunk(self.make_empty_byte_stream(repository))
2156
self.assertEqual(None, response)
2157
response = request.do_end()
2158
self.assertEqual(smart_req.SmartServerResponse(('ok', )), response)
2161
def test_insert_stream_with_wrong_lock_token(self):
2162
backing = self.get_transport()
2163
request = smart_repo.SmartServerRepositoryInsertStreamLocked(
2165
repository = self.make_repository('.', format='knit')
2166
lock_token = repository.lock_write().repository_token
2168
errors.TokenMismatch, request.execute, '', '', 'wrong-token')
2172
class TestSmartServerRepositoryUnlock(tests.TestCaseWithMemoryTransport):
2175
tests.TestCaseWithMemoryTransport.setUp(self)
2177
def test_unlock_on_locked_repo(self):
2178
backing = self.get_transport()
2179
request = smart_repo.SmartServerRepositoryUnlock(backing)
2180
repository = self.make_repository('.', format='knit')
2181
token = repository.lock_write().repository_token
2182
repository.leave_lock_in_place()
2184
response = request.execute('', token)
2186
smart_req.SmartServerResponse(('ok',)), response)
2187
# The repository is now unlocked. Verify that with a new repository
2189
new_repo = repository.bzrdir.open_repository()
2190
new_repo.lock_write()
2193
def test_unlock_on_unlocked_repo(self):
2194
backing = self.get_transport()
2195
request = smart_repo.SmartServerRepositoryUnlock(backing)
2196
repository = self.make_repository('.', format='knit')
2197
response = request.execute('', 'some token')
2199
smart_req.SmartServerResponse(('TokenMismatch',)), response)
2202
class TestSmartServerRepositoryGetPhysicalLockStatus(
2203
tests.TestCaseWithTransport):
2205
def test_with_write_lock(self):
2206
backing = self.get_transport()
2207
repo = self.make_repository('.')
2208
self.addCleanup(repo.lock_write().unlock)
2209
# lock_write() doesn't necessarily actually take a physical
2211
if repo.get_physical_lock_status():
2215
request_class = smart_repo.SmartServerRepositoryGetPhysicalLockStatus
2216
request = request_class(backing)
2217
self.assertEqual(smart_req.SuccessfulSmartServerResponse((expected,)),
2218
request.execute('', ))
2220
def test_without_write_lock(self):
2221
backing = self.get_transport()
2222
repo = self.make_repository('.')
2223
self.assertEquals(False, repo.get_physical_lock_status())
2224
request_class = smart_repo.SmartServerRepositoryGetPhysicalLockStatus
2225
request = request_class(backing)
2226
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('no',)),
2227
request.execute('', ))
2230
class TestSmartServerRepositoryReconcile(tests.TestCaseWithTransport):
2232
def test_reconcile(self):
2233
backing = self.get_transport()
2234
repo = self.make_repository('.')
2235
token = repo.lock_write().repository_token
2236
self.addCleanup(repo.unlock)
2237
request_class = smart_repo.SmartServerRepositoryReconcile
2238
request = request_class(backing)
2239
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
2241
'garbage_inventories: 0\n'
2242
'inconsistent_parents: 0\n'),
2243
request.execute('', token))
2246
class TestSmartServerIsReadonly(tests.TestCaseWithMemoryTransport):
2248
def test_is_readonly_no(self):
2249
backing = self.get_transport()
2250
request = smart_req.SmartServerIsReadonly(backing)
2251
response = request.execute()
2253
smart_req.SmartServerResponse(('no',)), response)
2255
def test_is_readonly_yes(self):
2256
backing = self.get_readonly_transport()
2257
request = smart_req.SmartServerIsReadonly(backing)
2258
response = request.execute()
2260
smart_req.SmartServerResponse(('yes',)), response)
2263
class TestSmartServerRepositorySetMakeWorkingTrees(
2264
tests.TestCaseWithMemoryTransport):
2266
def test_set_false(self):
2267
backing = self.get_transport()
2268
repo = self.make_repository('.', shared=True)
2269
repo.set_make_working_trees(True)
2270
request_class = smart_repo.SmartServerRepositorySetMakeWorkingTrees
2271
request = request_class(backing)
2272
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2273
request.execute('', 'False'))
2274
repo = repo.bzrdir.open_repository()
2275
self.assertFalse(repo.make_working_trees())
2277
def test_set_true(self):
2278
backing = self.get_transport()
2279
repo = self.make_repository('.', shared=True)
2280
repo.set_make_working_trees(False)
2281
request_class = smart_repo.SmartServerRepositorySetMakeWorkingTrees
2282
request = request_class(backing)
2283
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2284
request.execute('', 'True'))
2285
repo = repo.bzrdir.open_repository()
2286
self.assertTrue(repo.make_working_trees())
2289
class TestSmartServerRepositoryGetSerializerFormat(
2290
tests.TestCaseWithMemoryTransport):
2292
def test_get_serializer_format(self):
2293
backing = self.get_transport()
2294
repo = self.make_repository('.', format='2a')
2295
request_class = smart_repo.SmartServerRepositoryGetSerializerFormat
2296
request = request_class(backing)
2298
smart_req.SuccessfulSmartServerResponse(('ok', '10')),
2299
request.execute(''))
2302
class TestSmartServerRepositoryWriteGroup(
2303
tests.TestCaseWithMemoryTransport):
2305
def test_start_write_group(self):
2306
backing = self.get_transport()
2307
repo = self.make_repository('.')
2308
lock_token = repo.lock_write().repository_token
2309
self.addCleanup(repo.unlock)
2310
request_class = smart_repo.SmartServerRepositoryStartWriteGroup
2311
request = request_class(backing)
2312
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok', [])),
2313
request.execute('', lock_token))
2315
def test_start_write_group_unsuspendable(self):
2316
backing = self.get_transport()
2317
repo = self.make_repository('.', format='knit')
2318
lock_token = repo.lock_write().repository_token
2319
self.addCleanup(repo.unlock)
2320
request_class = smart_repo.SmartServerRepositoryStartWriteGroup
2321
request = request_class(backing)
2323
smart_req.FailedSmartServerResponse(('UnsuspendableWriteGroup',)),
2324
request.execute('', lock_token))
2326
def test_commit_write_group(self):
2327
backing = self.get_transport()
2328
repo = self.make_repository('.')
2329
lock_token = repo.lock_write().repository_token
2330
self.addCleanup(repo.unlock)
2331
repo.start_write_group()
2332
tokens = repo.suspend_write_group()
2333
request_class = smart_repo.SmartServerRepositoryCommitWriteGroup
2334
request = request_class(backing)
2335
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2336
request.execute('', lock_token, tokens))
2338
def test_abort_write_group(self):
2339
backing = self.get_transport()
2340
repo = self.make_repository('.')
2341
lock_token = repo.lock_write().repository_token
2342
repo.start_write_group()
2343
tokens = repo.suspend_write_group()
2344
self.addCleanup(repo.unlock)
2345
request_class = smart_repo.SmartServerRepositoryAbortWriteGroup
2346
request = request_class(backing)
2347
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2348
request.execute('', lock_token, tokens))
2350
def test_check_write_group(self):
2351
backing = self.get_transport()
2352
repo = self.make_repository('.')
2353
lock_token = repo.lock_write().repository_token
2354
repo.start_write_group()
2355
tokens = repo.suspend_write_group()
2356
self.addCleanup(repo.unlock)
2357
request_class = smart_repo.SmartServerRepositoryCheckWriteGroup
2358
request = request_class(backing)
2359
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2360
request.execute('', lock_token, tokens))
2362
def test_check_write_group_invalid(self):
2363
backing = self.get_transport()
2364
repo = self.make_repository('.')
2365
lock_token = repo.lock_write().repository_token
2366
self.addCleanup(repo.unlock)
2367
request_class = smart_repo.SmartServerRepositoryCheckWriteGroup
2368
request = request_class(backing)
2369
self.assertEqual(smart_req.FailedSmartServerResponse(
2370
('UnresumableWriteGroup', ['random'],
2371
'Malformed write group token')),
2372
request.execute('', lock_token, ["random"]))
2375
class TestSmartServerPackRepositoryAutopack(tests.TestCaseWithTransport):
2377
def make_repo_needing_autopacking(self, path='.'):
2378
# Make a repo in need of autopacking.
2379
tree = self.make_branch_and_tree('.', format='pack-0.92')
2380
repo = tree.branch.repository
2381
# monkey-patch the pack collection to disable autopacking
2382
repo._pack_collection._max_pack_count = lambda count: count
2384
tree.commit('commit %s' % x)
2385
self.assertEqual(10, len(repo._pack_collection.names()))
2386
del repo._pack_collection._max_pack_count
2389
def test_autopack_needed(self):
2390
repo = self.make_repo_needing_autopacking()
2392
self.addCleanup(repo.unlock)
2393
backing = self.get_transport()
2394
request = smart_packrepo.SmartServerPackRepositoryAutopack(
2396
response = request.execute('')
2397
self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
2398
repo._pack_collection.reload_pack_names()
2399
self.assertEqual(1, len(repo._pack_collection.names()))
2401
def test_autopack_not_needed(self):
2402
tree = self.make_branch_and_tree('.', format='pack-0.92')
2403
repo = tree.branch.repository
2405
self.addCleanup(repo.unlock)
2407
tree.commit('commit %s' % x)
2408
backing = self.get_transport()
2409
request = smart_packrepo.SmartServerPackRepositoryAutopack(
2411
response = request.execute('')
2412
self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
2413
repo._pack_collection.reload_pack_names()
2414
self.assertEqual(9, len(repo._pack_collection.names()))
2416
def test_autopack_on_nonpack_format(self):
2417
"""A request to autopack a non-pack repo is a no-op."""
2418
repo = self.make_repository('.', format='knit')
2419
backing = self.get_transport()
2420
request = smart_packrepo.SmartServerPackRepositoryAutopack(
2422
response = request.execute('')
2423
self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
2426
class TestSmartServerVfsGet(tests.TestCaseWithMemoryTransport):
2428
def test_unicode_path(self):
2429
"""VFS requests expect unicode paths to be escaped."""
2430
filename = u'foo\N{INTERROBANG}'
2431
filename_escaped = urlutils.escape(filename)
2432
backing = self.get_transport()
2433
request = vfs.GetRequest(backing)
2434
backing.put_bytes_non_atomic(filename_escaped, 'contents')
2435
self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'contents'),
2436
request.execute(filename_escaped))
2439
class TestHandlers(tests.TestCase):
2440
"""Tests for the request.request_handlers object."""
2442
def test_all_registrations_exist(self):
2443
"""All registered request_handlers can be found."""
2444
# If there's a typo in a register_lazy call, this loop will fail with
2445
# an AttributeError.
2446
for key in smart_req.request_handlers.keys():
2448
item = smart_req.request_handlers.get(key)
2449
except AttributeError, e:
2450
raise AttributeError('failed to get %s: %s' % (key, e))
2452
def assertHandlerEqual(self, verb, handler):
2453
self.assertEqual(smart_req.request_handlers.get(verb), handler)
2455
def test_registered_methods(self):
2456
"""Test that known methods are registered to the correct object."""
2457
self.assertHandlerEqual('Branch.break_lock',
2458
smart_branch.SmartServerBranchBreakLock)
2459
self.assertHandlerEqual('Branch.get_config_file',
2460
smart_branch.SmartServerBranchGetConfigFile)
2461
self.assertHandlerEqual('Branch.put_config_file',
2462
smart_branch.SmartServerBranchPutConfigFile)
2463
self.assertHandlerEqual('Branch.get_parent',
2464
smart_branch.SmartServerBranchGetParent)
2465
self.assertHandlerEqual('Branch.get_physical_lock_status',
2466
smart_branch.SmartServerBranchRequestGetPhysicalLockStatus)
2467
self.assertHandlerEqual('Branch.get_tags_bytes',
2468
smart_branch.SmartServerBranchGetTagsBytes)
2469
self.assertHandlerEqual('Branch.lock_write',
2470
smart_branch.SmartServerBranchRequestLockWrite)
2471
self.assertHandlerEqual('Branch.last_revision_info',
2472
smart_branch.SmartServerBranchRequestLastRevisionInfo)
2473
self.assertHandlerEqual('Branch.revision_history',
2474
smart_branch.SmartServerRequestRevisionHistory)
2475
self.assertHandlerEqual('Branch.revision_id_to_revno',
2476
smart_branch.SmartServerBranchRequestRevisionIdToRevno)
2477
self.assertHandlerEqual('Branch.set_config_option',
2478
smart_branch.SmartServerBranchRequestSetConfigOption)
2479
self.assertHandlerEqual('Branch.set_last_revision',
2480
smart_branch.SmartServerBranchRequestSetLastRevision)
2481
self.assertHandlerEqual('Branch.set_last_revision_info',
2482
smart_branch.SmartServerBranchRequestSetLastRevisionInfo)
2483
self.assertHandlerEqual('Branch.set_last_revision_ex',
2484
smart_branch.SmartServerBranchRequestSetLastRevisionEx)
2485
self.assertHandlerEqual('Branch.set_parent_location',
2486
smart_branch.SmartServerBranchRequestSetParentLocation)
2487
self.assertHandlerEqual('Branch.unlock',
2488
smart_branch.SmartServerBranchRequestUnlock)
2489
self.assertHandlerEqual('BzrDir.destroy_branch',
2490
smart_dir.SmartServerBzrDirRequestDestroyBranch)
2491
self.assertHandlerEqual('BzrDir.find_repository',
2492
smart_dir.SmartServerRequestFindRepositoryV1)
2493
self.assertHandlerEqual('BzrDir.find_repositoryV2',
2494
smart_dir.SmartServerRequestFindRepositoryV2)
2495
self.assertHandlerEqual('BzrDirFormat.initialize',
2496
smart_dir.SmartServerRequestInitializeBzrDir)
2497
self.assertHandlerEqual('BzrDirFormat.initialize_ex_1.16',
2498
smart_dir.SmartServerRequestBzrDirInitializeEx)
2499
self.assertHandlerEqual('BzrDir.checkout_metadir',
2500
smart_dir.SmartServerBzrDirRequestCheckoutMetaDir)
2501
self.assertHandlerEqual('BzrDir.cloning_metadir',
2502
smart_dir.SmartServerBzrDirRequestCloningMetaDir)
2503
self.assertHandlerEqual('BzrDir.get_config_file',
2504
smart_dir.SmartServerBzrDirRequestConfigFile)
2505
self.assertHandlerEqual('BzrDir.open_branch',
2506
smart_dir.SmartServerRequestOpenBranch)
2507
self.assertHandlerEqual('BzrDir.open_branchV2',
2508
smart_dir.SmartServerRequestOpenBranchV2)
2509
self.assertHandlerEqual('BzrDir.open_branchV3',
2510
smart_dir.SmartServerRequestOpenBranchV3)
2511
self.assertHandlerEqual('PackRepository.autopack',
2512
smart_packrepo.SmartServerPackRepositoryAutopack)
2513
self.assertHandlerEqual('Repository.add_signature_text',
2514
smart_repo.SmartServerRepositoryAddSignatureText)
2515
self.assertHandlerEqual('Repository.all_revision_ids',
2516
smart_repo.SmartServerRepositoryAllRevisionIds)
2517
self.assertHandlerEqual('Repository.break_lock',
2518
smart_repo.SmartServerRepositoryBreakLock)
2519
self.assertHandlerEqual('Repository.gather_stats',
2520
smart_repo.SmartServerRepositoryGatherStats)
2521
self.assertHandlerEqual('Repository.get_parent_map',
2522
smart_repo.SmartServerRepositoryGetParentMap)
2523
self.assertHandlerEqual('Repository.get_physical_lock_status',
2524
smart_repo.SmartServerRepositoryGetPhysicalLockStatus)
2525
self.assertHandlerEqual('Repository.get_rev_id_for_revno',
2526
smart_repo.SmartServerRepositoryGetRevIdForRevno)
2527
self.assertHandlerEqual('Repository.get_revision_graph',
2528
smart_repo.SmartServerRepositoryGetRevisionGraph)
2529
self.assertHandlerEqual('Repository.get_revision_signature_text',
2530
smart_repo.SmartServerRepositoryGetRevisionSignatureText)
2531
self.assertHandlerEqual('Repository.get_stream',
2532
smart_repo.SmartServerRepositoryGetStream)
2533
self.assertHandlerEqual('Repository.get_stream_1.19',
2534
smart_repo.SmartServerRepositoryGetStream_1_19)
2535
self.assertHandlerEqual('Repository.iter_revisions',
2536
smart_repo.SmartServerRepositoryIterRevisions)
2537
self.assertHandlerEqual('Repository.has_revision',
2538
smart_repo.SmartServerRequestHasRevision)
2539
self.assertHandlerEqual('Repository.insert_stream',
2540
smart_repo.SmartServerRepositoryInsertStream)
2541
self.assertHandlerEqual('Repository.insert_stream_locked',
2542
smart_repo.SmartServerRepositoryInsertStreamLocked)
2543
self.assertHandlerEqual('Repository.is_shared',
2544
smart_repo.SmartServerRepositoryIsShared)
2545
self.assertHandlerEqual('Repository.iter_files_bytes',
2546
smart_repo.SmartServerRepositoryIterFilesBytes)
2547
self.assertHandlerEqual('Repository.lock_write',
2548
smart_repo.SmartServerRepositoryLockWrite)
2549
self.assertHandlerEqual('Repository.make_working_trees',
2550
smart_repo.SmartServerRepositoryMakeWorkingTrees)
2551
self.assertHandlerEqual('Repository.pack',
2552
smart_repo.SmartServerRepositoryPack)
2553
self.assertHandlerEqual('Repository.reconcile',
2554
smart_repo.SmartServerRepositoryReconcile)
2555
self.assertHandlerEqual('Repository.tarball',
2556
smart_repo.SmartServerRepositoryTarball)
2557
self.assertHandlerEqual('Repository.unlock',
2558
smart_repo.SmartServerRepositoryUnlock)
2559
self.assertHandlerEqual('Repository.start_write_group',
2560
smart_repo.SmartServerRepositoryStartWriteGroup)
2561
self.assertHandlerEqual('Repository.check_write_group',
2562
smart_repo.SmartServerRepositoryCheckWriteGroup)
2563
self.assertHandlerEqual('Repository.commit_write_group',
2564
smart_repo.SmartServerRepositoryCommitWriteGroup)
2565
self.assertHandlerEqual('Repository.abort_write_group',
2566
smart_repo.SmartServerRepositoryAbortWriteGroup)
2567
self.assertHandlerEqual('VersionedFileRepository.get_serializer_format',
2568
smart_repo.SmartServerRepositoryGetSerializerFormat)
2569
self.assertHandlerEqual('VersionedFileRepository.get_inventories',
2570
smart_repo.SmartServerRepositoryGetInventories)
2571
self.assertHandlerEqual('Transport.is_readonly',
2572
smart_req.SmartServerIsReadonly)
2575
class SmartTCPServerHookTests(tests.TestCaseWithMemoryTransport):
2576
"""Tests for SmartTCPServer hooks."""
2579
super(SmartTCPServerHookTests, self).setUp()
2580
self.server = server.SmartTCPServer(self.get_transport())
2582
def test_run_server_started_hooks(self):
2583
"""Test the server started hooks get fired properly."""
2585
server.SmartTCPServer.hooks.install_named_hook('server_started',
2586
lambda backing_urls, url: started_calls.append((backing_urls, url)),
2588
started_ex_calls = []
2589
server.SmartTCPServer.hooks.install_named_hook('server_started_ex',
2590
lambda backing_urls, url: started_ex_calls.append((backing_urls, url)),
2592
self.server._sockname = ('example.com', 42)
2593
self.server.run_server_started_hooks()
2594
self.assertEquals(started_calls,
2595
[([self.get_transport().base], 'bzr://example.com:42/')])
2596
self.assertEquals(started_ex_calls,
2597
[([self.get_transport().base], self.server)])
2599
def test_run_server_started_hooks_ipv6(self):
2600
"""Test that socknames can contain 4-tuples."""
2601
self.server._sockname = ('::', 42, 0, 0)
2603
server.SmartTCPServer.hooks.install_named_hook('server_started',
2604
lambda backing_urls, url: started_calls.append((backing_urls, url)),
2606
self.server.run_server_started_hooks()
2607
self.assertEquals(started_calls,
2608
[([self.get_transport().base], 'bzr://:::42/')])
2610
def test_run_server_stopped_hooks(self):
2611
"""Test the server stopped hooks."""
2612
self.server._sockname = ('example.com', 42)
2614
server.SmartTCPServer.hooks.install_named_hook('server_stopped',
2615
lambda backing_urls, url: stopped_calls.append((backing_urls, url)),
2617
self.server.run_server_stopped_hooks()
2618
self.assertEquals(stopped_calls,
2619
[([self.get_transport().base], 'bzr://example.com:42/')])
2622
class TestSmartServerRepositoryPack(tests.TestCaseWithMemoryTransport):
2624
def test_pack(self):
2625
backing = self.get_transport()
2626
request = smart_repo.SmartServerRepositoryPack(backing)
2627
tree = self.make_branch_and_memory_tree('.')
2628
repo_token = tree.branch.repository.lock_write().repository_token
2630
self.assertIs(None, request.execute('', repo_token, False))
2633
smart_req.SuccessfulSmartServerResponse(('ok', ), ),
2634
request.do_body(''))
2637
class TestSmartServerRepositoryGetInventories(tests.TestCaseWithTransport):
2639
def _get_serialized_inventory_delta(self, repository, base_revid, revid):
2640
base_inv = repository.revision_tree(base_revid).inventory
2641
inv = repository.revision_tree(revid).inventory
2642
inv_delta = inv._make_delta(base_inv)
2643
serializer = inventory_delta.InventoryDeltaSerializer(True, False)
2644
return "".join(serializer.delta_to_lines(base_revid, revid, inv_delta))
2646
def test_single(self):
2647
backing = self.get_transport()
2648
request = smart_repo.SmartServerRepositoryGetInventories(backing)
2649
t = self.make_branch_and_tree('.', format='2a')
2650
self.addCleanup(t.lock_write().unlock)
2651
self.build_tree_contents([("file", "somecontents")])
2652
t.add(["file"], ["thefileid"])
2653
t.commit(rev_id='somerev', message="add file")
2654
self.assertIs(None, request.execute('', 'unordered'))
2655
response = request.do_body("somerev\n")
2656
self.assertTrue(response.is_successful())
2657
self.assertEquals(response.args, ("ok", ))
2658
stream = [('inventory-deltas', [
2659
versionedfile.FulltextContentFactory('somerev', None, None,
2660
self._get_serialized_inventory_delta(
2661
t.branch.repository, 'null:', 'somerev'))])]
2662
fmt = bzrdir.format_registry.get('2a')().repository_format
2664
"".join(response.body_stream),
2665
"".join(smart_repo._stream_to_byte_stream(stream, fmt)))
2667
def test_empty(self):
2668
backing = self.get_transport()
2669
request = smart_repo.SmartServerRepositoryGetInventories(backing)
2670
t = self.make_branch_and_tree('.', format='2a')
2671
self.addCleanup(t.lock_write().unlock)
2672
self.build_tree_contents([("file", "somecontents")])
2673
t.add(["file"], ["thefileid"])
2674
t.commit(rev_id='somerev', message="add file")
2675
self.assertIs(None, request.execute('', 'unordered'))
2676
response = request.do_body("")
2677
self.assertTrue(response.is_successful())
2678
self.assertEquals(response.args, ("ok", ))
2679
self.assertEquals("".join(response.body_stream),
2680
"Bazaar pack format 1 (introduced in 0.18)\nB54\n\nBazaar repository format 2a (needs bzr 1.16 or later)\nE")