/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
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
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
21
from bzrlib import dirstate, ignores
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
22
import bzrlib
1399.1.12 by Robert Collins
add new test script
23
from bzrlib.branch import Branch
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
24
from bzrlib import bzrdir, conflicts, errors, workingtree
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
25
from bzrlib.bzrdir import BzrDir
1508.1.3 by Robert Collins
Do not consider urls to be relative paths within working trees.
26
from bzrlib.errors import NotBranchError, NotVersionedError
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
27
from bzrlib.lockdir import LockDir
1986.1.8 by Robert Collins
Update to bzr.dev, which involves adding lock_tree_write to MutableTree and MemoryTree.
28
from bzrlib.mutabletree import needs_tree_write_lock
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
29
from bzrlib.osutils import pathjoin, getcwd, has_symlinks
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
30
from bzrlib.symbol_versioning import zero_thirteen
1997.1.1 by Robert Collins
Add WorkingTree.lock_tree_write.
31
from bzrlib.tests import TestCase, TestCaseWithTransport, TestSkipped
1399.1.12 by Robert Collins
add new test script
32
from bzrlib.trace import mutter
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
33
from bzrlib.transport import get_transport
1997.1.1 by Robert Collins
Add WorkingTree.lock_tree_write.
34
from bzrlib.workingtree import (
35
    TreeEntry,
36
    TreeDirectory,
37
    TreeFile,
38
    TreeLink,
39
    WorkingTree,
40
    )
1399.1.12 by Robert Collins
add new test script
41
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
42
class TestTreeDirectory(TestCaseWithTransport):
1399.1.12 by Robert Collins
add new test script
43
44
    def test_kind_character(self):
45
        self.assertEqual(TreeDirectory().kind_character(), '/')
46
47
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
48
class TestTreeEntry(TestCaseWithTransport):
1399.1.12 by Robert Collins
add new test script
49
50
    def test_kind_character(self):
51
        self.assertEqual(TreeEntry().kind_character(), '???')
52
53
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
54
class TestTreeFile(TestCaseWithTransport):
1399.1.12 by Robert Collins
add new test script
55
56
    def test_kind_character(self):
57
        self.assertEqual(TreeFile().kind_character(), '')
58
59
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
60
class TestTreeLink(TestCaseWithTransport):
1399.1.12 by Robert Collins
add new test script
61
62
    def test_kind_character(self):
63
        self.assertEqual(TreeLink().kind_character(), '')
64
65
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
66
class TestDefaultFormat(TestCaseWithTransport):
67
68
    def test_get_set_default_format(self):
69
        old_format = workingtree.WorkingTreeFormat.get_default_format()
70
        # default is 3
71
        self.assertTrue(isinstance(old_format, workingtree.WorkingTreeFormat3))
72
        workingtree.WorkingTreeFormat.set_default_format(SampleTreeFormat())
73
        try:
74
            # the default branch format is used by the meta dir format
75
            # which is not the default bzrdir format at this point
76
            dir = bzrdir.BzrDirMetaFormat1().initialize('.')
77
            dir.create_repository()
78
            dir.create_branch()
79
            result = dir.create_workingtree()
80
            self.assertEqual(result, 'A tree')
81
        finally:
82
            workingtree.WorkingTreeFormat.set_default_format(old_format)
83
        self.assertEqual(old_format, workingtree.WorkingTreeFormat.get_default_format())
84
85
86
class SampleTreeFormat(workingtree.WorkingTreeFormat):
87
    """A sample format
88
89
    this format is initializable, unsupported to aid in testing the 
90
    open and open_downlevel routines.
91
    """
92
93
    def get_format_string(self):
94
        """See WorkingTreeFormat.get_format_string()."""
95
        return "Sample tree format."
96
1508.1.24 by Robert Collins
Add update command for use with checkouts.
97
    def initialize(self, a_bzrdir, revision_id=None):
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
98
        """Sample branches cannot be created."""
99
        t = a_bzrdir.get_workingtree_transport(self)
1955.3.13 by John Arbash Meinel
Run the full test suite, and fix up any deprecation warnings.
100
        t.put_bytes('format', self.get_format_string())
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
101
        return 'A tree'
102
103
    def is_supported(self):
