/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.15 by John Arbash Meinel
Merge bzr.dev 5597 to resolve NEWS, aka bzr-2.3.txt
1
# Copyright (C) 2006-2011 Canonical Ltd
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2
# Authors:  Robert Collins <robert.collins@canonical.com>
2255.13.4 by Martin Pool
merge
3
#           and others
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
4
#
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
17
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
18
19
from cStringIO import StringIO
3136.1.10 by Aaron Bentley
Clean error if filesystem does not support hard-links
20
import errno
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
21
import os
22
3287.20.3 by John Arbash Meinel
Aaron recommended to make this a WT_impl test.
23
from bzrlib import (
24
    branch,
25
    bzrdir,
6059.4.4 by Vincent Ladeuil
Migrate bzr.workingtree.worth_saving_limit to stack-based config.
26
    config,
3287.20.3 by John Arbash Meinel
Aaron recommended to make this a WT_impl test.
27
    errors,
28
    osutils,
6241.3.1 by Jelmer Vernooij
Support WorkingTree.clone() having its revision argument set to the NULL revision.
29
    revision as _mod_revision,
5718.8.9 by Jelmer Vernooij
Avoid using _set_revision_history as it's not present on older branch formats.
30
    symbol_versioning,
3287.20.3 by John Arbash Meinel
Aaron recommended to make this a WT_impl test.
31
    tests,
6059.4.4 by Vincent Ladeuil
Migrate bzr.workingtree.worth_saving_limit to stack-based config.
32
    trace,
3287.20.3 by John Arbash Meinel
Aaron recommended to make this a WT_impl test.
33
    urlutils,
5582.4.3 by Jelmer Vernooij
remove more unused imports, avoid relying on a specific set of working tree formats that support references.
34
    )
35
from bzrlib.errors import (
36
    UnsupportedOperation,
37
    PathsNotVersionedError,
38
    )
1852.15.14 by Robert Collins
test that WorkingTree._write_inventory works as expected by the current code.
39
from bzrlib.inventory import Inventory
6435.1.1 by Jelmer Vernooij
Add post_build_tree hook.
40
from bzrlib.mutabletree import MutableTree
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
41
from bzrlib.osutils import pathjoin, getcwd, has_symlinks
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
42
from bzrlib.tests import (
43
    features,
44
    TestSkipped,
45
    TestNotApplicable,
46
    )
4523.1.4 by Martin Pool
Rename remaining *_implementations tests
47
from bzrlib.tests.per_workingtree import TestCaseWithWorkingTree
5582.4.3 by Jelmer Vernooij
remove more unused imports, avoid relying on a specific set of working tree formats that support references.
48
from bzrlib.workingtree import (
49
    TreeDirectory,
50
    TreeFile,
51
    TreeLink,
5807.1.2 by Jelmer Vernooij
Skip some inventory-specific tests for non-inventory working trees.
52
    InventoryWorkingTree,
5582.4.3 by Jelmer Vernooij
remove more unused imports, avoid relying on a specific set of working tree formats that support references.
53
    WorkingTree,
54
    )
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
55
from bzrlib.conflicts import ConflictList, TextConflict, ContentsConflict
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
56
1711.7.19 by John Arbash Meinel
file:// urls look slightly different on win32
57
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
58
class TestWorkingTree(TestCaseWithWorkingTree):
59
6437.70.6 by John Arbash Meinel
Fix a couple tests that wanted to directly create a wt where the branch was.
60
    def requireBranchReference(self):
61
        test_branch = self.make_branch('test-branch')
62
        try:
63
            # if there is a working tree now, this is not supported.
64
            test_branch.bzrdir.open_workingtree()
65
            raise TestNotApplicable("only on trees that can be separate"
66
                " from their branch.")
67
        except (errors.NoWorkingTree, errors.NotLocalUrl):
68
            pass
69
5516.1.1 by Vincent Ladeuil
TestCaseWithWorkingTree.make_branch_builder respects its relpath parameter.
70
    def test_branch_builder(self):
71
        # Just a smoke test that we get a branch at the specified relpath
72
        builder = self.make_branch_builder('foobar')
6437.70.9 by John Arbash Meinel
branch_builder builds in the branch/repository location, not in the wt location.
73
        br = branch.Branch.open(self.get_url('foobar'))
5516.1.1 by Vincent Ladeuil
TestCaseWithWorkingTree.make_branch_builder respects its relpath parameter.
74
1732.1.8 by John Arbash Meinel
Adding a test for list_files
75
    def test_list_files(self):
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
76
        tree = self.make_branch_and_tree('.')
1732.1.8 by John Arbash Meinel
Adding a test for list_files
77
        self.build_tree(['dir/', 'file'])
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
78
        if has_symlinks():
79
            os.symlink('target', 'symlink')
2255.2.52 by Robert Collins
Dirstate - fix workingtree.list_files to use the public interface to access the trees inventory.
80
        tree.lock_read()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
81
        files = list(tree.list_files())
2255.2.52 by Robert Collins
Dirstate - fix workingtree.list_files to use the public interface to access the trees inventory.
82
        tree.unlock()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
83
        self.assertEqual(files[0], ('dir', '?', 'directory', None, TreeDirectory()))
84
        self.assertEqual(files[1], ('file', '?', 'file', None, TreeFile()))
85
        if has_symlinks():
86
            self.assertEqual(files[2], ('symlink', '?', 'symlink', None, TreeLink()))
87
1732.1.8 by John Arbash Meinel
Adding a test for list_files
88
    def test_list_files_sorted(self):
89
        tree = self.make_branch_and_tree('.')
1836.1.18 by John Arbash Meinel
Cleaned up the last failing tests. All tests pass again.
90
        self.build_tree(['dir/', 'file', 'dir/file', 'dir/b',
91
                         'dir/subdir/', 'a', 'dir/subfile',
92
                         'zz_dir/', 'zz_dir/subfile'])
2255.2.52 by Robert Collins
Dirstate - fix workingtree.list_files to use the public interface to access the trees inventory.
93
        tree.lock_read()
1836.1.18 by John Arbash Meinel
Cleaned up the last failing tests. All tests pass again.
94
        files = [(path, kind) for (path, v, kind, file_id, entry)
95
                               in tree.list_files()]
2255.2.52 by Robert Collins
Dirstate - fix workingtree.list_files to use the public interface to access the trees inventory.
96
        tree.unlock()
1732.1.8 by John Arbash Meinel
Adding a test for list_files
97
        self.assertEqual([
98
            ('a', 'file'),
99
            ('dir', 'directory'),
100
            ('file', 'file'),
1732.1.25 by John Arbash Meinel
Fix list_files test, we don't need to check if children are empty if we fall off the loop.
101
            ('zz_dir', 'directory'),
1732.1.8 by John Arbash Meinel
Adding a test for list_files
102
            ], files)
103
1732.1.25 by John Arbash Meinel
Fix list_files test, we don't need to check if children are empty if we fall off the loop.
104
        tree.add(['dir', 'zz_dir'])
2255.2.52 by Robert Collins
Dirstate - fix workingtree.list_files to use the public interface to access the trees inventory.
105
        tree.lock_read()
1836.1.18 by John Arbash Meinel
Cleaned up the last failing tests. All tests pass again.
106
        files = [(path, kind) for (path, v, kind, file_id, entry)
107
                               in tree.list_files()]
2255.2.52 by Robert Collins
Dirstate - fix workingtree.list_files to use the public interface to access the trees inventory.
108
        tree.unlock()
1732.1.8 by John Arbash Meinel
Adding a test for list_files
109
        self.assertEqual([
110
            ('a', 'file'),
111
            ('dir', 'directory'),
112
            ('dir/b', 'file'),
113
            ('dir/file', 'file'),
114
            ('dir/subdir', 'directory'),
115
            ('dir/subfile', 'file'),
116
            ('file', 'file'),
1732.1.22 by John Arbash Meinel
Bug in list_files if the last entry in a directory is another directory
117
            ('zz_dir', 'directory'),
118
            ('zz_dir/subfile', 'file'),
1732.1.8 by John Arbash Meinel
Adding a test for list_files
119
            ], files)
120
1551.10.29 by Aaron Bentley
Fix tree.list_files when file kind changes
121
    def test_list_files_kind_change(self):
122
        tree = self.make_branch_and_tree('tree')
123
        self.build_tree(['tree/filename'])
124
        tree.add('filename', 'file-id')
125
        os.unlink('tree/filename')
126
        self.build_tree(['tree/filename/'])
127
        tree.lock_read()
128
        self.addCleanup(tree.unlock)
129
        result = list(tree.list_files())
130
        self.assertEqual(1, len(result))
131
        self.assertEqual(('filename', 'V', 'directory', 'file-id'),
132
                         result[0][:4])
133
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
134
    def test_open_containing(self):
6437.70.7 by John Arbash Meinel
one more test that wanted to have a branch reference
135
        local_wt = self.make_branch_and_tree('.')
136
        local_url = local_wt.bzrdir.root_transport.base
137
        local_base = urlutils.local_path_from_url(local_url)
138
        del local_wt
1711.7.28 by John Arbash Meinel
clean up the WorkingTree.open_containing tests
139
140
        # Empty opens '.'
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
141
        wt, relpath = WorkingTree.open_containing()
142
        self.assertEqual('', relpath)
1711.7.28 by John Arbash Meinel
clean up the WorkingTree.open_containing tests
143
        self.assertEqual(wt.basedir + '/', local_base)
144
145
        # '.' opens this dir
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
146
        wt, relpath = WorkingTree.open_containing(u'.')
147
        self.assertEqual('', relpath)
1711.7.28 by John Arbash Meinel
clean up the WorkingTree.open_containing tests
148
        self.assertEqual(wt.basedir + '/', local_base)
149
150
        # './foo' finds '.' and a relpath of 'foo'
151
        wt, relpath = WorkingTree.open_containing('./foo')
152
        self.assertEqual('foo', relpath)
153
        self.assertEqual(wt.basedir + '/', local_base)
154
155
        # abspath(foo) finds '.' and relpath of 'foo'
156
        wt, relpath = WorkingTree.open_containing('./foo')
