1
# Copyright (C) 2008-2012, 2016 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
18
"""Tests for foreign VCS utility code."""
37
from ..repofmt import groupcompress_repo
39
# This is the dummy foreign revision control system, used
40
# mainly here in the testsuite to test the foreign VCS infrastructure.
41
# It is basically standard Bazaar with some minor modifications to
44
# It has the following differences to "regular" Bazaar:
45
# - The control directory is named ".dummy", not ".bzr".
46
# - The revision ids are tuples, not strings.
47
# - Doesn't support more than one parent natively
50
class DummyForeignVcsMapping(foreign.VcsMapping):
51
"""A simple mapping for the dummy Foreign VCS, for use with testing."""
53
def __eq__(self, other):
54
return isinstance(self, type(other))
56
def revision_id_bzr_to_foreign(self, bzr_revid):
57
return tuple(bzr_revid[len("dummy-v1:"):].split("-")), self
59
def revision_id_foreign_to_bzr(self, foreign_revid):
60
return "dummy-v1:%s-%s-%s" % foreign_revid
63
class DummyForeignVcsMappingRegistry(foreign.VcsMappingRegistry):
65
def revision_id_bzr_to_foreign(self, revid):
66
if not revid.startswith("dummy-"):
67
raise errors.InvalidRevisionId(revid, None)
68
mapping_version = revid[len("dummy-"):len("dummy-vx")]
69
mapping = self.get(mapping_version)
70
return mapping.revision_id_bzr_to_foreign(revid)
73
class DummyForeignVcs(foreign.ForeignVcs):
74
"""A dummy Foreign VCS, for use with testing.
76
It has revision ids that are a tuple with three strings.
80
self.mapping_registry = DummyForeignVcsMappingRegistry()
81
self.mapping_registry.register("v1", DummyForeignVcsMapping(self),
83
self.abbreviation = "dummy"
85
def show_foreign_revid(self, foreign_revid):
86
return { "dummy ding": "%s/%s\\%s" % foreign_revid }
88
def serialize_foreign_revid(self, foreign_revid):
89
return "%s|%s|%s" % foreign_revid
92
class DummyForeignVcsBranch(bzrbranch.BzrBranch6,foreign.ForeignBranch):
93
"""A Dummy VCS Branch."""
96
def user_transport(self):
97
return self.bzrdir.user_transport
99
def __init__(self, _format, _control_files, a_bzrdir, *args, **kwargs):
100
self._format = _format
101
self._base = a_bzrdir.transport.base
102
self._ignore_fallbacks = False
103
self.bzrdir = a_bzrdir
104
foreign.ForeignBranch.__init__(self,
105
DummyForeignVcsMapping(DummyForeignVcs()))
106
bzrbranch.BzrBranch6.__init__(self, _format, _control_files, a_bzrdir,
109
def _get_checkout_format(self, lightweight=False):
110
"""Return the most suitable metadir for a checkout of this branch.
111
Weaves are used if this branch's repository uses weaves.
113
return self.bzrdir.checkout_metadir()
115
def import_last_revision_info_and_tags(self, source, revno, revid,
117
interbranch = InterToDummyVcsBranch(source, self)
118
result = interbranch.push(stop_revision=revid, lossy=True)
120
revid = result.revidmap[revid]
121
return (revno, revid)
124
class DummyForeignCommitBuilder(vf_repository.VersionedFileRootCommitBuilder):
126
def _generate_revision_if_needed(self):
127
mapping = DummyForeignVcsMapping(DummyForeignVcs())
129
self._new_revision_id = mapping.revision_id_foreign_to_bzr(
130
(str(self._timestamp), str(self._timezone), "UNKNOWN"))
131
self.random_revid = False
132
elif self._new_revision_id is not None:
133
self.random_revid = False
135
self._new_revision_id = self._gen_revision_id()
136
self.random_revid = True
139
class DummyForeignVcsRepository(groupcompress_repo.CHKInventoryRepository,
140
foreign.ForeignRepository):
141
"""Dummy foreign vcs repository."""
144
class DummyForeignVcsRepositoryFormat(groupcompress_repo.RepositoryFormat2a):
146
repository_class = DummyForeignVcsRepository
147
_commit_builder_class = DummyForeignCommitBuilder
150
def get_format_string(cls):
151
return "Dummy Foreign Vcs Repository"
153
def get_format_description(self):
154
return "Dummy Foreign Vcs Repository"
157
def branch_history(graph, revid):
158
ret = list(graph.iter_lefthand_ancestry(revid,
159
(revision.NULL_REVISION,)))
164
class InterToDummyVcsBranch(branch.GenericInterBranch):
167
def is_compatible(source, target):
168
return isinstance(target, DummyForeignVcsBranch)
170
def push(self, overwrite=False, stop_revision=None, lossy=False):
172
raise errors.NoRoundtrippingSupport(self.source, self.target)
173
result = branch.BranchPushResult()
174
result.source_branch = self.source
175
result.target_branch = self.target
176
result.old_revno, result.old_revid = self.target.last_revision_info()
177
self.source.lock_read()
179
graph = self.source.repository.get_graph()
180
# This just handles simple cases, but that's good enough for tests
181
my_history = branch_history(self.target.repository.get_graph(),
183
if stop_revision is None:
184
stop_revision = self.source.last_revision()
185
their_history = branch_history(graph, stop_revision)
186
if their_history[:min(len(my_history), len(their_history))] != my_history:
187
raise errors.DivergedBranches(self.target, self.source)
188
todo = their_history[len(my_history):]
191
rev = self.source.repository.get_revision(revid)
192
tree = self.source.repository.revision_tree(revid)
193
def get_file_with_stat(file_id, path=None):
194
return (tree.get_file(file_id), None)
195
tree.get_file_with_stat = get_file_with_stat
196
new_revid = self.target.mapping.revision_id_foreign_to_bzr(
197
(str(rev.timestamp), str(rev.timezone),
198
str(self.target.revno())))
199
parent_revno, parent_revid= self.target.last_revision_info()
200
if parent_revid == revision.NULL_REVISION:
203
parent_revids = [parent_revid]
204
builder = self.target.get_commit_builder(parent_revids,
205
self.target.get_config_stack(), rev.timestamp,
206
rev.timezone, rev.committer, rev.properties,
209
parent_tree = self.target.repository.revision_tree(
211
for path, ie in tree.iter_entries_by_dir():
213
new_ie.revision = None
214
builder.record_entry_contents(new_ie,
215
[parent_tree.root_inventory],
217
(ie.kind, ie.text_size, ie.executable, ie.text_sha1))
218
builder.finish_inventory()
222
revidmap[revid] = builder.commit(rev.message)
223
self.target.set_last_revision_info(parent_revno+1,
225
trace.mutter('lossily pushed revision %s -> %s',
226
revid, revidmap[revid])
229
result.new_revno, result.new_revid = self.target.last_revision_info()
230
result.revidmap = revidmap
234
class DummyForeignVcsBranchFormat(bzrbranch.BzrBranchFormat6):
237
def get_format_string(cls):
238
return "Branch for Testing"
241
def _matchingbzrdir(self):
242
return DummyForeignVcsDirFormat()
244
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
245
found_repository=None):
247
name = a_bzrdir._get_selected_branch()
249
raise NotImplementedError
251
transport = a_bzrdir.get_branch_transport(None, name=name)
252
control_files = lockable_files.LockableFiles(transport, 'lock',
254
if found_repository is None:
255
found_repository = a_bzrdir.find_repository()
256
return DummyForeignVcsBranch(_format=self,
257
_control_files=control_files,
259
_repository=found_repository,
261
except errors.NoSuchFile:
262
raise errors.NotBranchError(path=transport.base)
265
class DummyForeignVcsDirFormat(bzrdir.BzrDirMetaFormat1):
266
"""BzrDirFormat for the dummy foreign VCS."""
269
def get_format_string(cls):
270
return "A Dummy VCS Dir"
273
def get_format_description(cls):
274
return "A Dummy VCS Dir"
277
def is_supported(cls):
280
def get_branch_format(self):
281
return DummyForeignVcsBranchFormat()
284
def repository_format(self):
285
return DummyForeignVcsRepositoryFormat()
287
def initialize_on_transport(self, transport):
288
"""Initialize a new bzrdir in the base directory of a Transport."""
289
# Since we don't have a .bzr directory, inherit the
290
# mode from the root directory
291
temp_control = lockable_files.LockableFiles(transport,
292
'', lockable_files.TransportLock)
293
temp_control._transport.mkdir('.dummy',
294
# FIXME: RBC 20060121 don't peek under
296
mode=temp_control._dir_mode)
298
bzrdir_transport = transport.clone('.dummy')
299
# NB: no need to escape relative paths that are url safe.
300
control_files = lockable_files.LockableFiles(bzrdir_transport,
301
self._lock_file_name, self._lock_class)
302
control_files.create_lock()
303
return self.open(transport, _found=True)
305
def _open(self, transport):
306
return DummyForeignVcsDir(transport, self)
309
class DummyForeignVcsDir(bzrdir.BzrDirMeta1):
311
def __init__(self, _transport, _format):
312
self._format = _format
313
self.transport = _transport.clone('.dummy')
314
self.root_transport = _transport
315
self._mode_check_done = False
316
self._control_files = lockable_files.LockableFiles(self.transport,
317
"lock", lockable_files.TransportLock)
319
def create_workingtree(self):
320
# dirstate requires a ".bzr" entry to exist
321
self.root_transport.put_bytes(".bzr", "foo")
322
return super(DummyForeignVcsDir, self).create_workingtree()
324
def open_branch(self, name=None, unsupported=False, ignore_fallbacks=True,
325
possible_transports=None):
327
name = self._get_selected_branch()
329
raise errors.NoColocatedBranchSupport(self)
330
return self._format.get_branch_format().open(self, _found=True)
332
def cloning_metadir(self, stacked=False):
333
"""Produce a metadir suitable for cloning with."""
334
return controldir.format_registry.make_bzrdir("default")
336
def checkout_metadir(self):
337
return self.cloning_metadir()
339
def sprout(self, url, revision_id=None, force_new_repo=False,
340
recurse='down', possible_transports=None,
341
accelerator_tree=None, hardlink=False, stacked=False,
343
# dirstate doesn't cope with accelerator_trees well
344
# that have a different control dir
345
return super(DummyForeignVcsDir, self).sprout(
347
revision_id=revision_id, force_new_repo=force_new_repo,
348
recurse=recurse, possible_transports=possible_transports,
349
hardlink=hardlink, stacked=stacked, source_branch=source_branch)
352
def register_dummy_foreign_for_test(testcase):
353
controldir.ControlDirFormat.register_prober(DummyForeignProber)
354
testcase.addCleanup(controldir.ControlDirFormat.unregister_prober,
356
repository.format_registry.register(DummyForeignVcsRepositoryFormat())
357
testcase.addCleanup(repository.format_registry.remove,
358
DummyForeignVcsRepositoryFormat())
359
branch.format_registry.register(DummyForeignVcsBranchFormat())
360
testcase.addCleanup(branch.format_registry.remove,
361
DummyForeignVcsBranchFormat())
362
# We need to register the optimiser to make the dummy appears really
363
# different from a regular bzr repository.
364
branch.InterBranch.register_optimiser(InterToDummyVcsBranch)
365
testcase.addCleanup(branch.InterBranch.unregister_optimiser,
366
InterToDummyVcsBranch)
369
class DummyForeignProber(controldir.Prober):
372
def probe_transport(klass, transport):
373
"""Return the .bzrdir style format present in a directory."""
374
if not transport.has('.dummy'):
375
raise errors.NotBranchError(path=transport.base)
376
return DummyForeignVcsDirFormat()
379
def known_formats(cls):
380
return {DummyForeignVcsDirFormat()}
383
class ForeignVcsRegistryTests(tests.TestCase):
384
"""Tests for the ForeignVcsRegistry class."""
386
def test_parse_revision_id_no_dash(self):
387
reg = foreign.ForeignVcsRegistry()
388
self.assertRaises(errors.InvalidRevisionId,
389
reg.parse_revision_id, "invalid")
391
def test_parse_revision_id_unknown_mapping(self):
392
reg = foreign.ForeignVcsRegistry()
393
self.assertRaises(errors.InvalidRevisionId,
394
reg.parse_revision_id, "unknown-foreignrevid")
396
def test_parse_revision_id(self):
397
reg = foreign.ForeignVcsRegistry()
398
vcs = DummyForeignVcs()
399
reg.register("dummy", vcs, "Dummy VCS")
401
("some", "foreign", "revid"), DummyForeignVcsMapping(vcs)),
402
reg.parse_revision_id("dummy-v1:some-foreign-revid"))
405
class ForeignRevisionTests(tests.TestCase):
406
"""Tests for the ForeignRevision class."""
408
def test_create(self):
409
mapp = DummyForeignVcsMapping(DummyForeignVcs())
410
rev = foreign.ForeignRevision(("a", "foreign", "revid"),
411
mapp, "roundtripped-revid")
412
self.assertEqual("", rev.inventory_sha1)
413
self.assertEqual(("a", "foreign", "revid"), rev.foreign_revid)
414
self.assertEqual(mapp, rev.mapping)
417
class WorkingTreeFileUpdateTests(tests.TestCaseWithTransport):
418
"""Tests for update_workingtree_fileids()."""
420
def test_update_workingtree(self):
421
wt = self.make_branch_and_tree('br1')
422
self.build_tree_contents([('br1/bla', 'original contents\n')])
423
wt.add('bla', 'bla-a')
425
root_id = wt.get_root_id()
426
target = wt.bzrdir.sprout('br2').open_workingtree()
427
target.unversion(['bla-a'])
428
target.add('bla', 'bla-b')
429
target.commit('bla-b')
430
target_basis = target.basis_tree()
431
target_basis.lock_read()
432
self.addCleanup(target_basis.unlock)
433
foreign.update_workingtree_fileids(wt, target_basis)
436
self.assertEqual({root_id, "bla-b"}, set(wt.all_file_ids()))
441
class DummyForeignVcsTests(tests.TestCaseWithTransport):
442
"""Very basic test for DummyForeignVcs."""
445
super(DummyForeignVcsTests, self).setUp()
446
register_dummy_foreign_for_test(self)
448
def test_create(self):
449
"""Test we can create dummies."""
450
self.make_branch_and_tree("d", format=DummyForeignVcsDirFormat())
451
dir = controldir.ControlDir.open("d")
452
self.assertEqual("A Dummy VCS Dir", dir._format.get_format_string())
453
dir.open_repository()
455
dir.open_workingtree()
457
def test_sprout(self):
458
"""Test we can clone dummies and that the format is not preserved."""
459
self.make_branch_and_tree("d", format=DummyForeignVcsDirFormat())
460
dir = controldir.ControlDir.open("d")
461
newdir = dir.sprout("e")
462
self.assertNotEqual("A Dummy VCS Dir",
463
newdir._format.get_format_string())
465
def test_push_not_supported(self):
466
source_tree = self.make_branch_and_tree("source")
467
target_tree = self.make_branch_and_tree(
468
"target", format=DummyForeignVcsDirFormat())
469
self.assertRaises(errors.NoRoundtrippingSupport,
470
source_tree.branch.push, target_tree.branch)
472
def test_lossy_push_empty(self):
473
source_tree = self.make_branch_and_tree("source")
474
target_tree = self.make_branch_and_tree(
475
"target", format=DummyForeignVcsDirFormat())
476
pushresult = source_tree.branch.push(target_tree.branch, lossy=True)
477
self.assertEqual(revision.NULL_REVISION, pushresult.old_revid)
478
self.assertEqual(revision.NULL_REVISION, pushresult.new_revid)
479
self.assertEqual({}, pushresult.revidmap)
481
def test_lossy_push_simple(self):
482
source_tree = self.make_branch_and_tree("source")
483
self.build_tree(['source/a', 'source/b'])
484
source_tree.add(['a', 'b'])
485
revid1 = source_tree.commit("msg")
486
target_tree = self.make_branch_and_tree(
487
"target", format=DummyForeignVcsDirFormat())
488
target_tree.branch.lock_write()
490
pushresult = source_tree.branch.push(
491
target_tree.branch, lossy=True)
493
target_tree.branch.unlock()
494
self.assertEqual(revision.NULL_REVISION, pushresult.old_revid)
495
self.assertEqual({revid1: target_tree.branch.last_revision()},
497
self.assertEqual(pushresult.revidmap[revid1], pushresult.new_revid)