/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to brzlib/tests/test_foreign.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-21 12:41:27 UTC
  • mto: This revision was merged to the branch mainline in revision 6623.
  • Revision ID: jelmer@jelmer.uk-20170521124127-iv8etg0vwymyai6y
s/bzr/brz/ in apport config.

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
"""Tests for foreign VCS utility code."""
19
19
 
20
20
 
21
 
from .. import (
 
21
from brzlib import (
22
22
    branch,
 
23
    bzrdir,
23
24
    controldir,
24
25
    errors,
25
26
    foreign,
29
30
    revision,
30
31
    tests,
31
32
    trace,
32
 
    )
33
 
from ..bzr import (
34
 
    branch as bzrbranch,
35
 
    bzrdir,
36
33
    vf_repository,
37
34
    )
38
35
 
39
 
from ..bzr import groupcompress_repo
 
36
from brzlib.repofmt import groupcompress_repo
40
37
 
41
 
# This is the dummy foreign revision control system, used
 
38
# This is the dummy foreign revision control system, used 
42
39
# mainly here in the testsuite to test the foreign VCS infrastructure.
43
 
# It is basically standard Bazaar with some minor modifications to
44
 
# make it "foreign".
45
 
#
 
40
# It is basically standard Bazaar with some minor modifications to 
 
41
# make it "foreign". 
 
42
46
43
# It has the following differences to "regular" Bazaar:
47
44
# - The control directory is named ".dummy", not ".bzr".
48
45
# - The revision ids are tuples, not strings.
53
50
    """A simple mapping for the dummy Foreign VCS, for use with testing."""
54
51
 
55
52
    def __eq__(self, other):
56
 
        return isinstance(self, type(other))
 
53
        return type(self) == type(other)
57
54
 
58
55
    def revision_id_bzr_to_foreign(self, bzr_revid):
59
 
        return tuple(bzr_revid[len(b"dummy-v1:"):].split(b"-")), self
 
56
        return tuple(bzr_revid[len("dummy-v1:"):].split("-")), self
60
57
 
61
58
    def revision_id_foreign_to_bzr(self, foreign_revid):
62
 
        return b"dummy-v1:%s-%s-%s" % foreign_revid
 
59
        return "dummy-v1:%s-%s-%s" % foreign_revid
63
60
 
64
61
 
65
62
class DummyForeignVcsMappingRegistry(foreign.VcsMappingRegistry):
66
63
 
67
64
    def revision_id_bzr_to_foreign(self, revid):
68
 
        if not revid.startswith(b"dummy-"):
 
65
        if not revid.startswith("dummy-"):
69
66
            raise errors.InvalidRevisionId(revid, None)
70
 
        mapping_version = revid[len(b"dummy-"):len(b"dummy-vx")]
 
67
        mapping_version = revid[len("dummy-"):len("dummy-vx")]
71
68
        mapping = self.get(mapping_version)
72
69
        return mapping.revision_id_bzr_to_foreign(revid)
73
70
 
80
77
 
81
78
    def __init__(self):
82
79
        self.mapping_registry = DummyForeignVcsMappingRegistry()
83
 
        self.mapping_registry.register(b"v1", DummyForeignVcsMapping(self),
 
80
        self.mapping_registry.register("v1", DummyForeignVcsMapping(self),
84
81
                                       "Version 1")
85
82
        self.abbreviation = "dummy"
86
83
 
87
84
    def show_foreign_revid(self, foreign_revid):
88
 
        return {"dummy ding": "%s/%s\\%s" % foreign_revid}
 
85
        return { "dummy ding": "%s/%s\\%s" % foreign_revid }
89
86
 
90
87
    def serialize_foreign_revid(self, foreign_revid):
91
88
        return "%s|%s|%s" % foreign_revid
92
89
 
93
90
 
94
 
class DummyForeignVcsBranch(bzrbranch.BzrBranch6, foreign.ForeignBranch):
 
91
class DummyForeignVcsBranch(branch.BzrBranch6,foreign.ForeignBranch):
95
92
    """A Dummy VCS Branch."""
96
93
 
97
94
    @property
98
95
    def user_transport(self):
99
 
        return self.controldir.user_transport
 
96
        return self.bzrdir.user_transport
100
97
 
101
 
    def __init__(self, _format, _control_files, a_controldir, *args, **kwargs):
 
98
    def __init__(self, _format, _control_files, a_bzrdir, *args, **kwargs):
102
99
        self._format = _format
103
 
        self._base = a_controldir.transport.base
 
100
        self._base = a_bzrdir.transport.base
104
101
        self._ignore_fallbacks = False
105
 
        self.controldir = a_controldir
 
102
        self.bzrdir = a_bzrdir
106
103
        foreign.ForeignBranch.__init__(self,
107
 
                                       DummyForeignVcsMapping(DummyForeignVcs()))
108
 
        bzrbranch.BzrBranch6.__init__(self, _format, _control_files, a_controldir,
109
 
                                      *args, **kwargs)
 
104
            DummyForeignVcsMapping(DummyForeignVcs()))
 
105
        branch.BzrBranch6.__init__(self, _format, _control_files, a_bzrdir,
 
106
            *args, **kwargs)
110
107
 
111
108
    def _get_checkout_format(self, lightweight=False):
112
109
        """Return the most suitable metadir for a checkout of this branch.
113
110
        Weaves are used if this branch's repository uses weaves.
114
111
        """
115
 
        return self.controldir.checkout_metadir()
 
112
        return self.bzrdir.checkout_metadir()
116
113
 
117
114
    def import_last_revision_info_and_tags(self, source, revno, revid,
118
115
                                           lossy=False):
123
120
        return (revno, revid)
124
121
 
125
122
 
126
 
class DummyForeignCommitBuilder(vf_repository.VersionedFileCommitBuilder):
 
123
class DummyForeignCommitBuilder(vf_repository.VersionedFileRootCommitBuilder):
127
124
 
128
 
    def _generate_revision_if_needed(self, revid):
 
125
    def _generate_revision_if_needed(self):
129
126
        mapping = DummyForeignVcsMapping(DummyForeignVcs())
130
127
        if self._lossy:
131
128
            self._new_revision_id = mapping.revision_id_foreign_to_bzr(
132
 
                (b'%d' % self._timestamp,
133
 
                 str(self._timezone).encode('ascii'), b"UNKNOWN"))
 
129
                (str(self._timestamp), str(self._timezone), "UNKNOWN"))