157
        wt, relpath = WorkingTree.open_containing(getcwd() + '/foo')
158
        self.assertEqual('foo', relpath)
159
        self.assertEqual(wt.basedir + '/', local_base)
160
161
        # can even be a url: finds '.' and relpath of 'foo'
162
        wt, relpath = WorkingTree.open_containing('./foo')
163
        wt, relpath = WorkingTree.open_containing(
164
                    urlutils.local_path_to_url(getcwd() + '/foo'))
165
        self.assertEqual('foo', relpath)
166
        self.assertEqual(wt.basedir + '/', local_base)
167
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
168
    def test_basic_relpath(self):
169
        # for comprehensive relpath tests, see whitebox.py.
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
170
        tree = self.make_branch_and_tree('.')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
171
        self.assertEqual('child',
172
                         tree.relpath(pathjoin(getcwd(), 'child')))
173
174
    def test_lock_locks_branch(self):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
175
        tree = self.make_branch_and_tree('.')
6437.70.8 by John Arbash Meinel
trivially implement peek_lock_mode.
176
        self.assertEqual(None, tree.branch.peek_lock_mode())
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
177
        tree.lock_read()
178
        self.assertEqual('r', tree.branch.peek_lock_mode())
179
        tree.unlock()
180
        self.assertEqual(None, tree.branch.peek_lock_mode())
181
        tree.lock_write()
182
        self.assertEqual('w', tree.branch.peek_lock_mode())
183
        tree.unlock()
184
        self.assertEqual(None, tree.branch.peek_lock_mode())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
185
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
186
    def test_revert(self):
187
        """Test selected-file revert"""
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
188
        tree = self.make_branch_and_tree('.')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
189
190
        self.build_tree(['hello.txt'])
6437.20.3 by Wouter van Heyst
mechanically replace file().write() pattern with a with-keyword version
191
        with file('hello.txt', 'w') as f: f.write('initial hello')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
192
1551.7.17 by Aaron Bentley
Switch to PathsNotVersioned, accept extra_trees
193
        self.assertRaises(PathsNotVersionedError,
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
194
                          tree.revert, ['hello.txt'])
195
        tree.add(['hello.txt'])
196
        tree.commit('create initial hello.txt')
197
198
        self.check_file_contents('hello.txt', 'initial hello')
6437.20.3 by Wouter van Heyst
mechanically replace file().write() pattern with a with-keyword version
199
        with file('hello.txt', 'w') as f: f.write('new hello')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
200
        self.check_file_contents('hello.txt', 'new hello')
201
202
        # revert file modified since last revision
203
        tree.revert(['hello.txt'])
204
        self.check_file_contents('hello.txt', 'initial hello')
1534.10.29 by Aaron Bentley
Fixed backup numbering to match GNU standard better
205
        self.check_file_contents('hello.txt.~1~', 'new hello')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
206
207
        # reverting again does not clobber the backup
208
        tree.revert(['hello.txt'])
209
        self.check_file_contents('hello.txt', 'initial hello')
1534.10.29 by Aaron Bentley
Fixed backup numbering to match GNU standard better
210
        self.check_file_contents('hello.txt.~1~', 'new hello')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
211
1534.10.28 by Aaron Bentley
Use numbered backup files
212
        # backup files are numbered
6437.20.3 by Wouter van Heyst
mechanically replace file().write() pattern with a with-keyword version
213
        with file('hello.txt', 'w') as f: f.write('new hello2')
1534.10.28 by Aaron Bentley
Use numbered backup files
214
        tree.revert(['hello.txt'])
215
        self.check_file_contents('hello.txt', 'initial hello')
1534.10.29 by Aaron Bentley
Fixed backup numbering to match GNU standard better
216
        self.check_file_contents('hello.txt.~1~', 'new hello')
217
        self.check_file_contents('hello.txt.~2~', 'new hello2')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
218
1558.12.7 by Aaron Bentley
Fixed revert with missing files
219
    def test_revert_missing(self):
220
        # Revert a file that has been deleted since last commit
221
        tree = self.make_branch_and_tree('.')
6437.20.3 by Wouter van Heyst
mechanically replace file().write() pattern with a with-keyword version
222
        with file('hello.txt', 'w') as f: f.write('initial hello')
1558.12.7 by Aaron Bentley
Fixed revert with missing files
223
        tree.add('hello.txt')
224
        tree.commit('added hello.txt')
225
        os.unlink('hello.txt')
226
        tree.remove('hello.txt')
227
        tree.revert(['hello.txt'])
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
228
        self.assertPathExists('hello.txt')
1558.12.7 by Aaron Bentley
Fixed revert with missing files
229
1740.6.1 by Martin Pool
Remove Scratch objects used by doctests
230
    def test_versioned_files_not_unknown(self):
231
        tree = self.make_branch_and_tree('.')
1831.1.1 by Martin Pool
[merge] remove default ignore list & update
232
        self.build_tree(['hello.txt'])
1740.6.1 by Martin Pool
Remove Scratch objects used by doctests
233
        tree.add('hello.txt')
234
        self.assertEquals(list(tree.unknowns()),
235
                          [])
1831.1.1 by Martin Pool
[merge] remove default ignore list & update
236
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
237
    def test_unknowns(self):
238
        tree = self.make_branch_and_tree('.')
239
        self.build_tree(['hello.txt',
1534.10.29 by Aaron Bentley
Fixed backup numbering to match GNU standard better
240
                         'hello.txt.~1~'])
1765.1.1 by Robert Collins
Remove the default ignores list from bzr, lowering the minimum overhead in bzr add.
241
        self.build_tree_contents([('.bzrignore', '*.~*\n')])
242
        tree.add('.bzrignore')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
243
        self.assertEquals(list(tree.unknowns()),
244
                          ['hello.txt'])
245
246
    def test_initialize(self):
247
        # initialize should create a working tree and branch in an existing dir
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
248
        t = self.make_branch_and_tree('.')
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
249
        b = branch.Branch.open('.')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
250
        self.assertEqual(t.branch.base, b.base)
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
251
        t2 = WorkingTree.open('.')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
252
        self.assertEqual(t.basedir, t2.basedir)
253
        self.assertEqual(b.base, t2.branch.base)
254
        # TODO maybe we should check the branch format? not sure if its
255
        # appropriate here.
256
257
    def test_rename_dirs(self):
258
        """Test renaming directories and the files within them."""
259
        wt = self.make_branch_and_tree('.')
260
        b = wt.branch
261
        self.build_tree(['dir/', 'dir/sub/', 'dir/sub/file'])
262
        wt.add(['dir', 'dir/sub', 'dir/sub/file'])
263
264
        wt.commit('create initial state')
265
6165.4.4 by Jelmer Vernooij
Avoid .revision_history().
266
        revid = b.last_revision()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
267
        self.log('first revision_id is {%s}' % revid)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
268
5807.1.5 by Jelmer Vernooij
Fix more things to use tree objects.
269
        tree = b.repository.revision_tree(revid)
270
        self.log('contents of tree: %r' % list(tree.iter_entries_by_dir()))
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
271
5807.1.5 by Jelmer Vernooij
Fix more things to use tree objects.
272
        self.check_tree_shape(tree, ['dir/', 'dir/sub/', 'dir/sub/file'])
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
273
        wt.rename_one('dir', 'newdir')
274
2255.2.57 by Robert Collins
Dirstate test change: TestWorkingTree.test_rename_dirs should lock around accessing the trees inventory.
275
        wt.lock_read()
5807.1.5 by Jelmer Vernooij
Fix more things to use tree objects.
276
        self.check_tree_shape(wt,
2545.3.2 by James Westby
Add a test for check_inventory_shape.
277
                                   ['newdir/', 'newdir/sub/', 'newdir/sub/file'])
2255.2.57 by Robert Collins
Dirstate test change: TestWorkingTree.test_rename_dirs should lock around accessing the trees inventory.
278
        wt.unlock()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
279
        wt.rename_one('newdir/sub', 'newdir/newsub')
2255.2.57 by Robert Collins
Dirstate test change: TestWorkingTree.test_rename_dirs should lock around accessing the trees inventory.
280
        wt.lock_read()
5807.1.5 by Jelmer Vernooij
Fix more things to use tree objects.
281
        self.check_tree_shape(wt, ['newdir/', 'newdir/newsub/',
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
282
                                    'newdir/newsub/file'])
2255.2.57 by Robert Collins
Dirstate test change: TestWorkingTree.test_rename_dirs should lock around accessing the trees inventory.
283
        wt.unlock()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
284
285
    def test_add_in_unversioned(self):
286
        """Try to add a file in an unversioned directory.
287
288
        "bzr add" adds the parent as necessary, but simple working tree add
289
        doesn't do that.
290
        """
291
        from bzrlib.errors import NotVersionedError
292
        wt = self.make_branch_and_tree('.')
293
        self.build_tree(['foo/',
294
                         'foo/hello'])
6072.1.2 by Jelmer Vernooij
Fix versioned directories tests.
295
        if not wt._format.supports_versioned_directories:
6072.1.1 by Jelmer Vernooij
Various fixes for tests of foreign plugins.
296
            wt.add('foo/hello')
297
        else:
298
            self.assertRaises(NotVersionedError,
299
                              wt.add,
300
                              'foo/hello')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
301
302
    def test_add_missing(self):
303
        # adding a msising file -> NoSuchFile
304
        wt = self.make_branch_and_tree('.')
305
        self.assertRaises(errors.NoSuchFile, wt.add, 'fpp')
306
307
    def test_remove_verbose(self):
308
        #FIXME the remove api should not print or otherwise depend on the
309
        # text UI - RBC 20060124
310
        wt = self.make_branch_and_tree('.')
311
        self.build_tree(['hello'])
312
        wt.add(['hello'])
313
        wt.commit(message='add hello')
314
        stdout = StringIO()
315
        stderr = StringIO()
316
        self.assertEqual(None, self.apply_redirected(None, stdout, stderr,
317
                                                     wt.remove,
318
                                                     ['hello'],
319
                                                     verbose=True))
320
        self.assertEqual('?       hello\n', stdout.getvalue())
