~bzr-pqm/bzr/bzr.dev

1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
1
# Copyright (C) 2005, 2006 Canonical Ltd
1399.1.12 by Robert Collins
add new test script
2
# Authors:  Robert Collins <robert.collins@canonical.com>
3
#
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.
8
#
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.
13
#
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
18
from cStringIO import StringIO
1399.1.12 by Robert Collins
add new test script
19
import os
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
20
21
import bzrlib
1399.1.12 by Robert Collins
add new test script
22
from bzrlib.branch import Branch
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
23
from bzrlib import bzrdir, conflicts, errors, workingtree
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
24
from bzrlib.bzrdir import BzrDir
1508.1.3 by Robert Collins
Do not consider urls to be relative paths within working trees.
25
from bzrlib.errors import NotBranchError, NotVersionedError
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
26
from bzrlib.lockdir import LockDir
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
27
from bzrlib.osutils import pathjoin, getcwd, has_symlinks
1558.10.1 by Aaron Bentley
Handle lockdirs over NFS properly
28
from bzrlib.tests import TestCaseWithTransport, TestSkipped
1399.1.12 by Robert Collins
add new test script
29
from bzrlib.trace import mutter
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
30
from bzrlib.transport import get_transport
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
31
from bzrlib.workingtree import (TreeEntry, TreeDirectory, TreeFile, TreeLink,
32
                                WorkingTree)
1399.1.12 by Robert Collins
add new test script
33
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
34
class TestTreeDirectory(TestCaseWithTransport):
1399.1.12 by Robert Collins
add new test script
35
36
    def test_kind_character(self):
37
        self.assertEqual(TreeDirectory().kind_character(), '/')
38
39
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
40
class TestTreeEntry(TestCaseWithTransport):
1399.1.12 by Robert Collins
add new test script
41
42
    def test_kind_character(self):
43
        self.assertEqual(TreeEntry().kind_character(), '???')
44
45
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
46
class TestTreeFile(TestCaseWithTransport):
1399.1.12 by Robert Collins
add new test script
47
48
    def test_kind_character(self):
49
        self.assertEqual(TreeFile().kind_character(), '')
50
51
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
52
class TestTreeLink(TestCaseWithTransport):
1399.1.12 by Robert Collins
add new test script
53
54
    def test_kind_character(self):
55
        self.assertEqual(TreeLink().kind_character(), '')
56
57
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
58
class TestDefaultFormat(TestCaseWithTransport):
59
60
    def test_get_set_default_format(self):
61
        old_format = workingtree.WorkingTreeFormat.get_default_format()
62
        # default is 3
63
        self.assertTrue(isinstance(old_format, workingtree.WorkingTreeFormat3))
64
        workingtree.WorkingTreeFormat.set_default_format(SampleTreeFormat())
65
        try:
66
            # the default branch format is used by the meta dir format
67
            # which is not the default bzrdir format at this point
68
            dir = bzrdir.BzrDirMetaFormat1().initialize('.')
69
            dir.create_repository()
70
            dir.create_branch()
71
            result = dir.create_workingtree()
72
            self.assertEqual(result, 'A tree')
73
        finally:
74
            workingtree.WorkingTreeFormat.set_default_format(old_format)
75
        self.assertEqual(old_format, workingtree.WorkingTreeFormat.get_default_format())
76
77
78
class SampleTreeFormat(workingtree.WorkingTreeFormat):
79
    """A sample format
80
81
    this format is initializable, unsupported to aid in testing the 
82
    open and open_downlevel routines.
83
    """
84
85
    def get_format_string(self):
86
        """See WorkingTreeFormat.get_format_string()."""
87
        return "Sample tree format."
88
1508.1.24 by Robert Collins
Add update command for use with checkouts.
89
    def initialize(self, a_bzrdir, revision_id=None):
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
90
        """Sample branches cannot be created."""
91
        t = a_bzrdir.get_workingtree_transport(self)
92
        t.put('format', StringIO(self.get_format_string()))