134
130
            self.random_revid = False
135
 
        elif revid is not None:
136
 
            self._new_revision_id = revid
 
131
        elif self._new_revision_id is not None:
137
132
            self.random_revid = False
138
133
        else:
139
134
            self._new_revision_id = self._gen_revision_id()
141
136
 
142
137
 
143
138
class DummyForeignVcsRepository(groupcompress_repo.CHKInventoryRepository,
144
 
                                foreign.ForeignRepository):
 
139
    foreign.ForeignRepository):
145
140
    """Dummy foreign vcs repository."""
146
141
 
147
142
 
152
147
 
153
148
    @classmethod
154
149
    def get_format_string(cls):
155
 
        return b"Dummy Foreign Vcs Repository"
 
150
        return "Dummy Foreign Vcs Repository"
156
151
 
157
152
    def get_format_description(self):
158
153
        return "Dummy Foreign Vcs Repository"
160
155
 
161
156
def branch_history(graph, revid):
162
157
    ret = list(graph.iter_lefthand_ancestry(revid,
163
 
                                            (revision.NULL_REVISION,)))
 
158
        (revision.NULL_REVISION,)))
164
159
    ret.reverse()
165
160
    return ret
166
161
 
183
178
            graph = self.source.repository.get_graph()
184
179
            # This just handles simple cases, but that's good enough for tests
185
180
            my_history = branch_history(self.target.repository.get_graph(),
186
 
                                        result.old_revid)
 
181
                result.old_revid)
187
182
            if stop_revision is None:
188
183
                stop_revision = self.source.last_revision()