321
        self.assertEqual('', stderr.getvalue())
322
323
    def test_clone_trivial(self):
324
        wt = self.make_branch_and_tree('source')
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
325
        cloned_dir = wt.bzrdir.clone('target')
326
        cloned = cloned_dir.open_workingtree()
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
327
        self.assertEqual(cloned.get_parent_ids(), wt.get_parent_ids())
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
328
6241.3.1 by Jelmer Vernooij
Support WorkingTree.clone() having its revision argument set to the NULL revision.
329
    def test_clone_empty(self):
330
        wt = self.make_branch_and_tree('source')
331
        cloned_dir = wt.bzrdir.clone('target', revision_id=_mod_revision.NULL_REVISION)
332
        cloned = cloned_dir.open_workingtree()
333
        self.assertEqual(cloned.get_parent_ids(), wt.get_parent_ids())
334
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
335
    def test_last_revision(self):
336
        wt = self.make_branch_and_tree('source')
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
337
        self.assertEqual([], wt.get_parent_ids())
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
338
        wt.commit('A', allow_pointless=True, rev_id='A')
2249.5.7 by John Arbash Meinel
Make sure WorkingTree revision_ids are also returned as utf8 strings
339
        parent_ids = wt.get_parent_ids()
340
        self.assertEqual(['A'], parent_ids)
341
        for parent_id in parent_ids:
342
            self.assertIsInstance(parent_id, str)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
343
344
    def test_set_last_revision(self):
345
        wt = self.make_branch_and_tree('source')
1908.1.1 by Robert Collins
Relax WorkingTree.set_last-revision to allow any revision to be set.
346
        # set last-revision to one not in the history
347
        wt.set_last_revision('A')
348
        # set it back to None for an empty tree.
2598.5.3 by Aaron Bentley
Push NULL_REVISION deeper
349
        wt.set_last_revision('null:')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
350
        wt.commit('A', allow_pointless=True, rev_id='A')
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
351
        self.assertEqual(['A'], wt.get_parent_ids())
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
352
        # None is aways in the branch
2598.5.3 by Aaron Bentley
Push NULL_REVISION deeper
353
        wt.set_last_revision('null:')
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
354
        self.assertEqual([], wt.get_parent_ids())
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
355
        # and now we can set it to 'A'
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
356
        # because some formats mutate the branch to set it on the tree
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
357
        # we need to alter the branch to let this pass.
2230.3.27 by Aaron Bentley
Skip arbitrary revision-history test for Branch6
358
        try:
5718.8.9 by Jelmer Vernooij
Avoid using _set_revision_history as it's not present on older branch formats.
359
            self.applyDeprecated(symbol_versioning.deprecated_in((2, 4, 0)),
360
                wt.branch.set_revision_history, ['A', 'B'])
2230.3.27 by Aaron Bentley
Skip arbitrary revision-history test for Branch6
361
        except errors.NoSuchRevision, e:
362
            self.assertEqual('B', e.revision)
363
            raise TestSkipped("Branch format does not permit arbitrary"
364
                              " history")
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
365
        wt.set_last_revision('A')
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
366
        self.assertEqual(['A'], wt.get_parent_ids())
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
367
        self.assertRaises(errors.ReservedId, wt.set_last_revision, 'A:')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
368
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
369
    def test_set_last_revision_different_to_branch(self):
370
        # working tree formats from the meta-dir format and newer support
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
371
        # setting the last revision on a tree independently of that on the
372
        # branch. Its concievable that some future formats may want to
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
373
        # couple them again (i.e. because its really a smart server and
374
        # the working tree will always match the branch). So we test
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
375
        # that formats where initialising a branch does not initialise a
376
        # tree - and thus have separable entities - support skewing the
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
377
        # two things.
6437.70.7 by John Arbash Meinel
one more test that wanted to have a branch reference
378
        self.requireBranchReference()
379
        wt = self.make_branch_and_tree('tree')
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
380
        wt.commit('A', allow_pointless=True, rev_id='A')
381
        wt.set_last_revision(None)
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
382
        self.assertEqual([], wt.get_parent_ids())
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
383
        self.assertEqual('A', wt.branch.last_revision())
384
        # and now we can set it back to 'A'
385
        wt.set_last_revision('A')
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
386
        self.assertEqual(['A'], wt.get_parent_ids())
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
387
        self.assertEqual('A', wt.branch.last_revision())
388
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
389
    def test_clone_and_commit_preserves_last_revision(self):
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
390
        """Doing a commit into a clone tree does not affect the source."""
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
391
        wt = self.make_branch_and_tree('source')
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
392
        cloned_dir = wt.bzrdir.clone('target')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
393
        wt.commit('A', allow_pointless=True, rev_id='A')
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
394
        self.assertNotEqual(cloned_dir.open_workingtree().get_parent_ids(),
395
                            wt.get_parent_ids())
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
396
397
    def test_clone_preserves_content(self):
398
        wt = self.make_branch_and_tree('source')
2255.2.51 by John Arbash Meinel
simple rewrap for 79 char lines
399
        self.build_tree(['added', 'deleted', 'notadded'],
400
                        transport=wt.bzrdir.transport.clone('..'))
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
401
        wt.add('deleted', 'deleted')
402
        wt.commit('add deleted')
403
        wt.remove('deleted')
404
        wt.add('added', 'added')
405
        cloned_dir = wt.bzrdir.clone('target')
406
        cloned = cloned_dir.open_workingtree()
407
        cloned_transport = cloned.bzrdir.transport.clone('..')
408
        self.assertFalse(cloned_transport.has('deleted'))
409
        self.assertTrue(cloned_transport.has('added'))
410
        self.assertFalse(cloned_transport.has('notadded'))
411
        self.assertEqual('added', cloned.path2id('added'))
412
        self.assertEqual(None, cloned.path2id('deleted'))
413
        self.assertEqual(None, cloned.path2id('notadded'))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
414
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
415
    def test_basis_tree_returns_last_revision(self):
416
        wt = self.make_branch_and_tree('.')
417
        self.build_tree(['foo'])
418
        wt.add('foo', 'foo-id')
419
        wt.commit('A', rev_id='A')
420
        wt.rename_one('foo', 'bar')
421
        wt.commit('B', rev_id='B')
1908.6.3 by Robert Collins
Tidy up the last_revision_id and add_pending_merge conversion to use cleaner apis.
422
        wt.set_parent_ids(['B'])
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
423
        tree = wt.basis_tree()
2255.2.30 by Robert Collins
Some workingtree_implementations/test_workingtree.py test work - add DirStateRevisionTree.has_filename, locks around appropriate calls in tests.
424
        tree.lock_read()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
425
        self.assertTrue(tree.has_filename('bar'))
2255.2.30 by Robert Collins
Some workingtree_implementations/test_workingtree.py test work - add DirStateRevisionTree.has_filename, locks around appropriate calls in tests.
426
        tree.unlock()
1908.6.3 by Robert Collins
Tidy up the last_revision_id and add_pending_merge conversion to use cleaner apis.
427
        wt.set_parent_ids(['A'])
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
428
        tree = wt.basis_tree()
2255.2.30 by Robert Collins
Some workingtree_implementations/test_workingtree.py test work - add DirStateRevisionTree.has_filename, locks around appropriate calls in tests.
429
        tree.lock_read()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
430
        self.assertTrue(tree.has_filename('foo'))
2255.2.30 by Robert Collins
Some workingtree_implementations/test_workingtree.py test work - add DirStateRevisionTree.has_filename, locks around appropriate calls in tests.
431
        tree.unlock()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
432
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
433
    def test_clone_tree_revision(self):
434
        # make a tree with a last-revision,
435
        # and clone it with a different last-revision, this should switch
436
        # do it.
437
        #
438
        # also test that the content is merged
439
        # and conflicts recorded.
440
        # This should merge between the trees - local edits should be preserved
441
        # but other changes occured.
442
        # we test this by having one file that does
443
        # not change between two revisions, and another that does -
444
        # if the changed one is not changed, fail,
445
        # if the one that did not change has lost a local change, fail.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
446
        #
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
447
        raise TestSkipped('revision limiting is not implemented yet.')
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
448
449
    def test_initialize_with_revision_id(self):
450
        # a bzrdir can construct a working tree for itself @ a specific revision.
451
        source = self.make_branch_and_tree('source')
452
        source.commit('a', rev_id='a', allow_pointless=True)
453
        source.commit('b', rev_id='b', allow_pointless=True)
454
        self.build_tree(['new/'])
455
        made_control = self.bzrdir_format.initialize('new')
456
        source.branch.repository.clone(made_control)
457
        source.branch.clone(made_control)
5051.3.10 by Jelmer Vernooij
Pass colocated branch name around in more places.
458
        made_tree = self.workingtree_format.initialize(made_control,
459
            revision_id='a')
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
460
        self.assertEqual(['a'], made_tree.get_parent_ids())
1508.1.23 by Robert Collins
Test that the working tree last revision is indeed set during commit.
461
6435.1.1 by Jelmer Vernooij
Add post_build_tree hook.
462
    def test_post_build_tree_hook(self):
463
        calls = []
464
        def track_post_build_tree(tree):
465
            calls.append(tree.last_revision())
466
        source = self.make_branch_and_tree('source')
6435.1.2 by Jelmer Vernooij
Fix test against wt2.
467
        source.commit('a', rev_id='a', allow_pointless=True)
468
        source.commit('b', rev_id='b', allow_pointless=True)
469
        self.build_tree(['new/'])
470
        made_control = self.bzrdir_format.initialize('new')
471
        source.branch.repository.clone(made_control)
472
        source.branch.clone(made_control)
6435.1.1 by Jelmer Vernooij
Add post_build_tree hook.
473
        MutableTree.hooks.install_named_hook("post_build_tree",
474
            track_post_build_tree, "Test")
475
        made_tree = self.workingtree_format.initialize(made_control,
476
            revision_id='a')
477
        self.assertEqual(['a'], calls)
478
1508.1.24 by Robert Collins
Add update command for use with checkouts.
479
    def test_update_sets_last_revision(self):
