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