189
184
            their_history = branch_history(graph, stop_revision)
194
189
            for revid in todo:
195
190
                rev = self.source.repository.get_revision(revid)
196
191
                tree = self.source.repository.revision_tree(revid)
197
 
                def get_file_with_stat(path):
198
 
                    return (tree.get_file(path), None)
 
192
                def get_file_with_stat(file_id, path=None):
 
193
                    return (tree.get_file(file_id), None)
199
194
                tree.get_file_with_stat = get_file_with_stat
200
195
                new_revid = self.target.mapping.revision_id_foreign_to_bzr(
201
 
                    (b'%d' % rev.timestamp, str(rev.timezone).encode('ascii'),
202
 
                        str(self.target.revno()).encode('ascii')))
203
 
                parent_revno, parent_revid = self.target.last_revision_info()
 
196
                    (str(rev.timestamp), str(rev.timezone),
 
197
                        str(self.target.revno())))
 
198
                parent_revno, parent_revid= self.target.last_revision_info()
204
199
                if parent_revid == revision.NULL_REVISION:
205
200
                    parent_revids = []
206
201
                else:
207
202
                    parent_revids = [parent_revid]
208
 
                builder = self.target.get_commit_builder(
209
 
                    parent_revids, self.target.get_config_stack(), rev.timestamp,
210
 
                    rev.timezone, rev.committer, rev.properties,
211
 
                    new_revid)
 
203
                builder = self.target.get_commit_builder(parent_revids, 
 
204
                        self.target.get_config_stack(), rev.timestamp,
 
205
                        rev.timezone, rev.committer, rev.properties,
 
206
                        new_revid)
212
207
                try:
213
208
                    parent_tree = self.target.repository.revision_tree(
214
209
                        parent_revid)
215
 
                    iter_changes = tree.iter_changes(parent_tree)
216
 
                    list(builder.record_iter_changes(
217
 
                        tree, parent_revid, iter_changes))
 
210
                    for path, ie in tree.iter_entries_by_dir():
 
211
                        new_ie = ie.copy()
 
212
                        new_ie.revision = None
 
213
                        builder.record_entry_contents(new_ie, 
 
214
                            [parent_tree.root_inventory],
 
215
                            path, tree, 
 
216
                            (ie.kind, ie.text_size, ie.executable, ie.text_sha1))
218
217
                    builder.finish_inventory()
219
218
                except:
220
219
                    builder.abort()
221
220
                    raise
222
221
                revidmap[revid] = builder.commit(rev.message)
223
 
                self.target.set_last_revision_info(parent_revno + 1,
224
 
                                                   revidmap[revid])
225
 
                trace.mutter('lossily pushed revision %s -> %s',
226
 
                             revid, revidmap[revid])
 
222
                self.target.set_last_revision_info(parent_revno+1, 
 
223
                    revidmap[revid])
 
224
                trace.mutter('lossily pushed revision %s -> %s', 
 
225
                    revid, revidmap[revid])
227
226
        finally:
228
227
            self.source.unlock()
229
228
        result.new_revno, result.new_revid = self.target.last_revision_info()
231
230
        return result
232
231
 
233
232
 
234
 
class DummyForeignVcsBranchFormat(bzrbranch.BzrBranchFormat6):
 
233
class DummyForeignVcsBranchFormat(branch.BzrBranchFormat6):
235
234
 
236
235
    @classmethod
237
236
    def get_format_string(cls):
238
 
        return b"Branch for Testing"
 
237
        return "Branch for Testing"
239
238
 
240
239
    @property
241
 
    def _matchingcontroldir(self):
 
240
    def _matchingbzrdir(self):
242
241
        return DummyForeignVcsDirFormat()
243
242
 
244
 
    def open(self, a_controldir, name=None, _found=False, ignore_fallbacks=False,
245
 
             found_repository=None):
 
243
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
244
            found_repository=None):
246
245
        if name is None:
247
 
            name = a_controldir._get_selected_branch()
 
246
            name = a_bzrdir._get_selected_branch()
248
247
        if not _found:
