~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_foreign.py

  • Committer: Patch Queue Manager
  • Date: 2014-02-12 18:22:22 UTC
  • mfrom: (6589.2.1 trunk)
  • Revision ID: pqm@pqm.ubuntu.com-20140212182222-beouo25gaf1cny76
(vila) The XDG Base Directory Specification uses the XDG_CACHE_HOME,
 not XDG_CACHE_DIR. (Andrew Starr-Bochicchio)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008 Canonical Ltd
 
1
# Copyright (C) 2008-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
20
20
 
21
21
from bzrlib import (
22
22
    branch,
 
23
    bzrdir,
 
24
    controldir,
23
25
    errors,
24
26
    foreign,
25
27
    lockable_files,
26
28
    lockdir,
 
29
    repository,
 
30
    revision,
 
31
    tests,
27
32
    trace,
28
 
    )
29
 
from bzrlib.bzrdir import (
30
 
    BzrDir,
31
 
    BzrDirFormat,
32
 
    BzrDirMeta1,
33
 
    BzrDirMetaFormat1,
34
 
    format_registry,
35
 
    )
36
 
from bzrlib.inventory import Inventory
37
 
from bzrlib.revision import Revision
38
 
from bzrlib.tests import (
39
 
    TestCase,
40
 
    TestCaseWithTransport,
41
 
    )
 
33
    vf_repository,
 
34
    )
 
35
 
 
36
from bzrlib.repofmt import groupcompress_repo
42
37
 
43
38
# This is the dummy foreign revision control system, used 
44
39
# mainly here in the testsuite to test the foreign VCS infrastructure.
84
79
        self.mapping_registry = DummyForeignVcsMappingRegistry()
85
80
        self.mapping_registry.register("v1", DummyForeignVcsMapping(self),
86
81
                                       "Version 1")
 
82
        self.abbreviation = "dummy"
87
83
 
88
84
    def show_foreign_revid(self, foreign_revid):
89
85
        return { "dummy ding": "%s/%s\\%s" % foreign_revid }
90
86
 
 
87
    def serialize_foreign_revid(self, foreign_revid):
 
88
        return "%s|%s|%s" % foreign_revid
 
89
 
91
90
 
92
91
class DummyForeignVcsBranch(branch.BzrBranch6,foreign.ForeignBranch):
93
92
    """A Dummy VCS Branch."""
94
93
 
 
94
    @property
 
95
    def user_transport(self):
 
96
        return self.bzrdir.user_transport
 
97
 
95
98
    def __init__(self, _format, _control_files, a_bzrdir, *args, **kwargs):
96
99
        self._format = _format
97
100
        self._base = a_bzrdir.transport.base
98
101
        self._ignore_fallbacks = False