480
        # working tree formats from the meta-dir format and newer support
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
481
        # setting the last revision on a tree independently of that on the
482
        # branch. Its concievable that some future formats may want to
1508.1.24 by Robert Collins
Add update command for use with checkouts.
483
        # couple them again (i.e. because its really a smart server and
484
        # the working tree will always match the branch). So we test
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
485
        # that formats where initialising a branch does not initialise a
486
        # tree - and thus have separable entities - support skewing the
1508.1.24 by Robert Collins
Add update command for use with checkouts.
487
        # two things.
6437.70.14 by John Arbash Meinel
Finish bug #1046697 and run all per_workingtree tests against a checkout.
488
        self.requireBranchReference()
6437.70.6 by John Arbash Meinel
Fix a couple tests that wanted to directly create a wt where the branch was.
489
        wt = self.make_branch_and_tree('tree')
1508.1.24 by Robert Collins
Add update command for use with checkouts.
490
        # create an out of date working tree by making a checkout in this
491
        # current format
492
        self.build_tree(['checkout/', 'tree/file'])
493
        checkout = bzrdir.BzrDirMetaFormat1().initialize('checkout')
6437.70.6 by John Arbash Meinel
Fix a couple tests that wanted to directly create a wt where the branch was.
494
        checkout.set_branch_reference(wt.branch)
1508.1.24 by Robert Collins
Add update command for use with checkouts.
495
        old_tree = self.workingtree_format.initialize(checkout)
496
        # now commit to 'tree'
497
        wt.add('file')
498
        wt.commit('A', rev_id='A')
499
        # and update old_tree
500
        self.assertEqual(0, old_tree.update())
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
501
        self.assertPathExists('checkout/file')
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
502
        self.assertEqual(['A'], old_tree.get_parent_ids())
1508.1.24 by Robert Collins
Add update command for use with checkouts.
503
1731.1.33 by Aaron Bentley
Revert no-special-root changes
504
    def test_update_sets_root_id(self):
505
        """Ensure tree root is set properly by update.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
506
1731.1.33 by Aaron Bentley
Revert no-special-root changes
507
        Since empty trees don't have root_ids, but workingtrees do,
508
        an update of a checkout of revision 0 to a new revision,  should set
509
        the root id.
510
        """
511
        wt = self.make_branch_and_tree('tree')
512
        main_branch = wt.branch
513
        # create an out of date working tree by making a checkout in this
514
        # current format
515
        self.build_tree(['checkout/', 'tree/file'])
1731.1.43 by Aaron Bentley
Merge more checkout changes
516
        checkout = main_branch.create_checkout('checkout')
1731.1.33 by Aaron Bentley
Revert no-special-root changes
517
        # now commit to 'tree'
518
        wt.add('file')
519
        wt.commit('A', rev_id='A')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
520
        # and update checkout
1731.1.33 by Aaron Bentley
Revert no-special-root changes
521
        self.assertEqual(0, checkout.update())
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
522
        self.assertPathExists('checkout/file')
1731.1.33 by Aaron Bentley
Revert no-special-root changes
523
        self.assertEqual(wt.get_root_id(), checkout.get_root_id())
524
        self.assertNotEqual(None, wt.get_root_id())
525
4634.123.1 by John Arbash Meinel
Add a failing test for 'update'. When this branch lands, update should work.
526
    def test_update_sets_updated_root_id(self):
527
        wt = self.make_branch_and_tree('tree')
528
        wt.set_root_id('first_root_id')
529
        self.assertEqual('first_root_id', wt.get_root_id())
530
        self.build_tree(['tree/file'])
531
        wt.add(['file'])
532
        wt.commit('first')
533
        co = wt.branch.create_checkout('checkout')
534
        wt.set_root_id('second_root_id')
535
        wt.commit('second')
536
        self.assertEqual('second_root_id', wt.get_root_id())
537
        self.assertEqual(0, co.update())
538
        self.assertEqual('second_root_id', co.get_root_id())
539
1508.1.24 by Robert Collins
Add update command for use with checkouts.
540
    def test_update_returns_conflict_count(self):
541
        # working tree formats from the meta-dir format and newer support
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
542
        # setting the last revision on a tree independently of that on the
543
        # branch. Its concievable that some future formats may want to
1508.1.24 by Robert Collins
Add update command for use with checkouts.
544
        # couple them again (i.e. because its really a smart server and
545
        # the working tree will always match the branch). So we test
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
546
        # that formats where initialising a branch does not initialise a
547
        # tree - and thus have separable entities - support skewing the
1508.1.24 by Robert Collins
Add update command for use with checkouts.
548
        # two things.
6437.70.6 by John Arbash Meinel
Fix a couple tests that wanted to directly create a wt where the branch was.
549
        self.requireBranchReference()
550
        wt = self.make_branch_and_tree('tree')
1508.1.24 by Robert Collins
Add update command for use with checkouts.
551
        # create an out of date working tree by making a checkout in this
552
        # current format
553
        self.build_tree(['checkout/', 'tree/file'])
554
        checkout = bzrdir.BzrDirMetaFormat1().initialize('checkout')
6437.70.6 by John Arbash Meinel
Fix a couple tests that wanted to directly create a wt where the branch was.
555
        checkout.set_branch_reference(wt.branch)
1508.1.24 by Robert Collins
Add update command for use with checkouts.
556
        old_tree = self.workingtree_format.initialize(checkout)
557
        # now commit to 'tree'
558
        wt.add('file')
559
        wt.commit('A', rev_id='A')
560
        # and add a file file to the checkout
561
        self.build_tree(['checkout/file'])
562
        old_tree.add('file')
563
        # and update old_tree
564
        self.assertEqual(1, old_tree.update())
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
565
        self.assertEqual(['A'], old_tree.get_parent_ids())
1508.1.24 by Robert Collins
Add update command for use with checkouts.
566
1534.7.199 by Aaron Bentley
Moved merge/revert tests into test_workingtree.py
567
    def test_merge_revert(self):
568
        from bzrlib.merge import merge_inner
569
        this = self.make_branch_and_tree('b1')
4789.12.1 by John Arbash Meinel
Fix per_workingtree.test_workingtree.test_merge_revert
570
        self.build_tree_contents([('b1/a', 'a test\n'), ('b1/b', 'b test\n')])
571
        this.add(['a', 'b'])
1534.7.199 by Aaron Bentley
Moved merge/revert tests into test_workingtree.py
572
        this.commit(message='')
573
        base = this.bzrdir.clone('b2').open_workingtree()
4789.12.1 by John Arbash Meinel
Fix per_workingtree.test_workingtree.test_merge_revert
574
        self.build_tree_contents([('b2/a', 'b test\n')])
1534.7.199 by Aaron Bentley
Moved merge/revert tests into test_workingtree.py
575
        other = this.bzrdir.clone('b3').open_workingtree()
4789.12.1 by John Arbash Meinel
Fix per_workingtree.test_workingtree.test_merge_revert
576
        self.build_tree_contents([('b3/a', 'c test\n'), ('b3/c', 'c test\n')])
1534.7.199 by Aaron Bentley
Moved merge/revert tests into test_workingtree.py
577
        other.add('c')
578
4789.12.1 by John Arbash Meinel
Fix per_workingtree.test_workingtree.test_merge_revert
579
        self.build_tree_contents([('b1/b', 'q test\n'), ('b1/d', 'd test\n')])
580
        # Note: If we don't lock this before calling merge_inner, then we get a
581
        #       lock-contention failure. This probably indicates something
582
        #       weird going on inside merge_inner. Probably something about
583
        #       calling bt = this_tree.basis_tree() in one lock, and then
584
        #       locking both this_tree and bt separately, causing a dirstate
585
        #       locking race.
586
        this.lock_write()
587
        self.addCleanup(this.unlock)
1534.7.199 by Aaron Bentley
Moved merge/revert tests into test_workingtree.py
588
        merge_inner(this.branch, other, base, this_tree=this)
4789.12.1 by John Arbash Meinel
Fix per_workingtree.test_workingtree.test_merge_revert
589
        a = open('b1/a', 'rb')
590
        try:
591
            self.assertNotEqual(a.read(), 'a test\n')
592
        finally:
593
            a.close()
2748.3.2 by Aaron Bentley
Fix revert, remove-tree, and various tests to use None for 'no files specified'
594
        this.revert()
4789.12.1 by John Arbash Meinel
Fix per_workingtree.test_workingtree.test_merge_revert
595
        self.assertFileEqual('a test\n', 'b1/a')
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
596
        self.assertPathExists('b1/b.~1~')
597
        self.assertPathDoesNotExist('b1/c')
598
        self.assertPathDoesNotExist('b1/a.~1~')
599
        self.assertPathExists('b1/d')
1534.7.200 by Aaron Bentley
Merge from mainline
600
1587.1.10 by Robert Collins
update updates working tree and branch together.
601
    def test_update_updates_bound_branch_no_local_commits(self):
602
        # doing an update in a tree updates the branch its bound to too.
603
        master_tree = self.make_branch_and_tree('master')
604
        tree = self.make_branch_and_tree('tree')
605
        try:
606
            tree.branch.bind(master_tree.branch)
607
        except errors.UpgradeRequired:
608
            # legacy branches cannot bind
609
            return
610
        master_tree.commit('foo', rev_id='foo', allow_pointless=True)
611
        tree.update()
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
612
        self.assertEqual(['foo'], tree.get_parent_ids())
1587.1.10 by Robert Collins
update updates working tree and branch together.
613
        self.assertEqual('foo', tree.branch.last_revision())
1587.1.11 by Robert Collins
Local commits appear to be working properly.
614
615
    def test_update_turns_local_commit_into_merge(self):
616
        # doing an update with a few local commits and no master commits
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
617
        # makes pending-merges.
1587.1.13 by Robert Collins
Explain why update pivots more clearly in the relevant test.
618
        # this is done so that 'bzr update; bzr revert' will always produce
619
        # an exact copy of the 'logical branch' - the referenced branch for
620
        # a checkout, and the master for a bound branch.
621
        # its possible that we should instead have 'bzr update' when there
622
        # is nothing new on the master leave the current commits intact and