249
248
            raise NotImplementedError
250
249
        try:
251
 
            transport = a_controldir.get_branch_transport(None, name=name)
 
250
            transport = a_bzrdir.get_branch_transport(None, name=name)
252
251
            control_files = lockable_files.LockableFiles(transport, 'lock',
253
252
                                                         lockdir.LockDir)
254
253
            if found_repository is None:
255
 
                found_repository = a_controldir.find_repository()
 
254
                found_repository = a_bzrdir.find_repository()
256
255
            return DummyForeignVcsBranch(_format=self,
257
 
                                         _control_files=control_files,
258
 
                                         a_controldir=a_controldir,
259
 
                                         _repository=found_repository,
260
 
                                         name=name)
 
256
                              _control_files=control_files,
 
257
                              a_bzrdir=a_bzrdir,
 
258
                              _repository=found_repository,
 
259
                              name=name)
261
260
        except errors.NoSuchFile:
262
261
            raise errors.NotBranchError(path=transport.base)
263
262
 
267
266
 
268
267
    @classmethod
269
268
    def get_format_string(cls):
270
 
        return b"A Dummy VCS Dir"
 
269
        return "A Dummy VCS Dir"
271
270
 
272
271
    @classmethod
273
272
    def get_format_description(cls):
289
288
        # Since we don't have a .bzr directory, inherit the
290
289
        # mode from the root directory
291
290
        temp_control = lockable_files.LockableFiles(transport,
292
 
                                                    '', lockable_files.TransportLock)
 
291
                            '', lockable_files.TransportLock)
293
292
        temp_control._transport.mkdir('.dummy',
294
293
                                      # FIXME: RBC 20060121 don't peek under
295
294
                                      # the covers
298
297
        bzrdir_transport = transport.clone('.dummy')
299
298
        # NB: no need to escape relative paths that are url safe.
300
299
        control_files = lockable_files.LockableFiles(bzrdir_transport,
301
 
                                                     self._lock_file_name, self._lock_class)
 
300
            self._lock_file_name, self._lock_class)
302
301
        control_files.create_lock()
303
302
        return self.open(transport, _found=True)
304
303
 
314
313
        self.root_transport = _transport
315
314
        self._mode_check_done = False
316
315
        self._control_files = lockable_files.LockableFiles(self.transport,
317
 
                                                           "lock", lockable_files.TransportLock)
 
316
            "lock", lockable_files.TransportLock)
318
317
 
319
318
    def create_workingtree(self):
320
319
        # dirstate requires a ".bzr" entry to exist
321
 
        self.root_transport.put_bytes(".bzr", b"foo")
 
320
        self.root_transport.put_bytes(".bzr", "foo")
322
321
        return super(DummyForeignVcsDir, self).create_workingtree()
323
322
 
324
323
    def open_branch(self, name=None, unsupported=False, ignore_fallbacks=True,
331
330
 
332
331
    def cloning_metadir(self, stacked=False):
333
332
        """Produce a metadir suitable for cloning with."""
334
 
        return controldir.format_registry.make_controldir("default")
 
333
        return controldir.format_registry.make_bzrdir("default")
335
334
 
336
335
    def checkout_metadir(self):
337
336
        return self.cloning_metadir()
377
376
 
378
377
    @classmethod
379
378
    def known_formats(cls):
380
 
        return [DummyForeignVcsDirFormat()]
 
379
        return set([DummyForeignVcsDirFormat()])
381
380
 
382
381
 
383
382
class ForeignVcsRegistryTests(tests.TestCase):
386
385
    def test_parse_revision_id_no_dash(self):
387
386
        reg = foreign.ForeignVcsRegistry()
388
387
        self.assertRaises(errors.InvalidRevisionId,
389
 
                          reg.parse_revision_id, b"invalid")
 
388
                          reg.parse_revision_id, "invalid")
390
389
 
391
390
    def test_parse_revision_id_unknown_mapping(self):
392
391
        reg = foreign.ForeignVcsRegistry()