104
        return False
105
106
    def open(self, transport, _found=False):
107
        return "opened tree."
108
109
110
class TestWorkingTreeFormat(TestCaseWithTransport):
111
    """Tests for the WorkingTreeFormat facility."""
112
113
    def test_find_format(self):
114
        # is the right format object found for a working tree?
115
        # create a branch with a few known format objects.
116
        self.build_tree(["foo/", "bar/"])
117
        def check_format(format, url):
118
            dir = format._matchingbzrdir.initialize(url)
119
            dir.create_repository()
120
            dir.create_branch()
121
            format.initialize(dir)
122
            t = get_transport(url)
123
            found_format = workingtree.WorkingTreeFormat.find_format(dir)
124
            self.failUnless(isinstance(found_format, format.__class__))
125
        check_format(workingtree.WorkingTreeFormat3(), "bar")
126
        
127
    def test_find_format_no_tree(self):
128
        dir = bzrdir.BzrDirMetaFormat1().initialize('.')
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
129
        self.assertRaises(errors.NoWorkingTree,
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
130
                          workingtree.WorkingTreeFormat.find_format,
131
                          dir)
132
133
    def test_find_format_unknown_format(self):
134
        dir = bzrdir.BzrDirMetaFormat1().initialize('.')
135
        dir.create_repository()
136
        dir.create_branch()
137
        SampleTreeFormat().initialize(dir)
138
        self.assertRaises(errors.UnknownFormatError,
139
                          workingtree.WorkingTreeFormat.find_format,
140
                          dir)
141
142
    def test_register_unregister_format(self):
143
        format = SampleTreeFormat()
144
        # make a control dir
145
        dir = bzrdir.BzrDirMetaFormat1().initialize('.')
146
        dir.create_repository()
147
        dir.create_branch()
148
        # make a branch
149
        format.initialize(dir)
150
        # register a format for it.
151
        workingtree.WorkingTreeFormat.register_format(format)
152
        # which branch.Open will refuse (not supported)
153
        self.assertRaises(errors.UnsupportedFormatError, workingtree.WorkingTree.open, '.')
154
        # but open_downlevel will work
155
        self.assertEqual(format.open(dir), workingtree.WorkingTree.open_downlevel('.'))
156
        # unregister the format
157
        workingtree.WorkingTreeFormat.unregister_format(format)
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
158
159
160
class TestWorkingTreeFormat3(TestCaseWithTransport):
161
    """Tests specific to WorkingTreeFormat3."""
162
163
    def test_disk_layout(self):
164
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
165
        control.create_repository()
166
        control.create_branch()
167
        tree = workingtree.WorkingTreeFormat3().initialize(control)
168
        # we want:
169
        # format 'Bazaar-NG Working Tree format 3'
170
        # inventory = blank inventory
171
        # pending-merges = ''
172
        # stat-cache = ??
173
        # no inventory.basis yet
174
        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
175
        self.assertEqualDiff('Bazaar-NG Working Tree format 3',
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
176
                             t.get('format').read())
2100.3.12 by Aaron Bentley
Stop generating unique roots for WorkingTree3
177
        self.assertEqualDiff(t.get('inventory').read(), 
178
                              '<inventory format="5">\n'
1731.1.33 by Aaron Bentley
Revert no-special-root changes
179
                              '</inventory>\n',
180
                             )
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
181
        self.assertEqualDiff('### bzr hashcache v5\n',
182
                             t.get('stat-cache').read())
183
        self.assertFalse(t.has('inventory.basis'))
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
184
        # no last-revision file means 'None' or 'NULLREVISION'
185
        self.assertFalse(t.has('last-revision'))
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
186
        # 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.
187
        # correctly and last-revision file becomes present.
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
188
189
    def test_uses_lockdir(self):
190
        """WorkingTreeFormat3 uses its own LockDir:
191
            
192
            - lock is a directory
193
            - when the WorkingTree is locked, LockDir can see that
194
        """
195
        t = self.get_transport()
196
        url = self.get_url()
197
        dir = bzrdir.BzrDirMetaFormat1().initialize(url)
198
        repo = dir.create_repository()
199
        branch = dir.create_branch()
