1
# Copyright (C) 2006-2012 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
refreshed = _mod_branch.Branch.open(branch.base)
1300
self.assertEqual(None, refreshed.get_parent())
1302
def test_set_parent_something(self):
1303
branch = self.make_branch('base', format="1.9")
1304
request = smart_branch.SmartServerBranchRequestSetParentLocation(
1305
self.get_transport())
1306
branch_token, repo_token = self.get_lock_tokens(branch)
1308
response = request.execute('base', branch_token, repo_token,
1312
self.assertEqual(smart_req.SuccessfulSmartServerResponse(()), response)
1313
refreshed = _mod_branch.Branch.open(branch.base)
1314
self.assertEqual('http://bar/', refreshed.get_parent())
1317
class TestSmartServerBranchRequestGetTagsBytes(
1318
tests.TestCaseWithMemoryTransport):
1319
# Only called when the branch format and tags match [yay factory
1320
# methods] so only need to test straight forward cases.
1322
def test_get_bytes(self):
1323
base_branch = self.make_branch('base')
1324
request = smart_branch.SmartServerBranchGetTagsBytes(
1325
self.get_transport())
1326
response = request.execute('base')
1328
smart_req.SuccessfulSmartServerResponse(('',)), response)
1331
class TestSmartServerBranchRequestGetStackedOnURL(tests.TestCaseWithMemoryTransport):
1333
def test_get_stacked_on_url(self):
1334
base_branch = self.make_branch('base', format='1.6')
1335
stacked_branch = self.make_branch('stacked', format='1.6')
1336
# typically should be relative
1337
stacked_branch.set_stacked_on_url('../base')
1338
request = smart_branch.SmartServerBranchRequestGetStackedOnURL(
1339
self.get_transport())
1340
response = request.execute('stacked')
1342
smart_req.SmartServerResponse(('ok', '../base')),
1346
class TestSmartServerBranchRequestLockWrite(TestLockedBranch):
1349
tests.TestCaseWithMemoryTransport.setUp(self)
1351
def test_lock_write_on_unlocked_branch(self):
1352
backing = self.get_transport()
1353
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1354
branch = self.make_branch('.', format='knit')
1355
repository = branch.repository
1356
response = request.execute('')
1357
branch_nonce = branch.control_files._lock.peek().get('nonce')
1358
repository_nonce = repository.control_files._lock.peek().get('nonce')
1359
self.assertEqual(smart_req.SmartServerResponse(
1360
('ok', branch_nonce, repository_nonce)),
1362
# The branch (and associated repository) is now locked. Verify that
1363
# with a new branch object.
1364
new_branch = repository.bzrdir.open_branch()
1365
self.assertRaises(errors.LockContention, new_branch.lock_write)
1367
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1368
response = request.execute('', branch_nonce, repository_nonce)
1370
def test_lock_write_on_locked_branch(self):
1371
backing = self.get_transport()
1372
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1373
branch = self.make_branch('.')
1374
branch_token = branch.lock_write().branch_token
1375
branch.leave_lock_in_place()
1377
response = request.execute('')
1379
smart_req.SmartServerResponse(('LockContention',)), response)
1381
branch.lock_write(branch_token)
1382
branch.dont_leave_lock_in_place()
1385
def test_lock_write_with_tokens_on_locked_branch(self):
1386
backing = self.get_transport()
1387
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1388
branch = self.make_branch('.', format='knit')
1389
branch_token, repo_token = self.get_lock_tokens(branch)
1390
branch.leave_lock_in_place()
1391
branch.repository.leave_lock_in_place()
1393
response = request.execute('',
1394
branch_token, repo_token)
1396
smart_req.SmartServerResponse(('ok', branch_token, repo_token)),
1399
branch.repository.lock_write(repo_token)
1400
branch.repository.dont_leave_lock_in_place()
1401
branch.repository.unlock()
1402
branch.lock_write(branch_token)
1403
branch.dont_leave_lock_in_place()
1406
def test_lock_write_with_mismatched_tokens_on_locked_branch(self):
1407
backing = self.get_transport()
1408
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1409
branch = self.make_branch('.', format='knit')
1410
branch_token, repo_token = self.get_lock_tokens(branch)
1411
branch.leave_lock_in_place()
1412
branch.repository.leave_lock_in_place()
1414
response = request.execute('',
1415
branch_token+'xxx', repo_token)
1417
smart_req.SmartServerResponse(('TokenMismatch',)), response)
1419
branch.repository.lock_write(repo_token)
1420
branch.repository.dont_leave_lock_in_place()
1421
branch.repository.unlock()
1422
branch.lock_write(branch_token)
1423
branch.dont_leave_lock_in_place()
1426
def test_lock_write_on_locked_repo(self):
1427
backing = self.get_transport()
1428
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1429
branch = self.make_branch('.', format='knit')
1430
repo = branch.repository
1431
repo_token = repo.lock_write().repository_token
1432
repo.leave_lock_in_place()
1434
response = request.execute('')
1436
smart_req.SmartServerResponse(('LockContention',)), response)
1438
repo.lock_write(repo_token)
1439
repo.dont_leave_lock_in_place()
1442
def test_lock_write_on_readonly_transport(self):
1443
backing = self.get_readonly_transport()
1444
request = smart_branch.SmartServerBranchRequestLockWrite(backing)
1445
branch = self.make_branch('.')
1446
root = self.get_transport().clone('/')
1447
path = urlutils.relative_url(root.base, self.get_transport().base)
1448
response = request.execute(path)
1449
error_name, lock_str, why_str = response.args
1450
self.assertFalse(response.is_successful())
1451
self.assertEqual('LockFailed', error_name)
1454
class TestSmartServerBranchRequestGetPhysicalLockStatus(TestLockedBranch):
1457
tests.TestCaseWithMemoryTransport.setUp(self)
1459
def test_true(self):
1460
backing = self.get_transport()
1461
request = smart_branch.SmartServerBranchRequestGetPhysicalLockStatus(
1463
branch = self.make_branch('.')
1464
branch_token, repo_token = self.get_lock_tokens(branch)
1465
self.assertEquals(True, branch.get_physical_lock_status())
1466
response = request.execute('')
1468
smart_req.SmartServerResponse(('yes',)), response)
1471
def test_false(self):
1472
backing = self.get_transport()
1473
request = smart_branch.SmartServerBranchRequestGetPhysicalLockStatus(
1475
branch = self.make_branch('.')
1476
self.assertEquals(False, branch.get_physical_lock_status())
1477
response = request.execute('')
1479
smart_req.SmartServerResponse(('no',)), response)
1482
class TestSmartServerBranchRequestUnlock(TestLockedBranch):
1485
tests.TestCaseWithMemoryTransport.setUp(self)
1487
def test_unlock_on_locked_branch_and_repo(self):
1488
backing = self.get_transport()
1489
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1490
branch = self.make_branch('.', format='knit')
1492
branch_token, repo_token = self.get_lock_tokens(branch)
1493
# Unlock the branch (and repo) object, leaving the physical locks
1495
branch.leave_lock_in_place()
1496
branch.repository.leave_lock_in_place()
1498
response = request.execute('',
1499
branch_token, repo_token)
1501
smart_req.SmartServerResponse(('ok',)), response)
1502
# The branch is now unlocked. Verify that with a new branch
1504
new_branch = branch.bzrdir.open_branch()
1505
new_branch.lock_write()
1508
def test_unlock_on_unlocked_branch_unlocked_repo(self):
1509
backing = self.get_transport()
1510
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1511
branch = self.make_branch('.', format='knit')
1512
response = request.execute(
1513
'', 'branch token', 'repo token')
1515
smart_req.SmartServerResponse(('TokenMismatch',)), response)
1517
def test_unlock_on_unlocked_branch_locked_repo(self):
1518
backing = self.get_transport()
1519
request = smart_branch.SmartServerBranchRequestUnlock(backing)
1520
branch = self.make_branch('.', format='knit')
1521
# Lock the repository.
1522
repo_token = branch.repository.lock_write().repository_token
1523
branch.repository.leave_lock_in_place()
1524
branch.repository.unlock()
1525
# Issue branch lock_write request on the unlocked branch (with locked
1527
response = request.execute('', 'branch token', repo_token)
1529
smart_req.SmartServerResponse(('TokenMismatch',)), response)
1531
branch.repository.lock_write(repo_token)
1532
branch.repository.dont_leave_lock_in_place()
1533
branch.repository.unlock()
1536
class TestSmartServerRepositoryRequest(tests.TestCaseWithMemoryTransport):
1538
def test_no_repository(self):
1539
"""Raise NoRepositoryPresent when there is a bzrdir and no repo."""
1540
# we test this using a shared repository above the named path,
1541
# thus checking the right search logic is used - that is, that
1542
# its the exact path being looked at and the server is not
1544
backing = self.get_transport()
1545
request = smart_repo.SmartServerRepositoryRequest(backing)
1546
self.make_repository('.', shared=True)
1547
self.make_bzrdir('subdir')
1548
self.assertRaises(errors.NoRepositoryPresent,
1549
request.execute, 'subdir')
1552
class TestSmartServerRepositoryAddSignatureText(tests.TestCaseWithMemoryTransport):
1554
def test_add_text(self):
1555
backing = self.get_transport()
1556
request = smart_repo.SmartServerRepositoryAddSignatureText(backing)
1557
tree = self.make_branch_and_memory_tree('.')
1558
write_token = tree.lock_write()
1559
self.addCleanup(tree.unlock)
1561
tree.commit("Message", rev_id='rev1')
1562
tree.branch.repository.start_write_group()
1563
write_group_tokens = tree.branch.repository.suspend_write_group()
1564
self.assertEqual(None, request.execute('', write_token,
1565
'rev1', *write_group_tokens))
1566
response = request.do_body('somesignature')
1567
self.assertTrue(response.is_successful())
1568
self.assertEqual(response.args[0], 'ok')
1569
write_group_tokens = response.args[1:]
1570
tree.branch.repository.resume_write_group(write_group_tokens)
1571
tree.branch.repository.commit_write_group()
1573
self.assertEqual("somesignature",
1574
tree.branch.repository.get_signature_text("rev1"))
1577
class TestSmartServerRepositoryAllRevisionIds(
1578
tests.TestCaseWithMemoryTransport):
1580
def test_empty(self):
1581
"""An empty body should be returned for an empty repository."""
1582
backing = self.get_transport()
1583
request = smart_repo.SmartServerRepositoryAllRevisionIds(backing)
1584
self.make_repository('.')
1586
smart_req.SuccessfulSmartServerResponse(("ok", ), ""),
1587
request.execute(''))
1589
def test_some_revisions(self):
1590
"""An empty body should be returned for an empty repository."""
1591
backing = self.get_transport()
1592
request = smart_repo.SmartServerRepositoryAllRevisionIds(backing)
1593
tree = self.make_branch_and_memory_tree('.')
1596
tree.commit(rev_id='origineel', message="message")
1597
tree.commit(rev_id='nog-een-revisie', message="message")
1600
smart_req.SuccessfulSmartServerResponse(("ok", ),
1601
"origineel\nnog-een-revisie"),
1602
request.execute(''))
1605
class TestSmartServerRepositoryBreakLock(tests.TestCaseWithMemoryTransport):
1607
def test_lock_to_break(self):
1608
backing = self.get_transport()
1609
request = smart_repo.SmartServerRepositoryBreakLock(backing)
1610
tree = self.make_branch_and_memory_tree('.')
1611
tree.branch.repository.lock_write()
1613
smart_req.SuccessfulSmartServerResponse(('ok', ), None),
1614
request.execute(''))
1616
def test_nothing_to_break(self):
1617
backing = self.get_transport()
1618
request = smart_repo.SmartServerRepositoryBreakLock(backing)
1619
tree = self.make_branch_and_memory_tree('.')
1621
smart_req.SuccessfulSmartServerResponse(('ok', ), None),
1622
request.execute(''))
1625
class TestSmartServerRepositoryGetParentMap(tests.TestCaseWithMemoryTransport):
1627
def test_trivial_bzipped(self):
1628
# This tests that the wire encoding is actually bzipped
1629
backing = self.get_transport()
1630
request = smart_repo.SmartServerRepositoryGetParentMap(backing)
1631
tree = self.make_branch_and_memory_tree('.')
1633
self.assertEqual(None,
1634
request.execute('', 'missing-id'))
1635
# Note that it returns a body that is bzipped.
1637
smart_req.SuccessfulSmartServerResponse(('ok', ), bz2.compress('')),
1638
request.do_body('\n\n0\n'))
1640
def test_trivial_include_missing(self):
1641
backing = self.get_transport()
1642
request = smart_repo.SmartServerRepositoryGetParentMap(backing)
1643
tree = self.make_branch_and_memory_tree('.')
1645
self.assertEqual(None,
1646
request.execute('', 'missing-id', 'include-missing:'))
1648
smart_req.SuccessfulSmartServerResponse(('ok', ),
1649
bz2.compress('missing:missing-id')),
1650
request.do_body('\n\n0\n'))
1653
class TestSmartServerRepositoryGetRevisionGraph(
1654
tests.TestCaseWithMemoryTransport):
1656
def test_none_argument(self):
1657
backing = self.get_transport()
1658
request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1659
tree = self.make_branch_and_memory_tree('.')
1662
r1 = tree.commit('1st commit')
1663
r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1666
# the lines of revision_id->revision_parent_list has no guaranteed
1667
# order coming out of a dict, so sort both our test and response
1668
lines = sorted([' '.join([r2, r1]), r1])
1669
response = request.execute('', '')
1670
response.body = '\n'.join(sorted(response.body.split('\n')))
1673
smart_req.SmartServerResponse(('ok', ), '\n'.join(lines)), response)
1675
def test_specific_revision_argument(self):
1676
backing = self.get_transport()
1677
request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1678
tree = self.make_branch_and_memory_tree('.')
1681
rev_id_utf8 = u'\xc9'.encode('utf-8')
1682
r1 = tree.commit('1st commit', rev_id=rev_id_utf8)
1683
r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1686
self.assertEqual(smart_req.SmartServerResponse(('ok', ), rev_id_utf8),
1687
request.execute('', rev_id_utf8))
1689
def test_no_such_revision(self):
1690
backing = self.get_transport()
1691
request = smart_repo.SmartServerRepositoryGetRevisionGraph(backing)
1692
tree = self.make_branch_and_memory_tree('.')
1695
r1 = tree.commit('1st commit')
1698
# Note that it still returns body (of zero bytes).
1699
self.assertEqual(smart_req.SmartServerResponse(
1700
('nosuchrevision', 'missingrevision', ), ''),
1701
request.execute('', 'missingrevision'))
1704
class TestSmartServerRepositoryGetRevIdForRevno(
1705
tests.TestCaseWithMemoryTransport):
1707
def test_revno_found(self):
1708
backing = self.get_transport()
1709
request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1710
tree = self.make_branch_and_memory_tree('.')
1713
rev1_id_utf8 = u'\xc8'.encode('utf-8')
1714
rev2_id_utf8 = u'\xc9'.encode('utf-8')
1715
tree.commit('1st commit', rev_id=rev1_id_utf8)
1716
tree.commit('2nd commit', rev_id=rev2_id_utf8)
1719
self.assertEqual(smart_req.SmartServerResponse(('ok', rev1_id_utf8)),
1720
request.execute('', 1, (2, rev2_id_utf8)))
1722
def test_known_revid_missing(self):
1723
backing = self.get_transport()
1724
request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1725
repo = self.make_repository('.')
1727
smart_req.FailedSmartServerResponse(('nosuchrevision', 'ghost')),
1728
request.execute('', 1, (2, 'ghost')))
1730
def test_history_incomplete(self):
1731
backing = self.get_transport()
1732
request = smart_repo.SmartServerRepositoryGetRevIdForRevno(backing)
1733
parent = self.make_branch_and_memory_tree('parent', format='1.9')
1735
parent.add([''], ['TREE_ROOT'])
1736
r1 = parent.commit(message='first commit')
1737
r2 = parent.commit(message='second commit')
1739
local = self.make_branch_and_memory_tree('local', format='1.9')
1740
local.branch.pull(parent.branch)
1741
local.set_parent_ids([r2])
1742
r3 = local.commit(message='local commit')
1743
local.branch.create_clone_on_transport(
1744
self.get_transport('stacked'), stacked_on=self.get_url('parent'))
1746
smart_req.SmartServerResponse(('history-incomplete', 2, r2)),
1747
request.execute('stacked', 1, (3, r3)))
1750
class TestSmartServerRepositoryIterRevisions(
1751
tests.TestCaseWithMemoryTransport):
1753
def test_basic(self):
1754
backing = self.get_transport()
1755
request = smart_repo.SmartServerRepositoryIterRevisions(backing)
1756
tree = self.make_branch_and_memory_tree('.', format='2a')
1759
tree.commit('1st commit', rev_id="rev1")
1760
tree.commit('2nd commit', rev_id="rev2")
1763
self.assertIs(None, request.execute(''))
1764
response = request.do_body("rev1\nrev2")
1765
self.assertTrue(response.is_successful())
1766
# Format 2a uses serializer format 10
1767
self.assertEquals(response.args, ("ok", "10"))
1769
self.addCleanup(tree.branch.lock_read().unlock)
1770
entries = [zlib.compress(record.get_bytes_as("fulltext")) for record in
1771
tree.branch.repository.revisions.get_record_stream(
1772
[("rev1", ), ("rev2", )], "unordered", True)]
1774
contents = "".join(response.body_stream)
1775
self.assertTrue(contents in (
1776
"".join([entries[0], entries[1]]),
1777
"".join([entries[1], entries[0]])))
1779
def test_missing(self):
1780
backing = self.get_transport()
1781
request = smart_repo.SmartServerRepositoryIterRevisions(backing)
1782
tree = self.make_branch_and_memory_tree('.', format='2a')
1784
self.assertIs(None, request.execute(''))
1785
response = request.do_body("rev1\nrev2")
1786
self.assertTrue(response.is_successful())
1787
# Format 2a uses serializer format 10
1788
self.assertEquals(response.args, ("ok", "10"))
1790
contents = "".join(response.body_stream)
1791
self.assertEquals(contents, "")
1794
class GetStreamTestBase(tests.TestCaseWithMemoryTransport):
1796
def make_two_commit_repo(self):
1797
tree = self.make_branch_and_memory_tree('.')
1800
r1 = tree.commit('1st commit')
1801
r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
1803
repo = tree.branch.repository
1807
class TestSmartServerRepositoryGetStream(GetStreamTestBase):
1809
def test_ancestry_of(self):
1810
"""The search argument may be a 'ancestry-of' some heads'."""
1811
backing = self.get_transport()
1812
request = smart_repo.SmartServerRepositoryGetStream(backing)
1813
repo, r1, r2 = self.make_two_commit_repo()
1814
fetch_spec = ['ancestry-of', r2]
1815
lines = '\n'.join(fetch_spec)
1816
request.execute('', repo._format.network_name())
1817
response = request.do_body(lines)
1818
self.assertEqual(('ok',), response.args)
1819
stream_bytes = ''.join(response.body_stream)
1820
self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
1822
def test_search(self):
1823
"""The search argument may be a 'search' of some explicit keys."""
1824
backing = self.get_transport()
1825
request = smart_repo.SmartServerRepositoryGetStream(backing)
1826
repo, r1, r2 = self.make_two_commit_repo()
1827
fetch_spec = ['search', '%s %s' % (r1, r2), 'null:', '2']
1828
lines = '\n'.join(fetch_spec)
1829
request.execute('', repo._format.network_name())
1830
response = request.do_body(lines)
1831
self.assertEqual(('ok',), response.args)
1832
stream_bytes = ''.join(response.body_stream)
1833
self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
1835
def test_search_everything(self):
1836
"""A search of 'everything' returns a stream."""
1837
backing = self.get_transport()
1838
request = smart_repo.SmartServerRepositoryGetStream_1_19(backing)
1839
repo, r1, r2 = self.make_two_commit_repo()
1840
serialised_fetch_spec = 'everything'
1841
request.execute('', repo._format.network_name())
1842
response = request.do_body(serialised_fetch_spec)
1843
self.assertEqual(('ok',), response.args)
1844
stream_bytes = ''.join(response.body_stream)
1845
self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')
1848
class TestSmartServerRequestHasRevision(tests.TestCaseWithMemoryTransport):
1850
def test_missing_revision(self):
1851
"""For a missing revision, ('no', ) is returned."""
1852
backing = self.get_transport()
1853
request = smart_repo.SmartServerRequestHasRevision(backing)
1854
self.make_repository('.')
1855
self.assertEqual(smart_req.SmartServerResponse(('no', )),
1856
request.execute('', 'revid'))
1858
def test_present_revision(self):
1859
"""For a present revision, ('yes', ) is returned."""
1860
backing = self.get_transport()
1861
request = smart_repo.SmartServerRequestHasRevision(backing)
1862
tree = self.make_branch_and_memory_tree('.')
1865
rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1866
r1 = tree.commit('a commit', rev_id=rev_id_utf8)
1868
self.assertTrue(tree.branch.repository.has_revision(rev_id_utf8))
1869
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
1870
request.execute('', rev_id_utf8))
1873
class TestSmartServerRepositoryIterFilesBytes(tests.TestCaseWithTransport):
1875
def test_single(self):
1876
backing = self.get_transport()
1877
request = smart_repo.SmartServerRepositoryIterFilesBytes(backing)
1878
t = self.make_branch_and_tree('.')
1879
self.addCleanup(t.lock_write().unlock)
1880
self.build_tree_contents([("file", "somecontents")])
1881
t.add(["file"], ["thefileid"])
1882
t.commit(rev_id='somerev', message="add file")
1883
self.assertIs(None, request.execute(''))
1884
response = request.do_body("thefileid\0somerev\n")
1885
self.assertTrue(response.is_successful())
1886
self.assertEquals(response.args, ("ok", ))
1887
self.assertEquals("".join(response.body_stream),
1888
"ok\x000\n" + zlib.compress("somecontents"))
1890
def test_missing(self):
1891
backing = self.get_transport()
1892
request = smart_repo.SmartServerRepositoryIterFilesBytes(backing)
1893
t = self.make_branch_and_tree('.')
1894
self.addCleanup(t.lock_write().unlock)
1895
self.assertIs(None, request.execute(''))
1896
response = request.do_body("thefileid\0revision\n")
1897
self.assertTrue(response.is_successful())
1898
self.assertEquals(response.args, ("ok", ))
1899
self.assertEquals("".join(response.body_stream),
1900
"absent\x00thefileid\x00revision\x000\n")
1903
class TestSmartServerRequestHasSignatureForRevisionId(
1904
tests.TestCaseWithMemoryTransport):
1906
def test_missing_revision(self):
1907
"""For a missing revision, NoSuchRevision is returned."""
1908
backing = self.get_transport()
1909
request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
1911
self.make_repository('.')
1913
smart_req.FailedSmartServerResponse(
1914
('nosuchrevision', 'revid'), None),
1915
request.execute('', 'revid'))
1917
def test_missing_signature(self):
1918
"""For a missing signature, ('no', ) is returned."""
1919
backing = self.get_transport()
1920
request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
1922
tree = self.make_branch_and_memory_tree('.')
1925
r1 = tree.commit('a commit', rev_id='A')
1927
self.assertTrue(tree.branch.repository.has_revision('A'))
1928
self.assertEqual(smart_req.SmartServerResponse(('no', )),
1929
request.execute('', 'A'))
1931
def test_present_signature(self):
1932
"""For a present signature, ('yes', ) is returned."""
1933
backing = self.get_transport()
1934
request = smart_repo.SmartServerRequestHasSignatureForRevisionId(
1936
strategy = gpg.LoopbackGPGStrategy(None)
1937
tree = self.make_branch_and_memory_tree('.')
1940
r1 = tree.commit('a commit', rev_id='A')
1941
tree.branch.repository.start_write_group()
1942
tree.branch.repository.sign_revision('A', strategy)
1943
tree.branch.repository.commit_write_group()
1945
self.assertTrue(tree.branch.repository.has_revision('A'))
1946
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
1947
request.execute('', 'A'))
1950
class TestSmartServerRepositoryGatherStats(tests.TestCaseWithMemoryTransport):
1952
def test_empty_revid(self):
1953
"""With an empty revid, we get only size an number and revisions"""
1954
backing = self.get_transport()
1955
request = smart_repo.SmartServerRepositoryGatherStats(backing)
1956
repository = self.make_repository('.')
1957
stats = repository.gather_stats()
1958
expected_body = 'revisions: 0\n'
1959
self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
1960
request.execute('', '', 'no'))
1962
def test_revid_with_committers(self):
1963
"""For a revid we get more infos."""
1964
backing = self.get_transport()
1965
rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1966
request = smart_repo.SmartServerRepositoryGatherStats(backing)
1967
tree = self.make_branch_and_memory_tree('.')
1970
# Let's build a predictable result
1971
tree.commit('a commit', timestamp=123456.2, timezone=3600)
1972
tree.commit('a commit', timestamp=654321.4, timezone=0,
1976
stats = tree.branch.repository.gather_stats()
1977
expected_body = ('firstrev: 123456.200 3600\n'
1978
'latestrev: 654321.400 0\n'
1980
self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
1984
def test_not_empty_repository_with_committers(self):
1985
"""For a revid and requesting committers we get the whole thing."""
1986
backing = self.get_transport()
1987
rev_id_utf8 = u'\xc8abc'.encode('utf-8')
1988
request = smart_repo.SmartServerRepositoryGatherStats(backing)
1989
tree = self.make_branch_and_memory_tree('.')
1992
# Let's build a predictable result
1993
tree.commit('a commit', timestamp=123456.2, timezone=3600,
1995
tree.commit('a commit', timestamp=654321.4, timezone=0,
1996
committer='bar', rev_id=rev_id_utf8)
1998
stats = tree.branch.repository.gather_stats()
2000
expected_body = ('committers: 2\n'
2001
'firstrev: 123456.200 3600\n'
2002
'latestrev: 654321.400 0\n'
2004
self.assertEqual(smart_req.SmartServerResponse(('ok', ), expected_body),
2006
rev_id_utf8, 'yes'))
2008
def test_unknown_revid(self):
2009
"""An unknown revision id causes a 'nosuchrevision' error."""
2010
backing = self.get_transport()
2011
request = smart_repo.SmartServerRepositoryGatherStats(backing)
2012
repository = self.make_repository('.')
2013
expected_body = 'revisions: 0\n'
2015
smart_req.FailedSmartServerResponse(
2016
('nosuchrevision', 'mia'), None),
2017
request.execute('', 'mia', 'yes'))
2020
class TestSmartServerRepositoryIsShared(tests.TestCaseWithMemoryTransport):
2022
def test_is_shared(self):
2023
"""For a shared repository, ('yes', ) is returned."""
2024
backing = self.get_transport()
2025
request = smart_repo.SmartServerRepositoryIsShared(backing)
2026
self.make_repository('.', shared=True)
2027
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
2028
request.execute('', ))
2030
def test_is_not_shared(self):
2031
"""For a shared repository, ('no', ) is returned."""
2032
backing = self.get_transport()
2033
request = smart_repo.SmartServerRepositoryIsShared(backing)
2034
self.make_repository('.', shared=False)
2035
self.assertEqual(smart_req.SmartServerResponse(('no', )),
2036
request.execute('', ))
2039
class TestSmartServerRepositoryGetRevisionSignatureText(
2040
tests.TestCaseWithMemoryTransport):
2042
def test_get_signature(self):
2043
backing = self.get_transport()
2044
request = smart_repo.SmartServerRepositoryGetRevisionSignatureText(
2046
bb = self.make_branch_builder('.')
2047
bb.build_commit(rev_id='A')
2048
repo = bb.get_branch().repository
2049
strategy = gpg.LoopbackGPGStrategy(None)
2050
self.addCleanup(repo.lock_write().unlock)
2051
repo.start_write_group()
2052
repo.sign_revision('A', strategy)
2053
repo.commit_write_group()
2055
'-----BEGIN PSEUDO-SIGNED CONTENT-----\n' +
2056
Testament.from_revision(repo, 'A').as_short_text() +
2057
'-----END PSEUDO-SIGNED CONTENT-----\n')
2059
smart_req.SmartServerResponse(('ok', ), expected_body),
2060
request.execute('', 'A'))
2063
class TestSmartServerRepositoryMakeWorkingTrees(
2064
tests.TestCaseWithMemoryTransport):
2066
def test_make_working_trees(self):
2067
"""For a repository with working trees, ('yes', ) is returned."""
2068
backing = self.get_transport()
2069
request = smart_repo.SmartServerRepositoryMakeWorkingTrees(backing)
2070
r = self.make_repository('.')
2071
r.set_make_working_trees(True)
2072
self.assertEqual(smart_req.SmartServerResponse(('yes', )),
2073
request.execute('', ))
2075
def test_is_not_shared(self):
2076
"""For a repository with working trees, ('no', ) is returned."""
2077
backing = self.get_transport()
2078
request = smart_repo.SmartServerRepositoryMakeWorkingTrees(backing)
2079
r = self.make_repository('.')
2080
r.set_make_working_trees(False)
2081
self.assertEqual(smart_req.SmartServerResponse(('no', )),
2082
request.execute('', ))
2085
class TestSmartServerRepositoryLockWrite(tests.TestCaseWithMemoryTransport):
2087
def test_lock_write_on_unlocked_repo(self):
2088
backing = self.get_transport()
2089
request = smart_repo.SmartServerRepositoryLockWrite(backing)
2090
repository = self.make_repository('.', format='knit')
2091
response = request.execute('')
2092
nonce = repository.control_files._lock.peek().get('nonce')
2093
self.assertEqual(smart_req.SmartServerResponse(('ok', nonce)), response)
2094
# The repository is now locked. Verify that with a new repository
2096
new_repo = repository.bzrdir.open_repository()
2097
self.assertRaises(errors.LockContention, new_repo.lock_write)
2099
request = smart_repo.SmartServerRepositoryUnlock(backing)
2100
response = request.execute('', nonce)
2102
def test_lock_write_on_locked_repo(self):
2103
backing = self.get_transport()
2104
request = smart_repo.SmartServerRepositoryLockWrite(backing)
2105
repository = self.make_repository('.', format='knit')
2106
repo_token = repository.lock_write().repository_token
2107
repository.leave_lock_in_place()
2109
response = request.execute('')
2111
smart_req.SmartServerResponse(('LockContention',)), response)
2113
repository.lock_write(repo_token)
2114
repository.dont_leave_lock_in_place()
2117
def test_lock_write_on_readonly_transport(self):
2118
backing = self.get_readonly_transport()
2119
request = smart_repo.SmartServerRepositoryLockWrite(backing)
2120
repository = self.make_repository('.', format='knit')
2121
response = request.execute('')
2122
self.assertFalse(response.is_successful())
2123
self.assertEqual('LockFailed', response.args[0])
2126
class TestInsertStreamBase(tests.TestCaseWithMemoryTransport):
2128
def make_empty_byte_stream(self, repo):
2129
byte_stream = smart_repo._stream_to_byte_stream([], repo._format)
2130
return ''.join(byte_stream)
2133
class TestSmartServerRepositoryInsertStream(TestInsertStreamBase):
2135
def test_insert_stream_empty(self):
2136
backing = self.get_transport()
2137
request = smart_repo.SmartServerRepositoryInsertStream(backing)
2138
repository = self.make_repository('.')
2139
response = request.execute('', '')
2140
self.assertEqual(None, response)
2141
response = request.do_chunk(self.make_empty_byte_stream(repository))
2142
self.assertEqual(None, response)
2143
response = request.do_end()
2144
self.assertEqual(smart_req.SmartServerResponse(('ok', )), response)
2147
class TestSmartServerRepositoryInsertStreamLocked(TestInsertStreamBase):
2149
def test_insert_stream_empty(self):
2150
backing = self.get_transport()
2151
request = smart_repo.SmartServerRepositoryInsertStreamLocked(
2153
repository = self.make_repository('.', format='knit')
2154
lock_token = repository.lock_write().repository_token
2155
response = request.execute('', '', lock_token)
2156
self.assertEqual(None, response)
2157
response = request.do_chunk(self.make_empty_byte_stream(repository))
2158
self.assertEqual(None, response)
2159
response = request.do_end()
2160
self.assertEqual(smart_req.SmartServerResponse(('ok', )), response)
2163
def test_insert_stream_with_wrong_lock_token(self):
2164
backing = self.get_transport()
2165
request = smart_repo.SmartServerRepositoryInsertStreamLocked(
2167
repository = self.make_repository('.', format='knit')
2168
lock_token = repository.lock_write().repository_token
2170
errors.TokenMismatch, request.execute, '', '', 'wrong-token')
2174
class TestSmartServerRepositoryUnlock(tests.TestCaseWithMemoryTransport):
2177
tests.TestCaseWithMemoryTransport.setUp(self)
2179
def test_unlock_on_locked_repo(self):
2180
backing = self.get_transport()
2181
request = smart_repo.SmartServerRepositoryUnlock(backing)
2182
repository = self.make_repository('.', format='knit')
2183
token = repository.lock_write().repository_token
2184
repository.leave_lock_in_place()
2186
response = request.execute('', token)
2188
smart_req.SmartServerResponse(('ok',)), response)
2189
# The repository is now unlocked. Verify that with a new repository
2191
new_repo = repository.bzrdir.open_repository()
2192
new_repo.lock_write()
2195
def test_unlock_on_unlocked_repo(self):
2196
backing = self.get_transport()
2197
request = smart_repo.SmartServerRepositoryUnlock(backing)
2198
repository = self.make_repository('.', format='knit')
2199
response = request.execute('', 'some token')
2201
smart_req.SmartServerResponse(('TokenMismatch',)), response)
2204
class TestSmartServerRepositoryGetPhysicalLockStatus(
2205
tests.TestCaseWithTransport):
2207
def test_with_write_lock(self):
2208
backing = self.get_transport()
2209
repo = self.make_repository('.')
2210
self.addCleanup(repo.lock_write().unlock)
2211
# lock_write() doesn't necessarily actually take a physical
2213
if repo.get_physical_lock_status():
2217
request_class = smart_repo.SmartServerRepositoryGetPhysicalLockStatus
2218
request = request_class(backing)
2219
self.assertEqual(smart_req.SuccessfulSmartServerResponse((expected,)),
2220
request.execute('', ))
2222
def test_without_write_lock(self):
2223
backing = self.get_transport()
2224
repo = self.make_repository('.')
2225
self.assertEquals(False, repo.get_physical_lock_status())
2226
request_class = smart_repo.SmartServerRepositoryGetPhysicalLockStatus
2227
request = request_class(backing)
2228
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('no',)),
2229
request.execute('', ))
2232
class TestSmartServerRepositoryReconcile(tests.TestCaseWithTransport):
2234
def test_reconcile(self):
2235
backing = self.get_transport()
2236
repo = self.make_repository('.')
2237
token = repo.lock_write().repository_token
2238
self.addCleanup(repo.unlock)
2239
request_class = smart_repo.SmartServerRepositoryReconcile
2240
request = request_class(backing)
2241
self.assertEqual(smart_req.SuccessfulSmartServerResponse(
2243
'garbage_inventories: 0\n'
2244
'inconsistent_parents: 0\n'),
2245
request.execute('', token))
2248
class TestSmartServerIsReadonly(tests.TestCaseWithMemoryTransport):
2250
def test_is_readonly_no(self):
2251
backing = self.get_transport()
2252
request = smart_req.SmartServerIsReadonly(backing)
2253
response = request.execute()
2255
smart_req.SmartServerResponse(('no',)), response)
2257
def test_is_readonly_yes(self):
2258
backing = self.get_readonly_transport()
2259
request = smart_req.SmartServerIsReadonly(backing)
2260
response = request.execute()
2262
smart_req.SmartServerResponse(('yes',)), response)
2265
class TestSmartServerRepositorySetMakeWorkingTrees(
2266
tests.TestCaseWithMemoryTransport):
2268
def test_set_false(self):
2269
backing = self.get_transport()
2270
repo = self.make_repository('.', shared=True)
2271
repo.set_make_working_trees(True)
2272
request_class = smart_repo.SmartServerRepositorySetMakeWorkingTrees
2273
request = request_class(backing)
2274
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2275
request.execute('', 'False'))
2276
repo = repo.bzrdir.open_repository()
2277
self.assertFalse(repo.make_working_trees())
2279
def test_set_true(self):
2280
backing = self.get_transport()
2281
repo = self.make_repository('.', shared=True)
2282
repo.set_make_working_trees(False)
2283
request_class = smart_repo.SmartServerRepositorySetMakeWorkingTrees
2284
request = request_class(backing)
2285
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2286
request.execute('', 'True'))
2287
repo = repo.bzrdir.open_repository()
2288
self.assertTrue(repo.make_working_trees())
2291
class TestSmartServerRepositoryGetSerializerFormat(
2292
tests.TestCaseWithMemoryTransport):
2294
def test_get_serializer_format(self):
2295
backing = self.get_transport()
2296
repo = self.make_repository('.', format='2a')
2297
request_class = smart_repo.SmartServerRepositoryGetSerializerFormat
2298
request = request_class(backing)
2300
smart_req.SuccessfulSmartServerResponse(('ok', '10')),
2301
request.execute(''))
2304
class TestSmartServerRepositoryWriteGroup(
2305
tests.TestCaseWithMemoryTransport):
2307
def test_start_write_group(self):
2308
backing = self.get_transport()
2309
repo = self.make_repository('.')
2310
lock_token = repo.lock_write().repository_token
2311
self.addCleanup(repo.unlock)
2312
request_class = smart_repo.SmartServerRepositoryStartWriteGroup
2313
request = request_class(backing)
2314
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok', [])),
2315
request.execute('', lock_token))
2317
def test_start_write_group_unsuspendable(self):
2318
backing = self.get_transport()
2319
repo = self.make_repository('.', format='knit')
2320
lock_token = repo.lock_write().repository_token
2321
self.addCleanup(repo.unlock)
2322
request_class = smart_repo.SmartServerRepositoryStartWriteGroup
2323
request = request_class(backing)
2325
smart_req.FailedSmartServerResponse(('UnsuspendableWriteGroup',)),
2326
request.execute('', lock_token))
2328
def test_commit_write_group(self):
2329
backing = self.get_transport()
2330
repo = self.make_repository('.')
2331
lock_token = repo.lock_write().repository_token
2332
self.addCleanup(repo.unlock)
2333
repo.start_write_group()
2334
tokens = repo.suspend_write_group()
2335
request_class = smart_repo.SmartServerRepositoryCommitWriteGroup
2336
request = request_class(backing)
2337
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2338
request.execute('', lock_token, tokens))
2340
def test_abort_write_group(self):
2341
backing = self.get_transport()
2342
repo = self.make_repository('.')
2343
lock_token = repo.lock_write().repository_token
2344
repo.start_write_group()
2345
tokens = repo.suspend_write_group()
2346
self.addCleanup(repo.unlock)
2347
request_class = smart_repo.SmartServerRepositoryAbortWriteGroup
2348
request = request_class(backing)
2349
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2350
request.execute('', lock_token, tokens))
2352
def test_check_write_group(self):
2353
backing = self.get_transport()
2354
repo = self.make_repository('.')
2355
lock_token = repo.lock_write().repository_token
2356
repo.start_write_group()
2357
tokens = repo.suspend_write_group()
2358
self.addCleanup(repo.unlock)
2359
request_class = smart_repo.SmartServerRepositoryCheckWriteGroup
2360
request = request_class(backing)
2361
self.assertEqual(smart_req.SuccessfulSmartServerResponse(('ok',)),
2362
request.execute('', lock_token, tokens))
2364
def test_check_write_group_invalid(self):
2365
backing = self.get_transport()
2366
repo = self.make_repository('.')
2367
lock_token = repo.lock_write().repository_token
2368
self.addCleanup(repo.unlock)
2369
request_class = smart_repo.SmartServerRepositoryCheckWriteGroup
2370
request = request_class(backing)
2371
self.assertEqual(smart_req.FailedSmartServerResponse(
2372
('UnresumableWriteGroup', ['random'],
2373
'Malformed write group token')),
2374
request.execute('', lock_token, ["random"]))
2377
class TestSmartServerPackRepositoryAutopack(tests.TestCaseWithTransport):
2379
def make_repo_needing_autopacking(self, path='.'):
2380
# Make a repo in need of autopacking.
2381
tree = self.make_branch_and_tree('.', format='pack-0.92')
2382
repo = tree.branch.repository
2383
# monkey-patch the pack collection to disable autopacking
2384
repo._pack_collection._max_pack_count = lambda count: count
2386
tree.commit('commit %s' % x)
2387
self.assertEqual(10, len(repo._pack_collection.names()))
2388
del repo._pack_collection._max_pack_count
2391
def test_autopack_needed(self):
2392
repo = self.make_repo_needing_autopacking()
2394
self.addCleanup(repo.unlock)
2395
backing = self.get_transport()
2396
request = smart_packrepo.SmartServerPackRepositoryAutopack(
2398
response = request.execute('')
2399
self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
2400
repo._pack_collection.reload_pack_names()
2401
self.assertEqual(1, len(repo._pack_collection.names()))
2403
def test_autopack_not_needed(self):
2404
tree = self.make_branch_and_tree('.', format='pack-0.92')
2405
repo = tree.branch.repository
2407
self.addCleanup(repo.unlock)
2409
tree.commit('commit %s' % x)
2410
backing = self.get_transport()
2411
request = smart_packrepo.SmartServerPackRepositoryAutopack(
2413
response = request.execute('')
2414
self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
2415
repo._pack_collection.reload_pack_names()
2416
self.assertEqual(9, len(repo._pack_collection.names()))
2418
def test_autopack_on_nonpack_format(self):
2419
"""A request to autopack a non-pack repo is a no-op."""
2420
repo = self.make_repository('.', format='knit')
2421
backing = self.get_transport()
2422
request = smart_packrepo.SmartServerPackRepositoryAutopack(
2424
response = request.execute('')
2425
self.assertEqual(smart_req.SmartServerResponse(('ok',)), response)
2428
class TestSmartServerVfsGet(tests.TestCaseWithMemoryTransport):
2430
def test_unicode_path(self):
2431
"""VFS requests expect unicode paths to be escaped."""
2432
filename = u'foo\N{INTERROBANG}'
2433
filename_escaped = urlutils.escape(filename)
2434
backing = self.get_transport()
2435
request = vfs.GetRequest(backing)
2436
backing.put_bytes_non_atomic(filename_escaped, 'contents')
2437
self.assertEqual(smart_req.SmartServerResponse(('ok', ), 'contents'),
2438
request.execute(filename_escaped))
2441
class TestHandlers(tests.TestCase):
2442
"""Tests for the request.request_handlers object."""
2444
def test_all_registrations_exist(self):
2445
"""All registered request_handlers can be found."""
2446
# If there's a typo in a register_lazy call, this loop will fail with
2447
# an AttributeError.
2448
for key in smart_req.request_handlers.keys():
2450
item = smart_req.request_handlers.get(key)
2451
except AttributeError, e:
2452
raise AttributeError('failed to get %s: %s' % (key, e))
2454
def assertHandlerEqual(self, verb, handler):
2455
self.assertEqual(smart_req.request_handlers.get(verb), handler)
2457
def test_registered_methods(self):
2458
"""Test that known methods are registered to the correct object."""
2459
self.assertHandlerEqual('Branch.break_lock',
2460
smart_branch.SmartServerBranchBreakLock)
2461
self.assertHandlerEqual('Branch.get_config_file',
2462
smart_branch.SmartServerBranchGetConfigFile)
2463
self.assertHandlerEqual('Branch.put_config_file',
2464
smart_branch.SmartServerBranchPutConfigFile)
2465
self.assertHandlerEqual('Branch.get_parent',
2466
smart_branch.SmartServerBranchGetParent)
2467
self.assertHandlerEqual('Branch.get_physical_lock_status',
2468
smart_branch.SmartServerBranchRequestGetPhysicalLockStatus)
2469
self.assertHandlerEqual('Branch.get_tags_bytes',
2470
smart_branch.SmartServerBranchGetTagsBytes)
2471
self.assertHandlerEqual('Branch.lock_write',
2472
smart_branch.SmartServerBranchRequestLockWrite)
2473
self.assertHandlerEqual('Branch.last_revision_info',
2474
smart_branch.SmartServerBranchRequestLastRevisionInfo)
2475
self.assertHandlerEqual('Branch.revision_history',
2476
smart_branch.SmartServerRequestRevisionHistory)
2477
self.assertHandlerEqual('Branch.revision_id_to_revno',
2478
smart_branch.SmartServerBranchRequestRevisionIdToRevno)
2479
self.assertHandlerEqual('Branch.set_config_option',
2480
smart_branch.SmartServerBranchRequestSetConfigOption)
2481
self.assertHandlerEqual('Branch.set_last_revision',
2482
smart_branch.SmartServerBranchRequestSetLastRevision)
2483
self.assertHandlerEqual('Branch.set_last_revision_info',
2484
smart_branch.SmartServerBranchRequestSetLastRevisionInfo)
2485
self.assertHandlerEqual('Branch.set_last_revision_ex',
2486
smart_branch.SmartServerBranchRequestSetLastRevisionEx)
2487
self.assertHandlerEqual('Branch.set_parent_location',
2488
smart_branch.SmartServerBranchRequestSetParentLocation)
2489
self.assertHandlerEqual('Branch.unlock',
2490
smart_branch.SmartServerBranchRequestUnlock)
2491
self.assertHandlerEqual('BzrDir.destroy_branch',
2492
smart_dir.SmartServerBzrDirRequestDestroyBranch)
2493
self.assertHandlerEqual('BzrDir.find_repository',
2494
smart_dir.SmartServerRequestFindRepositoryV1)
2495
self.assertHandlerEqual('BzrDir.find_repositoryV2',
2496
smart_dir.SmartServerRequestFindRepositoryV2)
2497
self.assertHandlerEqual('BzrDirFormat.initialize',
2498
smart_dir.SmartServerRequestInitializeBzrDir)
2499
self.assertHandlerEqual('BzrDirFormat.initialize_ex_1.16',
2500
smart_dir.SmartServerRequestBzrDirInitializeEx)
2501
self.assertHandlerEqual('BzrDir.checkout_metadir',
2502
smart_dir.SmartServerBzrDirRequestCheckoutMetaDir)
2503
self.assertHandlerEqual('BzrDir.cloning_metadir',
2504
smart_dir.SmartServerBzrDirRequestCloningMetaDir)
2505
self.assertHandlerEqual('BzrDir.get_config_file',
2506
smart_dir.SmartServerBzrDirRequestConfigFile)
2507
self.assertHandlerEqual('BzrDir.open_branch',
2508
smart_dir.SmartServerRequestOpenBranch)
2509
self.assertHandlerEqual('BzrDir.open_branchV2',
2510
smart_dir.SmartServerRequestOpenBranchV2)
2511
self.assertHandlerEqual('BzrDir.open_branchV3',
2512
smart_dir.SmartServerRequestOpenBranchV3)
2513
self.assertHandlerEqual('PackRepository.autopack',
2514
smart_packrepo.SmartServerPackRepositoryAutopack)
2515
self.assertHandlerEqual('Repository.add_signature_text',
2516
smart_repo.SmartServerRepositoryAddSignatureText)
2517
self.assertHandlerEqual('Repository.all_revision_ids',
2518
smart_repo.SmartServerRepositoryAllRevisionIds)
2519
self.assertHandlerEqual('Repository.break_lock',
2520
smart_repo.SmartServerRepositoryBreakLock)
2521
self.assertHandlerEqual('Repository.gather_stats',
2522
smart_repo.SmartServerRepositoryGatherStats)
2523
self.assertHandlerEqual('Repository.get_parent_map',
2524
smart_repo.SmartServerRepositoryGetParentMap)
2525
self.assertHandlerEqual('Repository.get_physical_lock_status',
2526
smart_repo.SmartServerRepositoryGetPhysicalLockStatus)
2527
self.assertHandlerEqual('Repository.get_rev_id_for_revno',
2528
smart_repo.SmartServerRepositoryGetRevIdForRevno)
2529
self.assertHandlerEqual('Repository.get_revision_graph',
2530
smart_repo.SmartServerRepositoryGetRevisionGraph)
2531
self.assertHandlerEqual('Repository.get_revision_signature_text',
2532
smart_repo.SmartServerRepositoryGetRevisionSignatureText)
2533
self.assertHandlerEqual('Repository.get_stream',
2534
smart_repo.SmartServerRepositoryGetStream)
2535
self.assertHandlerEqual('Repository.get_stream_1.19',
2536
smart_repo.SmartServerRepositoryGetStream_1_19)
2537
self.assertHandlerEqual('Repository.iter_revisions',
2538
smart_repo.SmartServerRepositoryIterRevisions)
2539
self.assertHandlerEqual('Repository.has_revision',
2540
smart_repo.SmartServerRequestHasRevision)
2541
self.assertHandlerEqual('Repository.insert_stream',
2542
smart_repo.SmartServerRepositoryInsertStream)
2543
self.assertHandlerEqual('Repository.insert_stream_locked',
2544
smart_repo.SmartServerRepositoryInsertStreamLocked)
2545
self.assertHandlerEqual('Repository.is_shared',
2546
smart_repo.SmartServerRepositoryIsShared)
2547
self.assertHandlerEqual('Repository.iter_files_bytes',
2548
smart_repo.SmartServerRepositoryIterFilesBytes)
2549
self.assertHandlerEqual('Repository.lock_write',
2550
smart_repo.SmartServerRepositoryLockWrite)
2551
self.assertHandlerEqual('Repository.make_working_trees',
2552
smart_repo.SmartServerRepositoryMakeWorkingTrees)
2553
self.assertHandlerEqual('Repository.pack',
2554
smart_repo.SmartServerRepositoryPack)
2555
self.assertHandlerEqual('Repository.reconcile',
2556
smart_repo.SmartServerRepositoryReconcile)
2557
self.assertHandlerEqual('Repository.tarball',
2558
smart_repo.SmartServerRepositoryTarball)
2559
self.assertHandlerEqual('Repository.unlock',
2560
smart_repo.SmartServerRepositoryUnlock)
2561
self.assertHandlerEqual('Repository.start_write_group',
2562
smart_repo.SmartServerRepositoryStartWriteGroup)
2563
self.assertHandlerEqual('Repository.check_write_group',
2564
smart_repo.SmartServerRepositoryCheckWriteGroup)
2565
self.assertHandlerEqual('Repository.commit_write_group',
2566
smart_repo.SmartServerRepositoryCommitWriteGroup)
2567
self.assertHandlerEqual('Repository.abort_write_group',
2568
smart_repo.SmartServerRepositoryAbortWriteGroup)
2569
self.assertHandlerEqual('VersionedFileRepository.get_serializer_format',
2570
smart_repo.SmartServerRepositoryGetSerializerFormat)
2571
self.assertHandlerEqual('VersionedFileRepository.get_inventories',
2572
smart_repo.SmartServerRepositoryGetInventories)
2573
self.assertHandlerEqual('Transport.is_readonly',
2574
smart_req.SmartServerIsReadonly)
2577
class SmartTCPServerHookTests(tests.TestCaseWithMemoryTransport):
2578
"""Tests for SmartTCPServer hooks."""
2581
super(SmartTCPServerHookTests, self).setUp()
2582
self.server = server.SmartTCPServer(self.get_transport())
2584
def test_run_server_started_hooks(self):
2585
"""Test the server started hooks get fired properly."""
2587
server.SmartTCPServer.hooks.install_named_hook('server_started',
2588
lambda backing_urls, url: started_calls.append((backing_urls, url)),
2590
started_ex_calls = []
2591
server.SmartTCPServer.hooks.install_named_hook('server_started_ex',
2592
lambda backing_urls, url: started_ex_calls.append((backing_urls, url)),
2594
self.server._sockname = ('example.com', 42)
2595
self.server.run_server_started_hooks()
2596
self.assertEquals(started_calls,
2597
[([self.get_transport().base], 'bzr://example.com:42/')])
2598
self.assertEquals(started_ex_calls,
2599
[([self.get_transport().base], self.server)])
2601
def test_run_server_started_hooks_ipv6(self):
2602
"""Test that socknames can contain 4-tuples."""
2603
self.server._sockname = ('::', 42, 0, 0)
2605
server.SmartTCPServer.hooks.install_named_hook('server_started',
2606
lambda backing_urls, url: started_calls.append((backing_urls, url)),
2608
self.server.run_server_started_hooks()
2609
self.assertEquals(started_calls,
2610
[([self.get_transport().base], 'bzr://:::42/')])
2612
def test_run_server_stopped_hooks(self):
2613
"""Test the server stopped hooks."""
2614
self.server._sockname = ('example.com', 42)
2616
server.SmartTCPServer.hooks.install_named_hook('server_stopped',
2617
lambda backing_urls, url: stopped_calls.append((backing_urls, url)),
2619
self.server.run_server_stopped_hooks()
2620
self.assertEquals(stopped_calls,
2621
[([self.get_transport().base], 'bzr://example.com:42/')])
2624
class TestSmartServerRepositoryPack(tests.TestCaseWithMemoryTransport):
2626
def test_pack(self):
2627
backing = self.get_transport()
2628
request = smart_repo.SmartServerRepositoryPack(backing)
2629
tree = self.make_branch_and_memory_tree('.')
2630
repo_token = tree.branch.repository.lock_write().repository_token
2632
self.assertIs(None, request.execute('', repo_token, False))
2635
smart_req.SuccessfulSmartServerResponse(('ok', ), ),
2636
request.do_body(''))
2639
class TestSmartServerRepositoryGetInventories(tests.TestCaseWithTransport):
2641
def _get_serialized_inventory_delta(self, repository, base_revid, revid):
2642
base_inv = repository.revision_tree(base_revid).inventory
2643
inv = repository.revision_tree(revid).inventory
2644
inv_delta = inv._make_delta(base_inv)
2645
serializer = inventory_delta.InventoryDeltaSerializer(True, False)
2646
return "".join(serializer.delta_to_lines(base_revid, revid, inv_delta))
2648
def test_single(self):
2649
backing = self.get_transport()
2650
request = smart_repo.SmartServerRepositoryGetInventories(backing)
2651
t = self.make_branch_and_tree('.', format='2a')
2652
self.addCleanup(t.lock_write().unlock)
2653
self.build_tree_contents([("file", "somecontents")])
2654
t.add(["file"], ["thefileid"])
2655
t.commit(rev_id='somerev', message="add file")
2656
self.assertIs(None, request.execute('', 'unordered'))
2657
response = request.do_body("somerev\n")
2658
self.assertTrue(response.is_successful())
2659
self.assertEquals(response.args, ("ok", ))
2660
stream = [('inventory-deltas', [
2661
versionedfile.FulltextContentFactory('somerev', None, None,
2662
self._get_serialized_inventory_delta(
2663
t.branch.repository, 'null:', 'somerev'))])]
2664
fmt = bzrdir.format_registry.get('2a')().repository_format
2666
"".join(response.body_stream),
2667
"".join(smart_repo._stream_to_byte_stream(stream, fmt)))
2669
def test_empty(self):
2670
backing = self.get_transport()
2671
request = smart_repo.SmartServerRepositoryGetInventories(backing)
2672
t = self.make_branch_and_tree('.', format='2a')
2673
self.addCleanup(t.lock_write().unlock)
2674
self.build_tree_contents([("file", "somecontents")])
2675
t.add(["file"], ["thefileid"])
2676
t.commit(rev_id='somerev', message="add file")
2677
self.assertIs(None, request.execute('', 'unordered'))
2678
response = request.do_body("")
2679
self.assertTrue(response.is_successful())
2680
self.assertEquals(response.args, ("ok", ))
2681
self.assertEquals("".join(response.body_stream),
2682
"Bazaar pack format 1 (introduced in 0.18)\nB54\n\nBazaar repository format 2a (needs bzr 1.16 or later)\nE")