393
392
        self.assertRaises(errors.InvalidRevisionId,
394
 
                          reg.parse_revision_id, b"unknown-foreignrevid")
 
393
                          reg.parse_revision_id, "unknown-foreignrevid")
395
394
 
396
395
    def test_parse_revision_id(self):
397
396
        reg = foreign.ForeignVcsRegistry()
398
397
        vcs = DummyForeignVcs()
399
398
        reg.register("dummy", vcs, "Dummy VCS")
400
399
        self.assertEqual((
401
 
            (b"some", b"foreign", b"revid"), DummyForeignVcsMapping(vcs)),
402
 
            reg.parse_revision_id(b"dummy-v1:some-foreign-revid"))
 
400
            ("some", "foreign", "revid"), DummyForeignVcsMapping(vcs)),
 
401
            reg.parse_revision_id("dummy-v1:some-foreign-revid"))
403
402
 
404
403
 
405
404
class ForeignRevisionTests(tests.TestCase):
407
406
 
408
407
    def test_create(self):
409
408
        mapp = DummyForeignVcsMapping(DummyForeignVcs())
410
 
        rev = foreign.ForeignRevision((b"a", b"foreign", b"revid"),
411
 
                                      mapp, b"roundtripped-revid")
412
 
        self.assertEqual(b"", rev.inventory_sha1)
413
 
        self.assertEqual((b"a", b"foreign", b"revid"), rev.foreign_revid)
 
409
        rev = foreign.ForeignRevision(("a", "foreign", "revid"),
 
410
                                      mapp, "roundtripped-revid")
 
411
        self.assertEqual("", rev.inventory_sha1)
 
412
        self.assertEqual(("a", "foreign", "revid"), rev.foreign_revid)
414
413
        self.assertEqual(mapp, rev.mapping)
415
414
 
416
415
 
 
416
class WorkingTreeFileUpdateTests(tests.TestCaseWithTransport):
 
417
    """Tests for update_workingtree_fileids()."""
 
418
 
 
419
    def test_update_workingtree(self):
 
420
        wt = self.make_branch_and_tree('br1')
 
421
        self.build_tree_contents([('br1/bla', 'original contents\n')])
 
422
        wt.add('bla', 'bla-a')
 
423
        wt.commit('bla-a')
 
424
        root_id = wt.get_root_id()
 
425
        target = wt.bzrdir.sprout('br2').open_workingtree()
 
426
        target.unversion(['bla-a'])
 
427
        target.add('bla', 'bla-b')
 
428
        target.commit('bla-b')
 
429
        target_basis = target.basis_tree()
 
430
        target_basis.lock_read()
 
431
        self.addCleanup(target_basis.unlock)
 
432
        foreign.update_workingtree_fileids(wt, target_basis)
 
433
        wt.lock_read()
 
434
        try:
 
435
            self.assertEqual(set([root_id, "bla-b"]), set(wt.all_file_ids()))
 
436
        finally:
 
437
            wt.unlock()
 
438
 
 
439
 
417
440
class DummyForeignVcsTests(tests.TestCaseWithTransport):
418
441
    """Very basic test for DummyForeignVcs."""
419
442
 
425
448
        """Test we can create dummies."""
426
449
        self.make_branch_and_tree("d", format=DummyForeignVcsDirFormat())
427
450
        dir = controldir.ControlDir.open("d")
428
 
        self.assertEqual(b"A Dummy VCS Dir", dir._format.get_format_string())
 
451
        self.assertEqual("A Dummy VCS Dir", dir._format.get_format_string())
429
452
        dir.open_repository()
430
453
        dir.open_branch()
431
454
        dir.open_workingtree()
435
458
        self.make_branch_and_tree("d", format=DummyForeignVcsDirFormat())
436
459
        dir = controldir.ControlDir.open("d")
437
460
        newdir = dir.sprout("e")
438
 
        self.assertNotEqual(b"A Dummy VCS Dir",
 
461
        self.assertNotEqual("A Dummy VCS Dir",
439
462
                            newdir._format.get_format_string())
440
463
 
441
464
    def test_push_not_supported(self):