93
        return 'A tree'
94
95
    def is_supported(self):
96
        return False
97
98
    def open(self, transport, _found=False):
99
        return "opened tree."
100
101
102
class TestWorkingTreeFormat(TestCaseWithTransport):
103
    """Tests for the WorkingTreeFormat facility."""
104
105
    def test_find_format(self):
106
        # is the right format object found for a working tree?
107
        # create a branch with a few known format objects.
108
        self.build_tree(["foo/", "bar/"])
109
        def check_format(format, url):
110
            dir = format._matchingbzrdir.initialize(url)
111
            dir.create_repository()
112
            dir.create_branch()
113
            format.initialize(dir)
114
            t = get_transport(url)
115
            found_format = workingtree.WorkingTreeFormat.find_format(dir)
116
            self.failUnless(isinstance(found_format, format.__class__))
117
        check_format(workingtree.WorkingTreeFormat3(), "bar")
118
        
119
    def test_find_format_no_tree(self):
120
        dir = bzrdir.BzrDirMetaFormat1().initialize('.')
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
121
        self.assertRaises(errors.NoWorkingTree,
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
122
                          workingtree.WorkingTreeFormat.find_format,
123
                          dir)
124
125
    def test_find_format_unknown_format(self):
126
        dir = bzrdir.BzrDirMetaFormat1().initialize('.')
127
        dir.create_repository()
128
        dir.create_branch()
129
        SampleTreeFormat().initialize(dir)
130
        self.assertRaises(errors.UnknownFormatError,
131
                          workingtree.WorkingTreeFormat.find_format,
132
                          dir)
133
134
    def test_register_unregister_format(self):
135
        format = SampleTreeFormat()
136
        # make a control dir
137
        dir = bzrdir.BzrDirMetaFormat1().initialize('.')
138
        dir.create_repository()
139
        dir.create_branch()
140
        # make a branch
141
        format.initialize(dir)
142
        # register a format for it.
143
        workingtree.WorkingTreeFormat.register_format(format)
144
        # which branch.Open will refuse (not supported)
145
        self.assertRaises(errors.UnsupportedFormatError, workingtree.WorkingTree.open, '.')
146
        # but open_downlevel will work
147
        self.assertEqual(format.open(dir), workingtree.WorkingTree.open_downlevel('.'))
148
        # unregister the format
149
        workingtree.WorkingTreeFormat.unregister_format(format)
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
150
151
152
class TestWorkingTreeFormat3(TestCaseWithTransport):
153
    """Tests specific to WorkingTreeFormat3."""
154
155
    def test_disk_layout(self):
156
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
157
        control.create_repository()
158
        control.create_branch()
159
        tree = workingtree.WorkingTreeFormat3().initialize(control)
160
        # we want:
161
        # format 'Bazaar-NG Working Tree format 3'
162
        # inventory = blank inventory
163
        # pending-merges = ''
164
        # stat-cache = ??
165
        # no inventory.basis yet
166
        t = control.get_workingtree_transport(None)
1553.5.81 by Martin Pool
Revert change to WorkingTreeFormat3 format string; too many things want it the old way
167
        self.assertEqualDiff('Bazaar-NG Working Tree format 3',
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
168
                             t.get('format').read())
169
        self.assertEqualDiff('<inventory format="5">\n'
170
                             '</inventory>\n',
171
                             t.get('inventory').read())
172
        self.assertEqualDiff('### bzr hashcache v5\n',
173
                             t.get('stat-cache').read())
174
        self.assertFalse(t.has('inventory.basis'))
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
175
        # no last-revision file means 'None' or 'NULLREVISION'
176
        self.assertFalse(t.has('last-revision'))
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
177
        # TODO RBC 20060210 do a commit, check the inventory.basis is created 
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
178
        # correctly and last-revision file becomes present.
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
179
180
    def test_uses_lockdir(self):
181
        """WorkingTreeFormat3 uses its own LockDir:
182
            
183
            - lock is a directory
184
            - when the WorkingTree is locked, LockDir can see that
185
        """