1558.10.1 by Aaron Bentley
Handle lockdirs over NFS properly
200
        try:
201
            tree = workingtree.WorkingTreeFormat3().initialize(dir)
202
        except errors.NotLocalUrl:
203
            raise TestSkipped('Not a local URL')
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
204
        self.assertIsDirectory('.bzr', t)
205
        self.assertIsDirectory('.bzr/checkout', t)
206
        self.assertIsDirectory('.bzr/checkout/lock', t)
207
        our_lock = LockDir(t, '.bzr/checkout/lock')
208
        self.assertEquals(our_lock.peek(), None)
1553.5.75 by Martin Pool
Additional WorkingTree LockDir test
209
        tree.lock_write()
210
        self.assertTrue(our_lock.peek())
211
        tree.unlock()
212
        self.assertEquals(our_lock.peek(), None)
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
213
1815.2.2 by Jelmer Vernooij
Move missing_pending_merges test to WorkingTreeFormat3-specific tests.
214
    def test_missing_pending_merges(self):
215
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
216
        control.create_repository()
217
        control.create_branch()
218
        tree = workingtree.WorkingTreeFormat3().initialize(control)
219
        tree._control_files._transport.delete("pending-merges")
1908.6.11 by Robert Collins
Remove usage of tree.pending_merges().
220
        self.assertEqual([], tree.get_parent_ids())
1815.2.2 by Jelmer Vernooij
Move missing_pending_merges test to WorkingTreeFormat3-specific tests.
221
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
222
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
223
class TestWorkingTreeFormat4(TestCaseWithTransport):
224
    """Tests specific to WorkingTreeFormat4."""
225
226
    def test_disk_layout(self):
2255.2.11 by Robert Collins
Fix the format 4 tree layout test.
227
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
228
        control.create_repository()
229
        control.create_branch()
230
        tree = workingtree.WorkingTreeFormat4().initialize(control)
231
        # we want:
2255.2.2 by Robert Collins
Partial updates for API changes in trunk.
232
        # format 'Bazaar Working Tree format 4'
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
233
        # stat-cache = ??
234
        t = control.get_workingtree_transport(None)
2255.2.11 by Robert Collins
Fix the format 4 tree layout test.
235
        self.assertEqualDiff('Bazaar Working Tree format 4\n',
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
236
                             t.get('format').read())
237
        self.assertEqualDiff('### bzr hashcache v5\n',
238
                             t.get('stat-cache').read())
239
        self.assertFalse(t.has('inventory.basis'))
240
        # no last-revision file means 'None' or 'NULLREVISION'
241
        self.assertFalse(t.has('last-revision'))
242
        # TODO RBC 20060210 do a commit, check the inventory.basis is created 
243
        # correctly and last-revision file becomes present.
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
244
        # manually make a dirstate toc check the format is as desired.
245
        state = dirstate.DirState.on_file(t.local_abspath('dirstate'))
246
        self.assertEqual([], state.get_parent_ids())
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
247
248
    def test_uses_lockdir(self):
249
        """WorkingTreeFormat4 uses its own LockDir:
250
            
251
            - lock is a directory
252
            - when the WorkingTree is locked, LockDir can see that
253
        """
254
        # this test could be factored into a subclass of tests common to both
255
        # format 3 and 4, but for now its not much of an issue as there is only one in common.
256
        t = self.get_transport()
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
257
        tree = self.make_workingtree()
258
        self.assertIsDirectory('.bzr', t)
259
        self.assertIsDirectory('.bzr/checkout', t)
260
        self.assertIsDirectory('.bzr/checkout/lock', t)
261
        our_lock = LockDir(t, '.bzr/checkout/lock')
262
        self.assertEquals(our_lock.peek(), None)
263
        tree.lock_write()
264
        self.assertTrue(our_lock.peek())
265
        tree.unlock()
266
        self.assertEquals(our_lock.peek(), None)
267
268
    def make_workingtree(self):
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
269
        url = self.get_url()
270
        dir = bzrdir.BzrDirMetaFormat1().initialize(url)
271
        repo = dir.create_repository()
272
        branch = dir.create_branch()
273
        try:
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
274
            return workingtree.WorkingTreeFormat4().initialize(dir)
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
275
        except errors.NotLocalUrl:
276
            raise TestSkipped('Not a local URL')
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
277
278
    # TODO: test that dirstate also stores & retrieves the parent list of 
279
    # workingtree-parent revisions, including when they have multiple parents.
280
    # (in other words, the case when we're constructing a merge of 
281
    # revisions which are themselves merges.)
282
283
    # The simplest case is that the the workingtree's primary 
284
    # parent tree can be retrieved.  This is required for all WorkingTrees, 
285
    # and covered by the generic tests.
286
287
    def test_dirstate_stores_all_parent_inventories(self):
288
        tree = self.make_workingtree()
289
290
        # We're going to build in tree a working tree 
291
        # with three parent trees, with some files in common.  
292
    
293
        # We really don't want to do commit or merge in the new dirstate-based
294
        # tree, because that might not work yet.  So instead we build
295
        # revisions elsewhere and pull them across, doing by hand part of the
296
        # work that merge would do.
297
298
        subtree = self.make_branch_and_tree('subdir')
2255.2.78 by Robert Collins
Really finish the prior commit.
299
        # writelock the tree so its repository doesn't get readlocked by
300
        # the revision tree locks. This works around the bug where we dont
301
        # permit lock upgrading.
302
        subtree.lock_write()
303
        self.addCleanup(subtree.unlock)
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
304
        self.build_tree(['subdir/file-a',])
305
        subtree.add(['file-a'], ['id-a'])
306
        rev1 = subtree.commit('commit in subdir')
307
        rev1_tree = subtree.basis_tree()
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
308
        rev1_tree.lock_read()
309
        self.addCleanup(rev1_tree.unlock)
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
310
311
        subtree2 = subtree.bzrdir.sprout('subdir2').open_workingtree()
312
        self.build_tree(['subdir2/file-b'])
313
        subtree2.add(['file-b'], ['id-b'])
314
        rev2 = subtree2.commit('commit in subdir2')
315
        rev2_tree = subtree2.basis_tree()
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
316
        rev2_tree.lock_read()
317
        self.addCleanup(rev2_tree.unlock)
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
318
319
        subtree.merge_from_branch(subtree2.branch)
320
        rev3 = subtree.commit('merge from subdir2')
321
        rev3_tree = subtree.basis_tree()
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
322
        rev3_tree.lock_read()
323
        self.addCleanup(rev3_tree.unlock)
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
324
325
        repo = tree.branch.repository
326
        repo.fetch(subtree.branch.repository, rev3)
327
        # will also pull the others...
328
329
        # tree doesn't contain a text merge yet but we'll just
330
        # set the parents as if a merge had taken place. 
331
        # this should cause the tree data to be folded into the 
332
        # dirstate.
333
        tree.set_parent_trees([
334
            (rev1, rev1_tree),
335
            (rev2, rev2_tree),
336
            (rev3, rev3_tree), ])
337
338
        # now we should be able to get them back out
339
        self.assertTreesEqual(tree.revision_tree(rev1), rev1_tree)
340
        self.assertTreesEqual(tree.revision_tree(rev2), rev2_tree)
341
        self.assertTreesEqual(tree.revision_tree(rev3), rev3_tree)
342
343
    def test_dirstate_doesnt_read_parents_from_repo_when_setting(self):
344
        """Setting parent trees on a dirstate working tree takes
345
        the trees it's given and doesn't need to read them from the 
346
        repository.
347
        """
348
        tree = self.make_workingtree()
349
350
        subtree = self.make_branch_and_tree('subdir')
351
        rev1 = subtree.commit('commit in subdir')
352
        rev1_tree = subtree.basis_tree()
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
353
        rev1_tree.lock_read()
354
        self.addCleanup(rev1_tree.unlock)
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
355
356
        tree.branch.pull(subtree.branch)
357
358
        # break the repository's legs to make sure it only uses the trees
359
        # it's given; any calls to forbidden methods will raise an 
360
        # AssertionError
361
        repo = tree.branch.repository
362
        repo.get_revision = self.fail
363
        repo.get_inventory = self.fail
364
        repo.get_inventory_xml = self.fail
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
365
        # try to set the parent trees.