623
        # alter 'revert' to revert to the master always. But for now, its
624
        # good.
1587.1.11 by Robert Collins
Local commits appear to be working properly.
625
        master_tree = self.make_branch_and_tree('master')
1927.2.1 by Robert Collins
Alter set_pending_merges to shove the left most merge into the trees last-revision if that is not set. Related bugfixes include basis_tree handling ghosts, de-duping the merges with the last-revision and update changing where and how it adds its pending merge.
626
        master_tip = master_tree.commit('first master commit')
1587.1.11 by Robert Collins
Local commits appear to be working properly.
627
        tree = self.make_branch_and_tree('tree')
628
        try:
629
            tree.branch.bind(master_tree.branch)
630
        except errors.UpgradeRequired:
631
            # legacy branches cannot bind
632
            return
1927.2.1 by Robert Collins
Alter set_pending_merges to shove the left most merge into the trees last-revision if that is not set. Related bugfixes include basis_tree handling ghosts, de-duping the merges with the last-revision and update changing where and how it adds its pending merge.
633
        # sync with master
634
        tree.update()
635
        # work locally
1587.1.11 by Robert Collins
Local commits appear to be working properly.
636
        tree.commit('foo', rev_id='foo', allow_pointless=True, local=True)
637
        tree.commit('bar', rev_id='bar', allow_pointless=True, local=True)
1927.2.1 by Robert Collins
Alter set_pending_merges to shove the left most merge into the trees last-revision if that is not set. Related bugfixes include basis_tree handling ghosts, de-duping the merges with the last-revision and update changing where and how it adds its pending merge.
638
        # sync with master prepatory to committing
1587.1.11 by Robert Collins
Local commits appear to be working properly.
639
        tree.update()
1927.2.1 by Robert Collins
Alter set_pending_merges to shove the left most merge into the trees last-revision if that is not set. Related bugfixes include basis_tree handling ghosts, de-duping the merges with the last-revision and update changing where and how it adds its pending merge.
640
        # which should have pivoted the local tip into a merge
641
        self.assertEqual([master_tip, 'bar'], tree.get_parent_ids())
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
642
        # and the local branch history should match the masters now.
6165.4.4 by Jelmer Vernooij
Avoid .revision_history().
643
        self.assertEqual(master_tree.branch.last_revision(),
644
            tree.branch.last_revision())
1587.1.11 by Robert Collins
Local commits appear to be working properly.
645
4916.1.7 by Martin Pool
Add per_workingtree test you can update to arbitrary revisions
646
    def test_update_takes_revision_parameter(self):
647
        wt = self.make_branch_and_tree('wt')
648
        self.build_tree_contents([('wt/a', 'old content')])
649
        wt.add(['a'])
650
        rev1 = wt.commit('first master commit')
651
        self.build_tree_contents([('wt/a', 'new content')])
652
        rev2 = wt.commit('second master commit')
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
653
        # https://bugs.launchpad.net/bzr/+bug/45719/comments/20
4916.1.7 by Martin Pool
Add per_workingtree test you can update to arbitrary revisions
654
        # when adding 'update -r' we should make sure all wt formats support
655
        # it
656
        conflicts = wt.update(revision=rev1)
657
        self.assertFileEqual('old content', 'wt/a')
658
        self.assertEqual([rev1], wt.get_parent_ids())
659
2255.2.156 by Martin Pool
Merge WorkingTree implementation back from trunk
660
    def test_merge_modified_detects_corruption(self):
661
        # FIXME: This doesn't really test that it works; also this is not
662
        # implementation-independent. mbp 20070226
1558.3.3 by Aaron Bentley
Fix error handling for merge_modified
663
        tree = self.make_branch_and_tree('master')
6072.1.1 by Jelmer Vernooij
Various fixes for tests of foreign plugins.
664
        if not isinstance(tree, InventoryWorkingTree):
665
            raise TestNotApplicable("merge-hashes is specific to bzr "
666
                "working trees")
3407.2.7 by Martin Pool
Deprecate LockableFiles.put_utf8 and put_bytes.
667
        tree._transport.put_bytes('merge-hashes', 'asdfasdf')
1558.3.3 by Aaron Bentley
Fix error handling for merge_modified
668
        self.assertRaises(errors.MergeModifiedFormatError, tree.merge_modified)
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
669
2298.1.1 by Martin Pool
Add test for merge_modified
670
    def test_merge_modified(self):
671
        # merge_modified stores a map from file id to hash
672
        tree = self.make_branch_and_tree('tree')
673
        d = {'file-id': osutils.sha_string('hello')}
674
        self.build_tree_contents([('tree/somefile', 'hello')])
675
        tree.lock_write()
676
        try:
677
            tree.add(['somefile'], ['file-id'])
678
            tree.set_merge_modified(d)
679
            mm = tree.merge_modified()
680
            self.assertEquals(mm, d)
681
        finally:
682
            tree.unlock()
683
        mm = tree.merge_modified()
684
        self.assertEquals(mm, d)
685
1534.10.22 by Aaron Bentley
Got ConflictList implemented
686
    def test_conflicts(self):
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
687
        from bzrlib.tests.test_conflicts import example_conflicts
688
        tree = self.make_branch_and_tree('master')
689
        try:
1534.10.22 by Aaron Bentley
Got ConflictList implemented
690
            tree.set_conflicts(example_conflicts)
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
691
        except UnsupportedOperation:
1534.10.22 by Aaron Bentley
Got ConflictList implemented
692
            raise TestSkipped('set_conflicts not supported')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
693
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
694
        tree2 = WorkingTree.open('master')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
695
        self.assertEqual(tree2.conflicts(), example_conflicts)
3407.2.7 by Martin Pool
Deprecate LockableFiles.put_utf8 and put_bytes.
696
        tree2._transport.put_bytes('conflicts', '')
697
        self.assertRaises(errors.ConflictFormatError,
1955.3.14 by John Arbash Meinel
Correctly fix the workingtree put() test fixes
698
                          tree2.conflicts)
3407.2.7 by Martin Pool
Deprecate LockableFiles.put_utf8 and put_bytes.
699
        tree2._transport.put_bytes('conflicts', 'a')
700
        self.assertRaises(errors.ConflictFormatError,
1955.3.14 by John Arbash Meinel
Correctly fix the workingtree put() test fixes
701
                          tree2.conflicts)
1534.10.12 by Aaron Bentley
Merge produces new conflicts
702
703
    def make_merge_conflicts(self):
2255.2.32 by Robert Collins
Make test_clear_merge_conflicts pass for dirstate. This involved working
704
        from bzrlib.merge import merge_inner
1534.10.12 by Aaron Bentley
Merge produces new conflicts
705
        tree = self.make_branch_and_tree('mine')
6437.20.3 by Wouter van Heyst
mechanically replace file().write() pattern with a with-keyword version
706
        with file('mine/bloo', 'wb') as f: f.write('one')
707
        with file('mine/blo', 'wb') as f: f.write('on')
2255.2.32 by Robert Collins
Make test_clear_merge_conflicts pass for dirstate. This involved working
708
        tree.add(['bloo', 'blo'])
1534.10.12 by Aaron Bentley
Merge produces new conflicts
709
        tree.commit("blah", allow_pointless=False)
2255.5.3 by John Arbash Meinel
XXX Workaround the DirStateRevisionTree bug until we get a proper fix, tests pass again
710
        base = tree.branch.repository.revision_tree(tree.last_revision())
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
711
        bzrdir.BzrDir.open("mine").sprout("other")
6437.20.3 by Wouter van Heyst
mechanically replace file().write() pattern with a with-keyword version
712
        with file('other/bloo', 'wb') as f: f.write('two')
1534.10.12 by Aaron Bentley
Merge produces new conflicts
713
        othertree = WorkingTree.open('other')
714
        othertree.commit('blah', allow_pointless=False)
6437.20.3 by Wouter van Heyst
mechanically replace file().write() pattern with a with-keyword version
715
        with file('mine/bloo', 'wb') as f: f.write('three')
1534.10.12 by Aaron Bentley
Merge produces new conflicts
716
        tree.commit("blah", allow_pointless=False)
717
        merge_inner(tree.branch, othertree, base, this_tree=tree)
718
        return tree
719
720
    def test_merge_conflicts(self):
721
        tree = self.make_merge_conflicts()
1534.10.22 by Aaron Bentley
Got ConflictList implemented
722
        self.assertEqual(len(tree.conflicts()), 1)
1534.10.12 by Aaron Bentley
Merge produces new conflicts
723
724
    def test_clear_merge_conflicts(self):
725
        tree = self.make_merge_conflicts()
1534.10.22 by Aaron Bentley
Got ConflictList implemented
726
        self.assertEqual(len(tree.conflicts()), 1)
1534.10.12 by Aaron Bentley
Merge produces new conflicts
727
        try:
1534.10.22 by Aaron Bentley
Got ConflictList implemented
728
            tree.set_conflicts(ConflictList())
1534.10.12 by Aaron Bentley
Merge produces new conflicts
729
        except UnsupportedOperation:
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
730
            raise TestSkipped('unsupported operation')
1534.10.22 by Aaron Bentley
Got ConflictList implemented
731
        self.assertEqual(tree.conflicts(), ConflictList())
1534.10.14 by Aaron Bentley
Made revert clear conflicts
732
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
733
    def test_add_conflicts(self):
734
        tree = self.make_branch_and_tree('tree')
735
        try:
736
            tree.add_conflicts([TextConflict('path_a')])
737
        except UnsupportedOperation:
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
738
            raise TestSkipped('unsupported operation')
1551.7.13 by Aaron Bentley
Switched from actual, expected to expected, actual, for John.
739
        self.assertEqual(ConflictList([TextConflict('path_a')]),
740
                         tree.conflicts())
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
741
        tree.add_conflicts([TextConflict('path_a')])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
742
        self.assertEqual(ConflictList([TextConflict('path_a')]),
1551.7.13 by Aaron Bentley
Switched from actual, expected to expected, actual, for John.
743
                         tree.conflicts())
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
744
        tree.add_conflicts([ContentsConflict('path_a')])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