186
        t = self.get_transport()
187
        url = self.get_url()
188
        dir = bzrdir.BzrDirMetaFormat1().initialize(url)
189
        repo = dir.create_repository()
190
        branch = dir.create_branch()
1558.10.1 by Aaron Bentley
Handle lockdirs over NFS properly
191
        try:
192
            tree = workingtree.WorkingTreeFormat3().initialize(dir)
193
        except errors.NotLocalUrl:
194
            raise TestSkipped('Not a local URL')
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
195
        self.assertIsDirectory('.bzr', t)
196
        self.assertIsDirectory('.bzr/checkout', t)
197
        self.assertIsDirectory('.bzr/checkout/lock', t)
198
        our_lock = LockDir(t, '.bzr/checkout/lock')
199
        self.assertEquals(our_lock.peek(), None)
1553.5.75 by Martin Pool
Additional WorkingTree LockDir test
200
        tree.lock_write()
201
        self.assertTrue(our_lock.peek())
202
        tree.unlock()
203
        self.assertEquals(our_lock.peek(), None)
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
204
1815.2.2 by Jelmer Vernooij
Move missing_pending_merges test to WorkingTreeFormat3-specific tests.
205
    def test_missing_pending_merges(self):
206
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
207
        control.create_repository()
208
        control.create_branch()
209
        tree = workingtree.WorkingTreeFormat3().initialize(control)
210
        tree._control_files._transport.delete("pending-merges")
211
        self.assertEqual([], tree.pending_merges())
212
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
213
214
class TestFormat2WorkingTree(TestCaseWithTransport):
215
    """Tests that are specific to format 2 trees."""
216
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
217
    def create_format2_tree(self, url):
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
218
        return self.make_branch_and_tree(
219
            url, format=bzrlib.bzrdir.BzrDirFormat6())
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
220
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
221
    def test_conflicts(self):
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
222
        # test backwards compatability
223
        tree = self.create_format2_tree('.')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
224
        self.assertRaises(errors.UnsupportedOperation, tree.set_conflicts,
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
225
                          None)
226
        file('lala.BASE', 'wb').write('labase')
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
227
        expected = conflicts.ContentsConflict('lala')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
228
        self.assertEqual(list(tree.conflicts()), [expected])
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
229
        file('lala', 'wb').write('la')
230
        tree.add('lala', 'lala-id')
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
231
        expected = conflicts.ContentsConflict('lala', file_id='lala-id')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
232
        self.assertEqual(list(tree.conflicts()), [expected])
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
233
        file('lala.THIS', 'wb').write('lathis')
234
        file('lala.OTHER', 'wb').write('laother')
235
        # When "text conflict"s happen, stem, THIS and OTHER are text
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
236
        expected = conflicts.TextConflict('lala', file_id='lala-id')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
237
        self.assertEqual(list(tree.conflicts()), [expected])
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
238
        os.unlink('lala.OTHER')
239
        os.mkdir('lala.OTHER')
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
240
        expected = conflicts.ContentsConflict('lala', file_id='lala-id')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
241
        self.assertEqual(list(tree.conflicts()), [expected])
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
242
243
244
class TestNonFormatSpecificCode(TestCaseWithTransport):
245
    """This class contains tests of workingtree that are not format specific."""
246
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
247
    
248
    def test_gen_file_id(self):
249
        self.assertStartsWith(bzrlib.workingtree.gen_file_id('bar'), 'bar-')
250
        self.assertStartsWith(bzrlib.workingtree.gen_file_id('Mwoo oof\t m'), 'Mwoooofm-')
251
        self.assertStartsWith(bzrlib.workingtree.gen_file_id('..gam.py'), 'gam.py-')
252
        self.assertStartsWith(bzrlib.workingtree.gen_file_id('..Mwoo oof\t m'), 'Mwoooofm-')
253
254
    def test_next_id_suffix(self):
255
        bzrlib.workingtree._gen_id_suffix = None