1852.13.18 by Robert Collins
Write top level acceptance test for dirstate.
366
        tree.set_parent_trees([(rev1, rev1_tree)])
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
367
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
368
    def test_dirstate_doesnt_read_from_repo_when_returning_cache_tree(self):
369
        """Getting parent trees from a dirstate tree does not read from the 
370
        repos inventory store. This is an important part of the dirstate
371
        performance optimisation work.
372
        """
373
        tree = self.make_workingtree()
374
375
        subtree = self.make_branch_and_tree('subdir')
2255.2.78 by Robert Collins
Really finish the prior commit.
376
        # writelock the tree so its repository doesn't get readlocked by
377
        # the revision tree locks. This works around the bug where we dont
378
        # permit lock upgrading.
379
        subtree.lock_write()
380
        self.addCleanup(subtree.unlock)
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
381
        rev1 = subtree.commit('commit in subdir')
382
        rev1_tree = subtree.basis_tree()
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
383
        rev1_tree.lock_read()
384
        self.addCleanup(rev1_tree.unlock)
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
385
        rev2 = subtree.commit('second commit in subdir', allow_pointless=True)
386
        rev2_tree = subtree.basis_tree()
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
387
        rev2_tree.lock_read()
388
        self.addCleanup(rev2_tree.unlock)
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
389
390
        tree.branch.pull(subtree.branch)
391
392
        # break the repository's legs to make sure it only uses the trees
393
        # it's given; any calls to forbidden methods will raise an 
394
        # AssertionError
395
        repo = tree.branch.repository
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
396
        # dont uncomment this: the revision object must be accessed to 
397
        # answer 'get_parent_ids' for the revision tree- dirstate does not 
398
        # cache the parents of a parent tree at this point.
399
        #repo.get_revision = self.fail
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
400
        repo.get_inventory = self.fail
401
        repo.get_inventory_xml = self.fail
402
        # set the parent trees.
403
        tree.set_parent_trees([(rev1, rev1_tree), (rev2, rev2_tree)])
404
        # read the first tree
405
        result_rev1_tree = tree.revision_tree(rev1)
406
        # read the second
407
        result_rev2_tree = tree.revision_tree(rev2)
408
        # compare - there should be no differences between the handed and 
409
        # returned trees
410
        self.assertTreesEqual(rev1_tree, result_rev1_tree)
411
        self.assertTreesEqual(rev2_tree, result_rev2_tree)
412
413
    def test_dirstate_doesnt_cache_non_parent_trees(self):
414
        """Getting parent trees from a dirstate tree does not read from the 
415
        repos inventory store. This is an important part of the dirstate
416
        performance optimisation work.
417
        """
418
        tree = self.make_workingtree()
419
420
        # make a tree that we can try for, which is able to be returned but
421
        # must not be
422
        subtree = self.make_branch_and_tree('subdir')
423
        rev1 = subtree.commit('commit in subdir')
424
        tree.branch.pull(subtree.branch)
425
        # check it fails
426
        self.assertRaises(errors.NoSuchRevision, tree.revision_tree, rev1)
427
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
428
    def test_no_dirstate_outside_lock(self):
429
        # temporary test until the code is mature enough to test from outside.
430
        """Getting a dirstate object fails if there is no lock."""
431
        def lock_and_call_current_dirstate(tree, lock_method):
432
            getattr(tree, lock_method)()
433
            tree.current_dirstate()
434
            tree.unlock()
435
        tree = self.make_workingtree()
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
436
        self.assertRaises(errors.ObjectNotLocked, tree.current_dirstate)
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
437
        lock_and_call_current_dirstate(tree, 'lock_read')
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
438
        self.assertRaises(errors.ObjectNotLocked, tree.current_dirstate)
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
439
        lock_and_call_current_dirstate(tree, 'lock_write')
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
440
        self.assertRaises(errors.ObjectNotLocked, tree.current_dirstate)
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
441
        lock_and_call_current_dirstate(tree, 'lock_tree_write')
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
442
        self.assertRaises(errors.ObjectNotLocked, tree.current_dirstate)
1852.13.24 by Robert Collins
Get back to the broken-pending-revision-tree-from-dirstate state of development, changing dirstate from_tree to use _set_data rather than generating lines itself.
443
444
    def test_new_dirstate_on_new_lock(self):