745
        self.assertEqual(ConflictList([ContentsConflict('path_a'),
1551.7.13 by Aaron Bentley
Switched from actual, expected to expected, actual, for John.
746
                                       TextConflict('path_a')]),
747
                         tree.conflicts())
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
748
        tree.add_conflicts([TextConflict('path_b')])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
749
        self.assertEqual(ConflictList([ContentsConflict('path_a'),
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
750
                                       TextConflict('path_a'),
1551.7.13 by Aaron Bentley
Switched from actual, expected to expected, actual, for John.
751
                                       TextConflict('path_b')]),
752
                         tree.conflicts())
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
753
1534.10.14 by Aaron Bentley
Made revert clear conflicts
754
    def test_revert_clear_conflicts(self):
755
        tree = self.make_merge_conflicts()
1534.10.22 by Aaron Bentley
Got ConflictList implemented
756
        self.assertEqual(len(tree.conflicts()), 1)
1534.10.14 by Aaron Bentley
Made revert clear conflicts
757
        tree.revert(["blo"])
1534.10.22 by Aaron Bentley
Got ConflictList implemented
758
        self.assertEqual(len(tree.conflicts()), 1)
1534.10.14 by Aaron Bentley
Made revert clear conflicts
759
        tree.revert(["bloo"])
1534.10.22 by Aaron Bentley
Got ConflictList implemented
760
        self.assertEqual(len(tree.conflicts()), 0)
1534.10.14 by Aaron Bentley
Made revert clear conflicts
761
762
    def test_revert_clear_conflicts2(self):
763
        tree = self.make_merge_conflicts()
1534.10.22 by Aaron Bentley
Got ConflictList implemented
764
        self.assertEqual(len(tree.conflicts()), 1)
2748.3.2 by Aaron Bentley
Fix revert, remove-tree, and various tests to use None for 'no files specified'
765
        tree.revert()
1534.10.22 by Aaron Bentley
Got ConflictList implemented
766
        self.assertEqual(len(tree.conflicts()), 0)
1624.3.22 by Olaf Conradi
Merge bzr.dev
767
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
768
    def test_format_description(self):
769
        tree = self.make_branch_and_tree('tree')
770
        text = tree._format.get_format_description()
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
771
        self.assertTrue(len(text))
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
772
773
    def test_branch_attribute_is_not_settable(self):
774
        # the branch attribute is an aspect of the working tree, not a
775
        # configurable attribute
776
        tree = self.make_branch_and_tree('tree')
777
        def set_branch():
778
            tree.branch = tree.branch
779
        self.assertRaises(AttributeError, set_branch)
780
1713.3.1 by Robert Collins
Smoke tests for tree.list_files and bzr ignored when a versioned file matches an ignore rule.
781
    def test_list_files_versioned_before_ignored(self):
782
        """A versioned file matching an ignore rule should not be ignored."""
783
        tree = self.make_branch_and_tree('.')
784
        self.build_tree(['foo.pyc'])
785
        # ensure that foo.pyc is ignored
786
        self.build_tree_contents([('.bzrignore', 'foo.pyc')])
787
        tree.add('foo.pyc', 'anid')
2255.2.52 by Robert Collins
Dirstate - fix workingtree.list_files to use the public interface to access the trees inventory.
788
        tree.lock_read()
1713.3.1 by Robert Collins
Smoke tests for tree.list_files and bzr ignored when a versioned file matches an ignore rule.
789
        files = sorted(list(tree.list_files()))
2255.2.52 by Robert Collins
Dirstate - fix workingtree.list_files to use the public interface to access the trees inventory.
790
        tree.unlock()
1713.3.1 by Robert Collins
Smoke tests for tree.list_files and bzr ignored when a versioned file matches an ignore rule.
791
        self.assertEqual((u'.bzrignore', '?', 'file', None), files[0][:-1])
792
        self.assertEqual((u'foo.pyc', 'V', 'file', 'anid'), files[1][:-1])
793
        self.assertEqual(2, len(files))
1711.8.2 by John Arbash Meinel
Test that WorkingTree locks Branch before self, and unlocks self before Branch
794
1830.3.7 by John Arbash Meinel
Check that WorkingTree.add does the right thing.
795
    def test_non_normalized_add_accessible(self):
796
        try:
797
            self.build_tree([u'a\u030a'])
798
        except UnicodeError:
799
            raise TestSkipped('Filesystem does not support unicode filenames')
800
        tree = self.make_branch_and_tree('.')
801
        orig = osutils.normalized_filename
802
        osutils.normalized_filename = osutils._accessible_normalized_filename
803
        try:
804
            tree.add([u'a\u030a'])
2255.2.58 by Robert Collins
Fix the way we used osutils.normalized_filename in dirstate to support overriding in tests - and document this in the original location it was used.
805
            tree.lock_read()
1907.1.3 by Aaron Bentley
Fixed unicode test cases
806
            self.assertEqual([('', 'directory'), (u'\xe5', 'file')],
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
807
                    [(path, ie.kind) for path,ie in
5807.1.2 by Jelmer Vernooij
Skip some inventory-specific tests for non-inventory working trees.
808
                                tree.iter_entries_by_dir()])
2255.2.58 by Robert Collins
Fix the way we used osutils.normalized_filename in dirstate to support overriding in tests - and document this in the original location it was used.
809
            tree.unlock()
1830.3.7 by John Arbash Meinel
Check that WorkingTree.add does the right thing.
810
        finally:
811
            osutils.normalized_filename = orig
812
813
    def test_non_normalized_add_inaccessible(self):
814
        try:
815
            self.build_tree([u'a\u030a'])
816
        except UnicodeError:
817
            raise TestSkipped('Filesystem does not support unicode filenames')
818
        tree = self.make_branch_and_tree('.')
819
        orig = osutils.normalized_filename
820
        osutils.normalized_filename = osutils._inaccessible_normalized_filename
821
        try:
822
            self.assertRaises(errors.InvalidNormalization,
823
                tree.add, [u'a\u030a'])
824
        finally:
825
            osutils.normalized_filename = orig
2123.3.9 by Steffen Eichenberg
added tests for deprecated API workingtree.move
826
1852.15.14 by Robert Collins
test that WorkingTree._write_inventory works as expected by the current code.
827
    def test__write_inventory(self):
828
        # The private interface _write_inventory is currently used by transform.
829
        tree = self.make_branch_and_tree('.')
5807.1.2 by Jelmer Vernooij
Skip some inventory-specific tests for non-inventory working trees.
830
        if not isinstance(tree, InventoryWorkingTree):
831
            raise TestNotApplicable("_write_inventory does not exist on "
832
                "non-inventory working trees")
1852.15.14 by Robert Collins
test that WorkingTree._write_inventory works as expected by the current code.
833
        # if we write write an inventory then do a walkdirs we should get back
834
        # missing entries, and actual, and unknowns as appropriate.
835
        self.build_tree(['present', 'unknown'])
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
836
        inventory = Inventory(tree.get_root_id())
1852.15.14 by Robert Collins
test that WorkingTree._write_inventory works as expected by the current code.
837
        inventory.add_path('missing', 'file', 'missing-id')
838
        inventory.add_path('present', 'file', 'present-id')
2255.2.28 by Robert Collins
TestWorkingTree.test__write_inventory needs to lock the tree before calling _write_inventory for dirstate.
839
        # there is no point in being able to write an inventory to an unlocked
840
        # tree object - its a low level api not a convenience api.
841
        tree.lock_write()
1852.15.14 by Robert Collins
test that WorkingTree._write_inventory works as expected by the current code.
842
        tree._write_inventory(inventory)
2255.2.28 by Robert Collins
TestWorkingTree.test__write_inventory needs to lock the tree before calling _write_inventory for dirstate.
843
        tree.unlock()
1852.15.14 by Robert Collins
test that WorkingTree._write_inventory works as expected by the current code.
844
        tree.lock_read()
845
        try:
846
            present_stat = os.lstat('present')
847
            unknown_stat = os.lstat('unknown')
848
            expected_results = [
2946.3.3 by John Arbash Meinel
Prefer tree.get_root_id() as more explicit than tree.path2id('')
849
                (('', tree.get_root_id()),
1852.15.14 by Robert Collins
test that WorkingTree._write_inventory works as expected by the current code.
850
                 [('missing', 'missing', 'unknown', None, 'missing-id', 'file'),
851
                  ('present', 'present', 'file', present_stat, 'present-id', 'file'),
852
                  ('unknown', 'unknown', 'file', unknown_stat, None, None),
853
                 ]
854
                )]
855
            self.assertEqual(expected_results, list(tree.walkdirs()))
856
        finally:
857
            tree.unlock()
2255.7.56 by Robert Collins
Document behaviour of tree.path2id("path/").
858
859
    def test_path2id(self):
2255.7.62 by Robert Collins
Update the Tree.filter_unversioned_files docstring to reflect what the existing implementations actually do, and change the WorkingTree4 implementation to match a newly created test for it.
860
        # smoke test for path2id
2255.7.56 by Robert Collins
Document behaviour of tree.path2id("path/").
861
        tree = self.make_branch_and_tree('.')
862
        self.build_tree(['foo'])
863
        tree.add(['foo'], ['foo-id'])
864
        self.assertEqual('foo-id', tree.path2id('foo'))
865
        # the next assertion is for backwards compatability with WorkingTree3,
866
        # though its probably a bad idea, it makes things work. Perhaps
867
        # it should raise a deprecation warning?
868
        self.assertEqual('foo-id', tree.path2id('foo/'))
2255.7.62 by Robert Collins
Update the Tree.filter_unversioned_files docstring to reflect what the existing implementations actually do, and change the WorkingTree4 implementation to match a newly created test for it.
869
870
    def test_filter_unversioned_files(self):
871
        # smoke test for filter_unversioned_files
872
        tree = self.make_branch_and_tree('.')
873
        paths = ['here-and-versioned', 'here-and-not-versioned',
874
            'not-here-and-versioned', 'not-here-and-not-versioned']
875
        tree.add(['here-and-versioned', 'not-here-and-versioned'],
876
            kinds=['file', 'file'])
