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