256
        bzrlib.workingtree._next_id_suffix()
257
        self.assertNotEqual(None, bzrlib.workingtree._gen_id_suffix)
258
        bzrlib.workingtree._gen_id_suffix = "foo-"
259
        bzrlib.workingtree._gen_id_serial = 1
260
        self.assertEqual("foo-2", bzrlib.workingtree._next_id_suffix())
261
        self.assertEqual("foo-3", bzrlib.workingtree._next_id_suffix())
262
        self.assertEqual("foo-4", bzrlib.workingtree._next_id_suffix())
263
        self.assertEqual("foo-5", bzrlib.workingtree._next_id_suffix())
264
        self.assertEqual("foo-6", bzrlib.workingtree._next_id_suffix())
265
        self.assertEqual("foo-7", bzrlib.workingtree._next_id_suffix())
266
        self.assertEqual("foo-8", bzrlib.workingtree._next_id_suffix())
267
        self.assertEqual("foo-9", bzrlib.workingtree._next_id_suffix())
268
        self.assertEqual("foo-10", bzrlib.workingtree._next_id_suffix())
1714.1.2 by Robert Collins
Combine the ignore rules into a single regex rather than looping over them
269
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
270
    def test__translate_ignore_rule(self):
271
        tree = self.make_branch_and_tree('.')
272
        # translation should return the regex, the number of groups in it,
273
        # and the original rule in a tuple.
274
        # there are three sorts of ignore rules:
275
        # root only - regex is the rule itself without the leading ./
276
        self.assertEqual(
277
            "(rootdirrule$)", 
278
            tree._translate_ignore_rule("./rootdirrule"))
279
        # full path - regex is the rule itself
280
        self.assertEqual(
281
            "(path\\/to\\/file$)",
282
            tree._translate_ignore_rule("path/to/file"))
283
        # basename only rule - regex is a rule that ignores everything up
284
        # to the last / in the filename
285
        self.assertEqual(
286
            "((?:.*/)?(?!.*/)basenamerule$)",
287
            tree._translate_ignore_rule("basenamerule"))
288
289
    def test__combine_ignore_rules(self):
290
        tree = self.make_branch_and_tree('.')
291
        # the combined ignore regexs need the outer group indices
292
        # placed in a dictionary with the rules that were combined.
293
        # an empty set of rules
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
294
        # this is returned as a list of combined regex,rule sets, because
295
        # python has a limit of 100 combined regexes.
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
296
        compiled_rules = tree._combine_ignore_rules([])
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
297
        self.assertEqual([], compiled_rules)
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
298
        # one of each type of rule.
299
        compiled_rules = tree._combine_ignore_rules(
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
300
            ["rule1", "rule/two", "./three"])[0]
301
        # what type *is* the compiled regex to do an isinstance of ?
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
302
        self.assertEqual(3, compiled_rules[0].groups)
303
        self.assertEqual(
304
            {0:"rule1",1:"rule/two",2:"./three"},
305
            compiled_rules[1])
306
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
307
    def test__combine_ignore_rules_grouping(self):
308
        tree = self.make_branch_and_tree('.')
309
        # when there are too many rules, the output is split into groups of 100
310
        rules = []
311
        for index in range(198):
312
            rules.append('foo')
313
        self.assertEqual(2, len(tree._combine_ignore_rules(rules)))
314
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
315
    def test__get_ignore_rules_as_regex(self):
316
        tree = self.make_branch_and_tree('.')
1765.1.1 by Robert Collins
Remove the default ignores list from bzr, lowering the minimum overhead in bzr add.
317
        self.build_tree_contents([('.bzrignore', 'CVS\n.hg\n')])
318
        reference_output = tree._combine_ignore_rules(['CVS', '.hg'])[0]
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
319
        regex_rules = tree._get_ignore_rules_as_regex()[0]
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
320
        self.assertEqual(len(reference_output[1]), regex_rules[0].groups)
321
        self.assertEqual(reference_output[1], regex_rules[1])