877
        self.build_tree(['here-and-versioned', 'here-and-not-versioned'])
878
        tree.lock_read()
879
        self.addCleanup(tree.unlock)
880
        self.assertEqual(
881
            set(['not-here-and-not-versioned', 'here-and-not-versioned']),
882
            tree.filter_unversioned_files(paths))
2255.2.200 by Martin Pool
Add simple test for WorkingTree.kind
883
884
    def test_detect_real_kind(self):
885
        # working trees report the real kind of the file on disk, not the kind
886
        # they had when they were first added
887
        # create one file of every interesting type
888
        tree = self.make_branch_and_tree('.')
4100.2.2 by Aaron Bentley
Remove locking decorator
889
        tree.lock_write()
890
        self.addCleanup(tree.unlock)
2255.2.200 by Martin Pool
Add simple test for WorkingTree.kind
891
        self.build_tree(['file', 'directory/'])
892
        names = ['file', 'directory']
893
        if has_symlinks():
894
            os.symlink('target', 'symlink')
895
            names.append('symlink')
896
        tree.add(names, [n + '-id' for n in names])
897
        # now when we first look, we should see everything with the same kind
898
        # with which they were initially added
899
        for n in names:
900
            actual_kind = tree.kind(n + '-id')
901
            self.assertEqual(n, actual_kind)
902
        # move them around so the names no longer correspond to the types
903
        os.rename(names[0], 'tmp')
904
        for i in range(1, len(names)):
905
            os.rename(names[i], names[i-1])
906
        os.rename('tmp', names[-1])
2255.2.202 by Martin Pool
WorkingTree_4.kind should report tree-references if they're
907
        # now look and expect to see the correct types again
908
        for i in range(len(names)):
909
            actual_kind = tree.kind(names[i-1] + '-id')
910
            expected_kind = names[i]
911
            self.assertEqual(expected_kind, actual_kind)
2499.3.1 by Aaron Bentley
Fix Workingtree4.get_file_sha1 on missing files
912
3146.8.4 by Aaron Bentley
Eliminate direct use of inventory from transform application
913
    def test_stored_kind_with_missing(self):
914
        tree = self.make_branch_and_tree('tree')
915
        tree.lock_write()
916
        self.addCleanup(tree.unlock)
917
        self.build_tree(['tree/a', 'tree/b/'])
918
        tree.add(['a', 'b'], ['a-id', 'b-id'])
919
        os.unlink('tree/a')
920
        os.rmdir('tree/b')
921
        self.assertEqual('file', tree.stored_kind('a-id'))
922
        self.assertEqual('directory', tree.stored_kind('b-id'))
923
2499.3.1 by Aaron Bentley
Fix Workingtree4.get_file_sha1 on missing files
924
    def test_missing_file_sha1(self):
925
        """If a file is missing, its sha1 should be reported as None."""
926
        tree = self.make_branch_and_tree('.')
927
        tree.lock_write()
928
        self.addCleanup(tree.unlock)
929
        self.build_tree(['file'])
930
        tree.add('file', 'file-id')
931
        tree.commit('file added')
932
        os.unlink('file')
933
        self.assertIs(None, tree.get_file_sha1('file-id'))
1551.15.56 by Aaron Bentley
Raise NoSuchId when get_file_sha1 is invoked with a baed file id
934
935
    def test_no_file_sha1(self):
936
        """If a file is not present, get_file_sha1 should raise NoSuchId"""
937
        tree = self.make_branch_and_tree('.')
938
        tree.lock_write()
939
        self.addCleanup(tree.unlock)
940
        self.assertRaises(errors.NoSuchId, tree.get_file_sha1, 'file-id')
941
        self.build_tree(['file'])
942
        tree.add('file', 'file-id')
943
        tree.commit('foo')
944
        tree.remove('file')
945
        self.assertRaises(errors.NoSuchId, tree.get_file_sha1, 'file-id')
3034.4.5 by Aaron Bentley
Add workingtree test for case_insensitive var
946
947
    def test_case_sensitive(self):
948
        """If filesystem is case-sensitive, tree should report this.
949
950
        We check case-sensitivity by creating a file with a lowercase name,
951
        then testing whether it exists with an uppercase name.
952
        """
3034.4.9 by Alexander Belchenko
skip test_workingtree.TestWorkingTree.test_case_sensitive for WT2
953
        self.build_tree(['filename'])
3034.4.5 by Aaron Bentley
Add workingtree test for case_insensitive var
954
        if os.path.exists('FILENAME'):
955
            case_sensitive = False
956
        else:
957
            case_sensitive = True
958
        tree = self.make_branch_and_tree('test')
959
        self.assertEqual(case_sensitive, tree.case_sensitive)
6113.1.1 by Jelmer Vernooij
Skip some tests against foreign formats.
960
        if not isinstance(tree, InventoryWorkingTree):
961
            raise TestNotApplicable("get_format_string is only available "
962
                                    "on bzr working trees")
5632.1.1 by John Arbash Meinel
Make case_sensitive_filename an attribute of the format.
963
        # now we cheat, and make a file that matches the case-sensitive name
964
        t = tree.bzrdir.get_workingtree_transport(None)
965
        try:
966
            content = tree._format.get_format_string()
967
        except NotImplementedError:
968
            # All-in-one formats didn't have a separate format string.
969
            content = tree.bzrdir._format.get_format_string()
970
        t.put_bytes(tree._format.case_sensitive_filename, content)
971
        tree = tree.bzrdir.open_workingtree()
972
        self.assertFalse(tree.case_sensitive)
3146.8.2 by Aaron Bentley
Introduce iter_all_file_ids, to avoid hitting Inventory for this case
973
6379.7.1 by Jelmer Vernooij
Add and use WorkingTree._supports_executable.
974
    def test_supports_executable(self):
975
        self.build_tree(['filename'])
976
        tree = self.make_branch_and_tree('.')
977
        tree.add('filename')
978
        self.assertIsInstance(tree._supports_executable(), bool)
979
        if tree._supports_executable():
980
            tree.lock_read()
981
            try:
982
                self.assertFalse(tree.is_executable(tree.path2id('filename')))
983
            finally:
984
                tree.unlock()
985
            os.chmod('filename', 0755)
986
            self.addCleanup(tree.lock_read().unlock)
987
            self.assertTrue(tree.is_executable(tree.path2id('filename')))
988
        else:
989
            self.addCleanup(tree.lock_read().unlock)
990
            self.assertFalse(tree.is_executable(tree.path2id('filename')))
991
3146.8.16 by Aaron Bentley
Updates from review
992
    def test_all_file_ids_with_missing(self):
3146.8.2 by Aaron Bentley
Introduce iter_all_file_ids, to avoid hitting Inventory for this case
993
        tree = self.make_branch_and_tree('tree')
994
        tree.lock_write()
995
        self.addCleanup(tree.unlock)
996
        self.build_tree(['tree/a', 'tree/b'])
997
        tree.add(['a', 'b'], ['a-id', 'b-id'])
998
        os.unlink('tree/a')
999
        self.assertEqual(set(['a-id', 'b-id', tree.get_root_id()]),
3146.8.16 by Aaron Bentley
Updates from review
1000
                         tree.all_file_ids())
3146.8.19 by Aaron Bentley
Merge with bzr.dev
1001
3136.1.10 by Aaron Bentley
Clean error if filesystem does not support hard-links
1002
    def test_sprout_hardlink(self):
3619.6.9 by Mark Hammond
Move check for os.link to the start of the test
1003
        real_os_link = getattr(os, 'link', None)
1004
        if real_os_link is None:
1005
            raise TestNotApplicable("This platform doesn't provide os.link")
3136.1.10 by Aaron Bentley
Clean error if filesystem does not support hard-links
1006
        source = self.make_branch_and_tree('source')
1007
        self.build_tree(['source/file'])
1008
        source.add('file')
1009
        source.commit('added file')
1010
        def fake_link(source, target):
1011
            raise OSError(errno.EPERM, 'Operation not permitted')
1012
        os.link = fake_link
1013
        try:
1014
            # Hard-link support is optional, so supplying hardlink=True may
1015
            # or may not raise an exception.  But if it does, it must be
1016
            # HardLinkNotSupported
1017
            try:
1018
                source.bzrdir.sprout('target', accelerator_tree=source,
1019
                                     hardlink=True)
1020
            except errors.HardLinkNotSupported:
1021
                pass
1022
        finally:
1023
            os.link = real_os_link
3287.20.3 by John Arbash Meinel
Aaron recommended to make this a WT_impl test.
1024
1025
4985.3.18 by Vincent Ladeuil
Start rewriting the test.
1026
class TestWorkingTreeUpdate(TestCaseWithWorkingTree):
1027
1028
    def make_diverged_master_branch(self):
1029
        """
1030
        B: wt.branch.last_revision()
1031
        M: wt.branch.get_master_branch().last_revision()
1032
        W: wt.last_revision()
1033
1034
1035
            1
1036
            |\
1037
          B-2 3
1038
            | |
1039
            4 5-M
1040
            |
1041
            W
6162.3.2 by Jelmer Vernooij
Add WorkingTreeFormat.get_controldir_for_branch().
1042
        """
1043
        format = self.workingtree_format.get_controldir_for_branch()
1044
        builder = self.make_branch_builder(".", format=format)
4985.3.18 by Vincent Ladeuil
Start rewriting the test.
1045
        builder.start_series()
1046
        # mainline
1047
        builder.build_snapshot(
1048
            '1', None,
1049
            [('add', ('', 'root-id', 'directory', '')),
1050
             ('add', ('file1', 'file1-id', 'file', 'file1 content\n'))])
1051
        # branch
1052
        builder.build_snapshot('2', ['1'], [])
1053
        builder.build_snapshot(
1054
            '4', ['2'],
1055
            [('add', ('file4', 'file4-id', 'file', 'file4 content\n'))])
1056
        # master
1057
        builder.build_snapshot('3', ['1'], [])
1058
        builder.build_snapshot(
1059
            '5', ['3'],
1060
            [('add', ('file5', 'file5-id', 'file', 'file5 content\n'))])