99
 
        foreign.ForeignBranch.__init__(self, 
 
102
        self.bzrdir = a_bzrdir
 
103
        foreign.ForeignBranch.__init__(self,
100
104
            DummyForeignVcsMapping(DummyForeignVcs()))
101
 
        branch.BzrBranch6.__init__(self, _format, _control_files, a_bzrdir, 
 
105
        branch.BzrBranch6.__init__(self, _format, _control_files, a_bzrdir,
102
106
            *args, **kwargs)
103
107
 
104
 
    def dpull(self, source, stop_revision=None):
105
 
        source.lock_read()
 
108
    def _get_checkout_format(self, lightweight=False):
 
109
        """Return the most suitable metadir for a checkout of this branch.
 
110
        Weaves are used if this branch's repository uses weaves.
 
111
        """
 
112
        return self.bzrdir.checkout_metadir()
 
113
 
 
114
    def import_last_revision_info_and_tags(self, source, revno, revid,
 
115
                                           lossy=False):
 
116
        interbranch = InterToDummyVcsBranch(source, self)
 
117
        result = interbranch.push(stop_revision=revid, lossy=True)
 
118
        if lossy:
 
119
            revid = result.revidmap[revid]
 
120
        return (revno, revid)
 
121
 
 
122
 
 
123
class DummyForeignCommitBuilder(vf_repository.VersionedFileRootCommitBuilder):
 
124
 
 
125
    def _generate_revision_if_needed(self):
 
126
        mapping = DummyForeignVcsMapping(DummyForeignVcs())
 
127
        if self._lossy:
 
128
            self._new_revision_id = mapping.revision_id_foreign_to_bzr(
 
129
                (str(self._timestamp), str(self._timezone), "UNKNOWN"))
 
130
            self.random_revid = False
 
131
        elif self._new_revision_id is not None:
 
132
            self.random_revid = False
 
133
        else:
 
134
            self._new_revision_id = self._gen_revision_id()
 
135
            self.random_revid = True
 
136
 
 
137
 
 
138
class DummyForeignVcsRepository(groupcompress_repo.CHKInventoryRepository,
 
139
    foreign.ForeignRepository):
 
140
    """Dummy foreign vcs repository."""
 
141
 
 
142
 
 
143
class DummyForeignVcsRepositoryFormat(groupcompress_repo.RepositoryFormat2a):
 
144
 
 
145
    repository_class = DummyForeignVcsRepository
 
146
    _commit_builder_class = DummyForeignCommitBuilder
 
147
 
 
148
    @classmethod
 
149
    def get_format_string(cls):
 
150
        return "Dummy Foreign Vcs Repository"
 
151
 
 
152
    def get_format_description(self):
 
153
        return "Dummy Foreign Vcs Repository"
 
154
 
 
155
 
 
156
def branch_history(graph, revid):
 
157
    ret = list(graph.iter_lefthand_ancestry(revid,
 
158
        (revision.NULL_REVISION,)))
 
159
    ret.reverse()
 
160
    return ret
 
161
 
 
162
 
 
163
class InterToDummyVcsBranch(branch.GenericInterBranch):
 
164
 
 
165
    @staticmethod
 
166
    def is_compatible(source, target):
 
167
        return isinstance(target, DummyForeignVcsBranch)
 
168
 
 
169
    def push(self, overwrite=False, stop_revision=None, lossy=False):
 
170
        if not lossy:
 
171
            raise errors.NoRoundtrippingSupport(self.source, self.target)
 
172
        result = branch.BranchPushResult()
 
173
        result.source_branch = self.source
 
174
        result.target_branch = self.target
 
175
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
176
        self.source.lock_read()
106
177
        try:
 
178
            graph = self.source.repository.get_graph()
107
179
            # This just handles simple cases, but that's good enough for tests
108
 
            my_history = self.revision_history()
109
 
            their_history = source.revision_history()
 
180
            my_history = branch_history(self.target.repository.get_graph(),
 
181
                result.old_revid)
 
182
            if stop_revision is None:
 
183
                stop_revision = self.source.last_revision()
 
184
            their_history = branch_history(graph, stop_revision)
110
185
            if their_history[:min(len(my_history), len(their_history))] != my_history:
111
 
                raise errors.DivergedBranches(self, source)
 
186
                raise errors.DivergedBranches(self.target, self.source)
112
187
            todo = their_history[len(my_history):]
113
188
            revidmap = {}
114
189
            for revid in todo:
115
 
                rev = source.repository.get_revision(revid)
116
 
                tree = source.repository.revision_tree(revid)
 
190
                rev = self.source.repository.get_revision(revid)
 
191
                tree = self.source.repository.revision_tree(revid)
117
192
                def get_file_with_stat(file_id, path=None):
118
193
                    return (tree.get_file(file_id), None)
119
194
                tree.get_file_with_stat = get_file_with_stat
120
 
                new_revid = self.mapping.revision_id_foreign_to_bzr(
121
 
                    (str(rev.timestamp), str(rev.timezone), str(self.revno())))
122
 
                parent_revno, parent_revid= self.last_revision_info()
123
 
                builder = self.get_commit_builder([parent_revid], 
124
 
                        self.get_config(), rev.timestamp,
 
195
                new_revid = self.target.mapping.revision_id_foreign_to_bzr(
 
196
                    (str(rev.timestamp), str(rev.timezone),
 
197
                        str(self.target.revno())))
 
198
                parent_revno, parent_revid= self.target.last_revision_info()
 
199
                if parent_revid == revision.NULL_REVISION:
 
200
                    parent_revids = []
 
201
                else:
 
202
                    parent_revids = [parent_revid]
 
203
                builder = self.target.get_commit_builder(parent_revids, 
 
204
                        self.target.get_config_stack(), rev.timestamp,
125
205
                        rev.timezone, rev.committer, rev.properties,
126
206
                        new_revid)
127
207
                try:
128
 
                    for path, ie in tree.inventory.iter_entries():
 
208
                    parent_tree = self.target.repository.revision_tree(
 
209
                        parent_revid)
 
210
                    for path, ie in tree.iter_entries_by_dir():
129
211
                        new_ie = ie.copy()
130
212
                        new_ie.revision = None
131
213
                        builder.record_entry_contents(new_ie, 
132
 
                            [self.repository.get_inventory(parent_revid)],
 
214
                            [parent_tree.root_inventory],
133
215
                            path, tree, 
134
216
                            (ie.kind, ie.text_size, ie.executable, ie.text_sha1))
135
217
                    builder.finish_inventory()
137
219
                    builder.abort()
138
220
                    raise
139
221
                revidmap[revid] = builder.commit(rev.message)
140
 
                self.set_last_revision_info(parent_revno+1, revidmap[revid])
 
222
                self.target.set_last_revision_info(parent_revno+1, 
 
223
                    revidmap[revid])
141
224
                trace.mutter('lossily pushed revision %s -> %s', 
142
225
                    revid, revidmap[revid])
143
226
        finally:
144
 
            source.unlock()
145
 
        return revidmap
 
227
            self.source.unlock()
 
228
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
229
        result.revidmap = revidmap
 
230
        return result
146
231
 
147
232
 
148
233
class DummyForeignVcsBranchFormat(branch.BzrBranchFormat6):
149
234
 
150
 
    def get_format_string(self):
 
235
    @classmethod
 
236
    def get_format_string(cls):
151
237
        return "Branch for Testing"
152
238
 
153
 
    def __init__(self):
154
 
        super(DummyForeignVcsBranchFormat, self).__init__()
155
 
        self._matchingbzrdir = DummyForeignVcsDirFormat()
 
239
    @property
 
240
    def _matchingbzrdir(self):
 
241
        return DummyForeignVcsDirFormat()
156
242
 
157
 
    def open(self, a_bzrdir, _found=False):
 
243
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
244
            found_repository=None):
 
245
        if name is None:
 
246
            name = a_bzrdir._get_selected_branch()
158
247
        if not _found:
159
248
            raise NotImplementedError
160
249
        try:
161
 
            transport = a_bzrdir.get_branch_transport(None)
 
250
            transport = a_bzrdir.get_branch_transport(None, name=name)
162
251
            control_files = lockable_files.LockableFiles(transport, 'lock',
163
252
                                                         lockdir.LockDir)
 
253
            if found_repository is None:
 
254
                found_repository = a_bzrdir.find_repository()
164
255
            return DummyForeignVcsBranch(_format=self,
165
256
                              _control_files=control_files,
166
257
                              a_bzrdir=a_bzrdir,
167
 
                              _repository=a_bzrdir.find_repository())
 
258
                              _repository=found_repository,
 
259
                              name=name)
168
260
        except errors.NoSuchFile:
169
261
            raise errors.NotBranchError(path=transport.base)
170
262
 
171
263
 
172
 
class DummyForeignVcsDirFormat(BzrDirMetaFormat1):
 
264
class DummyForeignVcsDirFormat(bzrdir.BzrDirMetaFormat1):
173
265
    """BzrDirFormat for the dummy foreign VCS."""
174
266
 
175
267
    @classmethod
187
279
    def get_branch_format(self):
188
280
        return DummyForeignVcsBranchFormat()
189
281
 
190
 
    @classmethod
191
 
    def probe_transport(klass, transport):
192
 
        """Return the .bzrdir style format present in a directory."""
193
 
        if not transport.has('.dummy'):
194
 
            raise errors.NotBranchError(path=transport.base)
195
 
        return klass()
 
282
    @property
 
283
    def repository_format(self):
 
284
        return DummyForeignVcsRepositoryFormat()
196
285
 
197
286
    def initialize_on_transport(self, transport):
198
287
        """Initialize a new bzrdir in the base directory of a Transport."""
216
305
        return DummyForeignVcsDir(transport, self)
217
306
 
218
307
 
219
 
class DummyForeignVcsDir(BzrDirMeta1):
 
308
class DummyForeignVcsDir(bzrdir.BzrDirMeta1):
220
309
 
221
310
    def __init__(self, _transport, _format):
222
311
        self._format = _format
226
315
        self._control_files = lockable_files.LockableFiles(self.transport,
227
316
            "lock", lockable_files.TransportLock)
228
317
 
229
 
    def open_branch(self, ignore_fallbacks=True):
 
318
    def create_workingtree(self):
 
319
        # dirstate requires a ".bzr" entry to exist
 
320
        self.root_transport.put_bytes(".bzr", "foo")
 
321
        return super(DummyForeignVcsDir, self).create_workingtree()
 
322
 
 
323
    def open_branch(self, name=None, unsupported=False, ignore_fallbacks=True,
 
324
            possible_transports=None):
 
325
        if name is None:
 
326
            name = self._get_selected_branch()
 
327
        if name != "":
 
328
            raise errors.NoColocatedBranchSupport(self)
230
329
        return self._format.get_branch_format().open(self, _found=True)
231
330
 
232
331
    def cloning_metadir(self, stacked=False):
233
332
        """Produce a metadir suitable for cloning with."""
234
 
        return format_registry.make_bzrdir("default")
 
333
        return controldir.format_registry.make_bzrdir("default")
 
334
 
 
335
    def checkout_metadir(self):
 
336
        return self.cloning_metadir()
235
337
 
236
338
    def sprout(self, url, revision_id=None, force_new_repo=False,
237
339
               recurse='down', possible_transports=None,
245
347
                hardlink=hardlink, stacked=stacked, source_branch=source_branch)
246
348
 
247
349
 
248
 
class ForeignVcsRegistryTests(TestCase):
 
350
def register_dummy_foreign_for_test(testcase):
 
351
    controldir.ControlDirFormat.register_prober(DummyForeignProber)
 
352
    testcase.addCleanup(controldir.ControlDirFormat.unregister_prober,
 
353
        DummyForeignProber)
 
354
    repository.format_registry.register(DummyForeignVcsRepositoryFormat())
 
355
    testcase.addCleanup(repository.format_registry.remove,
 
356
            DummyForeignVcsRepositoryFormat())
 
357
    branch.format_registry.register(DummyForeignVcsBranchFormat())
 
358
    testcase.addCleanup(branch.format_registry.remove,
 
359
            DummyForeignVcsBranchFormat())
 
360
    # We need to register the optimiser to make the dummy appears really
 
361
    # different from a regular bzr repository.
 
362
    branch.InterBranch.register_optimiser(InterToDummyVcsBranch)
 
363
    testcase.addCleanup(branch.InterBranch.unregister_optimiser,
 
364
                        InterToDummyVcsBranch)
 
365
 
 
366
 
 
367
class DummyForeignProber(controldir.Prober):
 
368
 
 
369
    @classmethod
 
370
    def probe_transport(klass, transport):
 
371
        """Return the .bzrdir style format present in a directory."""
 
372
        if not transport.has('.dummy'):
 
373
            raise errors.NotBranchError(path=transport.base)
 
374
        return DummyForeignVcsDirFormat()
 
375
 
 
376
    @classmethod
 
377
    def known_formats(cls):
 
378
        return set([DummyForeignVcsDirFormat()])
 
379
 
 
380
 
 
381
class ForeignVcsRegistryTests(tests.TestCase):
249
382
    """Tests for the ForeignVcsRegistry class."""
250
383
 
251
384
    def test_parse_revision_id_no_dash(self):
262
395
        reg = foreign.ForeignVcsRegistry()
263
396
        vcs = DummyForeignVcs()
264
397
        reg.register("dummy", vcs, "Dummy VCS")
265
 
        self.assertEquals((("some", "foreign", "revid"), DummyForeignVcsMapping(vcs)),
266
 
                          reg.parse_revision_id("dummy-v1:some-foreign-revid"))
267
 
 
268
 
 
269
 
class ForeignRevisionTests(TestCase):
 
398
        self.assertEquals((
 
399
            ("some", "foreign", "revid"), DummyForeignVcsMapping(vcs)),
 
400
            reg.parse_revision_id("dummy-v1:some-foreign-revid"))
 
401
 
 
402
 
 
403
class ForeignRevisionTests(tests.TestCase):
270
404
    """Tests for the ForeignRevision class."""
271
405
 
272
406
    def test_create(self):
278
412
        self.assertEquals(mapp, rev.mapping)
279
413
 
280
414
 
281
 
class ShowForeignPropertiesTests(TestCase):
282
 
    """Tests for the show_foreign_properties() function."""
283
 
 
284
 
    def setUp(self):
285
 
        super(ShowForeignPropertiesTests, self).setUp()
286
 
        self.vcs = DummyForeignVcs()
287
 
        foreign.foreign_vcs_registry.register("dummy",
288
 
            self.vcs, "Dummy VCS")
289
 
 
290
 
    def tearDown(self):
291
 
        super(ShowForeignPropertiesTests, self).tearDown()
292
 
        foreign.foreign_vcs_registry.remove("dummy")
293
 
 
294
 
    def test_show_non_foreign(self):
295
 
        """Test use with a native (non-foreign) bzr revision."""
296
 
        self.assertEquals({}, foreign.show_foreign_properties(Revision("arevid")))
297
 
 
298
 
    def test_show_imported(self):
299
 
        rev = Revision("dummy-v1:my-foreign-revid")
300
 
        self.assertEquals({ "dummy ding": "my/foreign\\revid" },
301
 
                          foreign.show_foreign_properties(rev))
302
 
 
303
 
    def test_show_direct(self):
304
 
        rev = foreign.ForeignRevision(("some", "foreign", "revid"),
305
 
                                      DummyForeignVcsMapping(self.vcs),
306
 
                                      "roundtrip-revid")
307
 
        self.assertEquals({ "dummy ding": "some/foreign\\revid" },
308
 
                          foreign.show_foreign_properties(rev))
309
 
 
310
 
 
311
 
class WorkingTreeFileUpdateTests(TestCaseWithTransport):
 
415
class WorkingTreeFileUpdateTests(tests.TestCaseWithTransport):
312
416
    """Tests for update_workingtree_fileids()."""
313
417
 
314
418
    def test_update_workingtree(self):
316
420
        self.build_tree_contents([('br1/bla', 'original contents\n')])
317
421
        wt.add('bla', 'bla-a')
318
422
        wt.commit('bla-a')
 
423
        root_id = wt.get_root_id()
319
424
        target = wt.bzrdir.sprout('br2').open_workingtree()
320
425
        target.unversion(['bla-a'])
321
426
        target.add('bla', 'bla-b')
326
431
        foreign.update_workingtree_fileids(wt, target_basis)
327
432
        wt.lock_read()
328
433
        try:
329
 
            self.assertEquals(["TREE_ROOT", "bla-b"], list(wt.inventory))
 
434
            self.assertEquals(set([root_id, "bla-b"]), set(wt.all_file_ids()))
330
435
        finally:
331
436
            wt.unlock()
332
437
 
333
438
 
334
 
class DummyForeignVcsTests(TestCaseWithTransport):
 
439
class DummyForeignVcsTests(tests.TestCaseWithTransport):
335
440
    """Very basic test for DummyForeignVcs."""
336
441
 
337
442
    def setUp(self):
338
 
        BzrDirFormat.register_control_format(DummyForeignVcsDirFormat)
339
 
        self.addCleanup(self.unregister)
340
443
        super(DummyForeignVcsTests, self).setUp()
341
 
 
342
 
    def unregister(self):
343
 
        try:
344
 
            BzrDirFormat.unregister_control_format(DummyForeignVcsDirFormat)
345
 
        except ValueError:
346
 
            pass
 
444
        register_dummy_foreign_for_test(self)
347
445
 
348
446
    def test_create(self):
349
447
        """Test we can create dummies."""
350
448
        self.make_branch_and_tree("d", format=DummyForeignVcsDirFormat())
351
 
        dir = BzrDir.open("d")
 
449
        dir = controldir.ControlDir.open("d")
352
450
        self.assertEquals("A Dummy VCS Dir", dir._format.get_format_string())
353
451
        dir.open_repository()
354
452
        dir.open_branch()
357
455
    def test_sprout(self):
358
456
        """Test we can clone dummies and that the format is not preserved."""
359
457
        self.make_branch_and_tree("d", format=DummyForeignVcsDirFormat())
360
 
        dir = BzrDir.open("d")
 
458
        dir = controldir.ControlDir.open("d")
361
459
        newdir = dir.sprout("e")
362
 
        self.assertNotEquals("A Dummy VCS Dir", newdir._format.get_format_string())
 
460
        self.assertNotEquals("A Dummy VCS Dir",
 
461
                             newdir._format.get_format_string())
 
462
 
 
463
    def test_push_not_supported(self):
 
464
        source_tree = self.make_branch_and_tree("source")
 
465
        target_tree = self.make_branch_and_tree("target", 
 
466
            format=DummyForeignVcsDirFormat())
 
467
        self.assertRaises(errors.NoRoundtrippingSupport, 
 
468
            source_tree.branch.push, target_tree.branch)
 
469
 
 
470
    def test_lossy_push_empty(self):
 
471
        source_tree = self.make_branch_and_tree("source")
 
472
        target_tree = self.make_branch_and_tree("target", 
 
473
            format=DummyForeignVcsDirFormat())
 
474
        pushresult = source_tree.branch.push(target_tree.branch, lossy=True)
 
475
        self.assertEquals(revision.NULL_REVISION, pushresult.old_revid)
 
476
        self.assertEquals(revision.NULL_REVISION, pushresult.new_revid)
 
477
        self.assertEquals({}, pushresult.revidmap)
 
478
 
 
479
    def test_lossy_push_simple(self):
 
480
        source_tree = self.make_branch_and_tree("source")
 
481
        self.build_tree(['source/a', 'source/b'])
 
482
        source_tree.add(['a', 'b'])
 
483
        revid1 = source_tree.commit("msg")
 
484
        target_tree = self.make_branch_and_tree("target", 
 
485
            format=DummyForeignVcsDirFormat())
 
486
        target_tree.branch.lock_write()
 
487
        try:
 
488
            pushresult = source_tree.branch.push(
 
489
                target_tree.branch, lossy=True)
 
490
        finally:
 
491
            target_tree.branch.unlock()
 
492
        self.assertEquals(revision.NULL_REVISION, pushresult.old_revid)
 
493
        self.assertEquals({revid1:target_tree.branch.last_revision()}, 
 
494
                           pushresult.revidmap)
 
495
        self.assertEquals(pushresult.revidmap[revid1], pushresult.new_revid)