1
# Copyright (C) 2005-2012, 2016 Canonical Ltd
2
# Authors: Robert Collins <robert.collins@canonical.com>
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28
from ..lock import write_locked
29
from ..lockdir import LockDir
30
from ..mutabletree import needs_tree_write_lock
31
from . import TestCase, TestCaseWithTransport, TestSkipped
32
from ..workingtree import (
40
class TestTreeDirectory(TestCaseWithTransport):
42
def test_kind_character(self):
43
self.assertEqual(TreeDirectory().kind_character(), '/')
46
class TestTreeEntry(TestCaseWithTransport):
48
def test_kind_character(self):
49
self.assertEqual(TreeEntry().kind_character(), '???')
52
class TestTreeFile(TestCaseWithTransport):
54
def test_kind_character(self):
55
self.assertEqual(TreeFile().kind_character(), '')
58
class TestTreeLink(TestCaseWithTransport):
60
def test_kind_character(self):
61
self.assertEqual(TreeLink().kind_character(), '')
64
class TestDefaultFormat(TestCaseWithTransport):
66
def test_get_set_default_format(self):
67
old_format = workingtree.format_registry.get_default()
69
self.assertTrue(isinstance(old_format, workingtree_4.WorkingTreeFormat6))
70
workingtree.format_registry.set_default(SampleTreeFormat())
72
# the default branch format is used by the meta dir format
73
# which is not the default bzrdir format at this point
74
dir = bzrdir.BzrDirMetaFormat1().initialize('.')
75
dir.create_repository()
77
result = dir.create_workingtree()
78
self.assertEqual(result, 'A tree')
80
workingtree.format_registry.set_default(old_format)
81
self.assertEqual(old_format, workingtree.format_registry.get_default())
83
def test_from_string(self):
84
self.assertIsInstance(
85
SampleTreeFormat.from_string("Sample tree format."),
87
self.assertRaises(AssertionError,
88
SampleTreeFormat.from_string, "Different format string.")
90
def test_get_set_default_format_by_key(self):
91
old_format = workingtree.format_registry.get_default()
93
format = SampleTreeFormat()
94
workingtree.format_registry.register(format)
95
self.addCleanup(workingtree.format_registry.remove, format)
96
self.assertTrue(isinstance(old_format, workingtree_4.WorkingTreeFormat6))
97
workingtree.format_registry.set_default_key(format.get_format_string())
99
# the default branch format is used by the meta dir format
100
# which is not the default bzrdir format at this point
101
dir = bzrdir.BzrDirMetaFormat1().initialize('.')
102
dir.create_repository()
104
result = dir.create_workingtree()
105
self.assertEqual(result, 'A tree')
107
workingtree.format_registry.set_default_key(
108
old_format.get_format_string())
109
self.assertEqual(old_format, workingtree.format_registry.get_default())
112
tree = self.make_branch_and_tree('.')
113
open_direct = workingtree.WorkingTree.open('.')
114
self.assertEqual(tree.basedir, open_direct.basedir)
115
open_no_args = workingtree.WorkingTree.open()
116
self.assertEqual(tree.basedir, open_no_args.basedir)
118
def test_open_containing(self):
119
tree = self.make_branch_and_tree('.')
120
open_direct, relpath = workingtree.WorkingTree.open_containing('.')
121
self.assertEqual(tree.basedir, open_direct.basedir)
122
self.assertEqual('', relpath)
123
open_no_args, relpath = workingtree.WorkingTree.open_containing()
124
self.assertEqual(tree.basedir, open_no_args.basedir)
125
self.assertEqual('', relpath)
126
open_subdir, relpath = workingtree.WorkingTree.open_containing('subdir')
127
self.assertEqual(tree.basedir, open_subdir.basedir)
128
self.assertEqual('subdir', relpath)
131
class SampleTreeFormat(bzrworkingtree.WorkingTreeFormatMetaDir):
134
this format is initializable, unsupported to aid in testing the
135
open and open_downlevel routines.
139
def get_format_string(cls):
140
"""See WorkingTreeFormat.get_format_string()."""
141
return "Sample tree format."
143
def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
144
accelerator_tree=None, hardlink=False):
145
"""Sample branches cannot be created."""
146
t = a_bzrdir.get_workingtree_transport(self)
147
t.put_bytes('format', self.get_format_string())
150
def is_supported(self):
153
def open(self, transport, _found=False):
154
return "opened tree."
157
class SampleExtraTreeFormat(workingtree.WorkingTreeFormat):
158
"""A sample format that does not support use in a metadir.
162
def get_format_string(self):
163
# Not usable in a metadir, so no format string
166
def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
167
accelerator_tree=None, hardlink=False):
168
raise NotImplementedError(self.initialize)
170
def is_supported(self):
173
def open(self, transport, _found=False):
174
raise NotImplementedError(self.open)
177
class TestWorkingTreeFormat(TestCaseWithTransport):
178
"""Tests for the WorkingTreeFormat facility."""
180
def test_find_format_string(self):
181
# is the right format object found for a working tree?
182
branch = self.make_branch('branch')
183
self.assertRaises(errors.NoWorkingTree,
184
bzrworkingtree.WorkingTreeFormatMetaDir.find_format_string, branch.bzrdir)
185
transport = branch.bzrdir.get_workingtree_transport(None)
187
transport.put_bytes("format", "some format name")
188
# The format does not have to be known by Bazaar,
189
# find_format_string just retrieves the name
190
self.assertEqual("some format name",
191
bzrworkingtree.WorkingTreeFormatMetaDir.find_format_string(branch.bzrdir))
193
def test_find_format(self):
194
# is the right format object found for a working tree?
195
# create a branch with a few known format objects.
196
self.build_tree(["foo/", "bar/"])
197
def check_format(format, url):
198
dir = format._matchingbzrdir.initialize(url)
199
dir.create_repository()
201
format.initialize(dir)
202
t = transport.get_transport(url)
203
found_format = bzrworkingtree.WorkingTreeFormatMetaDir.find_format(dir)
204
self.assertIsInstance(found_format, format.__class__)
205
check_format(workingtree_3.WorkingTreeFormat3(), "bar")
207
def test_find_format_no_tree(self):
208
dir = bzrdir.BzrDirMetaFormat1().initialize('.')
209
self.assertRaises(errors.NoWorkingTree,
210
bzrworkingtree.WorkingTreeFormatMetaDir.find_format,
213
def test_find_format_unknown_format(self):
214
dir = bzrdir.BzrDirMetaFormat1().initialize('.')
215
dir.create_repository()
217
SampleTreeFormat().initialize(dir)
218
self.assertRaises(errors.UnknownFormatError,
219
bzrworkingtree.WorkingTreeFormatMetaDir.find_format,
222
def test_find_format_with_features(self):
223
tree = self.make_branch_and_tree('.', format='2a')
224
tree.update_feature_flags({"name": "necessity"})
225
found_format = bzrworkingtree.WorkingTreeFormatMetaDir.find_format(
227
self.assertIsInstance(found_format, workingtree.WorkingTreeFormat)
228
self.assertEqual(found_format.features.get("name"), "necessity")
229
self.assertRaises(errors.MissingFeature, found_format.check_support_status,
231
self.addCleanup(bzrworkingtree.WorkingTreeFormatMetaDir.unregister_feature,
233
bzrworkingtree.WorkingTreeFormatMetaDir.register_feature("name")
234
found_format.check_support_status(True)
237
class TestWorkingTreeIterEntriesByDir_wSubtrees(TestCaseWithTransport):
239
def make_simple_tree(self):
240
tree = self.make_branch_and_tree('tree', format='development-subtree')
241
self.build_tree(['tree/a/', 'tree/a/b/', 'tree/a/b/c'])
242
tree.set_root_id('root-id')
243
tree.add(['a', 'a/b', 'a/b/c'], ['a-id', 'b-id', 'c-id'])
244
tree.commit('initial')
247
def test_just_directory(self):
248
tree = self.make_simple_tree()
249
self.assertEqual([('directory', 'root-id'),
250
('directory', 'a-id'),
251
('directory', 'b-id'),
253
[(ie.kind, ie.file_id)
254
for path, ie in tree.iter_entries_by_dir()])
255
subtree = self.make_branch_and_tree('tree/a/b')
256
self.assertEqual([('tree-reference', 'b-id')],
257
[(ie.kind, ie.file_id)
258
for path, ie in tree.iter_entries_by_dir(['b-id'])])
260
def test_direct_subtree(self):
261
tree = self.make_simple_tree()
262
subtree = self.make_branch_and_tree('tree/a/b')
263
self.assertEqual([('directory', 'root-id'),
264
('directory', 'a-id'),
265
('tree-reference', 'b-id')],
266
[(ie.kind, ie.file_id)
267
for path, ie in tree.iter_entries_by_dir()])
269
def test_indirect_subtree(self):
270
tree = self.make_simple_tree()
271
subtree = self.make_branch_and_tree('tree/a')
272
self.assertEqual([('directory', 'root-id'),
273
('tree-reference', 'a-id')],
274
[(ie.kind, ie.file_id)
275
for path, ie in tree.iter_entries_by_dir()])
278
class TestWorkingTreeFormatRegistry(TestCase):
281
super(TestWorkingTreeFormatRegistry, self).setUp()
282
self.registry = workingtree.WorkingTreeFormatRegistry()
284
def test_register_unregister_format(self):
285
format = SampleTreeFormat()
286
self.registry.register(format)
287
self.assertEqual(format, self.registry.get("Sample tree format."))
288
self.registry.remove(format)
289
self.assertRaises(KeyError, self.registry.get, "Sample tree format.")
291
def test_get_all(self):
292
format = SampleTreeFormat()
293
self.assertEqual([], self.registry._get_all())
294
self.registry.register(format)
295
self.assertEqual([format], self.registry._get_all())
297
def test_register_extra(self):
298
format = SampleExtraTreeFormat()
299
self.assertEqual([], self.registry._get_all())
300
self.registry.register_extra(format)
301
self.assertEqual([format], self.registry._get_all())
303
def test_register_extra_lazy(self):
304
self.assertEqual([], self.registry._get_all())
305
self.registry.register_extra_lazy("breezy.tests.test_workingtree",
306
"SampleExtraTreeFormat")
307
formats = self.registry._get_all()
308
self.assertEqual(1, len(formats))
309
self.assertIsInstance(formats[0], SampleExtraTreeFormat)
312
class TestWorkingTreeFormat3(TestCaseWithTransport):
313
"""Tests specific to WorkingTreeFormat3."""
315
def test_disk_layout(self):
316
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
317
control.create_repository()
318
control.create_branch()
319
tree = workingtree_3.WorkingTreeFormat3().initialize(control)
321
# format 'Bazaar-NG Working Tree format 3'
322
# inventory = blank inventory
323
# pending-merges = ''
325
# no inventory.basis yet
326
t = control.get_workingtree_transport(None)
327
self.assertEqualDiff('Bazaar-NG Working Tree format 3',
328
t.get('format').read())
329
self.assertEqualDiff(t.get('inventory').read(),
330
'<inventory format="5">\n'
333
self.assertEqualDiff('### bzr hashcache v5\n',
334
t.get('stat-cache').read())
335
self.assertFalse(t.has('inventory.basis'))
336
# no last-revision file means 'None' or 'NULLREVISION'
337
self.assertFalse(t.has('last-revision'))
338
# TODO RBC 20060210 do a commit, check the inventory.basis is created
339
# correctly and last-revision file becomes present.
341
def test_uses_lockdir(self):
342
"""WorkingTreeFormat3 uses its own LockDir:
344
- lock is a directory
345
- when the WorkingTree is locked, LockDir can see that
347
t = self.get_transport()
349
dir = bzrdir.BzrDirMetaFormat1().initialize(url)
350
repo = dir.create_repository()
351
branch = dir.create_branch()
353
tree = workingtree_3.WorkingTreeFormat3().initialize(dir)
354
except errors.NotLocalUrl:
355
raise TestSkipped('Not a local URL')
356
self.assertIsDirectory('.bzr', t)
357
self.assertIsDirectory('.bzr/checkout', t)
358
self.assertIsDirectory('.bzr/checkout/lock', t)
359
our_lock = LockDir(t, '.bzr/checkout/lock')
360
self.assertEqual(our_lock.peek(), None)
362
self.assertTrue(our_lock.peek())
364
self.assertEqual(our_lock.peek(), None)
366
def test_missing_pending_merges(self):
367
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
368
control.create_repository()
369
control.create_branch()
370
tree = workingtree_3.WorkingTreeFormat3().initialize(control)
371
tree._transport.delete("pending-merges")
372
self.assertEqual([], tree.get_parent_ids())
375
class InstrumentedTree(object):
376
"""A instrumented tree to check the needs_tree_write_lock decorator."""
381
def lock_tree_write(self):
382
self._locks.append('t')
384
@needs_tree_write_lock
385
def method_with_tree_write_lock(self, *args, **kwargs):
386
"""A lock_tree_write decorated method that returns its arguments."""
389
@needs_tree_write_lock
390
def method_that_raises(self):
391
"""This method causes an exception when called with parameters.
393
This allows the decorator code to be checked - it should still call
398
self._locks.append('u')
401
class TestInstrumentedTree(TestCase):
403
def test_needs_tree_write_lock(self):
404
"""@needs_tree_write_lock should be semantically transparent."""
405
tree = InstrumentedTree()
407
'method_with_tree_write_lock',
408
tree.method_with_tree_write_lock.__name__)
409
self.assertDocstring(
410
"A lock_tree_write decorated method that returns its arguments.",
411
tree.method_with_tree_write_lock)
414
result = tree.method_with_tree_write_lock(1,2,3, a='b')
415
self.assertEqual((args, kwargs), result)
416
self.assertEqual(['t', 'u'], tree._locks)
417
self.assertRaises(TypeError, tree.method_that_raises, 'foo')
418
self.assertEqual(['t', 'u', 't', 'u'], tree._locks)
421
class TestRevert(TestCaseWithTransport):
423
def test_revert_conflicts_recursive(self):
424
this_tree = self.make_branch_and_tree('this-tree')
425
self.build_tree_contents([('this-tree/foo/',),
426
('this-tree/foo/bar', 'bar')])
427
this_tree.add(['foo', 'foo/bar'])
428
this_tree.commit('created foo/bar')
429
other_tree = this_tree.bzrdir.sprout('other-tree').open_workingtree()
430
self.build_tree_contents([('other-tree/foo/bar', 'baz')])
431
other_tree.commit('changed bar')
432
self.build_tree_contents([('this-tree/foo/bar', 'qux')])
433
this_tree.commit('changed qux')
434
this_tree.merge_from_branch(other_tree.branch)
435
self.assertEqual(1, len(this_tree.conflicts()))
436
this_tree.revert(['foo'])
437
self.assertEqual(0, len(this_tree.conflicts()))
440
class TestAutoResolve(TestCaseWithTransport):
442
def test_auto_resolve(self):
443
base = self.make_branch_and_tree('base')
444
self.build_tree_contents([('base/hello', 'Hello')])
445
base.add('hello', 'hello_id')
447
other = base.bzrdir.sprout('other').open_workingtree()
448
self.build_tree_contents([('other/hello', 'hELLO')])
449
other.commit('Case switch')
450
this = base.bzrdir.sprout('this').open_workingtree()
451
self.assertPathExists('this/hello')
452
self.build_tree_contents([('this/hello', 'Hello World')])
453
this.commit('Add World')
454
this.merge_from_branch(other.branch)
455
self.assertEqual([conflicts.TextConflict('hello', 'hello_id')],
458
self.assertEqual([conflicts.TextConflict('hello', 'hello_id')],
460
self.build_tree_contents([('this/hello', '<<<<<<<')])
462
self.assertEqual([conflicts.TextConflict('hello', 'hello_id')],
464
self.build_tree_contents([('this/hello', '=======')])
466
self.assertEqual([conflicts.TextConflict('hello', 'hello_id')],
468
self.build_tree_contents([('this/hello', '\n>>>>>>>')])
469
remaining, resolved = this.auto_resolve()
470
self.assertEqual([conflicts.TextConflict('hello', 'hello_id')],
472
self.assertEqual([], resolved)
473
self.build_tree_contents([('this/hello', 'hELLO wORLD')])
474
remaining, resolved = this.auto_resolve()
475
self.assertEqual([], this.conflicts())
476
self.assertEqual([conflicts.TextConflict('hello', 'hello_id')],
478
self.assertPathDoesNotExist('this/hello.BASE')
480
def test_auto_resolve_dir(self):
481
tree = self.make_branch_and_tree('tree')
482
self.build_tree(['tree/hello/'])
483
tree.add('hello', 'hello-id')
484
file_conflict = conflicts.TextConflict('file', 'hello-id')
485
tree.set_conflicts(conflicts.ConflictList([file_conflict]))
489
class TestFindTrees(TestCaseWithTransport):
491
def test_find_trees(self):
492
self.make_branch_and_tree('foo')
493
self.make_branch_and_tree('foo/bar')
494
# Sticking a tree inside a control dir is heinous, so let's skip it
495
self.make_branch_and_tree('foo/.bzr/baz')
496
self.make_branch('qux')
497
trees = workingtree.WorkingTree.find_trees('.')
498
self.assertEqual(2, len(list(trees)))
501
class TestStoredUncommitted(TestCaseWithTransport):
503
def store_uncommitted(self):
504
tree = self.make_branch_and_tree('tree')
505
tree.commit('get root in there')
506
self.build_tree_contents([('tree/file', 'content')])
507
tree.add('file', 'file-id')
508
tree.store_uncommitted()
511
def test_store_uncommitted(self):
512
self.store_uncommitted()
513
self.assertPathDoesNotExist('tree/file')
515
def test_store_uncommitted_no_change(self):
516
tree = self.make_branch_and_tree('tree')
517
tree.commit('get root in there')
518
tree.store_uncommitted()
519
self.assertIs(None, tree.branch.get_unshelver(tree))
521
def test_restore_uncommitted(self):
522
with write_locked(self.store_uncommitted()) as tree:
523
tree.restore_uncommitted()
524
self.assertPathExists('tree/file')
525
self.assertIs(None, tree.branch.get_unshelver(tree))
527
def test_restore_uncommitted_none(self):
528
tree = self.make_branch_and_tree('tree')
529
tree.restore_uncommitted()