1061
        builder.finish_series()
1062
        return builder, builder._branch.last_revision()
1063
4985.3.21 by Vincent Ladeuil
Final cleanup.
1064
    def make_checkout_and_master(self, builder, wt_path, master_path, wt_revid,
1065
                                 master_revid=None, branch_revid=None):
1066
        """Build a lightweight checkout and its master branch."""
1067
        if master_revid is None:
1068
            master_revid = wt_revid
1069
        if branch_revid is None:
1070
            branch_revid = master_revid
4985.3.18 by Vincent Ladeuil
Start rewriting the test.
1071
        final_branch = builder.get_branch()
1072
        # The master branch
4985.3.21 by Vincent Ladeuil
Final cleanup.
1073
        master = final_branch.bzrdir.sprout(master_path,
1074
                                            master_revid).open_branch()
1075
        # The checkout
1076
        wt = self.make_branch_and_tree(wt_path)
1077
        wt.pull(final_branch, stop_revision=wt_revid)
1078
        wt.branch.pull(final_branch, stop_revision=branch_revid, overwrite=True)
4985.3.18 by Vincent Ladeuil
Start rewriting the test.
1079
        try:
4985.3.21 by Vincent Ladeuil
Final cleanup.
1080
            wt.branch.bind(master)
4985.3.18 by Vincent Ladeuil
Start rewriting the test.
1081
        except errors.UpgradeRequired:
4985.3.21 by Vincent Ladeuil
Final cleanup.
1082
            raise TestNotApplicable(
1083
                "Can't bind %s" % wt.branch._format.__class__)
1084
        return wt, master
4985.3.18 by Vincent Ladeuil
Start rewriting the test.
1085
1086
    def test_update_remove_commit(self):
1087
        """Update should remove revisions when the branch has removed
1088
        some commits.
1089
1090
        We want to revert 4, so that strating with the
1091
        make_diverged_master_branch() graph the final result should be
1092
        equivalent to:
1093
1094
           1
1095
           |\
1096
           3 2
1097
           | |\
1098
        MB-5 | 4
1099
           |/
1100
           W
1101
1102
        And the changes in 4 have been removed from the WT.
1103
        """
1104
        builder, tip = self.make_diverged_master_branch()
4985.3.21 by Vincent Ladeuil
Final cleanup.
1105
        wt, master = self.make_checkout_and_master(
1106
            builder, 'checkout', 'master', '4',
1107
            master_revid=tip, branch_revid='2')
4985.3.19 by Vincent Ladeuil
Make the test more precise.
1108
        # First update the branch
1109
        old_tip = wt.branch.update()
4985.3.21 by Vincent Ladeuil
Final cleanup.
1110
        self.assertEqual('2', old_tip)
4985.3.18 by Vincent Ladeuil
Start rewriting the test.
1111
        # No conflicts should occur
4985.3.21 by Vincent Ladeuil
Final cleanup.
1112
        self.assertEqual(0, wt.update(old_tip=old_tip))
4985.3.19 by Vincent Ladeuil
Make the test more precise.
1113
        # We are in sync with the master
1114
        self.assertEqual(tip, wt.branch.last_revision())
4985.3.20 by Vincent Ladeuil
Remove the blackbox test and fix typo.
1115
        # We have the right parents ready to be committed
4985.3.19 by Vincent Ladeuil
Make the test more precise.
1116
        self.assertEqual(['5', '2'], wt.get_parent_ids())
4985.3.18 by Vincent Ladeuil
Start rewriting the test.
1117
4985.3.21 by Vincent Ladeuil
Final cleanup.
1118
    def test_update_revision(self):
1119
        builder, tip = self.make_diverged_master_branch()
1120
        wt, master = self.make_checkout_and_master(
1121
            builder, 'checkout', 'master', '4',
1122
            master_revid=tip, branch_revid='2')
1123
        self.assertEqual(0, wt.update(revision='1'))
1124
        self.assertEqual('1', wt.last_revision())
1125
        self.assertEqual(tip, wt.branch.last_revision())
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1126
        self.assertPathExists('checkout/file1')
1127
        self.assertPathDoesNotExist('checkout/file4')
1128
        self.assertPathDoesNotExist('checkout/file5')
4985.3.21 by Vincent Ladeuil
Final cleanup.
1129
4985.3.18 by Vincent Ladeuil
Start rewriting the test.
1130
3287.20.3 by John Arbash Meinel
Aaron recommended to make this a WT_impl test.
1131
class TestIllegalPaths(TestCaseWithWorkingTree):
1132
1133
    def test_bad_fs_path(self):
3638.3.14 by Vincent Ladeuil
Make test_bad_fs_path not applicable on OSX.
1134
        if osutils.normalizes_filenames():
1135
            # You *can't* create an illegal filename on OSX.
1136
            raise tests.TestNotApplicable('OSX normalizes filenames')
5967.12.1 by Martin Pool
Move all test features into bzrlib.tests.features
1137
        self.requireFeature(features.UTF8Filesystem)
3287.20.3 by John Arbash Meinel
Aaron recommended to make this a WT_impl test.
1138
        # We require a UTF8 filesystem, because otherwise we would need to get
1139
        # tricky to figure out how to create an illegal filename.
1140
        # \xb5 is an illegal path because it should be \xc2\xb5 for UTF-8
1141
        tree = self.make_branch_and_tree('tree')
1142
        self.build_tree(['tree/subdir/'])
1143
        tree.add('subdir')
1144
1145
        f = open('tree/subdir/m\xb5', 'wb')
1146
        try:
1147
            f.write('trivial\n')
1148
        finally:
1149
            f.close()
1150
1151
        tree.lock_read()
1152
        self.addCleanup(tree.unlock)
1153
        basis = tree.basis_tree()
1154
        basis.lock_read()
1155
        self.addCleanup(basis.unlock)
1156
1157
        e = self.assertListRaises(errors.BadFilenameEncoding,
1158
                                  tree.iter_changes, tree.basis_tree(),
1159
                                                     want_unversioned=True)
1160
        # We should display the relative path
1161
        self.assertEqual('subdir/m\xb5', e.filename)
1162
        self.assertEqual(osutils._fs_enc, e.fs_encoding)
5158.6.5 by Martin Pool
Implement ControlComponent on WorkingTree
1163
1164
1165
class TestControlComponent(TestCaseWithWorkingTree):
1166
    """WorkingTree implementations adequately implement ControlComponent."""
6059.4.4 by Vincent Ladeuil
Migrate bzr.workingtree.worth_saving_limit to stack-based config.
1167
5158.6.5 by Martin Pool
Implement ControlComponent on WorkingTree
1168
    def test_urls(self):
1169
        wt = self.make_branch_and_tree('wt')
1170
        self.assertIsInstance(wt.user_url, str)
1171
        self.assertEqual(wt.user_url, wt.user_transport.base)
1172
        # for all current bzrdir implementations the user dir must be 
1173
        # above the control dir but we might need to relax that?
1174
        self.assertEqual(wt.control_url.find(wt.user_url), 0)
1175
        self.assertEqual(wt.control_url, wt.control_transport.base)
5807.4.7 by John Arbash Meinel
Add a config setting.
1176
1177
1178
class TestWorthSavingLimit(TestCaseWithWorkingTree):
1179
1180
    def make_wt_with_worth_saving_limit(self):
1181
        wt = self.make_branch_and_tree('wt')
1182
        if getattr(wt, '_worth_saving_limit', None) is None:
1183
            raise tests.TestNotApplicable('no _worth_saving_limit for'
1184
                                          ' this tree type')
1185
        wt.lock_write()
1186
        self.addCleanup(wt.unlock)
1187
        return wt
1188
1189
    def test_not_set(self):
1190
        # Default should be 10
1191
        wt = self.make_wt_with_worth_saving_limit()
1192
        self.assertEqual(10, wt._worth_saving_limit())
1193
        ds = wt.current_dirstate()
1194
        self.assertEqual(10, ds._worth_saving_limit)
1195
1196
    def test_set_in_branch(self):
1197
        wt = self.make_wt_with_worth_saving_limit()
6059.4.4 by Vincent Ladeuil
Migrate bzr.workingtree.worth_saving_limit to stack-based config.
1198
        conf = config.BranchStack(wt.branch)
1199
        conf.set('bzr.workingtree.worth_saving_limit', '20')
5807.4.7 by John Arbash Meinel
Add a config setting.
1200
        self.assertEqual(20, wt._worth_saving_limit())
1201
        ds = wt.current_dirstate()
1202
        self.assertEqual(10, ds._worth_saving_limit)
1203
1204
    def test_invalid(self):
1205
        wt = self.make_wt_with_worth_saving_limit()
6059.4.4 by Vincent Ladeuil
Migrate bzr.workingtree.worth_saving_limit to stack-based config.
1206
        conf = config.BranchStack(wt.branch)
1207
        conf.set('bzr.workingtree.worth_saving_limit', 'a')
5807.4.7 by John Arbash Meinel
Add a config setting.
1208
        # If the config entry is invalid, default to 10
6059.4.4 by Vincent Ladeuil
Migrate bzr.workingtree.worth_saving_limit to stack-based config.
1209
        warnings = []
1210
        def warning(*args):
1211
            warnings.append(args[0] % args[1:])
1212
        self.overrideAttr(trace, 'warning', warning)
5807.4.7 by John Arbash Meinel
Add a config setting.
1213
        self.assertEqual(10, wt._worth_saving_limit())
6059.4.4 by Vincent Ladeuil
Migrate bzr.workingtree.worth_saving_limit to stack-based config.
1214
        self.assertLength(1, warnings)
1215
        self.assertEquals('Value "a" is not valid for'
1216
                          ' "bzr.workingtree.worth_saving_limit"',
1217
                          warnings[0])
5993.3.1 by Jelmer Vernooij
Add WorkingTreeFormat.supports_versioned_directories attribute.
1218
1219
1220
class TestFormatAttributes(TestCaseWithWorkingTree):
1221
1222
    def test_versioned_directories(self):
1223
        self.assertSubset(
1224
            [self.workingtree_format.supports_versioned_directories],
1225
            (True, False))