445
        # until we have detection for when a dirstate can be reused, we
446
        # want to reparse dirstate on every new lock.
447
        known_dirstates = set()
448
        def lock_and_compare_all_current_dirstate(tree, lock_method):
449
            getattr(tree, lock_method)()
450
            state = tree.current_dirstate()
451
            self.assertFalse(state in known_dirstates)
452
            known_dirstates.add(state)
453
            tree.unlock()
454
        tree = self.make_workingtree()
455
        # lock twice with each type to prevent silly per-lock-type bugs.
456
        # each lock and compare looks for a unique state object.
457
        lock_and_compare_all_current_dirstate(tree, 'lock_read')
458
        lock_and_compare_all_current_dirstate(tree, 'lock_read')
459
        lock_and_compare_all_current_dirstate(tree, 'lock_tree_write')
460
        lock_and_compare_all_current_dirstate(tree, 'lock_tree_write')
461
        lock_and_compare_all_current_dirstate(tree, 'lock_write')
462
        lock_and_compare_all_current_dirstate(tree, 'lock_write')
463
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
464
2100.3.37 by Aaron Bentley
rename working tree format 4 to AB1 everywhere
465
class TestWorkingTreeFormatAB1(TestCaseWithTransport):
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
466
    """Tests specific to WorkingTreeFormat3."""
467
468
    def test_disk_layout(self):
2100.3.17 by Aaron Bentley
Remove get_format_*, make FormatRegistry.register_metadir vary working tree
469
        tree = self.make_branch_and_tree('.', format='experimental-knit3')
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
470
        control = tree.bzrdir
471
        # we want:
2100.3.37 by Aaron Bentley
rename working tree format 4 to AB1 everywhere
472
        # format 'Bazaar-NG Working Tree format AB1'
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
473
        # inventory = 1 entry for root
474
        # pending-merges = ''
475
        # no inventory.basis yet
476
        t = control.get_workingtree_transport(None)
2100.3.37 by Aaron Bentley
rename working tree format 4 to AB1 everywhere
477
        self.assertEqualDiff('Bazaar-NG Working Tree format AB1',
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
478
                             t.get('format').read())
479
        self.assertContainsRe(t.get('inventory').read(), 
480
                              '<inventory format="7">\n'
481
                              '<directory file_id="[^"]*" name="" />\n'
482
                              '</inventory>\n',
483
                             )
484
        self.assertEqualDiff('### bzr hashcache v5\n',
485
                             t.get('stat-cache').read())
486
        self.assertFalse(t.has('basis-inventory-cache'))
487
        # no last-revision file means 'None' or 'NULLREVISION'
488
        self.assertFalse(t.has('last-revision'))
489
        tree.set_root_id('my-root-id')
490
        tree.commit('test', rev_id='revision-1')
491
        self.assertTrue(t.has('basis-inventory-cache'))
492
        self.assertTrue(t.has('last-revision'))
493
        self.assertEqualDiff(t.get('basis-inventory-cache').read(), 
494
            '<inventory format="7" revision_id="revision-1">\n'
495
            '<directory file_id="my-root-id" name="" revision="revision-1" />\n'
496
            '</inventory>\n')
497
    
498
    def test_incompatible_repo(self):
2100.3.17 by Aaron Bentley
Remove get_format_*, make FormatRegistry.register_metadir vary working tree
499
        control = bzrdir.format_registry.make_bzrdir('knit')
2100.3.37 by Aaron Bentley
rename working tree format 4 to AB1 everywhere
500
        control.workingtree_format = workingtree.WorkingTreeFormatAB1()
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
501
        tree = self.make_branch_and_tree('.', format=control)
502
        self.assertRaises(errors.RootNotRich, tree.commit)
503
504
    def test_compatible_repo(self):
2100.3.17 by Aaron Bentley
Remove get_format_*, make FormatRegistry.register_metadir vary working tree
505
        tree = self.make_branch_and_tree('.', format='experimental-knit3')
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
506
        tree.set_root_id('my-root-id')
507
        tree.commit('test', rev_id='revision-1')
508
        tree.commit('test', rev_id='revision-2')
509
        revision_tree = tree.branch.repository.revision_tree('revision-2')
510
        self.assertEqual('revision-1', 
511
                         revision_tree.inventory['my-root-id'].revision)
512
513
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
514
class TestFormat2WorkingTree(TestCaseWithTransport):
515
    """Tests that are specific to format 2 trees."""
516
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
517
    def create_format2_tree(self, url):
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
518
        return self.make_branch_and_tree(
519
            url, format=bzrlib.bzrdir.BzrDirFormat6())
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
520
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
521
    def test_conflicts(self):
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
522
        # test backwards compatability
523
        tree = self.create_format2_tree('.')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
524
        self.assertRaises(errors.UnsupportedOperation, tree.set_conflicts,
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
525
                          None)
526
        file('lala.BASE', 'wb').write('labase')
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
527
        expected = conflicts.ContentsConflict('lala')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
528
        self.assertEqual(list(tree.conflicts()), [expected])
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
529
        file('lala', 'wb').write('la')
530
        tree.add('lala', 'lala-id')
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
531
        expected = conflicts.ContentsConflict('lala', file_id='lala-id')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
532
        self.assertEqual(list(tree.conflicts()), [expected])
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
533
        file('lala.THIS', 'wb').write('lathis')
534
        file('lala.OTHER', 'wb').write('laother')
535
        # When "text conflict"s happen, stem, THIS and OTHER are text
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
536
        expected = conflicts.TextConflict('lala', file_id='lala-id')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
537
        self.assertEqual(list(tree.conflicts()), [expected])
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
538
        os.unlink('lala.OTHER')
539
        os.mkdir('lala.OTHER')
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
540
        expected = conflicts.ContentsConflict('lala', file_id='lala-id')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
541
        self.assertEqual(list(tree.conflicts()), [expected])
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
542
543
544
class TestNonFormatSpecificCode(TestCaseWithTransport):
545
    """This class contains tests of workingtree that are not format specific."""
546
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
547
    def test_gen_file_id(self):
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
548
        file_id = self.applyDeprecated(zero_thirteen, workingtree.gen_file_id,
549
                                      'filename')
550
        self.assertStartsWith(file_id, 'filename-')
551
552
    def test_gen_root_id(self):
553
        file_id = self.applyDeprecated(zero_thirteen, workingtree.gen_root_id)
554
        self.assertStartsWith(file_id, 'tree_root-')
1864.4.1 by John Arbash Meinel
Fix bug #43801 by squashing file ids a little bit more.
555
        
1997.1.1 by Robert Collins
Add WorkingTree.lock_tree_write.
556
557
class InstrumentedTree(object):
558
    """A instrumented tree to check the needs_tree_write_lock decorator."""
559
560
    def __init__(self):
561
        self._locks = []
562
563
    def lock_tree_write(self):
564
        self._locks.append('t')
565
566
    @needs_tree_write_lock
567
    def method_with_tree_write_lock(self, *args, **kwargs):
568
        """A lock_tree_write decorated method that returns its arguments."""
569
        return args, kwargs
570
571
    @needs_tree_write_lock
572
    def method_that_raises(self):
573
        """This method causes an exception when called with parameters.
574
        
575
        This allows the decorator code to be checked - it should still call
576
        unlock.
577
        """
578
579
    def unlock(self):
580
        self._locks.append('u')
581
582
583
class TestInstrumentedTree(TestCase):
584
585
    def test_needs_tree_write_lock(self):
586
        """@needs_tree_write_lock should be semantically transparent."""
587
        tree = InstrumentedTree()
588
        self.assertEqual(
589
            'method_with_tree_write_lock',
590
            tree.method_with_tree_write_lock.__name__)
591
        self.assertEqual(
592
            "A lock_tree_write decorated method that returns its arguments.",
593
            tree.method_with_tree_write_lock.__doc__)
594
        args = (1, 2, 3)
595
        kwargs = {'a':'b'}
596
        result = tree.method_with_tree_write_lock(1,2,3, a='b')
597
        self.assertEqual((args, kwargs), result)
598
        self.assertEqual(['t', 'u'], tree._locks)
599
        self.assertRaises(TypeError, tree.method_that_raises, 'foo')
600
        self.assertEqual(['t', 'u', 't', 'u'], tree._locks)