~bzr-pqm/bzr/bzr.dev

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
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
16
5582.8.1 by Martin
Make bt.test_transform.TestTreeTransform.test_rename_fails not care about the exact stringification of the exception instance
17
import errno
1534.7.106 by Aaron Bentley
Cleaned up imports, added copyright statements
18
import os
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
19
from StringIO import StringIO
2027.1.1 by John Arbash Meinel
Fix bug #56549, and write a direct test that the right path is being statted
20
import sys
4934.1.1 by John Arbash Meinel
Basic implementation for windows and bug #488724.
21
import time
1558.1.3 by Aaron Bentley
Fixed deprecated op use in test suite
22
2027.1.1 by John Arbash Meinel
Fix bug #56549, and write a direct test that the right path is being statted
23
from bzrlib import (
2694.5.4 by Jelmer Vernooij
Move bzrlib.util.bencode to bzrlib._bencode_py.
24
    bencode,
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
25
    errors,
4826.1.5 by Andrew Bennetts
Add test that content filtered files are not hardlinked by build_tree.
26
    filters,
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
27
    generate_ids,
3199.1.4 by Vincent Ladeuil
Fix 16 leaked tmp dirs. Probably indicates a lock handling problem with TransformPreview
28
    osutils,
3008.1.18 by Aaron Bentley
Get supported PreviewTree functionality under test
29
    revision as _mod_revision,
4826.1.5 by Andrew Bennetts
Add test that content filtered files are not hardlinked by build_tree.
30
    rules,
5409.1.11 by Vincent Ladeuil
Slightly cleanup bzrlib.transform and deprecate unused code.
31
    symbol_versioning,
2027.1.1 by John Arbash Meinel
Fix bug #56549, and write a direct test that the right path is being statted
32
    tests,
5409.1.17 by Vincent Ladeuil
Ensures we fallback to the default policy if a bogus one is specified.
33
    trace,
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
34
    transform,
2027.1.1 by John Arbash Meinel
Fix bug #56549, and write a direct test that the right path is being statted
35
    urlutils,
36
    )
1558.1.3 by Aaron Bentley
Fixed deprecated op use in test suite
37
from bzrlib.bzrdir import BzrDir
5162.4.1 by Aaron Bentley
TreeTransform supports normal commit parameters and includes branch nick.
38
from bzrlib.conflicts import (
39
    DeletingParent,
40
    DuplicateEntry,
41
    DuplicateID,
42
    MissingParent,
43
    NonDirectoryParent,
44
    ParentLoop,
45
    UnversionedParent,
46
)
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
47
from bzrlib.diff import show_diff_trees
5162.4.1 by Aaron Bentley
TreeTransform supports normal commit parameters and includes branch nick.
48
from bzrlib.errors import (
49
    DuplicateKey,
50
    ExistingLimbo,
51
    ExistingPendingDeletion,
52
    ImmortalLimbo,
53
    ImmortalPendingDeletion,
54
    LockError,
55
    MalformedTransform,
56
    ReusingTransform,
57
)
58
from bzrlib.osutils import (
59
    file_kind,
60
    pathjoin,
61
)
3363.17.1 by Aaron Bentley
Avoid inventory for merge and transform code
62
from bzrlib.merge import Merge3Merger, Merger
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
63
from bzrlib.tests import (
5050.44.1 by Vincent Ladeuil
One more fixed test related to bug #646133
64
    features,
3136.1.1 by Aaron Bentley
Add support for hardlinks to TreeTransform
65
    HardlinkFeature,
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
66
    SymlinkFeature,
67
    TestCaseInTempDir,
68
    TestSkipped,
5162.4.1 by Aaron Bentley
TreeTransform supports normal commit parameters and includes branch nick.
69
)
70
from bzrlib.transform import (
71
    build_tree,
72
    create_from_tree,
73
    cook_conflicts,
74
    _FileMover,
75
    FinalPaths,
76
    resolve_conflicts,
77
    resolve_checkout,
78
    ROOT_PARENT,
79
    TransformPreview,
80
    TreeTransform,
81
)
0.13.13 by Aaron Bentley
Add direct test of serialization records
82
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
83
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
84
class TestTreeTransform(tests.TestCaseWithTransport):
1740.2.4 by Aaron Bentley
Update transform tests and docs
85
1534.7.59 by Aaron Bentley
Simplified tests
86
    def setUp(self):
87
        super(TestTreeTransform, self).setUp()
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
88
        self.wt = self.make_branch_and_tree('.', format='dirstate-with-subtree')
1534.7.161 by Aaron Bentley
Used appropriate control_files
89
        os.chdir('..')
1534.7.59 by Aaron Bentley
Simplified tests
90
91
    def get_transform(self):
92
        transform = TreeTransform(self.wt)
3453.2.7 by Aaron Bentley
Remove test kipple
93
        self.addCleanup(transform.finalize)
1731.1.33 by Aaron Bentley
Revert no-special-root changes
94
        return transform, transform.root
1534.7.59 by Aaron Bentley
Simplified tests
95
5752.3.5 by John Arbash Meinel
Refactor tests into a common helper.
96
    def get_transform_for_sha1_test(self):
97
        trans, root = self.get_transform()
98
        self.wt.lock_tree_write()
99
        self.addCleanup(self.wt.unlock)
100
        contents = ['just some content\n']
101
        sha1 = osutils.sha_strings(contents)
102
        # Roll back the clock
103
        trans._creation_mtime = time.time() - 20.0
104
        return trans, root, contents, sha1
105
1534.7.162 by Aaron Bentley
Handle failures creating/deleting the Limbo directory
106
    def test_existing_limbo(self):
107
        transform, root = self.get_transform()
2733.2.6 by Aaron Bentley
Make TreeTransform commits rollbackable
108
        limbo_name = transform._limbodir
109
        deletion_path = transform._deletiondir
1534.7.176 by abentley
Fixed up tests for Windows
110
        os.mkdir(pathjoin(limbo_name, 'hehe'))
1534.7.162 by Aaron Bentley
Handle failures creating/deleting the Limbo directory
111
        self.assertRaises(ImmortalLimbo, transform.apply)
112
        self.assertRaises(LockError, self.wt.unlock)
113
        self.assertRaises(ExistingLimbo, self.get_transform)
114
        self.assertRaises(LockError, self.wt.unlock)
1534.7.176 by abentley
Fixed up tests for Windows
115
        os.rmdir(pathjoin(limbo_name, 'hehe'))
1534.7.162 by Aaron Bentley
Handle failures creating/deleting the Limbo directory
116
        os.rmdir(limbo_name)
2733.2.6 by Aaron Bentley
Make TreeTransform commits rollbackable
117
        os.rmdir(deletion_path)
1534.7.162 by Aaron Bentley
Handle failures creating/deleting the Limbo directory
118
        transform, root = self.get_transform()
119
        transform.apply()
1534.7.59 by Aaron Bentley
Simplified tests
120
2733.2.11 by Aaron Bentley
Detect irregularities with the pending-deletion directory
121
    def test_existing_pending_deletion(self):
122
        transform, root = self.get_transform()
123
        deletion_path = self._limbodir = urlutils.local_path_from_url(
3407.2.8 by Martin Pool
Deprecate LockableFiles.controlfilename
124
            transform._tree._transport.abspath('pending-deletion'))
2733.2.11 by Aaron Bentley
Detect irregularities with the pending-deletion directory
125
        os.mkdir(pathjoin(deletion_path, 'blocking-directory'))
126
        self.assertRaises(ImmortalPendingDeletion, transform.apply)
127
        self.assertRaises(LockError, self.wt.unlock)
128
        self.assertRaises(ExistingPendingDeletion, self.get_transform)
129
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
130
    def test_build(self):
3034.2.1 by Aaron Bentley
Fix is_executable tests for win32
131
        transform, root = self.get_transform()
132
        self.wt.lock_tree_write()
133
        self.addCleanup(self.wt.unlock)
1534.7.59 by Aaron Bentley
Simplified tests
134
        self.assertIs(transform.get_tree_parent(root), ROOT_PARENT)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
135
        imaginary_id = transform.trans_id_tree_path('imaginary')
1534.10.32 by Aaron Bentley
Test and fix case where name has trailing slash
136
        imaginary_id2 = transform.trans_id_tree_path('imaginary/')
137
        self.assertEqual(imaginary_id, imaginary_id2)
4597.9.7 by Vincent Ladeuil
transform.final_kind() now returns None instead of raising NoSuchFile.
138
        self.assertEqual(root, transform.get_tree_parent(imaginary_id))
139
        self.assertEqual('directory', transform.final_kind(root))
140
        self.assertEqual(self.wt.get_root_id(), transform.final_file_id(root))
1534.7.59 by Aaron Bentley
Simplified tests
141
        trans_id = transform.create_path('name', root)
142
        self.assertIs(transform.final_file_id(trans_id), None)
4597.9.7 by Vincent Ladeuil
transform.final_kind() now returns None instead of raising NoSuchFile.
143
        self.assertIs(None, transform.final_kind(trans_id))
1534.7.59 by Aaron Bentley
Simplified tests
144
        transform.create_file('contents', trans_id)
145
        transform.set_executability(True, trans_id)
146
        transform.version_file('my_pretties', trans_id)
147
        self.assertRaises(DuplicateKey, transform.version_file,
148
                          'my_pretties', trans_id)
149
        self.assertEqual(transform.final_file_id(trans_id), 'my_pretties')
150
        self.assertEqual(transform.final_parent(trans_id), root)
151
        self.assertIs(transform.final_parent(root), ROOT_PARENT)
152
        self.assertIs(transform.get_tree_parent(root), ROOT_PARENT)
153
        oz_id = transform.create_path('oz', root)
154
        transform.create_directory(oz_id)
155
        transform.version_file('ozzie', oz_id)
156
        trans_id2 = transform.create_path('name2', root)
157
        transform.create_file('contents', trans_id2)
158
        transform.set_executability(False, trans_id2)
159
        transform.version_file('my_pretties2', trans_id2)
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
160
        modified_paths = transform.apply().modified_paths
1534.7.100 by Aaron Bentley
Fixed path-relative test cases
161
        self.assertEqual('contents', self.wt.get_file_byname('name').read())
1534.7.59 by Aaron Bentley
Simplified tests
162
        self.assertEqual(self.wt.path2id('name'), 'my_pretties')
163
        self.assertIs(self.wt.is_executable('my_pretties'), True)
164
        self.assertIs(self.wt.is_executable('my_pretties2'), False)
1534.7.100 by Aaron Bentley
Fixed path-relative test cases
165
        self.assertEqual('directory', file_kind(self.wt.abspath('oz')))
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
166
        self.assertEqual(len(modified_paths), 3)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
167
        tree_mod_paths = [self.wt.id2abspath(f) for f in
1534.7.191 by Aaron Bentley
Got transform.apply to list modified paths
168
                          ('ozzie', 'my_pretties', 'my_pretties2')]
169
        self.assertSubset(tree_mod_paths, modified_paths)
1534.7.1 by Aaron Bentley
Got creation of a versioned file working
170
        # is it safe to finalize repeatedly?
171
        transform.finalize()
1534.7.59 by Aaron Bentley
Simplified tests
172
        transform.finalize()
1534.7.2 by Aaron Bentley
Added convenience function
173
5752.3.6 by John Arbash Meinel
More direct tests of TreeTransform behavior wrt _observed_sha1s
174
    def test_apply_informs_tree_of_observed_sha1(self):
175
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
176
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
177
                                  sha1=sha1)
178
        calls = []
179
        orig = self.wt._observed_sha1
180
        def _observed_sha1(*args):
181
            calls.append(args)
182
            orig(*args)
183
        self.wt._observed_sha1 = _observed_sha1
184
        trans.apply()
185
        self.assertEqual([(None, 'file1', trans._observed_sha1s[trans_id])],
186
                         calls)
187
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
188
    def test_create_file_caches_sha1(self):
5752.3.5 by John Arbash Meinel
Refactor tests into a common helper.
189
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
190
        trans_id = trans.create_path('file1', root)
5752.3.5 by John Arbash Meinel
Refactor tests into a common helper.
191
        trans.create_file(contents, trans_id, sha1=sha1)
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
192
        st_val = osutils.lstat(trans._limbo_name(trans_id))
193
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
194
        self.assertEqual(o_sha1, sha1)
195
        self.assertEqualStat(o_st_val, st_val)
196
197
    def test__apply_insertions_updates_sha1(self):
5752.3.5 by John Arbash Meinel
Refactor tests into a common helper.
198
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
199
        trans_id = trans.create_path('file1', root)
5752.3.5 by John Arbash Meinel
Refactor tests into a common helper.
200
        trans.create_file(contents, trans_id, sha1=sha1)
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
201
        st_val = osutils.lstat(trans._limbo_name(trans_id))
202
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
203
        self.assertEqual(o_sha1, sha1)
204
        self.assertEqualStat(o_st_val, st_val)
5752.3.5 by John Arbash Meinel
Refactor tests into a common helper.
205
        creation_mtime = trans._creation_mtime + 10.0
5752.3.1 by John Arbash Meinel
Merge up from 2.4-windows-lfstat
206
        # We fake a time difference from when the file was created until now it
207
        # is being renamed by using os.utime. Note that the change we actually
208
        # want to see is the real ctime change from 'os.rename()', but as long
209
        # as we observe a new stat value, we should be fine.
210
        os.utime(trans._limbo_name(trans_id), (creation_mtime, creation_mtime))
211
        trans.apply()
212
        new_st_val = osutils.lstat(self.wt.abspath('file1'))
213
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
214
        self.assertEqual(o_sha1, sha1)
215
        self.assertEqualStat(o_st_val, new_st_val)
216
        self.assertNotEqual(st_val.st_mtime, new_st_val.st_mtime)
217
5752.3.4 by John Arbash Meinel
Add new_file(sha1=XXX) and pass that down to create_file.
218
    def test_new_file_caches_sha1(self):
5752.3.5 by John Arbash Meinel
Refactor tests into a common helper.
219
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
220
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
5752.3.4 by John Arbash Meinel
Add new_file(sha1=XXX) and pass that down to create_file.
221
                                  sha1=sha1)
222
        st_val = osutils.lstat(trans._limbo_name(trans_id))
223
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
224
        self.assertEqual(o_sha1, sha1)
225
        self.assertEqualStat(o_st_val, st_val)
226
5752.3.5 by John Arbash Meinel
Refactor tests into a common helper.
227
    def test_cancel_creation_removes_observed_sha1(self):
228
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
229
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
230
                                  sha1=sha1)
231
        self.assertTrue(trans_id in trans._observed_sha1s)
232
        trans.cancel_creation(trans_id)
233
        self.assertFalse(trans_id in trans._observed_sha1s)
234
4934.1.1 by John Arbash Meinel
Basic implementation for windows and bug #488724.
235
    def test_create_files_same_timestamp(self):
236
        transform, root = self.get_transform()
237
        self.wt.lock_tree_write()
238
        self.addCleanup(self.wt.unlock)
239
        # Roll back the clock, so that we know everything is being set to the
240
        # exact time
4934.1.10 by John Arbash Meinel
Rework the tests a bit.
241
        transform._creation_mtime = creation_mtime = time.time() - 20.0
4934.1.1 by John Arbash Meinel
Basic implementation for windows and bug #488724.
242
        transform.create_file('content-one',
243
                              transform.create_path('one', root))
244
        time.sleep(1) # *ugly*
245
        transform.create_file('content-two',
246
                              transform.create_path('two', root))
247
        transform.apply()
248
        fo, st1 = self.wt.get_file_with_stat(None, path='one', filtered=False)
249
        fo.close()
250
        fo, st2 = self.wt.get_file_with_stat(None, path='two', filtered=False)
251
        fo.close()
4934.2.2 by Martin
Rearrange osutils.fset_mtime tests a little and make them robust on FAT filesystems
252
        # We only guarantee 2s resolution
4934.1.11 by John Arbash Meinel
2 => 2.0 because it looks better.
253
        self.assertTrue(abs(creation_mtime - st1.st_mtime) < 2.0,
4934.1.10 by John Arbash Meinel
Rework the tests a bit.
254
            "%s != %s within 2 seconds" % (creation_mtime, st1.st_mtime))
4934.1.6 by John Arbash Meinel
It turns out that with os/python/C buffering, we need to flush
255
        # But if we have more than that, all files should get the same result
4934.1.1 by John Arbash Meinel
Basic implementation for windows and bug #488724.
256
        self.assertEqual(st1.st_mtime, st2.st_mtime)
257
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
258
    def test_change_root_id(self):
259
        transform, root = self.get_transform()
260
        self.assertNotEqual('new-root-id', self.wt.get_root_id())
261
        transform.new_directory('', ROOT_PARENT, 'new-root-id')
262
        transform.delete_contents(root)
263
        transform.unversion_file(root)
264
        transform.fixup_new_roots()
265
        transform.apply()
266
        self.assertEqual('new-root-id', self.wt.get_root_id())
267
268
    def test_change_root_id_add_files(self):
269
        transform, root = self.get_transform()
270
        self.assertNotEqual('new-root-id', self.wt.get_root_id())
271
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
272
        transform.new_file('file', new_trans_id, ['new-contents\n'],
273
                           'new-file-id')
274
        transform.delete_contents(root)
275
        transform.unversion_file(root)
276
        transform.fixup_new_roots()
277
        transform.apply()
278
        self.assertEqual('new-root-id', self.wt.get_root_id())
279
        self.assertEqual('new-file-id', self.wt.path2id('file'))
280
        self.assertFileEqual('new-contents\n', self.wt.abspath('file'))
281
282
    def test_add_two_roots(self):
283
        transform, root = self.get_transform()
284
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
285
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
286
        self.assertRaises(ValueError, transform.fixup_new_roots)
287
6011.1.1 by Aaron Bentley
Merging an unrelated tree retains root.
288
    def test_retain_existing_root(self):
289
        tt, root = self.get_transform()
290
        with tt:
291
            tt.new_directory('', ROOT_PARENT, 'new-root-id')
292
            tt.fixup_new_roots()
293
            self.assertNotEqual('new-root-id', tt.final_file_id(tt.root))
294
295
    def test_retain_existing_root_added_file(self):
296
        tt, root = self.get_transform()
297
        new_trans_id = tt.new_directory('', ROOT_PARENT, 'new-root-id')
298
        child = tt.new_directory('child', new_trans_id, 'child-id')
299
        tt.fixup_new_roots()
300
        self.assertEqual(tt.root, tt.final_parent(child))
301
5954.4.7 by Aaron Bentley
Add test for unversioned roots.
302
    def test_add_unversioned_root(self):
303
        transform, root = self.get_transform()
304
        new_trans_id = transform.new_directory('', ROOT_PARENT, None)
6011.1.1 by Aaron Bentley
Merging an unrelated tree retains root.
305
        transform.delete_contents(transform.root)
5954.4.7 by Aaron Bentley
Add test for unversioned roots.
306
        transform.fixup_new_roots()
5954.4.11 by Aaron Bentley
Eschew testtools.testcase.ExpectedException from too-new testtools.
307
        self.assertNotIn(transform.root, transform._new_id)
5954.4.7 by Aaron Bentley
Add test for unversioned roots.
308
5993.2.3 by Jelmer Vernooij
Update NEWS, consistently use require_tree_root as argument everywhere.
309
    def test_remove_root_fixup(self):
310
        transform, root = self.get_transform()
311
        old_root_id = self.wt.get_root_id()
312
        self.assertNotEqual('new-root-id', old_root_id)
313
        transform.delete_contents(root)
314
        transform.unversion_file(root)
5993.2.4 by Jelmer Vernooij
Remove feature flag.
315
        transform.fixup_new_roots()
5993.2.3 by Jelmer Vernooij
Update NEWS, consistently use require_tree_root as argument everywhere.
316
        transform.apply()
317
        self.assertEqual(old_root_id, self.wt.get_root_id())
318
319
        transform, root = self.get_transform()
320
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
321
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
322
        self.assertRaises(ValueError, transform.fixup_new_roots)
323
6024.1.1 by Aaron Bentley
Move empty-tree prevention into TreeTransform.apply.
324
    def test_fixup_new_roots_permits_empty_tree(self):
325
        transform, root = self.get_transform()
326
        transform.delete_contents(root)
327
        transform.unversion_file(root)
328
        transform.fixup_new_roots()
329
        self.assertIs(None, transform.final_kind(root))
330
        self.assertIs(None, transform.final_file_id(root))
331
5954.4.1 by Aaron Bentley
Never attempt to delete the tree root.
332
    def test_apply_retains_root_directory(self):
333
        # Do not attempt to delete the physical root directory, because that
334
        # is impossible.
335
        transform, root = self.get_transform()
336
        with transform:
337
            transform.delete_contents(root)
5954.4.12 by Aaron Bentley
Eschew more ExpectedException.
338
            e = self.assertRaises(AssertionError, self.assertRaises,
339
                                  errors.TransformRenameFailed,
340
                                  transform.apply)
341
        self.assertContainsRe('TransformRenameFailed not raised', str(e))
5954.4.1 by Aaron Bentley
Never attempt to delete the tree root.
342
6024.1.1 by Aaron Bentley
Move empty-tree prevention into TreeTransform.apply.
343
    def test_apply_retains_file_id(self):
344
        transform, root = self.get_transform()
345
        old_root_id = transform.tree_file_id(root)
346
        transform.unversion_file(root)
347
        transform.apply()
348
        self.assertEqual(old_root_id, self.wt.get_root_id())
349
3136.1.1 by Aaron Bentley
Add support for hardlinks to TreeTransform
350
    def test_hardlink(self):
351
        self.requireFeature(HardlinkFeature)
352
        transform, root = self.get_transform()
353
        transform.new_file('file1', root, 'contents')
354
        transform.apply()
355
        target = self.make_branch_and_tree('target')
356
        target_transform = TreeTransform(target)
357
        trans_id = target_transform.create_path('file1', target_transform.root)
358
        target_transform.create_hardlink(self.wt.abspath('file1'), trans_id)
359
        target_transform.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
360
        self.assertPathExists('target/file1')
3136.1.1 by Aaron Bentley
Add support for hardlinks to TreeTransform
361
        source_stat = os.stat(self.wt.abspath('file1'))
362
        target_stat = os.stat('target/file1')
363
        self.assertEqual(source_stat, target_stat)
364
1534.7.2 by Aaron Bentley
Added convenience function
365
    def test_convenience(self):
1534.7.59 by Aaron Bentley
Simplified tests
366
        transform, root = self.get_transform()
3034.2.1 by Aaron Bentley
Fix is_executable tests for win32
367
        self.wt.lock_tree_write()
368
        self.addCleanup(self.wt.unlock)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
369
        trans_id = transform.new_file('name', root, 'contents',
1534.7.59 by Aaron Bentley
Simplified tests
370
                                      'my_pretties', True)
371
        oz = transform.new_directory('oz', root, 'oz-id')
372
        dorothy = transform.new_directory('dorothy', oz, 'dorothy-id')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
373
        toto = transform.new_file('toto', dorothy, 'toto-contents',
1534.7.59 by Aaron Bentley
Simplified tests
374
                                  'toto-id', False)
375
376
        self.assertEqual(len(transform.find_conflicts()), 0)
377
        transform.apply()
378
        self.assertRaises(ReusingTransform, transform.find_conflicts)
1534.7.100 by Aaron Bentley
Fixed path-relative test cases
379
        self.assertEqual('contents', file(self.wt.abspath('name')).read())
1534.7.59 by Aaron Bentley
Simplified tests
380
        self.assertEqual(self.wt.path2id('name'), 'my_pretties')
381
        self.assertIs(self.wt.is_executable('my_pretties'), True)
382
        self.assertEqual(self.wt.path2id('oz'), 'oz-id')
383
        self.assertEqual(self.wt.path2id('oz/dorothy'), 'dorothy-id')
384
        self.assertEqual(self.wt.path2id('oz/dorothy/toto'), 'toto-id')
385
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
386
        self.assertEqual('toto-contents',
1534.7.100 by Aaron Bentley
Fixed path-relative test cases
387
                         self.wt.get_file_byname('oz/dorothy/toto').read())
1534.7.59 by Aaron Bentley
Simplified tests
388
        self.assertIs(self.wt.is_executable('toto-id'), False)
1534.7.6 by Aaron Bentley
Added conflict handling
389
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
390
    def test_tree_reference(self):
391
        transform, root = self.get_transform()
392
        tree = transform._tree
393
        trans_id = transform.new_directory('reference', root, 'subtree-id')
394
        transform.set_tree_reference('subtree-revision', trans_id)
395
        transform.apply()
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
396
        tree.lock_read()
397
        self.addCleanup(tree.unlock)
398
        self.assertEqual('subtree-revision',
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
399
                         tree.inventory['subtree-id'].reference_revision)
400
1534.7.6 by Aaron Bentley
Added conflict handling
401
    def test_conflicts(self):
1534.7.59 by Aaron Bentley
Simplified tests
402
        transform, root = self.get_transform()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
403
        trans_id = transform.new_file('name', root, 'contents',
1534.7.59 by Aaron Bentley
Simplified tests
404
                                      'my_pretties')
405
        self.assertEqual(len(transform.find_conflicts()), 0)
406
        trans_id2 = transform.new_file('name', root, 'Crontents', 'toto')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
407
        self.assertEqual(transform.find_conflicts(),
1534.7.59 by Aaron Bentley
Simplified tests
408
                         [('duplicate', trans_id, trans_id2, 'name')])
409
        self.assertRaises(MalformedTransform, transform.apply)
410
        transform.adjust_path('name', trans_id, trans_id2)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
411
        self.assertEqual(transform.find_conflicts(),
1534.7.59 by Aaron Bentley
Simplified tests
412
                         [('non-directory parent', trans_id)])
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
413
        tinman_id = transform.trans_id_tree_path('tinman')
1534.7.59 by Aaron Bentley
Simplified tests
414
        transform.adjust_path('name', tinman_id, trans_id2)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
415
        self.assertEqual(transform.find_conflicts(),
416
                         [('unversioned parent', tinman_id),
1534.7.59 by Aaron Bentley
Simplified tests
417
                          ('missing parent', tinman_id)])
418
        lion_id = transform.create_path('lion', root)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
419
        self.assertEqual(transform.find_conflicts(),
420
                         [('unversioned parent', tinman_id),
1534.7.59 by Aaron Bentley
Simplified tests
421
                          ('missing parent', tinman_id)])
422
        transform.adjust_path('name', lion_id, trans_id2)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
423
        self.assertEqual(transform.find_conflicts(),
1534.7.59 by Aaron Bentley
Simplified tests
424
                         [('unversioned parent', lion_id),
425
                          ('missing parent', lion_id)])
426
        transform.version_file("Courage", lion_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
427
        self.assertEqual(transform.find_conflicts(),
428
                         [('missing parent', lion_id),
1534.7.59 by Aaron Bentley
Simplified tests
429
                          ('versioning no contents', lion_id)])
430
        transform.adjust_path('name2', root, trans_id2)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
431
        self.assertEqual(transform.find_conflicts(),
1534.7.59 by Aaron Bentley
Simplified tests
432
                         [('versioning no contents', lion_id)])
433
        transform.create_file('Contents, okay?', lion_id)
434
        transform.adjust_path('name2', trans_id2, trans_id2)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
435
        self.assertEqual(transform.find_conflicts(),
436
                         [('parent loop', trans_id2),
1534.7.59 by Aaron Bentley
Simplified tests
437
                          ('non-directory parent', trans_id2)])
438
        transform.adjust_path('name2', root, trans_id2)
439
        oz_id = transform.new_directory('oz', root)
440
        transform.set_executability(True, oz_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
441
        self.assertEqual(transform.find_conflicts(),
1534.7.59 by Aaron Bentley
Simplified tests
442
                         [('unversioned executability', oz_id)])
443
        transform.version_file('oz-id', oz_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
444
        self.assertEqual(transform.find_conflicts(),
1534.7.59 by Aaron Bentley
Simplified tests
445
                         [('non-file executability', oz_id)])
446
        transform.set_executability(None, oz_id)
1534.7.71 by abentley
All tests pass under Windows
447
        tip_id = transform.new_file('tip', oz_id, 'ozma', 'tip-id')
1534.7.59 by Aaron Bentley
Simplified tests
448
        transform.apply()
449
        self.assertEqual(self.wt.path2id('name'), 'my_pretties')
450
        self.assertEqual('contents', file(self.wt.abspath('name')).read())
451
        transform2, root = self.get_transform()
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
452
        oz_id = transform2.trans_id_tree_file_id('oz-id')
1534.7.59 by Aaron Bentley
Simplified tests
453
        newtip = transform2.new_file('tip', oz_id, 'other', 'tip-id')
454
        result = transform2.find_conflicts()
1534.7.135 by Aaron Bentley
Fixed deletion handling
455
        fp = FinalPaths(transform2)
1534.7.59 by Aaron Bentley
Simplified tests
456
        self.assert_('oz/tip' in transform2._tree_path_ids)
1534.7.176 by abentley
Fixed up tests for Windows
457
        self.assertEqual(fp.get_path(newtip), pathjoin('oz', 'tip'))
1534.7.59 by Aaron Bentley
Simplified tests
458
        self.assertEqual(len(result), 2)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
459
        self.assertEqual((result[0][0], result[0][1]),
1534.7.59 by Aaron Bentley
Simplified tests
460
                         ('duplicate', newtip))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
461
        self.assertEqual((result[1][0], result[1][2]),
1534.7.59 by Aaron Bentley
Simplified tests
462
                         ('duplicate id', newtip))
1534.7.73 by Aaron Bentley
Changed model again. Now iterator is used immediately.
463
        transform2.finalize()
1534.7.59 by Aaron Bentley
Simplified tests
464
        transform3 = TreeTransform(self.wt)
465
        self.addCleanup(transform3.finalize)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
466
        oz_id = transform3.trans_id_tree_file_id('oz-id')
1534.7.59 by Aaron Bentley
Simplified tests
467
        transform3.delete_contents(oz_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
468
        self.assertEqual(transform3.find_conflicts(),
1534.7.59 by Aaron Bentley
Simplified tests
469
                         [('missing parent', oz_id)])
1731.1.33 by Aaron Bentley
Revert no-special-root changes
470
        root_id = transform3.root
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
471
        tip_id = transform3.trans_id_tree_file_id('tip-id')
1534.7.59 by Aaron Bentley
Simplified tests
472
        transform3.adjust_path('tip', root_id, tip_id)
473
        transform3.apply()
1534.7.36 by Aaron Bentley
Added rename tests
474
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
475
    def test_conflict_on_case_insensitive(self):
476
        tree = self.make_branch_and_tree('tree')
477
        # Don't try this at home, kids!
478
        # Force the tree to report that it is case sensitive, for conflict
479
        # resolution tests
480
        tree.case_sensitive = True
481
        transform = TreeTransform(tree)
482
        self.addCleanup(transform.finalize)
483
        transform.new_file('file', transform.root, 'content')
484
        transform.new_file('FiLe', transform.root, 'content')
485
        result = transform.find_conflicts()
486
        self.assertEqual([], result)
3008.1.15 by Aaron Bentley
Make case_sensitive an aspect of the transform, not the source tree
487
        transform.finalize()
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
488
        # Force the tree to report that it is case insensitive, for conflict
489
        # generation tests
490
        tree.case_sensitive = False
3008.1.15 by Aaron Bentley
Make case_sensitive an aspect of the transform, not the source tree
491
        transform = TreeTransform(tree)
492
        self.addCleanup(transform.finalize)
493
        transform.new_file('file', transform.root, 'content')
494
        transform.new_file('FiLe', transform.root, 'content')
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
495
        result = transform.find_conflicts()
496
        self.assertEqual([('duplicate', 'new-1', 'new-2', 'file')], result)
497
3034.4.7 by Aaron Bentley
Add test for filename conflicts with existing files
498
    def test_conflict_on_case_insensitive_existing(self):
499
        tree = self.make_branch_and_tree('tree')
500
        self.build_tree(['tree/FiLe'])
501
        # Don't try this at home, kids!
502
        # Force the tree to report that it is case sensitive, for conflict
503
        # resolution tests
504
        tree.case_sensitive = True
505
        transform = TreeTransform(tree)
506
        self.addCleanup(transform.finalize)
507
        transform.new_file('file', transform.root, 'content')
508
        result = transform.find_conflicts()
509
        self.assertEqual([], result)
3008.1.15 by Aaron Bentley
Make case_sensitive an aspect of the transform, not the source tree
510
        transform.finalize()
3034.4.7 by Aaron Bentley
Add test for filename conflicts with existing files
511
        # Force the tree to report that it is case insensitive, for conflict
512
        # generation tests
513
        tree.case_sensitive = False
3008.1.15 by Aaron Bentley
Make case_sensitive an aspect of the transform, not the source tree
514
        transform = TreeTransform(tree)
515
        self.addCleanup(transform.finalize)
516
        transform.new_file('file', transform.root, 'content')
3034.4.7 by Aaron Bentley
Add test for filename conflicts with existing files
517
        result = transform.find_conflicts()
518
        self.assertEqual([('duplicate', 'new-1', 'new-2', 'file')], result)
519
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
520
    def test_resolve_case_insensitive_conflict(self):
521
        tree = self.make_branch_and_tree('tree')
522
        # Don't try this at home, kids!
523
        # Force the tree to report that it is case insensitive, for conflict
524
        # resolution tests
525
        tree.case_sensitive = False
526
        transform = TreeTransform(tree)
527
        self.addCleanup(transform.finalize)
528
        transform.new_file('file', transform.root, 'content')
529
        transform.new_file('FiLe', transform.root, 'content')
530
        resolve_conflicts(transform)
531
        transform.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
532
        self.assertPathExists('tree/file')
533
        self.assertPathExists('tree/FiLe.moved')
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
534
3034.4.2 by Aaron Bentley
Get conflict handling and case-insensitive tree creation under test
535
    def test_resolve_checkout_case_conflict(self):
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
536
        tree = self.make_branch_and_tree('tree')
537
        # Don't try this at home, kids!
538
        # Force the tree to report that it is case insensitive, for conflict
539
        # resolution tests
540
        tree.case_sensitive = False
541
        transform = TreeTransform(tree)
542
        self.addCleanup(transform.finalize)
543
        transform.new_file('file', transform.root, 'content')
544
        transform.new_file('FiLe', transform.root, 'content')
3034.4.2 by Aaron Bentley
Get conflict handling and case-insensitive tree creation under test
545
        resolve_conflicts(transform,
546
                          pass_func=lambda t, c: resolve_checkout(t, c, []))
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
547
        transform.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
548
        self.assertPathExists('tree/file')
549
        self.assertPathExists('tree/FiLe.moved')
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
550
3034.4.2 by Aaron Bentley
Get conflict handling and case-insensitive tree creation under test
551
    def test_apply_case_conflict(self):
3034.4.6 by Aaron Bentley
Update apply_case_conflict tests
552
        """Ensure that a transform with case conflicts can always be applied"""
3034.4.2 by Aaron Bentley
Get conflict handling and case-insensitive tree creation under test
553
        tree = self.make_branch_and_tree('tree')
554
        transform = TreeTransform(tree)
555
        self.addCleanup(transform.finalize)
556
        transform.new_file('file', transform.root, 'content')
557
        transform.new_file('FiLe', transform.root, 'content')
3034.4.6 by Aaron Bentley
Update apply_case_conflict tests
558
        dir = transform.new_directory('dir', transform.root)
559
        transform.new_file('dirfile', dir, 'content')
560
        transform.new_file('dirFiLe', dir, 'content')
561
        resolve_conflicts(transform)
3034.4.2 by Aaron Bentley
Get conflict handling and case-insensitive tree creation under test
562
        transform.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
563
        self.assertPathExists('tree/file')
3034.4.3 by Aaron Bentley
Add case-sensitivity handling to WorkingTree
564
        if not os.path.exists('tree/FiLe.moved'):
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
565
            self.assertPathExists('tree/FiLe')
566
        self.assertPathExists('tree/dir/dirfile')
3034.4.6 by Aaron Bentley
Update apply_case_conflict tests
567
        if not os.path.exists('tree/dir/dirFiLe.moved'):
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
568
            self.assertPathExists('tree/dir/dirFiLe')
3034.4.2 by Aaron Bentley
Get conflict handling and case-insensitive tree creation under test
569
3034.4.1 by Aaron Bentley
Start handling case-insensitivity
570
    def test_case_insensitive_limbo(self):
571
        tree = self.make_branch_and_tree('tree')
572
        # Don't try this at home, kids!
573
        # Force the tree to report that it is case insensitive
574
        tree.case_sensitive = False
575
        transform = TreeTransform(tree)
576
        self.addCleanup(transform.finalize)
577
        dir = transform.new_directory('dir', transform.root)
578
        first = transform.new_file('file', dir, 'content')
579
        second = transform.new_file('FiLe', dir, 'content')
580
        self.assertContainsRe(transform._limbo_name(first), 'new-1/file')
581
        self.assertNotContainsRe(transform._limbo_name(second), 'new-1/FiLe')
582
4634.78.1 by Aaron Bentley
adjust_path updatest limbo paths.
583
    def test_adjust_path_updates_child_limbo_names(self):
584
        tree = self.make_branch_and_tree('tree')
585
        transform = TreeTransform(tree)
586
        self.addCleanup(transform.finalize)
587
        foo_id = transform.new_directory('foo', transform.root)
588
        bar_id = transform.new_directory('bar', foo_id)
589
        baz_id = transform.new_directory('baz', bar_id)
590
        qux_id = transform.new_directory('qux', baz_id)
591
        transform.adjust_path('quxx', foo_id, bar_id)
592
        self.assertStartsWith(transform._limbo_name(qux_id),
593
                              transform._limbo_name(bar_id))
594
1558.7.11 by Aaron Bentley
Avoid spurious conflict on add/delete
595
    def test_add_del(self):
596
        start, root = self.get_transform()
597
        start.new_directory('a', root, 'a')
598
        start.apply()
599
        transform, root = self.get_transform()
600
        transform.delete_versioned(transform.trans_id_tree_file_id('a'))
601
        transform.new_directory('a', root, 'a')
602
        transform.apply()
603
1534.7.46 by Aaron Bentley
Ensured a conflict when parents of versioned files are unversioned
604
    def test_unversioning(self):
1534.7.59 by Aaron Bentley
Simplified tests
605
        create_tree, root = self.get_transform()
606
        parent_id = create_tree.new_directory('parent', root, 'parent-id')
607
        create_tree.new_file('child', parent_id, 'child', 'child-id')
608
        create_tree.apply()
609
        unversion = TreeTransform(self.wt)
610
        self.addCleanup(unversion.finalize)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
611
        parent = unversion.trans_id_tree_path('parent')
1534.7.59 by Aaron Bentley
Simplified tests
612
        unversion.unversion_file(parent)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
613
        self.assertEqual(unversion.find_conflicts(),
1534.7.59 by Aaron Bentley
Simplified tests
614
                         [('unversioned parent', parent_id)])
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
615
        file_id = unversion.trans_id_tree_file_id('child-id')
1534.7.59 by Aaron Bentley
Simplified tests
616
        unversion.unversion_file(file_id)
617
        unversion.apply()
1534.7.46 by Aaron Bentley
Ensured a conflict when parents of versioned files are unversioned
618
1534.7.36 by Aaron Bentley
Added rename tests
619
    def test_name_invariants(self):
1534.7.59 by Aaron Bentley
Simplified tests
620
        create_tree, root = self.get_transform()
621
        # prepare tree
1731.1.33 by Aaron Bentley
Revert no-special-root changes
622
        root = create_tree.root
1534.7.59 by Aaron Bentley
Simplified tests
623
        create_tree.new_file('name1', root, 'hello1', 'name1')
624
        create_tree.new_file('name2', root, 'hello2', 'name2')
625
        ddir = create_tree.new_directory('dying_directory', root, 'ddir')
626
        create_tree.new_file('dying_file', ddir, 'goodbye1', 'dfile')
627
        create_tree.new_file('moving_file', ddir, 'later1', 'mfile')
628
        create_tree.new_file('moving_file2', root, 'later2', 'mfile2')
629
        create_tree.apply()
630
631
        mangle_tree,root = self.get_transform()
1731.1.33 by Aaron Bentley
Revert no-special-root changes
632
        root = mangle_tree.root
1534.7.59 by Aaron Bentley
Simplified tests
633
        #swap names
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
634
        name1 = mangle_tree.trans_id_tree_file_id('name1')
635
        name2 = mangle_tree.trans_id_tree_file_id('name2')
1534.7.59 by Aaron Bentley
Simplified tests
636
        mangle_tree.adjust_path('name2', root, name1)
637
        mangle_tree.adjust_path('name1', root, name2)
638
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
639
        #tests for deleting parent directories
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
640
        ddir = mangle_tree.trans_id_tree_file_id('ddir')
1534.7.59 by Aaron Bentley
Simplified tests
641
        mangle_tree.delete_contents(ddir)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
642
        dfile = mangle_tree.trans_id_tree_file_id('dfile')
1534.7.59 by Aaron Bentley
Simplified tests
643
        mangle_tree.delete_versioned(dfile)
644
        mangle_tree.unversion_file(dfile)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
645
        mfile = mangle_tree.trans_id_tree_file_id('mfile')
1534.7.59 by Aaron Bentley
Simplified tests
646
        mangle_tree.adjust_path('mfile', root, mfile)
647
648
        #tests for adding parent directories
649
        newdir = mangle_tree.new_directory('new_directory', root, 'newdir')
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
650
        mfile2 = mangle_tree.trans_id_tree_file_id('mfile2')
1534.7.59 by Aaron Bentley
Simplified tests
651
        mangle_tree.adjust_path('mfile2', newdir, mfile2)
652
        mangle_tree.new_file('newfile', newdir, 'hello3', 'dfile')
653
        self.assertEqual(mangle_tree.final_file_id(mfile2), 'mfile2')
654
        self.assertEqual(mangle_tree.final_parent(mfile2), newdir)
655
        self.assertEqual(mangle_tree.final_file_id(mfile2), 'mfile2')
656
        mangle_tree.apply()
657
        self.assertEqual(file(self.wt.abspath('name1')).read(), 'hello2')
658
        self.assertEqual(file(self.wt.abspath('name2')).read(), 'hello1')
1534.7.176 by abentley
Fixed up tests for Windows
659
        mfile2_path = self.wt.abspath(pathjoin('new_directory','mfile2'))
1534.7.41 by Aaron Bentley
Got inventory ID movement working
660
        self.assertEqual(mangle_tree.final_parent(mfile2), newdir)
1534.7.38 by Aaron Bentley
Tested adding paths
661
        self.assertEqual(file(mfile2_path).read(), 'later2')
1534.7.59 by Aaron Bentley
Simplified tests
662
        self.assertEqual(self.wt.id2path('mfile2'), 'new_directory/mfile2')
663
        self.assertEqual(self.wt.path2id('new_directory/mfile2'), 'mfile2')
1534.7.176 by abentley
Fixed up tests for Windows
664
        newfile_path = self.wt.abspath(pathjoin('new_directory','newfile'))
1534.7.38 by Aaron Bentley
Tested adding paths
665
        self.assertEqual(file(newfile_path).read(), 'hello3')
1534.7.59 by Aaron Bentley
Simplified tests
666
        self.assertEqual(self.wt.path2id('dying_directory'), 'ddir')
667
        self.assertIs(self.wt.path2id('dying_directory/dying_file'), None)
1534.7.176 by abentley
Fixed up tests for Windows
668
        mfile2_path = self.wt.abspath(pathjoin('new_directory','mfile2'))
1534.7.43 by abentley
Fixed some Windows bugs, introduced a conflicts bug
669
1534.7.150 by Aaron Bentley
Handled simultaneous renames of parent and child better
670
    def test_both_rename(self):
671
        create_tree,root = self.get_transform()
672
        newdir = create_tree.new_directory('selftest', root, 'selftest-id')
673
        create_tree.new_file('blackbox.py', newdir, 'hello1', 'blackbox-id')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
674
        create_tree.apply()
1534.7.150 by Aaron Bentley
Handled simultaneous renames of parent and child better
675
        mangle_tree,root = self.get_transform()
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
676
        selftest = mangle_tree.trans_id_tree_file_id('selftest-id')
677
        blackbox = mangle_tree.trans_id_tree_file_id('blackbox-id')
1534.7.150 by Aaron Bentley
Handled simultaneous renames of parent and child better
678
        mangle_tree.adjust_path('test', root, selftest)
679
        mangle_tree.adjust_path('test_too_much', root, selftest)
680
        mangle_tree.set_executability(True, blackbox)
681
        mangle_tree.apply()
682
683
    def test_both_rename2(self):
684
        create_tree,root = self.get_transform()
685
        bzrlib = create_tree.new_directory('bzrlib', root, 'bzrlib-id')
686
        tests = create_tree.new_directory('tests', bzrlib, 'tests-id')
687
        blackbox = create_tree.new_directory('blackbox', tests, 'blackbox-id')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
688
        create_tree.new_file('test_too_much.py', blackbox, 'hello1',
1534.7.150 by Aaron Bentley
Handled simultaneous renames of parent and child better
689
                             'test_too_much-id')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
690
        create_tree.apply()
1534.7.150 by Aaron Bentley
Handled simultaneous renames of parent and child better
691
        mangle_tree,root = self.get_transform()
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
692
        bzrlib = mangle_tree.trans_id_tree_file_id('bzrlib-id')
693
        tests = mangle_tree.trans_id_tree_file_id('tests-id')
694
        test_too_much = mangle_tree.trans_id_tree_file_id('test_too_much-id')
1534.7.150 by Aaron Bentley
Handled simultaneous renames of parent and child better
695
        mangle_tree.adjust_path('selftest', bzrlib, tests)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
696
        mangle_tree.adjust_path('blackbox.py', tests, test_too_much)
1534.7.150 by Aaron Bentley
Handled simultaneous renames of parent and child better
697
        mangle_tree.set_executability(True, test_too_much)
698
        mangle_tree.apply()
699
700
    def test_both_rename3(self):
701
        create_tree,root = self.get_transform()
702
        tests = create_tree.new_directory('tests', root, 'tests-id')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
703
        create_tree.new_file('test_too_much.py', tests, 'hello1',
1534.7.150 by Aaron Bentley
Handled simultaneous renames of parent and child better
704
                             'test_too_much-id')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
705
        create_tree.apply()
1534.7.150 by Aaron Bentley
Handled simultaneous renames of parent and child better
706
        mangle_tree,root = self.get_transform()
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
707
        tests = mangle_tree.trans_id_tree_file_id('tests-id')
708
        test_too_much = mangle_tree.trans_id_tree_file_id('test_too_much-id')
1534.7.150 by Aaron Bentley
Handled simultaneous renames of parent and child better
709
        mangle_tree.adjust_path('selftest', root, tests)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
710
        mangle_tree.adjust_path('blackbox.py', tests, test_too_much)
1534.7.150 by Aaron Bentley
Handled simultaneous renames of parent and child better
711
        mangle_tree.set_executability(True, test_too_much)
712
        mangle_tree.apply()
713
1534.7.48 by Aaron Bentley
Ensured we can move/rename dangling inventory entries
714
    def test_move_dangling_ie(self):
1534.7.59 by Aaron Bentley
Simplified tests
715
        create_tree, root = self.get_transform()
716
        # prepare tree
1731.1.33 by Aaron Bentley
Revert no-special-root changes
717
        root = create_tree.root
1534.7.59 by Aaron Bentley
Simplified tests
718
        create_tree.new_file('name1', root, 'hello1', 'name1')
719
        create_tree.apply()
720
        delete_contents, root = self.get_transform()
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
721
        file = delete_contents.trans_id_tree_file_id('name1')
1534.7.59 by Aaron Bentley
Simplified tests
722
        delete_contents.delete_contents(file)
723
        delete_contents.apply()
724
        move_id, root = self.get_transform()
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
725
        name1 = move_id.trans_id_tree_file_id('name1')
1534.7.59 by Aaron Bentley
Simplified tests
726
        newdir = move_id.new_directory('dir', root, 'newdir')
727
        move_id.adjust_path('name2', newdir, name1)
728
        move_id.apply()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
729
1534.7.50 by Aaron Bentley
Detect duplicate inventory ids
730
    def test_replace_dangling_ie(self):
1534.7.59 by Aaron Bentley
Simplified tests
731
        create_tree, root = self.get_transform()
732
        # prepare tree
1731.1.33 by Aaron Bentley
Revert no-special-root changes
733
        root = create_tree.root
1534.7.59 by Aaron Bentley
Simplified tests
734
        create_tree.new_file('name1', root, 'hello1', 'name1')
735
        create_tree.apply()
736
        delete_contents = TreeTransform(self.wt)
737
        self.addCleanup(delete_contents.finalize)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
738
        file = delete_contents.trans_id_tree_file_id('name1')
1534.7.59 by Aaron Bentley
Simplified tests
739
        delete_contents.delete_contents(file)
740
        delete_contents.apply()
741
        delete_contents.finalize()
742
        replace = TreeTransform(self.wt)
743
        self.addCleanup(replace.finalize)
744
        name2 = replace.new_file('name2', root, 'hello2', 'name1')
745
        conflicts = replace.find_conflicts()
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
746
        name1 = replace.trans_id_tree_file_id('name1')
1534.7.59 by Aaron Bentley
Simplified tests
747
        self.assertEqual(conflicts, [('duplicate id', name1, name2)])
748
        resolve_conflicts(replace)
749
        replace.apply()
1534.7.48 by Aaron Bentley
Ensured we can move/rename dangling inventory entries
750
4241.14.17 by Vincent Ladeuil
Add more tests for unicode symlinks to test_transform.
751
    def _test_symlinks(self, link_name1,link_target1,
752
                       link_name2, link_target2):
753
754
        def ozpath(p): return 'oz/' + p
755
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
756
        self.requireFeature(SymlinkFeature)
4241.14.12 by Vincent Ladeuil
Far too many modifications for a single commit, need to restart.
757
        transform, root = self.get_transform()
1534.7.59 by Aaron Bentley
Simplified tests
758
        oz_id = transform.new_directory('oz', root, 'oz-id')
4241.14.17 by Vincent Ladeuil
Add more tests for unicode symlinks to test_transform.
759
        wizard = transform.new_symlink(link_name1, oz_id, link_target1,
1534.7.59 by Aaron Bentley
Simplified tests
760
                                       'wizard-id')
4241.14.17 by Vincent Ladeuil
Add more tests for unicode symlinks to test_transform.
761
        wiz_id = transform.create_path(link_name2, oz_id)
762
        transform.create_symlink(link_target2, wiz_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
763
        transform.version_file('wiz-id2', wiz_id)
1534.7.71 by abentley
All tests pass under Windows
764
        transform.set_executability(True, wiz_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
765
        self.assertEqual(transform.find_conflicts(),
1534.7.71 by abentley
All tests pass under Windows
766
                         [('non-file executability', wiz_id)])
767
        transform.set_executability(None, wiz_id)
1534.7.59 by Aaron Bentley
Simplified tests
768
        transform.apply()
4241.14.17 by Vincent Ladeuil
Add more tests for unicode symlinks to test_transform.
769
        self.assertEqual(self.wt.path2id(ozpath(link_name1)), 'wizard-id')
770
        self.assertEqual('symlink',
771
                         file_kind(self.wt.abspath(ozpath(link_name1))))
772
        self.assertEqual(link_target2,
773
                         osutils.readlink(self.wt.abspath(ozpath(link_name2))))
774
        self.assertEqual(link_target1,
775
                         osutils.readlink(self.wt.abspath(ozpath(link_name1))))
776
777
    def test_symlinks(self):
778
        self._test_symlinks('wizard', 'wizard-target',
779
                            'wizard2', 'behind_curtain')
780
781
    def test_symlinks_unicode(self):
782
        self.requireFeature(tests.UnicodeFilenameFeature)
783
        self._test_symlinks(u'\N{Euro Sign}wizard',
784
                            u'wizard-targ\N{Euro Sign}t',
785
                            u'\N{Euro Sign}wizard2',
786
                            u'b\N{Euro Sign}hind_curtain')
1534.7.60 by Aaron Bentley
Tested existing conflict resolution functionality
787
3006.2.2 by Alexander Belchenko
tests added.
788
    def test_unable_create_symlink(self):
789
        def tt_helper():
790
            wt = self.make_branch_and_tree('.')
791
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
792
            try:
793
                tt.new_symlink('foo', tt.root, 'bar')
794
                tt.apply()
795
            finally:
796
                wt.unlock()
797
        os_symlink = getattr(os, 'symlink', None)
798
        os.symlink = None
799
        try:
800
            err = self.assertRaises(errors.UnableCreateSymlink, tt_helper)
801
            self.assertEquals(
802
                "Unable to create symlink 'foo' on this platform",
803
                str(err))
804
        finally:
805
            if os_symlink:
806
                os.symlink = os_symlink
807
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
808
    def get_conflicted(self):
1534.7.60 by Aaron Bentley
Tested existing conflict resolution functionality
809
        create,root = self.get_transform()
810
        create.new_file('dorothy', root, 'dorothy', 'dorothy-id')
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
811
        oz = create.new_directory('oz', root, 'oz-id')
812
        create.new_directory('emeraldcity', oz, 'emerald-id')
1534.7.60 by Aaron Bentley
Tested existing conflict resolution functionality
813
        create.apply()
814
        conflicts,root = self.get_transform()
1534.7.65 by Aaron Bentley
Text cleaup/docs
815
        # set up duplicate entry, duplicate id
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
816
        new_dorothy = conflicts.new_file('dorothy', root, 'dorothy',
1534.7.60 by Aaron Bentley
Tested existing conflict resolution functionality
817
                                         'dorothy-id')
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
818
        old_dorothy = conflicts.trans_id_tree_file_id('dorothy-id')
819
        oz = conflicts.trans_id_tree_file_id('oz-id')
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
820
        # set up DeletedParent parent conflict
1534.7.65 by Aaron Bentley
Text cleaup/docs
821
        conflicts.delete_versioned(oz)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
822
        emerald = conflicts.trans_id_tree_file_id('emerald-id')
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
823
        # set up MissingParent conflict
824
        munchkincity = conflicts.trans_id_file_id('munchkincity-id')
825
        conflicts.adjust_path('munchkincity', root, munchkincity)
826
        conflicts.new_directory('auntem', munchkincity, 'auntem-id')
1534.7.65 by Aaron Bentley
Text cleaup/docs
827
        # set up parent loop
1534.7.61 by Aaron Bentley
Handled parent loops, missing parents, unversioned parents
828
        conflicts.adjust_path('emeraldcity', emerald, emerald)
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
829
        return conflicts, emerald, oz, old_dorothy, new_dorothy
830
831
    def test_conflict_resolution(self):
832
        conflicts, emerald, oz, old_dorothy, new_dorothy =\
833
            self.get_conflicted()
1534.7.60 by Aaron Bentley
Tested existing conflict resolution functionality
834
        resolve_conflicts(conflicts)
835
        self.assertEqual(conflicts.final_name(old_dorothy), 'dorothy.moved')
836
        self.assertIs(conflicts.final_file_id(old_dorothy), None)
837
        self.assertEqual(conflicts.final_name(new_dorothy), 'dorothy')
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
838
        self.assertEqual(conflicts.final_file_id(new_dorothy), 'dorothy-id')
1534.7.64 by Aaron Bentley
Extra testing
839
        self.assertEqual(conflicts.final_parent(emerald), oz)
1534.7.63 by Aaron Bentley
Ensure transform can be applied after resolution
840
        conflicts.apply()
1534.7.62 by Aaron Bentley
Fixed moving versioned directories
841
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
842
    def test_cook_conflicts(self):
843
        tt, emerald, oz, old_dorothy, new_dorothy = self.get_conflicted()
844
        raw_conflicts = resolve_conflicts(tt)
845
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
846
        duplicate = DuplicateEntry('Moved existing file to', 'dorothy.moved',
1534.10.20 by Aaron Bentley
Got all tests passing
847
                                   'dorothy', None, 'dorothy-id')
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
848
        self.assertEqual(cooked_conflicts[0], duplicate)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
849
        duplicate_id = DuplicateID('Unversioned existing file',
1534.10.20 by Aaron Bentley
Got all tests passing
850
                                   'dorothy.moved', 'dorothy', None,
851
                                   'dorothy-id')
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
852
        self.assertEqual(cooked_conflicts[1], duplicate_id)
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
853
        missing_parent = MissingParent('Created directory', 'munchkincity',
854
                                       'munchkincity-id')
855
        deleted_parent = DeletingParent('Not deleting', 'oz', 'oz-id')
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
856
        self.assertEqual(cooked_conflicts[2], missing_parent)
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
857
        unversioned_parent = UnversionedParent('Versioned directory',
858
                                               'munchkincity',
859
                                               'munchkincity-id')
860
        unversioned_parent2 = UnversionedParent('Versioned directory', 'oz',
1534.10.20 by Aaron Bentley
Got all tests passing
861
                                               'oz-id')
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
862
        self.assertEqual(cooked_conflicts[3], unversioned_parent)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
863
        parent_loop = ParentLoop('Cancelled move', 'oz/emeraldcity',
1534.10.20 by Aaron Bentley
Got all tests passing
864
                                 'oz/emeraldcity', 'emerald-id', 'emerald-id')
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
865
        self.assertEqual(cooked_conflicts[4], deleted_parent)
866
        self.assertEqual(cooked_conflicts[5], unversioned_parent2)
867
        self.assertEqual(cooked_conflicts[6], parent_loop)
868
        self.assertEqual(len(cooked_conflicts), 7)
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
869
        tt.finalize()
870
871
    def test_string_conflicts(self):
872
        tt, emerald, oz, old_dorothy, new_dorothy = self.get_conflicted()
873
        raw_conflicts = resolve_conflicts(tt)
874
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
875
        tt.finalize()
5898.1.7 by Martin
Fix TestTreeTransform.test_string_conflicts to use unicode()
876
        conflicts_s = [unicode(c) for c in cooked_conflicts]
1534.7.171 by Aaron Bentley
Implemented stringifying filesystem conflicts
877
        self.assertEqual(len(cooked_conflicts), len(conflicts_s))
878
        self.assertEqual(conflicts_s[0], 'Conflict adding file dorothy.  '
879
                                         'Moved existing file to '
880
                                         'dorothy.moved.')
881
        self.assertEqual(conflicts_s[1], 'Conflict adding id to dorothy.  '
882
                                         'Unversioned existing file '
883
                                         'dorothy.moved.')
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
884
        self.assertEqual(conflicts_s[2], 'Conflict adding files to'
885
                                         ' munchkincity.  Created directory.')
886
        self.assertEqual(conflicts_s[3], 'Conflict because munchkincity is not'
887
                                         ' versioned, but has versioned'
888
                                         ' children.  Versioned directory.')
1551.8.23 by Aaron Bentley
Tweaked conflict message to be more understandable
889
        self.assertEqualDiff(conflicts_s[4], "Conflict: can't delete oz because it"
890
                                         " is not empty.  Not deleting.")
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
891
        self.assertEqual(conflicts_s[5], 'Conflict because oz is not'
892
                                         ' versioned, but has versioned'
893
                                         ' children.  Versioned directory.')
894
        self.assertEqual(conflicts_s[6], 'Conflict moving oz/emeraldcity into'
4597.8.11 by Vincent Ladeuil
The ParentLoop.format has been updated, fix fallouts.
895
                                         ' oz/emeraldcity. Cancelled move.')
1534.7.170 by Aaron Bentley
Cleaned up filesystem conflict handling
896
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
897
    def prepare_wrong_parent_kind(self):
898
        tt, root = self.get_transform()
899
        tt.new_file('parent', root, 'contents', 'parent-id')
900
        tt.apply()
901
        tt, root = self.get_transform()
902
        parent_id = tt.trans_id_file_id('parent-id')
903
        tt.new_file('child,', parent_id, 'contents2', 'file-id')
904
        return tt
905
3144.4.1 by Aaron Bentley
Handle trying to list parents of a non-directory
906
    def test_find_conflicts_wrong_parent_kind(self):
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
907
        tt = self.prepare_wrong_parent_kind()
3144.4.1 by Aaron Bentley
Handle trying to list parents of a non-directory
908
        tt.find_conflicts()
909
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
910
    def test_resolve_conflicts_wrong_existing_parent_kind(self):
911
        tt = self.prepare_wrong_parent_kind()
912
        raw_conflicts = resolve_conflicts(tt)
913
        self.assertEqual(set([('non-directory parent', 'Created directory',
914
                         'new-3')]), raw_conflicts)
915
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
916
        self.assertEqual([NonDirectoryParent('Created directory', 'parent.new',
917
        'parent-id')], cooked_conflicts)
918
        tt.apply()
919
        self.assertEqual(None, self.wt.path2id('parent'))
920
        self.assertEqual('parent-id', self.wt.path2id('parent.new'))
921
922
    def test_resolve_conflicts_wrong_new_parent_kind(self):
923
        tt, root = self.get_transform()
924
        parent_id = tt.new_directory('parent', root, 'parent-id')
925
        tt.new_file('child,', parent_id, 'contents2', 'file-id')
926
        tt.apply()
927
        tt, root = self.get_transform()
928
        parent_id = tt.trans_id_file_id('parent-id')
929
        tt.delete_contents(parent_id)
930
        tt.create_file('contents', parent_id)
931
        raw_conflicts = resolve_conflicts(tt)
932
        self.assertEqual(set([('non-directory parent', 'Created directory',
933
                         'new-3')]), raw_conflicts)
934
        tt.apply()
935
        self.assertEqual(None, self.wt.path2id('parent'))
936
        self.assertEqual('parent-id', self.wt.path2id('parent.new'))
937
938
    def test_resolve_conflicts_wrong_parent_kind_unversioned(self):
939
        tt, root = self.get_transform()
940
        parent_id = tt.new_directory('parent', root)
941
        tt.new_file('child,', parent_id, 'contents2')
942
        tt.apply()
943
        tt, root = self.get_transform()
944
        parent_id = tt.trans_id_tree_path('parent')
945
        tt.delete_contents(parent_id)
946
        tt.create_file('contents', parent_id)
947
        resolve_conflicts(tt)
948
        tt.apply()
949
        self.assertIs(None, self.wt.path2id('parent'))
950
        self.assertIs(None, self.wt.path2id('parent.new'))
951
5409.5.1 by Vincent Ladeuil
Tweak test_resolve_conflicts_missing_parent (renamed from test_resolve_no_parent), puttinh it in the right place.
952
    def test_resolve_conflicts_missing_parent(self):
953
        wt = self.make_branch_and_tree('.')
954
        tt = TreeTransform(wt)
955
        self.addCleanup(tt.finalize)
956
        parent = tt.trans_id_file_id('parent-id')
957
        tt.new_file('file', parent, 'Contents')
958
        raw_conflicts = resolve_conflicts(tt)
5409.6.2 by Vincent Ladeuil
Fix typo in the comment.
959
        # Since the directory doesn't exist it's seen as 'missing'.  So
960
        # 'resolve_conflicts' create a conflict asking for it to be created.
5409.5.1 by Vincent Ladeuil
Tweak test_resolve_conflicts_missing_parent (renamed from test_resolve_no_parent), puttinh it in the right place.
961
        self.assertLength(1, raw_conflicts)
962
        self.assertEqual(('missing parent', 'Created directory', 'new-1'),
963
                         raw_conflicts.pop())
5409.6.1 by Vincent Ladeuil
Clarify test intent and behaviour.
964
        # apply fail since the missing directory doesn't exist
965
        self.assertRaises(errors.NoFinalPath, tt.apply)
5409.5.1 by Vincent Ladeuil
Tweak test_resolve_conflicts_missing_parent (renamed from test_resolve_no_parent), puttinh it in the right place.
966
1534.7.62 by Aaron Bentley
Fixed moving versioned directories
967
    def test_moving_versioned_directories(self):
968
        create, root = self.get_transform()
969
        kansas = create.new_directory('kansas', root, 'kansas-id')
970
        create.new_directory('house', kansas, 'house-id')
971
        create.new_directory('oz', root, 'oz-id')
972
        create.apply()
973
        cyclone, root = self.get_transform()
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
974
        oz = cyclone.trans_id_tree_file_id('oz-id')
975
        house = cyclone.trans_id_tree_file_id('house-id')
1534.7.62 by Aaron Bentley
Fixed moving versioned directories
976
        cyclone.adjust_path('house', oz, house)
977
        cyclone.apply()
1534.7.66 by Aaron Bentley
Ensured we don't accidentally move the root directory
978
979
    def test_moving_root(self):
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
980
        create, root = self.get_transform()
981
        fun = create.new_directory('fun', root, 'fun-id')
982
        create.new_directory('sun', root, 'sun-id')
983
        create.new_directory('moon', root, 'moon')
984
        create.apply()
1534.7.66 by Aaron Bentley
Ensured we don't accidentally move the root directory
985
        transform, root = self.get_transform()
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
986
        transform.adjust_root_path('oldroot', fun)
4634.122.2 by Aaron Bentley, John Arbash Meinel
Bring the fixup_new_roots code from the nested-trees code.
987
        new_root = transform.trans_id_tree_path('')
1534.7.69 by Aaron Bentley
Got real root moves working
988
        transform.version_file('new-root', new_root)
1534.7.68 by Aaron Bentley
Got semi-reasonable root directory renaming working
989
        transform.apply()
1534.7.93 by Aaron Bentley
Added text merge test
990
1534.7.114 by Aaron Bentley
Added file renaming test case
991
    def test_renames(self):
992
        create, root = self.get_transform()
993
        old = create.new_directory('old-parent', root, 'old-id')
994
        intermediate = create.new_directory('intermediate', old, 'im-id')
995
        myfile = create.new_file('myfile', intermediate, 'myfile-text',
996
                                 'myfile-id')
997
        create.apply()
998
        rename, root = self.get_transform()
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
999
        old = rename.trans_id_file_id('old-id')
1534.7.114 by Aaron Bentley
Added file renaming test case
1000
        rename.adjust_path('new', root, old)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
1001
        myfile = rename.trans_id_file_id('myfile-id')
1534.7.114 by Aaron Bentley
Added file renaming test case
1002
        rename.set_executability(True, myfile)
1003
        rename.apply()
1004
5186.2.4 by Martin Pool
Add failing specific test for 491763
1005
    def test_rename_fails(self):
5050.43.1 by Vincent Ladeuil
Fix one more failure when the test suite is run as root.
1006
        self.requireFeature(features.not_running_as_root)
5186.2.4 by Martin Pool
Add failing specific test for 491763
1007
        # see https://bugs.launchpad.net/bzr/+bug/491763
1008
        create, root_id = self.get_transform()
1009
        first_dir = create.new_directory('first-dir', root_id, 'first-id')
1010
        myfile = create.new_file('myfile', root_id, 'myfile-text',
1011
                                 'myfile-id')
1012
        create.apply()
5050.15.2 by Martin
Correct bt.test_transform.TestTreeTransform.test_rename_fails on non-posix platforms
1013
        if os.name == "posix" and sys.platform != "cygwin":
1014
            # posix filesystems fail on renaming if the readonly bit is set
1015
            osutils.make_readonly(self.wt.abspath('first-dir'))
1016
        elif os.name == "nt":
1017
            # windows filesystems fail on renaming open files
1018
            self.addCleanup(file(self.wt.abspath('myfile')).close)
1019
        else:
1020
            self.skip("Don't know how to force a permissions error on rename")
5186.2.4 by Martin Pool
Add failing specific test for 491763
1021
        # now transform to rename
1022
        rename_transform, root_id = self.get_transform()
1023
        file_trans_id = rename_transform.trans_id_file_id('myfile-id')
1024
        dir_id = rename_transform.trans_id_file_id('first-id')
1025
        rename_transform.adjust_path('newname', dir_id, file_trans_id)
5186.2.5 by Martin Pool
Raise a specific clearer error when a rename fails inside transform
1026
        e = self.assertRaises(errors.TransformRenameFailed,
1027
            rename_transform.apply)
5050.15.2 by Martin
Correct bt.test_transform.TestTreeTransform.test_rename_fails on non-posix platforms
1028
        # On nix looks like: 
5186.2.5 by Martin Pool
Raise a specific clearer error when a rename fails inside transform
1029
        # "Failed to rename .../work/.bzr/checkout/limbo/new-1
1030
        # to .../first-dir/newname: [Errno 13] Permission denied"
5050.15.2 by Martin
Correct bt.test_transform.TestTreeTransform.test_rename_fails on non-posix platforms
1031
        # On windows looks like:
1032
        # "Failed to rename .../work/myfile to 
1033
        # .../work/.bzr/checkout/limbo/new-1: [Errno 13] Permission denied"
5582.8.1 by Martin
Make bt.test_transform.TestTreeTransform.test_rename_fails not care about the exact stringification of the exception instance
1034
        # This test isn't concerned with exactly what the error looks like,
1035
        # and the strerror will vary across OS and locales, but the assert
1036
        # that the exeception attributes are what we expect
1037
        self.assertEqual(e.errno, errno.EACCES)
1038
        if os.name == "posix":
1039
            self.assertEndsWith(e.to_path, "/first-dir/newname")
1040
        else:
1041
            self.assertEqual(os.path.basename(e.from_path), "myfile")
5186.2.4 by Martin Pool
Add failing specific test for 491763
1042
1740.2.4 by Aaron Bentley
Update transform tests and docs
1043
    def test_set_executability_order(self):
1044
        """Ensure that executability behaves the same, no matter what order.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1045
1740.2.4 by Aaron Bentley
Update transform tests and docs
1046
        - create file and set executability simultaneously
1047
        - create file and set executability afterward
1048
        - unsetting the executability of a file whose executability has not been
1049
        declared should throw an exception (this may happen when a
1050
        merge attempts to create a file with a duplicate ID)
1051
        """
1052
        transform, root = self.get_transform()
1053
        wt = transform._tree
3034.2.1 by Aaron Bentley
Fix is_executable tests for win32
1054
        wt.lock_read()
1055
        self.addCleanup(wt.unlock)
1740.2.4 by Aaron Bentley
Update transform tests and docs
1056
        transform.new_file('set_on_creation', root, 'Set on creation', 'soc',
1057
                           True)
2502.1.1 by Aaron Bentley
Ensure renames only root children are renamed when building trees
1058
        sac = transform.new_file('set_after_creation', root,
1059
                                 'Set after creation', 'sac')
1740.2.4 by Aaron Bentley
Update transform tests and docs
1060
        transform.set_executability(True, sac)
2502.1.1 by Aaron Bentley
Ensure renames only root children are renamed when building trees
1061
        uws = transform.new_file('unset_without_set', root, 'Unset badly',
1062
                                 'uws')
1740.2.4 by Aaron Bentley
Update transform tests and docs
1063
        self.assertRaises(KeyError, transform.set_executability, None, uws)
1064
        transform.apply()
1065
        self.assertTrue(wt.is_executable('soc'))
1066
        self.assertTrue(wt.is_executable('sac'))
1067
1534.12.2 by Aaron Bentley
Added test for preserving file mode
1068
    def test_preserve_mode(self):
1069
        """File mode is preserved when replacing content"""
1070
        if sys.platform == 'win32':
1071
            raise TestSkipped('chmod has no effect on win32')
1072
        transform, root = self.get_transform()
1073
        transform.new_file('file1', root, 'contents', 'file1-id', True)
1074
        transform.apply()
3146.4.12 by Aaron Bentley
Add needed write lock to test
1075
        self.wt.lock_write()
1076
        self.addCleanup(self.wt.unlock)
1534.12.2 by Aaron Bentley
Added test for preserving file mode
1077
        self.assertTrue(self.wt.is_executable('file1-id'))
1078
        transform, root = self.get_transform()
1079
        file1_id = transform.trans_id_tree_file_id('file1-id')
1080
        transform.delete_contents(file1_id)
1081
        transform.create_file('contents2', file1_id)
1082
        transform.apply()
1083
        self.assertTrue(self.wt.is_executable('file1-id'))
1084
2027.1.1 by John Arbash Meinel
Fix bug #56549, and write a direct test that the right path is being statted
1085
    def test__set_mode_stats_correctly(self):
1086
        """_set_mode stats to determine file mode."""
1087
        if sys.platform == 'win32':
1088
            raise TestSkipped('chmod has no effect on win32')
1089
1090
        stat_paths = []
1091
        real_stat = os.stat
1092
        def instrumented_stat(path):
1093
            stat_paths.append(path)
1094
            return real_stat(path)
1095
1096
        transform, root = self.get_transform()
1097
1098
        bar1_id = transform.new_file('bar', root, 'bar contents 1\n',
1099
                                     file_id='bar-id-1', executable=False)
1100
        transform.apply()
1101
1102
        transform, root = self.get_transform()
1103
        bar1_id = transform.trans_id_tree_path('bar')
1104
        bar2_id = transform.trans_id_tree_path('bar2')
1105
        try:
1106
            os.stat = instrumented_stat
1107
            transform.create_file('bar2 contents\n', bar2_id, mode_id=bar1_id)
1108
        finally:
1109
            os.stat = real_stat
1110
            transform.finalize()
1111
1112
        bar1_abspath = self.wt.abspath('bar')
1113
        self.assertEqual([bar1_abspath], stat_paths)
1114
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1115
    def test_iter_changes(self):
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1116
        self.wt.set_root_id('eert_toor')
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1117
        transform, root = self.get_transform()
1118
        transform.new_file('old', root, 'blah', 'id-1', True)
1119
        transform.apply()
1120
        transform, root = self.get_transform()
1121
        try:
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1122
            self.assertEqual([], list(transform.iter_changes()))
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1123
            old = transform.trans_id_tree_file_id('id-1')
1124
            transform.unversion_file(old)
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1125
            self.assertEqual([('id-1', ('old', None), False, (True, False),
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1126
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1127
                (True, True))], list(transform.iter_changes()))
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1128
            transform.new_directory('new', root, 'id-1')
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1129
            self.assertEqual([('id-1', ('old', 'new'), True, (True, True),
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1130
                ('eert_toor', 'eert_toor'), ('old', 'new'),
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1131
                ('file', 'directory'),
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1132
                (True, False))], list(transform.iter_changes()))
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1133
        finally:
1134
            transform.finalize()
1135
1136
    def test_iter_changes_new(self):
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1137
        self.wt.set_root_id('eert_toor')
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1138
        transform, root = self.get_transform()
1139
        transform.new_file('old', root, 'blah')
1140
        transform.apply()
1141
        transform, root = self.get_transform()
1142
        try:
1143
            old = transform.trans_id_tree_path('old')
1144
            transform.version_file('id-1', old)
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1145
            self.assertEqual([('id-1', (None, 'old'), False, (False, True),
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1146
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1147
                (False, False))], list(transform.iter_changes()))
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1148
        finally:
1149
            transform.finalize()
1150
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1151
    def test_iter_changes_modifications(self):
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1152
        self.wt.set_root_id('eert_toor')
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1153
        transform, root = self.get_transform()
1154
        transform.new_file('old', root, 'blah', 'id-1')
1155
        transform.new_file('new', root, 'blah')
1156
        transform.new_directory('subdir', root, 'subdir-id')
1157
        transform.apply()
1158
        transform, root = self.get_transform()
1159
        try:
1160
            old = transform.trans_id_tree_path('old')
1161
            subdir = transform.trans_id_tree_file_id('subdir-id')
1162
            new = transform.trans_id_tree_path('new')
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1163
            self.assertEqual([], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1164
1165
            #content deletion
1166
            transform.delete_contents(old)
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1167
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1168
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', None),
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1169
                (False, False))], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1170
1171
            #content change
1172
            transform.create_file('blah', old)
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1173
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1174
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1175
                (False, False))], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1176
            transform.cancel_deletion(old)
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1177
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1178
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1179
                (False, False))], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1180
            transform.cancel_creation(old)
1181
1182
            # move file_id to a different file
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1183
            self.assertEqual([], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1184
            transform.unversion_file(old)
1185
            transform.version_file('id-1', new)
1186
            transform.adjust_path('old', root, new)
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1187
            self.assertEqual([('id-1', ('old', 'old'), True, (True, True),
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1188
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1189
                (False, False))], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1190
            transform.cancel_versioning(new)
1191
            transform._removed_id = set()
1192
1193
            #execute bit
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1194
            self.assertEqual([], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1195
            transform.set_executability(True, old)
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1196
            self.assertEqual([('id-1', ('old', 'old'), False, (True, True),
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1197
                ('eert_toor', 'eert_toor'), ('old', 'old'), ('file', 'file'),
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1198
                (False, True))], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1199
            transform.set_executability(None, old)
1200
1201
            # filename
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1202
            self.assertEqual([], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1203
            transform.adjust_path('new', root, old)
1204
            transform._new_parent = {}
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1205
            self.assertEqual([('id-1', ('old', 'new'), False, (True, True),
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1206
                ('eert_toor', 'eert_toor'), ('old', 'new'), ('file', 'file'),
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1207
                (False, False))], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1208
            transform._new_name = {}
1209
1210
            # parent directory
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1211
            self.assertEqual([], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1212
            transform.adjust_path('new', subdir, old)
1213
            transform._new_name = {}
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1214
            self.assertEqual([('id-1', ('old', 'subdir/old'), False,
2255.2.180 by Martin Pool
merge dirstate
1215
                (True, True), ('eert_toor', 'subdir-id'), ('old', 'old'),
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1216
                ('file', 'file'), (False, False))],
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1217
                list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1218
            transform._new_path = {}
1219
1220
        finally:
1221
            transform.finalize()
1222
1551.11.7 by Aaron Bentley
Stop modified flag bleeding into later changes
1223
    def test_iter_changes_modified_bleed(self):
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1224
        self.wt.set_root_id('eert_toor')
1551.11.7 by Aaron Bentley
Stop modified flag bleeding into later changes
1225
        """Modified flag should not bleed from one change to another"""
1226
        # unfortunately, we have no guarantee that file1 (which is modified)
1227
        # will be applied before file2.  And if it's applied after file2, it
1228
        # obviously can't bleed into file2's change output.  But for now, it
1229
        # works.
1230
        transform, root = self.get_transform()
1231
        transform.new_file('file1', root, 'blah', 'id-1')
1232
        transform.new_file('file2', root, 'blah', 'id-2')
1233
        transform.apply()
1234
        transform, root = self.get_transform()
1235
        try:
1236
            transform.delete_contents(transform.trans_id_file_id('id-1'))
1237
            transform.set_executability(True,
1238
            transform.trans_id_file_id('id-2'))
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1239
            self.assertEqual([('id-1', (u'file1', u'file1'), True, (True, True),
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1240
                ('eert_toor', 'eert_toor'), ('file1', u'file1'),
1551.11.7 by Aaron Bentley
Stop modified flag bleeding into later changes
1241
                ('file', None), (False, False)),
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1242
                ('id-2', (u'file2', u'file2'), False, (True, True),
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1243
                ('eert_toor', 'eert_toor'), ('file2', u'file2'),
1551.11.7 by Aaron Bentley
Stop modified flag bleeding into later changes
1244
                ('file', 'file'), (False, True))],
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1245
                list(transform.iter_changes()))
1551.11.7 by Aaron Bentley
Stop modified flag bleeding into later changes
1246
        finally:
1247
            transform.finalize()
1248
1551.10.37 by Aaron Bentley
recommit of TreeTransform._iter_changes fix with missing files
1249
    def test_iter_changes_move_missing(self):
1250
        """Test moving ids with no files around"""
1251
        self.wt.set_root_id('toor_eert')
1252
        # Need two steps because versioning a non-existant file is a conflict.
1253
        transform, root = self.get_transform()
1254
        transform.new_directory('floater', root, 'floater-id')
1255
        transform.apply()
1256
        transform, root = self.get_transform()
1257
        transform.delete_contents(transform.trans_id_tree_path('floater'))
1258
        transform.apply()
1259
        transform, root = self.get_transform()
1260
        floater = transform.trans_id_tree_path('floater')
1261
        try:
1262
            transform.adjust_path('flitter', root, floater)
1263
            self.assertEqual([('floater-id', ('floater', 'flitter'), False,
1264
            (True, True), ('toor_eert', 'toor_eert'), ('floater', 'flitter'),
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1265
            (None, None), (False, False))], list(transform.iter_changes()))
1551.10.37 by Aaron Bentley
recommit of TreeTransform._iter_changes fix with missing files
1266
        finally:
1267
            transform.finalize()
1268
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1269
    def test_iter_changes_pointless(self):
1270
        """Ensure that no-ops are not treated as modifications"""
2100.3.33 by Aaron Bentley
Handle unique roots in tests for TreeTransform.iter_changes
1271
        self.wt.set_root_id('eert_toor')
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1272
        transform, root = self.get_transform()
1273
        transform.new_file('old', root, 'blah', 'id-1')
1274
        transform.new_directory('subdir', root, 'subdir-id')
1275
        transform.apply()
1276
        transform, root = self.get_transform()
1277
        try:
1278
            old = transform.trans_id_tree_path('old')
1279
            subdir = transform.trans_id_tree_file_id('subdir-id')
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1280
            self.assertEqual([], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1281
            transform.delete_contents(subdir)
1282
            transform.create_directory(subdir)
1283
            transform.set_executability(False, old)
1284
            transform.unversion_file(old)
1285
            transform.version_file('id-1', old)
1286
            transform.adjust_path('old', root, old)
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
1287
            self.assertEqual([], list(transform.iter_changes()))
1551.11.2 by Aaron Bentley
Get kind change detection working for iter_changes
1288
        finally:
1289
            transform.finalize()
1534.7.93 by Aaron Bentley
Added text merge test
1290
2502.1.1 by Aaron Bentley
Ensure renames only root children are renamed when building trees
1291
    def test_rename_count(self):
1292
        transform, root = self.get_transform()
2502.1.8 by Aaron Bentley
Updates from review comments
1293
        transform.new_file('name1', root, 'contents')
2502.1.1 by Aaron Bentley
Ensure renames only root children are renamed when building trees
1294
        self.assertEqual(transform.rename_count, 0)
1295
        transform.apply()
1296
        self.assertEqual(transform.rename_count, 1)
1297
        transform2, root = self.get_transform()
2502.1.8 by Aaron Bentley
Updates from review comments
1298
        transform2.adjust_path('name2', root,
1299
                               transform2.trans_id_tree_path('name1'))
2502.1.1 by Aaron Bentley
Ensure renames only root children are renamed when building trees
1300
        self.assertEqual(transform2.rename_count, 0)
1301
        transform2.apply()
1302
        self.assertEqual(transform2.rename_count, 2)
1303
2502.1.2 by Aaron Bentley
Make the limited-renames functionality safer in the general case
1304
    def test_change_parent(self):
2502.1.8 by Aaron Bentley
Updates from review comments
1305
        """Ensure that after we change a parent, the results are still right.
1306
1307
        Renames and parent changes on pending transforms can happen as part
1308
        of conflict resolution, and are explicitly permitted by the
1309
        TreeTransform API.
1310
1311
        This test ensures they work correctly with the rename-avoidance
1312
        optimization.
1313
        """
2502.1.2 by Aaron Bentley
Make the limited-renames functionality safer in the general case
1314
        transform, root = self.get_transform()
2502.1.8 by Aaron Bentley
Updates from review comments
1315
        parent1 = transform.new_directory('parent1', root)
1316
        child1 = transform.new_file('child1', parent1, 'contents')
1317
        parent2 = transform.new_directory('parent2', root)
1318
        transform.adjust_path('child1', parent2, child1)
2502.1.2 by Aaron Bentley
Make the limited-renames functionality safer in the general case
1319
        transform.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1320
        self.assertPathDoesNotExist(self.wt.abspath('parent1/child1'))
1321
        self.assertPathExists(self.wt.abspath('parent2/child1'))
2502.1.8 by Aaron Bentley
Updates from review comments
1322
        # rename limbo/new-1 => parent1, rename limbo/new-3 => parent2
1323
        # no rename for child1 (counting only renames during apply)
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1324
        self.assertEqual(2, transform.rename_count)
2502.1.2 by Aaron Bentley
Make the limited-renames functionality safer in the general case
1325
1326
    def test_cancel_parent(self):
1327
        """Cancelling a parent doesn't cause deletion of a non-empty directory
1328
1329
        This is like the test_change_parent, except that we cancel the parent
1330
        before adjusting the path.  The transform must detect that the
1331
        directory is non-empty, and move children to safe locations.
1332
        """
1333
        transform, root = self.get_transform()
2502.1.8 by Aaron Bentley
Updates from review comments
1334
        parent1 = transform.new_directory('parent1', root)
1335
        child1 = transform.new_file('child1', parent1, 'contents')
1336
        child2 = transform.new_file('child2', parent1, 'contents')
1337
        try:
1338
            transform.cancel_creation(parent1)
1339
        except OSError:
1340
            self.fail('Failed to move child1 before deleting parent1')
1341
        transform.cancel_creation(child2)
1342
        transform.create_directory(parent1)
1343
        try:
1344
            transform.cancel_creation(parent1)
1345
        # If the transform incorrectly believes that child2 is still in
1346
        # parent1's limbo directory, it will try to rename it and fail
1347
        # because was already moved by the first cancel_creation.
1348
        except OSError:
1349
            self.fail('Transform still thinks child2 is a child of parent1')
1350
        parent2 = transform.new_directory('parent2', root)
1351
        transform.adjust_path('child1', parent2, child1)
2502.1.2 by Aaron Bentley
Make the limited-renames functionality safer in the general case
1352
        transform.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1353
        self.assertPathDoesNotExist(self.wt.abspath('parent1'))
1354
        self.assertPathExists(self.wt.abspath('parent2/child1'))
2502.1.8 by Aaron Bentley
Updates from review comments
1355
        # rename limbo/new-3 => parent2, rename limbo/new-2 => child1
5784.1.1 by Martin Pool
Stop using failIf, failUnless, etc
1356
        self.assertEqual(2, transform.rename_count)
2502.1.2 by Aaron Bentley
Make the limited-renames functionality safer in the general case
1357
1358
    def test_adjust_and_cancel(self):
2502.1.8 by Aaron Bentley
Updates from review comments
1359
        """Make sure adjust_path keeps track of limbo children properly"""
2502.1.2 by Aaron Bentley
Make the limited-renames functionality safer in the general case
1360
        transform, root = self.get_transform()
2502.1.8 by Aaron Bentley
Updates from review comments
1361
        parent1 = transform.new_directory('parent1', root)
1362
        child1 = transform.new_file('child1', parent1, 'contents')
1363
        parent2 = transform.new_directory('parent2', root)
1364
        transform.adjust_path('child1', parent2, child1)
1365
        transform.cancel_creation(child1)
2502.1.2 by Aaron Bentley
Make the limited-renames functionality safer in the general case
1366
        try:
2502.1.8 by Aaron Bentley
Updates from review comments
1367
            transform.cancel_creation(parent1)
1368
        # if the transform thinks child1 is still in parent1's limbo
1369
        # directory, it will attempt to move it and fail.
2502.1.2 by Aaron Bentley
Make the limited-renames functionality safer in the general case
1370
        except OSError:
2502.1.8 by Aaron Bentley
Updates from review comments
1371
            self.fail('Transform still thinks child1 is a child of parent1')
2502.1.2 by Aaron Bentley
Make the limited-renames functionality safer in the general case
1372
        transform.finalize()
1373
2502.1.3 by Aaron Bentley
Don't cause errors when creating contents for trans_ids with no parent/name
1374
    def test_noname_contents(self):
2502.1.8 by Aaron Bentley
Updates from review comments
1375
        """TreeTransform should permit deferring naming files."""
2502.1.3 by Aaron Bentley
Don't cause errors when creating contents for trans_ids with no parent/name
1376
        transform, root = self.get_transform()
2502.1.8 by Aaron Bentley
Updates from review comments
1377
        parent = transform.trans_id_file_id('parent-id')
2502.1.3 by Aaron Bentley
Don't cause errors when creating contents for trans_ids with no parent/name
1378
        try:
2502.1.8 by Aaron Bentley
Updates from review comments
1379
            transform.create_directory(parent)
2502.1.3 by Aaron Bentley
Don't cause errors when creating contents for trans_ids with no parent/name
1380
        except KeyError:
1381
            self.fail("Can't handle contents with no name")
1382
        transform.finalize()
1383
2502.1.9 by Aaron Bentley
Add additional test for no-name contents
1384
    def test_noname_contents_nested(self):
1385
        """TreeTransform should permit deferring naming files."""
1386
        transform, root = self.get_transform()
1387
        parent = transform.trans_id_file_id('parent-id')
1388
        try:
1389
            transform.create_directory(parent)
1390
        except KeyError:
1391
            self.fail("Can't handle contents with no name")
1392
        child = transform.new_directory('child', parent)
1393
        transform.adjust_path('parent', root, parent)
1394
        transform.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1395
        self.assertPathExists(self.wt.abspath('parent/child'))
2502.1.9 by Aaron Bentley
Add additional test for no-name contents
1396
        self.assertEqual(1, transform.rename_count)
1397
2502.1.4 by Aaron Bentley
Ensure we only reuse limbo names appropriately
1398
    def test_reuse_name(self):
1399
        """Avoid reusing the same limbo name for different files"""
1400
        transform, root = self.get_transform()
2502.1.8 by Aaron Bentley
Updates from review comments
1401
        parent = transform.new_directory('parent', root)
1402
        child1 = transform.new_directory('child', parent)
2502.1.4 by Aaron Bentley
Ensure we only reuse limbo names appropriately
1403
        try:
2502.1.8 by Aaron Bentley
Updates from review comments
1404
            child2 = transform.new_directory('child', parent)
2502.1.4 by Aaron Bentley
Ensure we only reuse limbo names appropriately
1405
        except OSError:
1406
            self.fail('Tranform tried to use the same limbo name twice')
2502.1.8 by Aaron Bentley
Updates from review comments
1407
        transform.adjust_path('child2', parent, child2)
2502.1.4 by Aaron Bentley
Ensure we only reuse limbo names appropriately
1408
        transform.apply()
2502.1.8 by Aaron Bentley
Updates from review comments
1409
        # limbo/new-1 => parent, limbo/new-3 => parent/child2
1410
        # child2 is put into top-level limbo because child1 has already
1411
        # claimed the direct limbo path when child2 is created.  There is no
1412
        # advantage in renaming files once they're in top-level limbo, except
1413
        # as part of apply.
2502.1.4 by Aaron Bentley
Ensure we only reuse limbo names appropriately
1414
        self.assertEqual(2, transform.rename_count)
1415
1416
    def test_reuse_when_first_moved(self):
1417
        """Don't avoid direct paths when it is safe to use them"""
1418
        transform, root = self.get_transform()
2502.1.8 by Aaron Bentley
Updates from review comments
1419
        parent = transform.new_directory('parent', root)
1420
        child1 = transform.new_directory('child', parent)
1421
        transform.adjust_path('child1', parent, child1)
1422
        child2 = transform.new_directory('child', parent)
2502.1.4 by Aaron Bentley
Ensure we only reuse limbo names appropriately
1423
        transform.apply()
2502.1.8 by Aaron Bentley
Updates from review comments
1424
        # limbo/new-1 => parent
2502.1.4 by Aaron Bentley
Ensure we only reuse limbo names appropriately
1425
        self.assertEqual(1, transform.rename_count)
1426
1427
    def test_reuse_after_cancel(self):
1428
        """Don't avoid direct paths when it is safe to use them"""
1429
        transform, root = self.get_transform()
2502.1.8 by Aaron Bentley
Updates from review comments
1430
        parent2 = transform.new_directory('parent2', root)
1431
        child1 = transform.new_directory('child1', parent2)
1432
        transform.cancel_creation(parent2)
1433
        transform.create_directory(parent2)
1434
        child2 = transform.new_directory('child1', parent2)
1435
        transform.adjust_path('child2', parent2, child1)
2502.1.4 by Aaron Bentley
Ensure we only reuse limbo names appropriately
1436
        transform.apply()
2502.1.8 by Aaron Bentley
Updates from review comments
1437
        # limbo/new-1 => parent2, limbo/new-2 => parent2/child1
2502.1.4 by Aaron Bentley
Ensure we only reuse limbo names appropriately
1438
        self.assertEqual(2, transform.rename_count)
1439
2502.1.7 by Aaron Bentley
Fix finalize deletion ordering
1440
    def test_finalize_order(self):
2502.1.8 by Aaron Bentley
Updates from review comments
1441
        """Finalize must be done in child-to-parent order"""
2502.1.7 by Aaron Bentley
Fix finalize deletion ordering
1442
        transform, root = self.get_transform()
2502.1.8 by Aaron Bentley
Updates from review comments
1443
        parent = transform.new_directory('parent', root)
1444
        child = transform.new_directory('child', parent)
2502.1.7 by Aaron Bentley
Fix finalize deletion ordering
1445
        try:
1446
            transform.finalize()
1447
        except OSError:
2502.1.8 by Aaron Bentley
Updates from review comments
1448
            self.fail('Tried to remove parent before child1')
2502.1.7 by Aaron Bentley
Fix finalize deletion ordering
1449
2502.1.13 by Aaron Bentley
Updates from review
1450
    def test_cancel_with_cancelled_child_should_succeed(self):
2502.1.12 by Aaron Bentley
Avoid renaming children with no content
1451
        transform, root = self.get_transform()
1452
        parent = transform.new_directory('parent', root)
1453
        child = transform.new_directory('child', parent)
1454
        transform.cancel_creation(child)
2502.1.13 by Aaron Bentley
Updates from review
1455
        transform.cancel_creation(parent)
2502.1.12 by Aaron Bentley
Avoid renaming children with no content
1456
        transform.finalize()
1457
3638.3.15 by Vincent Ladeuil
Fix test_case_insensitive_clash to pass on all platforms (renamed too).
1458
    def test_rollback_on_directory_clash(self):
3063.1.1 by Alexander Belchenko
Catch OSError 17 (file exists) in final phase of tree transform and show filename to user (#111758).
1459
        def tt_helper():
3638.3.17 by Vincent Ladeuil
Fixed as per Aaron's review.
1460
            wt = self.make_branch_and_tree('.')
3063.1.1 by Alexander Belchenko
Catch OSError 17 (file exists) in final phase of tree transform and show filename to user (#111758).
1461
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
1462
            try:
3638.3.15 by Vincent Ladeuil
Fix test_case_insensitive_clash to pass on all platforms (renamed too).
1463
                foo = tt.new_directory('foo', tt.root)
1464
                tt.new_file('bar', foo, 'foobar')
1465
                baz = tt.new_directory('baz', tt.root)
1466
                tt.new_file('qux', baz, 'quux')
1467
                # Ask for a rename 'foo' -> 'baz'
1468
                tt.adjust_path('baz', tt.root, foo)
3063.1.3 by Aaron Bentley
Update for Linux
1469
                # Lie to tt that we've already resolved all conflicts.
3063.1.1 by Alexander Belchenko
Catch OSError 17 (file exists) in final phase of tree transform and show filename to user (#111758).
1470
                tt.apply(no_conflicts=True)
3063.1.3 by Aaron Bentley
Update for Linux
1471
            except:
3063.1.1 by Alexander Belchenko
Catch OSError 17 (file exists) in final phase of tree transform and show filename to user (#111758).
1472
                wt.unlock()
3063.1.3 by Aaron Bentley
Update for Linux
1473
                raise
3638.3.17 by Vincent Ladeuil
Fixed as per Aaron's review.
1474
        # The rename will fail because the target directory is not empty (but
1475
        # raises FileExists anyway).
3063.1.1 by Alexander Belchenko
Catch OSError 17 (file exists) in final phase of tree transform and show filename to user (#111758).
1476
        err = self.assertRaises(errors.FileExists, tt_helper)
1477
        self.assertContainsRe(str(err),
3638.3.15 by Vincent Ladeuil
Fix test_case_insensitive_clash to pass on all platforms (renamed too).
1478
            "^File exists: .+/baz")
3063.1.1 by Alexander Belchenko
Catch OSError 17 (file exists) in final phase of tree transform and show filename to user (#111758).
1479
3063.1.2 by Alexander Belchenko
test for two directories clash
1480
    def test_two_directories_clash(self):
1481
        def tt_helper():
1482
            wt = self.make_branch_and_tree('.')
1483
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
1484
            try:
3063.1.3 by Aaron Bentley
Update for Linux
1485
                foo_1 = tt.new_directory('foo', tt.root)
1486
                tt.new_directory('bar', foo_1)
3638.3.15 by Vincent Ladeuil
Fix test_case_insensitive_clash to pass on all platforms (renamed too).
1487
                # Adding the same directory with a different content
3063.1.3 by Aaron Bentley
Update for Linux
1488
                foo_2 = tt.new_directory('foo', tt.root)
1489
                tt.new_directory('baz', foo_2)
1490
                # Lie to tt that we've already resolved all conflicts.
3063.1.2 by Alexander Belchenko
test for two directories clash
1491
                tt.apply(no_conflicts=True)
3063.1.3 by Aaron Bentley
Update for Linux
1492
            except:
3063.1.2 by Alexander Belchenko
test for two directories clash
1493
                wt.unlock()
3063.1.3 by Aaron Bentley
Update for Linux
1494
                raise
3063.1.2 by Alexander Belchenko
test for two directories clash
1495
        err = self.assertRaises(errors.FileExists, tt_helper)
1496
        self.assertContainsRe(str(err),
1497
            "^File exists: .+/foo")
1498
3100.1.1 by Aaron Bentley
Fix ImmortalLimbo errors when transforms fail
1499
    def test_two_directories_clash_finalize(self):
1500
        def tt_helper():
1501
            wt = self.make_branch_and_tree('.')
1502
            tt = TreeTransform(wt)  # TreeTransform obtains write lock
1503
            try:
1504
                foo_1 = tt.new_directory('foo', tt.root)
1505
                tt.new_directory('bar', foo_1)
3638.3.15 by Vincent Ladeuil
Fix test_case_insensitive_clash to pass on all platforms (renamed too).
1506
                # Adding the same directory with a different content
3100.1.1 by Aaron Bentley
Fix ImmortalLimbo errors when transforms fail
1507
                foo_2 = tt.new_directory('foo', tt.root)
1508
                tt.new_directory('baz', foo_2)
1509
                # Lie to tt that we've already resolved all conflicts.
1510
                tt.apply(no_conflicts=True)
1511
            except:
1512
                tt.finalize()
1513
                raise
1514
        err = self.assertRaises(errors.FileExists, tt_helper)
1515
        self.assertContainsRe(str(err),
1516
            "^File exists: .+/foo")
1517
3535.6.1 by James Westby
Handle a file turning in to a directory in TreeTransform.
1518
    def test_file_to_directory(self):
1519
        wt = self.make_branch_and_tree('.')
3535.6.2 by James Westby
Fixes from review. Thanks Aaron and John.
1520
        self.build_tree(['foo'])
3535.6.1 by James Westby
Handle a file turning in to a directory in TreeTransform.
1521
        wt.add(['foo'])
3590.3.1 by James Westby
Make TreeTransform update the inventory with new kind information.
1522
        wt.commit("one")
3535.6.1 by James Westby
Handle a file turning in to a directory in TreeTransform.
1523
        tt = TreeTransform(wt)
3535.6.2 by James Westby
Fixes from review. Thanks Aaron and John.
1524
        self.addCleanup(tt.finalize)
3535.6.3 by James Westby
Fix the test to not create transform conflicts.
1525
        foo_trans_id = tt.trans_id_tree_path("foo")
1526
        tt.delete_contents(foo_trans_id)
1527
        tt.create_directory(foo_trans_id)
1528
        bar_trans_id = tt.trans_id_tree_path("foo/bar")
1529
        tt.create_file(["aa\n"], bar_trans_id)
1530
        tt.version_file("bar-1", bar_trans_id)
3535.6.2 by James Westby
Fixes from review. Thanks Aaron and John.
1531
        tt.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1532
        self.assertPathExists("foo/bar")
3590.3.2 by James Westby
Handle ->symlink changes as well.
1533
        wt.lock_read()
1534
        try:
1535
            self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1536
                    "directory")
1537
        finally:
1538
            wt.unlock()
3590.3.1 by James Westby
Make TreeTransform update the inventory with new kind information.
1539
        wt.commit("two")
1540
        changes = wt.changes_from(wt.basis_tree())
1541
        self.assertFalse(changes.has_changed(), changes)
3535.6.1 by James Westby
Handle a file turning in to a directory in TreeTransform.
1542
3590.3.2 by James Westby
Handle ->symlink changes as well.
1543
    def test_file_to_symlink(self):
3590.3.3 by James Westby
Make ->file changes work as well.
1544
        self.requireFeature(SymlinkFeature)
3590.3.2 by James Westby
Handle ->symlink changes as well.
1545
        wt = self.make_branch_and_tree('.')
1546
        self.build_tree(['foo'])
1547
        wt.add(['foo'])
1548
        wt.commit("one")
1549
        tt = TreeTransform(wt)
1550
        self.addCleanup(tt.finalize)
1551
        foo_trans_id = tt.trans_id_tree_path("foo")
1552
        tt.delete_contents(foo_trans_id)
1553
        tt.create_symlink("bar", foo_trans_id)
1554
        tt.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1555
        self.assertPathExists("foo")
3590.3.2 by James Westby
Handle ->symlink changes as well.
1556
        wt.lock_read()
1557
        self.addCleanup(wt.unlock)
1558
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1559
                "symlink")
1560
3590.3.3 by James Westby
Make ->file changes work as well.
1561
    def test_dir_to_file(self):
1562
        wt = self.make_branch_and_tree('.')
1563
        self.build_tree(['foo/', 'foo/bar'])
1564
        wt.add(['foo', 'foo/bar'])
1565
        wt.commit("one")
1566
        tt = TreeTransform(wt)
1567
        self.addCleanup(tt.finalize)
1568
        foo_trans_id = tt.trans_id_tree_path("foo")
1569
        bar_trans_id = tt.trans_id_tree_path("foo/bar")
1570
        tt.delete_contents(foo_trans_id)
1571
        tt.delete_versioned(bar_trans_id)
1572
        tt.create_file(["aa\n"], foo_trans_id)
1573
        tt.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1574
        self.assertPathExists("foo")
3590.3.3 by James Westby
Make ->file changes work as well.
1575
        wt.lock_read()
1576
        self.addCleanup(wt.unlock)
1577
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1578
                "file")
1579
3590.3.4 by James Westby
Add a test for creating hardlinks as well.
1580
    def test_dir_to_hardlink(self):
3590.3.5 by James Westby
Use HardlinkFeature for the hardlink test.
1581
        self.requireFeature(HardlinkFeature)
3590.3.4 by James Westby
Add a test for creating hardlinks as well.
1582
        wt = self.make_branch_and_tree('.')
1583
        self.build_tree(['foo/', 'foo/bar'])
1584
        wt.add(['foo', 'foo/bar'])
1585
        wt.commit("one")
1586
        tt = TreeTransform(wt)
1587
        self.addCleanup(tt.finalize)
1588
        foo_trans_id = tt.trans_id_tree_path("foo")
1589
        bar_trans_id = tt.trans_id_tree_path("foo/bar")
1590
        tt.delete_contents(foo_trans_id)
1591
        tt.delete_versioned(bar_trans_id)
1592
        self.build_tree(['baz'])
1593
        tt.create_hardlink("baz", foo_trans_id)
1594
        tt.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1595
        self.assertPathExists("foo")
1596
        self.assertPathExists("baz")
3590.3.4 by James Westby
Add a test for creating hardlinks as well.
1597
        wt.lock_read()
1598
        self.addCleanup(wt.unlock)
1599
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1600
                "file")
1601
3619.2.10 by Aaron Bentley
Compensate for stale entries in TT._needs_rename
1602
    def test_no_final_path(self):
1603
        transform, root = self.get_transform()
1604
        trans_id = transform.trans_id_file_id('foo')
1605
        transform.create_file('bar', trans_id)
1606
        transform.cancel_creation(trans_id)
1607
        transform.apply()
1608
3363.17.24 by Aaron Bentley
Implement create_by_tree
1609
    def test_create_from_tree(self):
1610
        tree1 = self.make_branch_and_tree('tree1')
1611
        self.build_tree_contents([('tree1/foo/',), ('tree1/bar', 'baz')])
1612
        tree1.add(['foo', 'bar'], ['foo-id', 'bar-id'])
1613
        tree2 = self.make_branch_and_tree('tree2')
1614
        tt = TreeTransform(tree2)
1615
        foo_trans_id = tt.create_path('foo', tt.root)
1616
        create_from_tree(tt, foo_trans_id, tree1, 'foo-id')
1617
        bar_trans_id = tt.create_path('bar', tt.root)
1618
        create_from_tree(tt, bar_trans_id, tree1, 'bar-id')
1619
        tt.apply()
1620
        self.assertEqual('directory', osutils.file_kind('tree2/foo'))
1621
        self.assertFileEqual('baz', 'tree2/bar')
1622
3363.17.25 by Aaron Bentley
remove get_inventory_entry, replace with create_from_tree
1623
    def test_create_from_tree_bytes(self):
1624
        """Provided lines are used instead of tree content."""
1625
        tree1 = self.make_branch_and_tree('tree1')
1626
        self.build_tree_contents([('tree1/foo', 'bar'),])
1627
        tree1.add('foo', 'foo-id')
1628
        tree2 = self.make_branch_and_tree('tree2')
1629
        tt = TreeTransform(tree2)
1630
        foo_trans_id = tt.create_path('foo', tt.root)
1631
        create_from_tree(tt, foo_trans_id, tree1, 'foo-id', bytes='qux')
1632
        tt.apply()
1633
        self.assertFileEqual('qux', 'tree2/foo')
1634
1635
    def test_create_from_tree_symlink(self):
3363.17.24 by Aaron Bentley
Implement create_by_tree
1636
        self.requireFeature(SymlinkFeature)
1637
        tree1 = self.make_branch_and_tree('tree1')
1638
        os.symlink('bar', 'tree1/foo')
1639
        tree1.add('foo', 'foo-id')
1640
        tt = TreeTransform(self.make_branch_and_tree('tree2'))
1641
        foo_trans_id = tt.create_path('foo', tt.root)
1642
        create_from_tree(tt, foo_trans_id, tree1, 'foo-id')
1643
        tt.apply()
1644
        self.assertEqual('bar', os.readlink('tree2/foo'))
1645
2502.1.3 by Aaron Bentley
Don't cause errors when creating contents for trans_ids with no parent/name
1646
1534.7.93 by Aaron Bentley
Added text merge test
1647
class TransformGroup(object):
3063.1.1 by Alexander Belchenko
Catch OSError 17 (file exists) in final phase of tree transform and show filename to user (#111758).
1648
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1649
    def __init__(self, dirname, root_id):
1534.7.101 by Aaron Bentley
Got conflicts on symlinks working properly
1650
        self.name = dirname
1534.7.93 by Aaron Bentley
Added text merge test
1651
        os.mkdir(dirname)
1558.1.3 by Aaron Bentley
Fixed deprecated op use in test suite
1652
        self.wt = BzrDir.create_standalone_workingtree(dirname)
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1653
        self.wt.set_root_id(root_id)
1558.1.3 by Aaron Bentley
Fixed deprecated op use in test suite
1654
        self.b = self.wt.branch
1534.7.93 by Aaron Bentley
Added text merge test
1655
        self.tt = TreeTransform(self.wt)
1534.7.181 by Aaron Bentley
Renamed a bunch of functions
1656
        self.root = self.tt.trans_id_tree_file_id(self.wt.get_root_id())
1534.7.93 by Aaron Bentley
Added text merge test
1657
1551.11.1 by Aaron Bentley
Initial work on converting TreeTransform to iter_changes format
1658
1534.7.95 by Aaron Bentley
Added more text merge tests
1659
def conflict_text(tree, merge):
1660
    template = '%s TREE\n%s%s\n%s%s MERGE-SOURCE\n'
1661
    return template % ('<' * 7, tree, '=' * 7, merge, '>' * 7)
1662
1534.7.93 by Aaron Bentley
Added text merge test
1663
5954.2.2 by Aaron Bentley
Include parent id changes for changed inventory entries.
1664
class TestInventoryAltered(tests.TestCaseWithTransport):
1665
1666
    def test_inventory_altered_unchanged(self):
1667
        tree = self.make_branch_and_tree('tree')
1668
        self.build_tree(['tree/foo'])
1669
        tree.add('foo', 'foo-id')
1670
        with TransformPreview(tree) as tt:
1671
            self.assertEqual([], tt._inventory_altered())
1672
1673
    def test_inventory_altered_changed_parent_id(self):
1674
        tree = self.make_branch_and_tree('tree')
1675
        self.build_tree(['tree/foo'])
1676
        tree.add('foo', 'foo-id')
1677
        with TransformPreview(tree) as tt:
1678
            tt.unversion_file(tt.root)
1679
            tt.version_file('new-id', tt.root)
1680
            foo_trans_id = tt.trans_id_tree_file_id('foo-id')
1681
            foo_tuple = ('foo', foo_trans_id)
1682
            root_tuple = ('', tt.root)
1683
            self.assertEqual([root_tuple, foo_tuple], tt._inventory_altered())
1684
1685
    def test_inventory_altered_noop_changed_parent_id(self):
1686
        tree = self.make_branch_and_tree('tree')
1687
        self.build_tree(['tree/foo'])
1688
        tree.add('foo', 'foo-id')
1689
        with TransformPreview(tree) as tt:
1690
            tt.unversion_file(tt.root)
1691
            tt.version_file(tree.get_root_id(), tt.root)
1692
            foo_trans_id = tt.trans_id_tree_file_id('foo-id')
1693
            self.assertEqual([], tt._inventory_altered())
1694
1695
1534.7.93 by Aaron Bentley
Added text merge test
1696
class TestTransformMerge(TestCaseInTempDir):
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
1697
1534.7.93 by Aaron Bentley
Added text merge test
1698
    def test_text_merge(self):
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
1699
        root_id = generate_ids.gen_root_id()
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1700
        base = TransformGroup("base", root_id)
1534.7.93 by Aaron Bentley
Added text merge test
1701
        base.tt.new_file('a', base.root, 'a\nb\nc\nd\be\n', 'a')
1534.7.95 by Aaron Bentley
Added more text merge tests
1702
        base.tt.new_file('b', base.root, 'b1', 'b')
1703
        base.tt.new_file('c', base.root, 'c', 'c')
1704
        base.tt.new_file('d', base.root, 'd', 'd')
1705
        base.tt.new_file('e', base.root, 'e', 'e')
1706
        base.tt.new_file('f', base.root, 'f', 'f')
1534.7.96 by Aaron Bentley
Tested with BASE as directory
1707
        base.tt.new_directory('g', base.root, 'g')
1534.7.97 by Aaron Bentley
Ensured foo.BASE is a directory if there's a conflict
1708
        base.tt.new_directory('h', base.root, 'h')
1534.7.93 by Aaron Bentley
Added text merge test
1709
        base.tt.apply()
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1710
        other = TransformGroup("other", root_id)
1534.7.93 by Aaron Bentley
Added text merge test
1711
        other.tt.new_file('a', other.root, 'y\nb\nc\nd\be\n', 'a')
1534.7.95 by Aaron Bentley
Added more text merge tests
1712
        other.tt.new_file('b', other.root, 'b2', 'b')
1713
        other.tt.new_file('c', other.root, 'c2', 'c')
1714
        other.tt.new_file('d', other.root, 'd', 'd')
1715
        other.tt.new_file('e', other.root, 'e2', 'e')
1716
        other.tt.new_file('f', other.root, 'f', 'f')
1534.7.96 by Aaron Bentley
Tested with BASE as directory
1717
        other.tt.new_file('g', other.root, 'g', 'g')
1534.7.97 by Aaron Bentley
Ensured foo.BASE is a directory if there's a conflict
1718
        other.tt.new_file('h', other.root, 'h\ni\nj\nk\n', 'h')
1534.7.99 by Aaron Bentley
Handle non-existent BASE properly
1719
        other.tt.new_file('i', other.root, 'h\ni\nj\nk\n', 'i')
1534.7.93 by Aaron Bentley
Added text merge test
1720
        other.tt.apply()
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1721
        this = TransformGroup("this", root_id)
1534.7.93 by Aaron Bentley
Added text merge test
1722
        this.tt.new_file('a', this.root, 'a\nb\nc\nd\bz\n', 'a')
1534.7.95 by Aaron Bentley
Added more text merge tests
1723
        this.tt.new_file('b', this.root, 'b', 'b')
1724
        this.tt.new_file('c', this.root, 'c', 'c')
1725
        this.tt.new_file('d', this.root, 'd2', 'd')
1726
        this.tt.new_file('e', this.root, 'e2', 'e')
1727
        this.tt.new_file('f', this.root, 'f', 'f')
1534.7.96 by Aaron Bentley
Tested with BASE as directory
1728
        this.tt.new_file('g', this.root, 'g', 'g')
1534.7.97 by Aaron Bentley
Ensured foo.BASE is a directory if there's a conflict
1729
        this.tt.new_file('h', this.root, '1\n2\n3\n4\n', 'h')
1534.7.99 by Aaron Bentley
Handle non-existent BASE properly
1730
        this.tt.new_file('i', this.root, '1\n2\n3\n4\n', 'i')
1534.7.93 by Aaron Bentley
Added text merge test
1731
        this.tt.apply()
3008.1.11 by Michael Hudson
restore the default behaviour of Merge3Merger.__init__().
1732
        Merge3Merger(this.wt, this.wt, base.wt, other.wt)
3008.1.6 by Michael Hudson
chop up Merge3Merger.__init__ into pieces
1733
1534.7.95 by Aaron Bentley
Added more text merge tests
1734
        # textual merge
1534.7.93 by Aaron Bentley
Added text merge test
1735
        self.assertEqual(this.wt.get_file('a').read(), 'y\nb\nc\nd\bz\n')
1534.7.95 by Aaron Bentley
Added more text merge tests
1736
        # three-way text conflict
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1737
        self.assertEqual(this.wt.get_file('b').read(),
1534.7.95 by Aaron Bentley
Added more text merge tests
1738
                         conflict_text('b', 'b2'))
1739
        # OTHER wins
1740
        self.assertEqual(this.wt.get_file('c').read(), 'c2')
1741
        # THIS wins
1742
        self.assertEqual(this.wt.get_file('d').read(), 'd2')
1743
        # Ambigious clean merge
1744
        self.assertEqual(this.wt.get_file('e').read(), 'e2')
1745
        # No change
1746
        self.assertEqual(this.wt.get_file('f').read(), 'f')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1747
        # Correct correct results when THIS == OTHER
1534.7.96 by Aaron Bentley
Tested with BASE as directory
1748
        self.assertEqual(this.wt.get_file('g').read(), 'g')
1534.7.97 by Aaron Bentley
Ensured foo.BASE is a directory if there's a conflict
1749
        # Text conflict when THIS & OTHER are text and BASE is dir
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1750
        self.assertEqual(this.wt.get_file('h').read(),
1534.7.97 by Aaron Bentley
Ensured foo.BASE is a directory if there's a conflict
1751
                         conflict_text('1\n2\n3\n4\n', 'h\ni\nj\nk\n'))
1752
        self.assertEqual(this.wt.get_file_byname('h.THIS').read(),
1753
                         '1\n2\n3\n4\n')
1754
        self.assertEqual(this.wt.get_file_byname('h.OTHER').read(),
1755
                         'h\ni\nj\nk\n')
1756
        self.assertEqual(file_kind(this.wt.abspath('h.BASE')), 'directory')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1757
        self.assertEqual(this.wt.get_file('i').read(),
1534.7.99 by Aaron Bentley
Handle non-existent BASE properly
1758
                         conflict_text('1\n2\n3\n4\n', 'h\ni\nj\nk\n'))
1759
        self.assertEqual(this.wt.get_file_byname('i.THIS').read(),
1760
                         '1\n2\n3\n4\n')
1761
        self.assertEqual(this.wt.get_file_byname('i.OTHER').read(),
1762
                         'h\ni\nj\nk\n')
1763
        self.assertEqual(os.path.exists(this.wt.abspath('i.BASE')), False)
1534.7.192 by Aaron Bentley
Record hashes produced by merges
1764
        modified = ['a', 'b', 'c', 'h', 'i']
1765
        merge_modified = this.wt.merge_modified()
1766
        self.assertSubset(merge_modified, modified)
1767
        self.assertEqual(len(merge_modified), len(modified))
1768
        file(this.wt.id2abspath('a'), 'wb').write('booga')
1769
        modified.pop(0)
1770
        merge_modified = this.wt.merge_modified()
1771
        self.assertSubset(merge_modified, modified)
1772
        self.assertEqual(len(merge_modified), len(modified))
1558.12.10 by Aaron Bentley
Be robust when merge_hash file_id not in inventory
1773
        this.wt.remove('b')
2796.1.4 by Aaron Bentley
Fix up various test cases
1774
        this.wt.revert()
1534.7.101 by Aaron Bentley
Got conflicts on symlinks working properly
1775
1776
    def test_file_merge(self):
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
1777
        self.requireFeature(SymlinkFeature)
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
1778
        root_id = generate_ids.gen_root_id()
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1779
        base = TransformGroup("BASE", root_id)
1780
        this = TransformGroup("THIS", root_id)
1781
        other = TransformGroup("OTHER", root_id)
1534.7.101 by Aaron Bentley
Got conflicts on symlinks working properly
1782
        for tg in this, base, other:
1783
            tg.tt.new_directory('a', tg.root, 'a')
1784
            tg.tt.new_symlink('b', tg.root, 'b', 'b')
1785
            tg.tt.new_file('c', tg.root, 'c', 'c')
1786
            tg.tt.new_symlink('d', tg.root, tg.name, 'd')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1787
        targets = ((base, 'base-e', 'base-f', None, None),
1788
                   (this, 'other-e', 'this-f', 'other-g', 'this-h'),
1534.7.104 by Aaron Bentley
Fixed set_versioned, enhanced conflict testing
1789
                   (other, 'other-e', None, 'other-g', 'other-h'))
1790
        for tg, e_target, f_target, g_target, h_target in targets:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1791
            for link, target in (('e', e_target), ('f', f_target),
1534.7.104 by Aaron Bentley
Fixed set_versioned, enhanced conflict testing
1792
                                 ('g', g_target), ('h', h_target)):
1793
                if target is not None:
1794
                    tg.tt.new_symlink(link, tg.root, target, link)
1534.7.102 by Aaron Bentley
Deleted old pre-conflict contents
1795
1796
        for tg in this, base, other:
1534.7.101 by Aaron Bentley
Got conflicts on symlinks working properly
1797
            tg.tt.apply()
3008.1.11 by Michael Hudson
restore the default behaviour of Merge3Merger.__init__().
1798
        Merge3Merger(this.wt, this.wt, base.wt, other.wt)
1534.7.101 by Aaron Bentley
Got conflicts on symlinks working properly
1799
        self.assertIs(os.path.isdir(this.wt.abspath('a')), True)
1800
        self.assertIs(os.path.islink(this.wt.abspath('b')), True)
1801
        self.assertIs(os.path.isfile(this.wt.abspath('c')), True)
1802
        for suffix in ('THIS', 'BASE', 'OTHER'):
1803
            self.assertEqual(os.readlink(this.wt.abspath('d.'+suffix)), suffix)
1534.7.102 by Aaron Bentley
Deleted old pre-conflict contents
1804
        self.assertIs(os.path.lexists(this.wt.abspath('d')), False)
1534.7.104 by Aaron Bentley
Fixed set_versioned, enhanced conflict testing
1805
        self.assertEqual(this.wt.id2path('d'), 'd.OTHER')
1806
        self.assertEqual(this.wt.id2path('f'), 'f.THIS')
1534.7.102 by Aaron Bentley
Deleted old pre-conflict contents
1807
        self.assertEqual(os.readlink(this.wt.abspath('e')), 'other-e')
1808
        self.assertIs(os.path.lexists(this.wt.abspath('e.THIS')), False)
1809
        self.assertIs(os.path.lexists(this.wt.abspath('e.OTHER')), False)
1810
        self.assertIs(os.path.lexists(this.wt.abspath('e.BASE')), False)
1534.7.104 by Aaron Bentley
Fixed set_versioned, enhanced conflict testing
1811
        self.assertIs(os.path.lexists(this.wt.abspath('g')), True)
1812
        self.assertIs(os.path.lexists(this.wt.abspath('g.BASE')), False)
1813
        self.assertIs(os.path.lexists(this.wt.abspath('h')), False)
1814
        self.assertIs(os.path.lexists(this.wt.abspath('h.BASE')), False)
1815
        self.assertIs(os.path.lexists(this.wt.abspath('h.THIS')), True)
1816
        self.assertIs(os.path.lexists(this.wt.abspath('h.OTHER')), True)
1534.7.105 by Aaron Bentley
Got merge with rename working
1817
1818
    def test_filename_merge(self):
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
1819
        root_id = generate_ids.gen_root_id()
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1820
        base = TransformGroup("BASE", root_id)
1821
        this = TransformGroup("THIS", root_id)
1822
        other = TransformGroup("OTHER", root_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1823
        base_a, this_a, other_a = [t.tt.new_directory('a', t.root, 'a')
1534.7.105 by Aaron Bentley
Got merge with rename working
1824
                                   for t in [base, this, other]]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1825
        base_b, this_b, other_b = [t.tt.new_directory('b', t.root, 'b')
1534.7.105 by Aaron Bentley
Got merge with rename working
1826
                                   for t in [base, this, other]]
1827
        base.tt.new_directory('c', base_a, 'c')
1828
        this.tt.new_directory('c1', this_a, 'c')
1829
        other.tt.new_directory('c', other_b, 'c')
1830
1831
        base.tt.new_directory('d', base_a, 'd')
1832
        this.tt.new_directory('d1', this_b, 'd')
1833
        other.tt.new_directory('d', other_a, 'd')
1834
1835
        base.tt.new_directory('e', base_a, 'e')
1836
        this.tt.new_directory('e', this_a, 'e')
1837
        other.tt.new_directory('e1', other_b, 'e')
1838
1839
        base.tt.new_directory('f', base_a, 'f')
1840
        this.tt.new_directory('f1', this_b, 'f')
1841
        other.tt.new_directory('f1', other_b, 'f')
1842
1843
        for tg in [this, base, other]:
1844
            tg.tt.apply()
3008.1.11 by Michael Hudson
restore the default behaviour of Merge3Merger.__init__().
1845
        Merge3Merger(this.wt, this.wt, base.wt, other.wt)
1534.7.176 by abentley
Fixed up tests for Windows
1846
        self.assertEqual(this.wt.id2path('c'), pathjoin('b/c1'))
1847
        self.assertEqual(this.wt.id2path('d'), pathjoin('b/d1'))
1848
        self.assertEqual(this.wt.id2path('e'), pathjoin('b/e1'))
1849
        self.assertEqual(this.wt.id2path('f'), pathjoin('b/f1'))
1534.7.105 by Aaron Bentley
Got merge with rename working
1850
1851
    def test_filename_merge_conflicts(self):
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
1852
        root_id = generate_ids.gen_root_id()
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1853
        base = TransformGroup("BASE", root_id)
1854
        this = TransformGroup("THIS", root_id)
1855
        other = TransformGroup("OTHER", root_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1856
        base_a, this_a, other_a = [t.tt.new_directory('a', t.root, 'a')
1534.7.105 by Aaron Bentley
Got merge with rename working
1857
                                   for t in [base, this, other]]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1858
        base_b, this_b, other_b = [t.tt.new_directory('b', t.root, 'b')
1534.7.105 by Aaron Bentley
Got merge with rename working
1859
                                   for t in [base, this, other]]
1860
1861
        base.tt.new_file('g', base_a, 'g', 'g')
1862
        other.tt.new_file('g1', other_b, 'g1', 'g')
1863
1864
        base.tt.new_file('h', base_a, 'h', 'h')
1865
        this.tt.new_file('h1', this_b, 'h1', 'h')
1866
1867
        base.tt.new_file('i', base.root, 'i', 'i')
1534.7.153 by Aaron Bentley
Handled test cases involving symlinks
1868
        other.tt.new_directory('i1', this_b, 'i')
1534.7.105 by Aaron Bentley
Got merge with rename working
1869
1870
        for tg in [this, base, other]:
1871
            tg.tt.apply()
3008.1.11 by Michael Hudson
restore the default behaviour of Merge3Merger.__init__().
1872
        Merge3Merger(this.wt, this.wt, base.wt, other.wt)
1534.7.105 by Aaron Bentley
Got merge with rename working
1873
1534.7.176 by abentley
Fixed up tests for Windows
1874
        self.assertEqual(this.wt.id2path('g'), pathjoin('b/g1.OTHER'))
1534.7.105 by Aaron Bentley
Got merge with rename working
1875
        self.assertIs(os.path.lexists(this.wt.abspath('b/g1.BASE')), True)
1876
        self.assertIs(os.path.lexists(this.wt.abspath('b/g1.THIS')), False)
1534.7.176 by abentley
Fixed up tests for Windows
1877
        self.assertEqual(this.wt.id2path('h'), pathjoin('b/h1.THIS'))
1534.7.105 by Aaron Bentley
Got merge with rename working
1878
        self.assertIs(os.path.lexists(this.wt.abspath('b/h1.BASE')), True)
1879
        self.assertIs(os.path.lexists(this.wt.abspath('b/h1.OTHER')), False)
1534.7.176 by abentley
Fixed up tests for Windows
1880
        self.assertEqual(this.wt.id2path('i'), pathjoin('b/i1.OTHER'))
1534.7.183 by Aaron Bentley
Fixed build_tree with symlinks
1881
2027.1.1 by John Arbash Meinel
Fix bug #56549, and write a direct test that the right path is being statted
1882
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1883
class TestBuildTree(tests.TestCaseWithTransport):
1884
3006.2.2 by Alexander Belchenko
tests added.
1885
    def test_build_tree_with_symlinks(self):
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
1886
        self.requireFeature(SymlinkFeature)
1534.7.183 by Aaron Bentley
Fixed build_tree with symlinks
1887
        os.mkdir('a')
1888
        a = BzrDir.create_standalone_workingtree('a')
1889
        os.mkdir('a/foo')
1890
        file('a/foo/bar', 'wb').write('contents')
1891
        os.symlink('a/foo/bar', 'a/foo/baz')
1892
        a.add(['foo', 'foo/bar', 'foo/baz'])
1893
        a.commit('initial commit')
1894
        b = BzrDir.create_standalone_workingtree('b')
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
1895
        basis = a.basis_tree()
1896
        basis.lock_read()
1897
        self.addCleanup(basis.unlock)
1898
        build_tree(basis, b)
1534.7.183 by Aaron Bentley
Fixed build_tree with symlinks
1899
        self.assertIs(os.path.isdir('b/foo'), True)
1900
        self.assertEqual(file('b/foo/bar', 'rb').read(), "contents")
1901
        self.assertEqual(os.readlink('b/foo/baz'), 'a/foo/bar')
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1902
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
1903
    def test_build_with_references(self):
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
1904
        tree = self.make_branch_and_tree('source',
1905
            format='dirstate-with-subtree')
1906
        subtree = self.make_branch_and_tree('source/subtree',
1907
            format='dirstate-with-subtree')
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
1908
        tree.add_reference(subtree)
1909
        tree.commit('a revision')
1910
        tree.branch.create_checkout('target')
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1911
        self.assertPathExists('target')
1912
        self.assertPathExists('target/subtree')
2100.3.21 by Aaron Bentley
Work on checking out by-reference trees
1913
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1914
    def test_file_conflict_handling(self):
1915
        """Ensure that when building trees, conflict handling is done"""
1916
        source = self.make_branch_and_tree('source')
1917
        target = self.make_branch_and_tree('target')
1918
        self.build_tree(['source/file', 'target/file'])
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1919
        source.add('file', 'new-file')
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1920
        source.commit('added file')
1921
        build_tree(source.basis_tree(), target)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1922
        self.assertEqual([DuplicateEntry('Moved existing file to',
1923
                          'file.moved', 'file', None, 'new-file')],
1924
                         target.conflicts())
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1925
        target2 = self.make_branch_and_tree('target2')
1926
        target_file = file('target2/file', 'wb')
1927
        try:
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1928
            source_file = file('source/file', 'rb')
1929
            try:
1930
                target_file.write(source_file.read())
1931
            finally:
1932
                source_file.close()
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1933
        finally:
1934
            target_file.close()
1935
        build_tree(source.basis_tree(), target2)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1936
        self.assertEqual([], target2.conflicts())
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1937
1938
    def test_symlink_conflict_handling(self):
1939
        """Ensure that when building trees, conflict handling is done"""
2949.5.1 by Alexander Belchenko
selftest: use SymlinkFeature instead of TestSkipped where appropriate
1940
        self.requireFeature(SymlinkFeature)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1941
        source = self.make_branch_and_tree('source')
1942
        os.symlink('foo', 'source/symlink')
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1943
        source.add('symlink', 'new-symlink')
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1944
        source.commit('added file')
1945
        target = self.make_branch_and_tree('target')
1946
        os.symlink('bar', 'target/symlink')
1947
        build_tree(source.basis_tree(), target)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1948
        self.assertEqual([DuplicateEntry('Moved existing file to',
1949
            'symlink.moved', 'symlink', None, 'new-symlink')],
1950
            target.conflicts())
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1951
        target = self.make_branch_and_tree('target2')
1952
        os.symlink('foo', 'target2/symlink')
1953
        build_tree(source.basis_tree(), target)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1954
        self.assertEqual([], target.conflicts())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1955
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1956
    def test_directory_conflict_handling(self):
1957
        """Ensure that when building trees, conflict handling is done"""
1958
        source = self.make_branch_and_tree('source')
1959
        target = self.make_branch_and_tree('target')
1960
        self.build_tree(['source/dir1/', 'source/dir1/file', 'target/dir1/'])
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1961
        source.add(['dir1', 'dir1/file'], ['new-dir1', 'new-file'])
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1962
        source.commit('added file')
1963
        build_tree(source.basis_tree(), target)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1964
        self.assertEqual([], target.conflicts())
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1965
        self.assertPathExists('target/dir1/file')
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1966
1967
        # Ensure contents are merged
1968
        target = self.make_branch_and_tree('target2')
1969
        self.build_tree(['target2/dir1/', 'target2/dir1/file2'])
1970
        build_tree(source.basis_tree(), target)
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1971
        self.assertEqual([], target.conflicts())
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1972
        self.assertPathExists('target2/dir1/file2')
1973
        self.assertPathExists('target2/dir1/file')
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1974
1975
        # Ensure new contents are suppressed for existing branches
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1976
        target = self.make_branch_and_tree('target3')
1977
        self.make_branch('target3/dir1')
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1978
        self.build_tree(['target3/dir1/file2'])
1979
        build_tree(source.basis_tree(), target)
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1980
        self.assertPathDoesNotExist('target3/dir1/file')
1981
        self.assertPathExists('target3/dir1/file2')
1982
        self.assertPathExists('target3/dir1.diverted/file')
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1983
        self.assertEqual([DuplicateEntry('Diverted to',
1984
            'dir1.diverted', 'dir1', 'new-dir1', None)],
1985
            target.conflicts())
1986
1987
        target = self.make_branch_and_tree('target4')
1988
        self.build_tree(['target4/dir1/'])
1989
        self.make_branch('target4/dir1/file')
1990
        build_tree(source.basis_tree(), target)
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1991
        self.assertPathExists('target4/dir1/file')
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1992
        self.assertEqual('directory', file_kind('target4/dir1/file'))
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
1993
        self.assertPathExists('target4/dir1/file.diverted')
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
1994
        self.assertEqual([DuplicateEntry('Diverted to',
1995
            'dir1/file.diverted', 'dir1/file', 'new-file', None)],
1996
            target.conflicts())
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
1997
1998
    def test_mixed_conflict_handling(self):
1999
        """Ensure that when building trees, conflict handling is done"""
2000
        source = self.make_branch_and_tree('source')
2001
        target = self.make_branch_and_tree('target')
2002
        self.build_tree(['source/name', 'target/name/'])
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2003
        source.add('name', 'new-name')
2004
        source.commit('added file')
2005
        build_tree(source.basis_tree(), target)
2006
        self.assertEqual([DuplicateEntry('Moved existing file to',
2007
            'name.moved', 'name', None, 'new-name')], target.conflicts())
2008
2009
    def test_raises_in_populated(self):
2010
        source = self.make_branch_and_tree('source')
2011
        self.build_tree(['source/name'])
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2012
        source.add('name')
1966.1.2 by Aaron Bentley
Divert files instead of failing to create them, update from review
2013
        source.commit('added name')
2014
        target = self.make_branch_and_tree('target')
2015
        self.build_tree(['target/name'])
2016
        target.add('name')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2017
        self.assertRaises(errors.WorkingTreeAlreadyPopulated,
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
2018
            build_tree, source.basis_tree(), target)
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2019
2502.1.1 by Aaron Bentley
Ensure renames only root children are renamed when building trees
2020
    def test_build_tree_rename_count(self):
2021
        source = self.make_branch_and_tree('source')
2022
        self.build_tree(['source/file1', 'source/dir1/'])
2023
        source.add(['file1', 'dir1'])
2024
        source.commit('add1')
2025
        target1 = self.make_branch_and_tree('target1')
2502.1.6 by Aaron Bentley
Update from review comments
2026
        transform_result = build_tree(source.basis_tree(), target1)
2027
        self.assertEqual(2, transform_result.rename_count)
2502.1.1 by Aaron Bentley
Ensure renames only root children are renamed when building trees
2028
2029
        self.build_tree(['source/dir1/file2'])
2030
        source.add(['dir1/file2'])
2031
        source.commit('add3')
2032
        target2 = self.make_branch_and_tree('target2')
2502.1.6 by Aaron Bentley
Update from review comments
2033
        transform_result = build_tree(source.basis_tree(), target2)
2502.1.1 by Aaron Bentley
Ensure renames only root children are renamed when building trees
2034
        # children of non-root directories should not be renamed
2502.1.6 by Aaron Bentley
Update from review comments
2035
        self.assertEqual(2, transform_result.rename_count)
2502.1.1 by Aaron Bentley
Ensure renames only root children are renamed when building trees
2036
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2037
    def create_ab_tree(self):
2038
        """Create a committed test tree with two files"""
2039
        source = self.make_branch_and_tree('source')
2040
        self.build_tree_contents([('source/file1', 'A')])
2041
        self.build_tree_contents([('source/file2', 'B')])
2042
        source.add(['file1', 'file2'], ['file1-id', 'file2-id'])
2043
        source.commit('commit files')
2044
        source.lock_write()
2045
        self.addCleanup(source.unlock)
2046
        return source
2047
3123.5.1 by Aaron Bentley
Make build-tree able to use an additional 'accelerator' tree
2048
    def test_build_tree_accelerator_tree(self):
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2049
        source = self.create_ab_tree()
3123.5.1 by Aaron Bentley
Make build-tree able to use an additional 'accelerator' tree
2050
        self.build_tree_contents([('source/file2', 'C')])
2051
        calls = []
2052
        real_source_get_file = source.get_file
2053
        def get_file(file_id, path=None):
2054
            calls.append(file_id)
2055
            return real_source_get_file(file_id, path)
2056
        source.get_file = get_file
2057
        target = self.make_branch_and_tree('target')
3123.5.19 by Aaron Bentley
Ensure content is exactly the same, when accelerator used
2058
        revision_tree = source.basis_tree()
2059
        revision_tree.lock_read()
2060
        self.addCleanup(revision_tree.unlock)
2061
        build_tree(revision_tree, target, source)
3123.5.1 by Aaron Bentley
Make build-tree able to use an additional 'accelerator' tree
2062
        self.assertEqual(['file1-id'], calls)
3123.5.19 by Aaron Bentley
Ensure content is exactly the same, when accelerator used
2063
        target.lock_read()
2064
        self.addCleanup(target.unlock)
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2065
        self.assertEqual([], list(target.iter_changes(revision_tree)))
3123.5.1 by Aaron Bentley
Make build-tree able to use an additional 'accelerator' tree
2066
5752.5.1 by John Arbash Meinel
Merge up transform-create-file
2067
    def test_build_tree_accelerator_tree_observes_sha1(self):
2068
        source = self.create_ab_tree()
2069
        sha1 = osutils.sha_string('A')
2070
        target = self.make_branch_and_tree('target')
2071
        target.lock_write()
2072
        self.addCleanup(target.unlock)
2073
        state = target.current_dirstate()
2074
        state._cutoff_time = time.time() + 60
2075
        build_tree(source.basis_tree(), target, source)
2076
        entry = state._get_entry(0, path_utf8='file1')
2077
        self.assertEqual(sha1, entry[1][0][1])
2078
3123.5.4 by Aaron Bentley
Use an accelerator tree when branching, handle no-such-id correctly
2079
    def test_build_tree_accelerator_tree_missing_file(self):
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2080
        source = self.create_ab_tree()
3123.5.4 by Aaron Bentley
Use an accelerator tree when branching, handle no-such-id correctly
2081
        os.unlink('source/file1')
2082
        source.remove(['file2'])
2083
        target = self.make_branch_and_tree('target')
3123.5.19 by Aaron Bentley
Ensure content is exactly the same, when accelerator used
2084
        revision_tree = source.basis_tree()
2085
        revision_tree.lock_read()
2086
        self.addCleanup(revision_tree.unlock)
2087
        build_tree(revision_tree, target, source)
2088
        target.lock_read()
2089
        self.addCleanup(target.unlock)
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2090
        self.assertEqual([], list(target.iter_changes(revision_tree)))
3123.5.4 by Aaron Bentley
Use an accelerator tree when branching, handle no-such-id correctly
2091
3123.5.16 by Aaron Bentley
Test handling of conversion to non-file
2092
    def test_build_tree_accelerator_wrong_kind(self):
3146.4.8 by Aaron Bentley
Add missing symlink requirement
2093
        self.requireFeature(SymlinkFeature)
3123.5.16 by Aaron Bentley
Test handling of conversion to non-file
2094
        source = self.make_branch_and_tree('source')
2095
        self.build_tree_contents([('source/file1', '')])
2096
        self.build_tree_contents([('source/file2', '')])
2097
        source.add(['file1', 'file2'], ['file1-id', 'file2-id'])
2098
        source.commit('commit files')
2099
        os.unlink('source/file2')
2100
        self.build_tree_contents([('source/file2/', 'C')])
2101
        os.unlink('source/file1')
2102
        os.symlink('file2', 'source/file1')
2103
        calls = []
2104
        real_source_get_file = source.get_file
2105
        def get_file(file_id, path=None):
2106
            calls.append(file_id)
2107
            return real_source_get_file(file_id, path)
2108
        source.get_file = get_file
2109
        target = self.make_branch_and_tree('target')
3123.5.19 by Aaron Bentley
Ensure content is exactly the same, when accelerator used
2110
        revision_tree = source.basis_tree()
2111
        revision_tree.lock_read()
2112
        self.addCleanup(revision_tree.unlock)
2113
        build_tree(revision_tree, target, source)
3123.5.16 by Aaron Bentley
Test handling of conversion to non-file
2114
        self.assertEqual([], calls)
3123.5.19 by Aaron Bentley
Ensure content is exactly the same, when accelerator used
2115
        target.lock_read()
2116
        self.addCleanup(target.unlock)
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2117
        self.assertEqual([], list(target.iter_changes(revision_tree)))
3123.5.16 by Aaron Bentley
Test handling of conversion to non-file
2118
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2119
    def test_build_tree_hardlink(self):
2120
        self.requireFeature(HardlinkFeature)
2121
        source = self.create_ab_tree()
2122
        target = self.make_branch_and_tree('target')
2123
        revision_tree = source.basis_tree()
2124
        revision_tree.lock_read()
2125
        self.addCleanup(revision_tree.unlock)
2126
        build_tree(revision_tree, target, source, hardlink=True)
2127
        target.lock_read()
2128
        self.addCleanup(target.unlock)
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2129
        self.assertEqual([], list(target.iter_changes(revision_tree)))
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2130
        source_stat = os.stat('source/file1')
2131
        target_stat = os.stat('target/file1')
2132
        self.assertEqual(source_stat, target_stat)
2133
2134
        # Explicitly disallowing hardlinks should prevent them.
2135
        target2 = self.make_branch_and_tree('target2')
2136
        build_tree(revision_tree, target2, source, hardlink=False)
2137
        target2.lock_read()
2138
        self.addCleanup(target2.unlock)
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2139
        self.assertEqual([], list(target2.iter_changes(revision_tree)))
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2140
        source_stat = os.stat('source/file1')
2141
        target2_stat = os.stat('target2/file1')
2142
        self.assertNotEqual(source_stat, target2_stat)
2143
3137.1.1 by Aaron Bentley
Fix build_tree acceleration when file is moved in accelerator_tree
2144
    def test_build_tree_accelerator_tree_moved(self):
2145
        source = self.make_branch_and_tree('source')
2146
        self.build_tree_contents([('source/file1', 'A')])
2147
        source.add(['file1'], ['file1-id'])
2148
        source.commit('commit files')
2149
        source.rename_one('file1', 'file2')
2150
        source.lock_read()
2151
        self.addCleanup(source.unlock)
2152
        target = self.make_branch_and_tree('target')
2153
        revision_tree = source.basis_tree()
2154
        revision_tree.lock_read()
2155
        self.addCleanup(revision_tree.unlock)
2156
        build_tree(revision_tree, target, source)
2157
        target.lock_read()
2158
        self.addCleanup(target.unlock)
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2159
        self.assertEqual([], list(target.iter_changes(revision_tree)))
3137.1.1 by Aaron Bentley
Fix build_tree acceleration when file is moved in accelerator_tree
2160
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2161
    def test_build_tree_hardlinks_preserve_execute(self):
2162
        self.requireFeature(HardlinkFeature)
2163
        source = self.create_ab_tree()
2164
        tt = TreeTransform(source)
2165
        trans_id = tt.trans_id_tree_file_id('file1-id')
2166
        tt.set_executability(True, trans_id)
2167
        tt.apply()
2168
        self.assertTrue(source.is_executable('file1-id'))
2169
        target = self.make_branch_and_tree('target')
2170
        revision_tree = source.basis_tree()
2171
        revision_tree.lock_read()
2172
        self.addCleanup(revision_tree.unlock)
2173
        build_tree(revision_tree, target, source, hardlink=True)
2174
        target.lock_read()
2175
        self.addCleanup(target.unlock)
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2176
        self.assertEqual([], list(target.iter_changes(revision_tree)))
3136.1.2 by Aaron Bentley
Implement hard-linking for build_tree
2177
        self.assertTrue(source.is_executable('file1-id'))
2178
4826.1.5 by Andrew Bennetts
Add test that content filtered files are not hardlinked by build_tree.
2179
    def install_rot13_content_filter(self, pattern):
4985.2.1 by Vincent Ladeuil
Deploy addAttrCleanup on the whole test suite.
2180
        # We could use
2181
        # self.addCleanup(filters._reset_registry, filters._reset_registry())
2182
        # below, but that looks a bit... hard to read even if it's exactly
2183
        # the same thing.
4826.1.5 by Andrew Bennetts
Add test that content filtered files are not hardlinked by build_tree.
2184
        original_registry = filters._reset_registry()
2185
        def restore_registry():
2186
            filters._reset_registry(original_registry)
2187
        self.addCleanup(restore_registry)
2188
        def rot13(chunks, context=None):
2189
            return [''.join(chunks).encode('rot13')]
2190
        rot13filter = filters.ContentFilter(rot13, rot13)
2191
        filters.register_filter_stack_map('rot13', {'yes': [rot13filter]}.get)
2192
        os.mkdir(self.test_home_dir + '/.bazaar')
2193
        rules_filename = self.test_home_dir + '/.bazaar/rules'
4826.1.8 by Andrew Bennetts
Tweaks suggested by John.
2194
        f = open(rules_filename, 'wb')
4826.1.5 by Andrew Bennetts
Add test that content filtered files are not hardlinked by build_tree.
2195
        f.write('[name %s]\nrot13=yes\n' % (pattern,))
2196
        f.close()
2197
        def uninstall_rules():
2198
            os.remove(rules_filename)
2199
            rules.reset_rules()
2200
        self.addCleanup(uninstall_rules)
2201
        rules.reset_rules()
2202
2203
    def test_build_tree_content_filtered_files_are_not_hardlinked(self):
2204
        """build_tree will not hardlink files that have content filtering rules
2205
        applied to them (but will still hardlink other files from the same tree
2206
        if it can).
2207
        """
2208
        self.requireFeature(HardlinkFeature)
2209
        self.install_rot13_content_filter('file1')
2210
        source = self.create_ab_tree()
2211
        target = self.make_branch_and_tree('target')
2212
        revision_tree = source.basis_tree()
2213
        revision_tree.lock_read()
2214
        self.addCleanup(revision_tree.unlock)
2215
        build_tree(revision_tree, target, source, hardlink=True)
2216
        target.lock_read()
2217
        self.addCleanup(target.unlock)
2218
        self.assertEqual([], list(target.iter_changes(revision_tree)))
2219
        source_stat = os.stat('source/file1')
2220
        target_stat = os.stat('target/file1')
2221
        self.assertNotEqual(source_stat, target_stat)
2222
        source_stat = os.stat('source/file2')
2223
        target_stat = os.stat('target/file2')
4826.1.8 by Andrew Bennetts
Tweaks suggested by John.
2224
        self.assertEqualStat(source_stat, target_stat)
4826.1.5 by Andrew Bennetts
Add test that content filtered files are not hardlinked by build_tree.
2225
3453.2.4 by Aaron Bentley
Disable fast-path when conflicts are encountered
2226
    def test_case_insensitive_build_tree_inventory(self):
4241.14.12 by Vincent Ladeuil
Far too many modifications for a single commit, need to restart.
2227
        if (tests.CaseInsensitiveFilesystemFeature.available()
2228
            or tests.CaseInsCasePresFilenameFeature.available()):
4241.9.4 by Vincent Ladeuil
Fix test_case_insensitive_build_tree_inventory failure on OSX.
2229
            raise tests.UnavailableFeature('Fully case sensitive filesystem')
3453.2.4 by Aaron Bentley
Disable fast-path when conflicts are encountered
2230
        source = self.make_branch_and_tree('source')
2231
        self.build_tree(['source/file', 'source/FILE'])
2232
        source.add(['file', 'FILE'], ['lower-id', 'upper-id'])
2233
        source.commit('added files')
2234
        # Don't try this at home, kids!
2235
        # Force the tree to report that it is case insensitive
2236
        target = self.make_branch_and_tree('target')
2237
        target.case_sensitive = False
3453.2.6 by Aaron Bentley
Rename mutate_tree to delta_from_tree, add comment
2238
        build_tree(source.basis_tree(), target, source, delta_from_tree=True)
3453.2.4 by Aaron Bentley
Disable fast-path when conflicts are encountered
2239
        self.assertEqual('file.moved', target.id2path('lower-id'))
2240
        self.assertEqual('FILE', target.id2path('upper-id'))
2241
5752.5.1 by John Arbash Meinel
Merge up transform-create-file
2242
    def test_build_tree_observes_sha(self):
2243
        source = self.make_branch_and_tree('source')
2244
        self.build_tree(['source/file1', 'source/dir/', 'source/dir/file2'])
2245
        source.add(['file1', 'dir', 'dir/file2'],
2246
                   ['file1-id', 'dir-id', 'file2-id'])
2247
        source.commit('new files')
2248
        target = self.make_branch_and_tree('target')
2249
        target.lock_write()
2250
        self.addCleanup(target.unlock)
2251
        # We make use of the fact that DirState caches its cutoff time. So we
2252
        # set the 'safe' time to one minute in the future.
2253
        state = target.current_dirstate()
2254
        state._cutoff_time = time.time() + 60
2255
        build_tree(source.basis_tree(), target)
2256
        entry1_sha = osutils.sha_file_by_name('source/file1')
2257
        entry2_sha = osutils.sha_file_by_name('source/dir/file2')
2258
        # entry[1] is the state information, entry[1][0] is the state of the
2259
        # working tree, entry[1][0][1] is the sha value for the current working
2260
        # tree
2261
        entry1 = state._get_entry(0, path_utf8='file1')
2262
        self.assertEqual(entry1_sha, entry1[1][0][1])
2263
        # The 'size' field must also be set.
2264
        self.assertEqual(25, entry1[1][0][2])
2265
        entry1_state = entry1[1][0]
2266
        entry2 = state._get_entry(0, path_utf8='dir/file2')
2267
        self.assertEqual(entry2_sha, entry2[1][0][1])
2268
        self.assertEqual(29, entry2[1][0][2])
2269
        entry2_state = entry2[1][0]
2270
        # Now, make sure that we don't have to re-read the content. The
2271
        # packed_stat should match exactly.
2272
        self.assertEqual(entry1_sha, target.get_file_sha1('file1-id', 'file1'))
2273
        self.assertEqual(entry2_sha,
2274
                         target.get_file_sha1('file2-id', 'dir/file2'))
2275
        self.assertEqual(entry1_state, entry1[1][0])
2276
        self.assertEqual(entry2_state, entry2[1][0])
2277
1966.1.1 by Aaron Bentley
Implement disk-content merge and conflict resolution for build_tree
2278
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
2279
class TestCommitTransform(tests.TestCaseWithTransport):
2280
2281
    def get_branch(self):
2282
        tree = self.make_branch_and_tree('tree')
2283
        tree.lock_write()
2284
        self.addCleanup(tree.unlock)
2285
        tree.commit('empty commit')
2286
        return tree.branch
2287
2288
    def get_branch_and_transform(self):
2289
        branch = self.get_branch()
2290
        tt = TransformPreview(branch.basis_tree())
2291
        self.addCleanup(tt.finalize)
2292
        return branch, tt
2293
2294
    def test_commit_wrong_basis(self):
2295
        branch = self.get_branch()
2296
        basis = branch.repository.revision_tree(
2297
            _mod_revision.NULL_REVISION)
2298
        tt = TransformPreview(basis)
2299
        self.addCleanup(tt.finalize)
4526.8.5 by Aaron Bentley
Updates from review.
2300
        e = self.assertRaises(ValueError, tt.commit, branch, '')
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
2301
        self.assertEqual('TreeTransform not based on branch basis: null:',
2302
                         str(e))
2303
2304
    def test_empy_commit(self):
2305
        branch, tt = self.get_branch_and_transform()
2306
        rev = tt.commit(branch, 'my message')
2307
        self.assertEqual(2, branch.revno())
2308
        repo = branch.repository
2309
        self.assertEqual('my message', repo.get_revision(rev).message)
2310
2311
    def test_merge_parents(self):
2312
        branch, tt = self.get_branch_and_transform()
2313
        rev = tt.commit(branch, 'my message', ['rev1b', 'rev1c'])
2314
        self.assertEqual(['rev1b', 'rev1c'],
2315
                         branch.basis_tree().get_parent_ids()[1:])
2316
4526.8.3 by Aaron Bentley
Clean up merge parent handling.
2317
    def test_first_commit(self):
2318
        branch = self.make_branch('branch')
2319
        branch.lock_write()
2320
        self.addCleanup(branch.unlock)
2321
        tt = TransformPreview(branch.basis_tree())
4659.2.4 by Vincent Ladeuil
Cleanup remaining bzr-limbo-XXXXXX leaks in /tmp during selftest.
2322
        self.addCleanup(tt.finalize)
4526.9.23 by Robert Collins
Change the tree transform test_first_commit test to set a root id in the new tree, and workaround an apparent bug in TreeTransform._determine_path.
2323
        tt.new_directory('', ROOT_PARENT, 'TREE_ROOT')
4526.8.3 by Aaron Bentley
Clean up merge parent handling.
2324
        rev = tt.commit(branch, 'my message')
2325
        self.assertEqual([], branch.basis_tree().get_parent_ids())
4526.8.5 by Aaron Bentley
Updates from review.
2326
        self.assertNotEqual(_mod_revision.NULL_REVISION,
2327
                            branch.last_revision())
4526.8.3 by Aaron Bentley
Clean up merge parent handling.
2328
4526.8.5 by Aaron Bentley
Updates from review.
2329
    def test_first_commit_with_merge_parents(self):
4526.8.3 by Aaron Bentley
Clean up merge parent handling.
2330
        branch = self.make_branch('branch')
2331
        branch.lock_write()
2332
        self.addCleanup(branch.unlock)
2333
        tt = TransformPreview(branch.basis_tree())
4659.2.4 by Vincent Ladeuil
Cleanup remaining bzr-limbo-XXXXXX leaks in /tmp during selftest.
2334
        self.addCleanup(tt.finalize)
4526.8.5 by Aaron Bentley
Updates from review.
2335
        e = self.assertRaises(ValueError, tt.commit, branch,
4526.8.3 by Aaron Bentley
Clean up merge parent handling.
2336
                          'my message', ['rev1b-id'])
4526.8.5 by Aaron Bentley
Updates from review.
2337
        self.assertEqual('Cannot supply merge parents for first commit.',
2338
                         str(e))
2339
        self.assertEqual(_mod_revision.NULL_REVISION, branch.last_revision())
4526.8.3 by Aaron Bentley
Clean up merge parent handling.
2340
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
2341
    def test_add_files(self):
2342
        branch, tt = self.get_branch_and_transform()
2343
        tt.new_file('file', tt.root, 'contents', 'file-id')
2344
        trans_id = tt.new_directory('dir', tt.root, 'dir-id')
4789.25.2 by John Arbash Meinel
Fix 3 tests that meant to skip exec or symlink testing on win32
2345
        if SymlinkFeature.available():
2346
            tt.new_symlink('symlink', trans_id, 'target', 'symlink-id')
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
2347
        rev = tt.commit(branch, 'message')
2348
        tree = branch.basis_tree()
2349
        self.assertEqual('file', tree.id2path('file-id'))
2350
        self.assertEqual('contents', tree.get_file_text('file-id'))
2351
        self.assertEqual('dir', tree.id2path('dir-id'))
4789.25.2 by John Arbash Meinel
Fix 3 tests that meant to skip exec or symlink testing on win32
2352
        if SymlinkFeature.available():
2353
            self.assertEqual('dir/symlink', tree.id2path('symlink-id'))
2354
            self.assertEqual('target', tree.get_symlink_target('symlink-id'))
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
2355
4526.8.2 by Aaron Bentley
Proved strict commit handling.
2356
    def test_add_unversioned(self):
2357
        branch, tt = self.get_branch_and_transform()
2358
        tt.new_file('file', tt.root, 'contents')
2359
        self.assertRaises(errors.StrictCommitFailed, tt.commit, branch,
2360
                          'message', strict=True)
2361
2362
    def test_modify_strict(self):
2363
        branch, tt = self.get_branch_and_transform()
2364
        tt.new_file('file', tt.root, 'contents', 'file-id')
2365
        tt.commit(branch, 'message', strict=True)
2366
        tt = TransformPreview(branch.basis_tree())
4659.2.4 by Vincent Ladeuil
Cleanup remaining bzr-limbo-XXXXXX leaks in /tmp during selftest.
2367
        self.addCleanup(tt.finalize)
4526.8.2 by Aaron Bentley
Proved strict commit handling.
2368
        trans_id = tt.trans_id_file_id('file-id')
2369
        tt.delete_contents(trans_id)
2370
        tt.create_file('contents', trans_id)
2371
        tt.commit(branch, 'message', strict=True)
2372
4526.8.6 by Aaron Bentley
Check for malformed transforms before committing.
2373
    def test_commit_malformed(self):
2374
        """Committing a malformed transform should raise an exception.
2375
2376
        In this case, we are adding a file without adding its parent.
2377
        """
2378
        branch, tt = self.get_branch_and_transform()
2379
        parent_id = tt.trans_id_file_id('parent-id')
2380
        tt.new_file('file', parent_id, 'contents', 'file-id')
2381
        self.assertRaises(errors.MalformedTransform, tt.commit, branch,
2382
                          'message')
2383
5162.4.1 by Aaron Bentley
TreeTransform supports normal commit parameters and includes branch nick.
2384
    def test_commit_rich_revision_data(self):
2385
        branch, tt = self.get_branch_and_transform()
5162.4.3 by Aaron Bentley
Fix failing test.
2386
        rev_id = tt.commit(branch, 'message', timestamp=1, timezone=43201,
5162.4.1 by Aaron Bentley
TreeTransform supports normal commit parameters and includes branch nick.
2387
                           committer='me <me@example.com>',
2388
                           revprops={'foo': 'bar'}, revision_id='revid-1',
2389
                           authors=['Author1 <author1@example.com>',
2390
                              'Author2 <author2@example.com>',
2391
                               ])
2392
        self.assertEqual('revid-1', rev_id)
2393
        revision = branch.repository.get_revision(rev_id)
2394
        self.assertEqual(1, revision.timestamp)
5162.4.3 by Aaron Bentley
Fix failing test.
2395
        self.assertEqual(43201, revision.timezone)
5162.4.1 by Aaron Bentley
TreeTransform supports normal commit parameters and includes branch nick.
2396
        self.assertEqual('me <me@example.com>', revision.committer)
2397
        self.assertEqual(['Author1 <author1@example.com>',
2398
                          'Author2 <author2@example.com>'],
2399
                         revision.get_apparent_authors())
2400
        del revision.properties['authors']
2401
        self.assertEqual({'foo': 'bar',
2402
                          'branch-nick': 'tree'},
2403
                         revision.properties)
2404
2405
    def test_no_explicit_revprops(self):
2406
        branch, tt = self.get_branch_and_transform()
2407
        rev_id = tt.commit(branch, 'message', authors=[
2408
            'Author1 <author1@example.com>',
2409
            'Author2 <author2@example.com>', ])
2410
        revision = branch.repository.get_revision(rev_id)
2411
        self.assertEqual(['Author1 <author1@example.com>',
2412
                          'Author2 <author2@example.com>'],
2413
                         revision.get_apparent_authors())
2414
        self.assertEqual('tree', revision.properties['branch-nick'])
2415
4526.8.1 by Aaron Bentley
Support committing a TreeTransform to a branch.
2416
5409.1.11 by Vincent Ladeuil
Slightly cleanup bzrlib.transform and deprecate unused code.
2417
class TestBackupName(tests.TestCase):
2418
2419
    def test_deprecations(self):
2420
        class MockTransform(object):
2421
2422
            def has_named_child(self, by_parent, parent_id, name):
2423
                return name in by_parent.get(parent_id, [])
2424
2425
        class MockEntry(object):
2426
2427
            def __init__(self):
2428
                object.__init__(self)
2429
                self.name = "name"
2430
1534.10.28 by Aaron Bentley
Use numbered backup files
2431
        tt = MockTransform()
5409.1.11 by Vincent Ladeuil
Slightly cleanup bzrlib.transform and deprecate unused code.
2432
        name1 = self.applyDeprecated(
5409.8.4 by Vincent Ladeuil
Fix indentations.
2433
            symbol_versioning.deprecated_in((2, 3, 0)),
2434
            transform.get_backup_name, MockEntry(), {'a':[]}, 'a', tt)
5409.1.11 by Vincent Ladeuil
Slightly cleanup bzrlib.transform and deprecate unused code.
2435
        self.assertEqual('name.~1~', name1)
2436
        name2 = self.applyDeprecated(
5409.8.4 by Vincent Ladeuil
Fix indentations.
2437
            symbol_versioning.deprecated_in((2, 3, 0)),
2438
            transform._get_backup_name, 'name', {'a':['name.~1~']}, 'a', tt)
5409.1.11 by Vincent Ladeuil
Slightly cleanup bzrlib.transform and deprecate unused code.
2439
        self.assertEqual('name.~2~', name2)
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2440
2441
2442
class TestFileMover(tests.TestCaseWithTransport):
2443
2444
    def test_file_mover(self):
2445
        self.build_tree(['a/', 'a/b', 'c/', 'c/d'])
2446
        mover = _FileMover()
2447
        mover.rename('a', 'q')
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
2448
        self.assertPathExists('q')
2449
        self.assertPathDoesNotExist('a')
2450
        self.assertPathExists('q/b')
2451
        self.assertPathExists('c')
2452
        self.assertPathExists('c/d')
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2453
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2454
    def test_pre_delete_rollback(self):
2455
        self.build_tree(['a/'])
2456
        mover = _FileMover()
2457
        mover.pre_delete('a', 'q')
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
2458
        self.assertPathExists('q')
2459
        self.assertPathDoesNotExist('a')
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2460
        mover.rollback()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
2461
        self.assertPathDoesNotExist('q')
2462
        self.assertPathExists('a')
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2463
2464
    def test_apply_deletions(self):
2733.2.12 by Aaron Bentley
Updates from review
2465
        self.build_tree(['a/', 'b/'])
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2466
        mover = _FileMover()
2467
        mover.pre_delete('a', 'q')
2733.2.12 by Aaron Bentley
Updates from review
2468
        mover.pre_delete('b', 'r')
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
2469
        self.assertPathExists('q')
2470
        self.assertPathExists('r')
2471
        self.assertPathDoesNotExist('a')
2472
        self.assertPathDoesNotExist('b')
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2473
        mover.apply_deletions()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
2474
        self.assertPathDoesNotExist('q')
2475
        self.assertPathDoesNotExist('r')
2476
        self.assertPathDoesNotExist('a')
2477
        self.assertPathDoesNotExist('b')
2733.2.5 by Aaron Bentley
Implement FileMover.pre_delete and FileMover.apply_deletions
2478
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2479
    def test_file_mover_rollback(self):
2480
        self.build_tree(['a/', 'a/b', 'c/', 'c/d/', 'c/e/'])
2481
        mover = _FileMover()
2482
        mover.rename('c/d', 'c/f')
2483
        mover.rename('c/e', 'c/d')
2484
        try:
2485
            mover.rename('a', 'c')
3063.1.3 by Aaron Bentley
Update for Linux
2486
        except errors.FileExists, e:
2733.2.1 by Aaron Bentley
Implement FileMover, to support TreeTransform rollback
2487
            mover.rollback()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
2488
        self.assertPathExists('a')
2489
        self.assertPathExists('c/d')
2733.2.3 by Aaron Bentley
Test tranform rollback
2490
2491
2492
class Bogus(Exception):
2493
    pass
2494
2495
2496
class TestTransformRollback(tests.TestCaseWithTransport):
2497
2498
    class ExceptionFileMover(_FileMover):
2499
2733.2.4 by Aaron Bentley
Test transform rollback when renaming into place
2500
        def __init__(self, bad_source=None, bad_target=None):
2501
            _FileMover.__init__(self)
2502
            self.bad_source = bad_source
2503
            self.bad_target = bad_target
2504
2733.2.3 by Aaron Bentley
Test tranform rollback
2505
        def rename(self, source, target):
2733.2.4 by Aaron Bentley
Test transform rollback when renaming into place
2506
            if (self.bad_source is not None and
2507
                source.endswith(self.bad_source)):
2508
                raise Bogus
2509
            elif (self.bad_target is not None and
2510
                target.endswith(self.bad_target)):
2733.2.3 by Aaron Bentley
Test tranform rollback
2511
                raise Bogus
2512
            else:
2513
                _FileMover.rename(self, source, target)
2514
2515
    def test_rollback_rename(self):
2516
        tree = self.make_branch_and_tree('.')
2517
        self.build_tree(['a/', 'a/b'])
2518
        tt = TreeTransform(tree)
2519
        self.addCleanup(tt.finalize)
2520
        a_id = tt.trans_id_tree_path('a')
2521
        tt.adjust_path('c', tt.root, a_id)
2522
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2733.2.4 by Aaron Bentley
Test transform rollback when renaming into place
2523
        self.assertRaises(Bogus, tt.apply,
2524
                          _mover=self.ExceptionFileMover(bad_source='a'))
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
2525
        self.assertPathExists('a')
2526
        self.assertPathExists('a/b')
2733.2.4 by Aaron Bentley
Test transform rollback when renaming into place
2527
        tt.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
2528
        self.assertPathExists('c')
2529
        self.assertPathExists('c/d')
2733.2.4 by Aaron Bentley
Test transform rollback when renaming into place
2530
2531
    def test_rollback_rename_into_place(self):
2532
        tree = self.make_branch_and_tree('.')
2533
        self.build_tree(['a/', 'a/b'])
2534
        tt = TreeTransform(tree)
2535
        self.addCleanup(tt.finalize)
2536
        a_id = tt.trans_id_tree_path('a')
2537
        tt.adjust_path('c', tt.root, a_id)
2538
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2539
        self.assertRaises(Bogus, tt.apply,
2540
                          _mover=self.ExceptionFileMover(bad_target='c/d'))
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
2541
        self.assertPathExists('a')
2542
        self.assertPathExists('a/b')
2733.2.4 by Aaron Bentley
Test transform rollback when renaming into place
2543
        tt.apply()
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
2544
        self.assertPathExists('c')
2545
        self.assertPathExists('c/d')
2733.2.6 by Aaron Bentley
Make TreeTransform commits rollbackable
2546
2547
    def test_rollback_deletion(self):
2548
        tree = self.make_branch_and_tree('.')
2549
        self.build_tree(['a/', 'a/b'])
2550
        tt = TreeTransform(tree)
2551
        self.addCleanup(tt.finalize)
2552
        a_id = tt.trans_id_tree_path('a')
2553
        tt.delete_contents(a_id)
2554
        tt.adjust_path('d', tt.root, tt.trans_id_tree_path('a/b'))
2555
        self.assertRaises(Bogus, tt.apply,
2556
                          _mover=self.ExceptionFileMover(bad_target='d'))
5784.1.3 by Martin Pool
Switch away from using failUnlessExists and failIfExists
2557
        self.assertPathExists('a')
2558
        self.assertPathExists('a/b')
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
2559
2560
5876.3.3 by Martin
Use better test class name
2561
class TestFinalizeRobustness(tests.TestCaseWithTransport):
2562
    """Ensure treetransform creation errors can be safely cleaned up after"""
5876.3.1 by Martin
Tests for DiskTreeTransform.finalize issues when create_file is interrupted
2563
2564
    def _override_globals_in_method(self, instance, method_name, globals):
2565
        """Replace method on instance with one with updated globals"""
2566
        import types
2567
        func = getattr(instance, method_name).im_func
2568
        new_globals = dict(func.func_globals)
2569
        new_globals.update(globals)
2570
        new_func = types.FunctionType(func.func_code, new_globals,
2571
            func.func_name, func.func_defaults)
2572
        setattr(instance, method_name,
2573
            types.MethodType(new_func, instance, instance.__class__))
2574
        self.addCleanup(delattr, instance, method_name)
2575
2576
    @staticmethod
2577
    def _fake_open_raises_before(name, mode):
2578
        """Like open() but raises before doing anything"""
2579
        raise RuntimeError
2580
2581
    @staticmethod
2582
    def _fake_open_raises_after(name, mode):
2583
        """Like open() but raises after creating file without returning"""
2584
        open(name, mode).close()
2585
        raise RuntimeError
2586
2587
    def create_transform_and_root_trans_id(self):
2588
        """Setup a transform creating a file in limbo"""
2589
        tree = self.make_branch_and_tree('.')
2590
        tt = TreeTransform(tree)
2591
        return tt, tt.create_path("a", tt.root)
2592
2593
    def create_transform_and_subdir_trans_id(self):
2594
        """Setup a transform creating a directory containing a file in limbo"""
2595
        tree = self.make_branch_and_tree('.')
2596
        tt = TreeTransform(tree)
2597
        d_trans_id = tt.create_path("d", tt.root)
2598
        tt.create_directory(d_trans_id)
2599
        f_trans_id = tt.create_path("a", d_trans_id)
2600
        tt.adjust_path("a", d_trans_id, f_trans_id)
2601
        return tt, f_trans_id
2602
2603
    def test_root_create_file_open_raises_before_creation(self):
2604
        tt, trans_id = self.create_transform_and_root_trans_id()
2605
        self._override_globals_in_method(tt, "create_file",
2606
            {"open": self._fake_open_raises_before})
2607
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2608
        path = tt._limbo_name(trans_id)
2609
        self.assertPathDoesNotExist(path)
2610
        tt.finalize()
2611
        self.assertPathDoesNotExist(tt._limbodir)
2612
2613
    def test_root_create_file_open_raises_after_creation(self):
2614
        tt, trans_id = self.create_transform_and_root_trans_id()
2615
        self._override_globals_in_method(tt, "create_file",
2616
            {"open": self._fake_open_raises_after})
2617
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2618
        path = tt._limbo_name(trans_id)
2619
        self.assertPathExists(path)
5876.3.2 by Martin
Change test that expects ImmortalLimbo to want the sensible thing instead, and fail for now
2620
        tt.finalize()
2621
        self.assertPathDoesNotExist(path)
2622
        self.assertPathDoesNotExist(tt._limbodir)
5876.3.1 by Martin
Tests for DiskTreeTransform.finalize issues when create_file is interrupted
2623
2624
    def test_subdir_create_file_open_raises_before_creation(self):
2625
        tt, trans_id = self.create_transform_and_subdir_trans_id()
2626
        self._override_globals_in_method(tt, "create_file",
2627
            {"open": self._fake_open_raises_before})
2628
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2629
        path = tt._limbo_name(trans_id)
2630
        self.assertPathDoesNotExist(path)
2631
        tt.finalize()
2632
        self.assertPathDoesNotExist(tt._limbodir)
2633
2634
    def test_subdir_create_file_open_raises_after_creation(self):
2635
        tt, trans_id = self.create_transform_and_subdir_trans_id()
2636
        self._override_globals_in_method(tt, "create_file",
2637
            {"open": self._fake_open_raises_after})
2638
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2639
        path = tt._limbo_name(trans_id)
2640
        self.assertPathExists(path)
2641
        tt.finalize()
2642
        self.assertPathDoesNotExist(path)
2643
        self.assertPathDoesNotExist(tt._limbodir)
2644
5876.4.4 by Andrew Bennetts
Fix edge cases in handling interrupts during _rename_in_limbo, with messy tests
2645
    def test_rename_in_limbo_rename_raises_after_rename(self):
2646
        tt, trans_id = self.create_transform_and_root_trans_id()
2647
        parent1 = tt.new_directory('parent1', tt.root)
2648
        child1 = tt.new_file('child1', parent1, 'contents')
2649
        parent2 = tt.new_directory('parent2', tt.root)
2650
2651
        class FakeOSModule(object):
2652
            def rename(self, old, new):
2653
                os.rename(old, new)
2654
                raise RuntimeError
2655
        self._override_globals_in_method(tt, "_rename_in_limbo",
2656
            {"os": FakeOSModule()})
2657
        self.assertRaises(
2658
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
2659
        path = osutils.pathjoin(tt._limbo_name(parent2), "child1")
2660
        self.assertPathExists(path)
2661
        tt.finalize()
2662
        self.assertPathDoesNotExist(path)
2663
        self.assertPathDoesNotExist(tt._limbodir)
2664
2665
    def test_rename_in_limbo_rename_raises_before_rename(self):
2666
        tt, trans_id = self.create_transform_and_root_trans_id()
2667
        parent1 = tt.new_directory('parent1', tt.root)
2668
        child1 = tt.new_file('child1', parent1, 'contents')
2669
        parent2 = tt.new_directory('parent2', tt.root)
2670
2671
        class FakeOSModule(object):
2672
            def rename(self, old, new):
2673
                raise RuntimeError
2674
        self._override_globals_in_method(tt, "_rename_in_limbo",
2675
            {"os": FakeOSModule()})
2676
        self.assertRaises(
2677
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
2678
        path = osutils.pathjoin(tt._limbo_name(parent1), "child1")
2679
        self.assertPathExists(path)
2680
        tt.finalize()
2681
        self.assertPathDoesNotExist(path)
2682
        self.assertPathDoesNotExist(tt._limbodir)
2683
5876.3.1 by Martin
Tests for DiskTreeTransform.finalize issues when create_file is interrupted
2684
5409.1.6 by Vincent Ladeuil
Add failing tests for bug #323111.
2685
class TestTransformMissingParent(tests.TestCaseWithTransport):
2686
5409.7.4 by Vincent Ladeuil
Take jam's review comments into account.
2687
    def make_tt_with_versioned_dir(self):
5409.1.6 by Vincent Ladeuil
Add failing tests for bug #323111.
2688
        wt = self.make_branch_and_tree('.')
2689
        self.build_tree(['dir/',])
2690
        wt.add(['dir'], ['dir-id'])
2691
        wt.commit('Create dir')
2692
        tt = TreeTransform(wt)
2693
        self.addCleanup(tt.finalize)
2694
        return wt, tt
2695
2696
    def test_resolve_create_parent_for_versioned_file(self):
5409.7.4 by Vincent Ladeuil
Take jam's review comments into account.
2697
        wt, tt = self.make_tt_with_versioned_dir()
5409.1.6 by Vincent Ladeuil
Add failing tests for bug #323111.
2698
        dir_tid = tt.trans_id_tree_file_id('dir-id')
2699
        file_tid = tt.new_file('file', dir_tid, 'Contents', file_id='file-id')
2700
        tt.delete_contents(dir_tid)
2701
        tt.unversion_file(dir_tid)
2702
        conflicts = resolve_conflicts(tt)
2703
        # one conflict for the missing directory, one for the unversioned
2704
        # parent
2705
        self.assertLength(2, conflicts)
2706
5409.1.20 by Vincent Ladeuil
Revert to 'conflict' being the default orphaning policy and fix fallouts.
2707
    def test_non_versioned_file_create_conflict(self):
5409.7.4 by Vincent Ladeuil
Take jam's review comments into account.
2708
        wt, tt = self.make_tt_with_versioned_dir()
5409.1.6 by Vincent Ladeuil
Add failing tests for bug #323111.
2709
        dir_tid = tt.trans_id_tree_file_id('dir-id')
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
2710
        tt.new_file('file', dir_tid, 'Contents')
5409.1.6 by Vincent Ladeuil
Add failing tests for bug #323111.
2711
        tt.delete_contents(dir_tid)
2712
        tt.unversion_file(dir_tid)
2713
        conflicts = resolve_conflicts(tt)
5409.7.2 by Vincent Ladeuil
Add NEWS entry, a missing test and some cleanup.
2714
        # no conflicts or rather: orphaning 'file' resolve the 'dir' conflict
5409.1.20 by Vincent Ladeuil
Revert to 'conflict' being the default orphaning policy and fix fallouts.
2715
        self.assertLength(1, conflicts)
2716
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
2717
                         conflicts.pop())
5409.1.6 by Vincent Ladeuil
Add failing tests for bug #323111.
2718
2719
3363.19.1 by Aaron Bentley
Make PreviewTree.iter_changes accept all options.
2720
A_ENTRY = ('a-id', ('a', 'a'), True, (True, True),
2721
                  ('TREE_ROOT', 'TREE_ROOT'), ('a', 'a'), ('file', 'file'),
2722
                  (False, False))
2723
ROOT_ENTRY = ('TREE_ROOT', ('', ''), False, (True, True), (None, None),
5050.57.1 by Aaron Bentley
Make is_executable treat symlinks and directories the same across tree types.
2724
              ('', ''), ('directory', 'directory'), (False, False))
3363.19.1 by Aaron Bentley
Make PreviewTree.iter_changes accept all options.
2725
2726
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
2727
class TestTransformPreview(tests.TestCaseWithTransport):
2728
2729
    def create_tree(self):
2730
        tree = self.make_branch_and_tree('.')
2731
        self.build_tree_contents([('a', 'content 1')])
4600.3.1 by Robert Collins
Set tree root ID in tree transform tests that don't care about the root id.
2732
        tree.set_root_id('TREE_ROOT')
3008.2.1 by Aaron Bentley
Ensure conflict resolution works
2733
        tree.add('a', 'a-id')
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
2734
        tree.commit('rev1', rev_id='rev1')
2735
        return tree.branch.repository.revision_tree('rev1')
2736
3008.1.18 by Aaron Bentley
Get supported PreviewTree functionality under test
2737
    def get_empty_preview(self):
2738
        repository = self.make_repository('repo')
2739
        tree = repository.revision_tree(_mod_revision.NULL_REVISION)
3199.1.4 by Vincent Ladeuil
Fix 16 leaked tmp dirs. Probably indicates a lock handling problem with TransformPreview
2740
        preview = TransformPreview(tree)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
2741
        self.addCleanup(preview.finalize)
3199.1.4 by Vincent Ladeuil
Fix 16 leaked tmp dirs. Probably indicates a lock handling problem with TransformPreview
2742
        return preview
2743
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
2744
    def test_transform_preview(self):
2745
        revision_tree = self.create_tree()
2746
        preview = TransformPreview(revision_tree)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
2747
        self.addCleanup(preview.finalize)
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
2748
2749
    def test_transform_preview_tree(self):
2750
        revision_tree = self.create_tree()
2751
        preview = TransformPreview(revision_tree)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
2752
        self.addCleanup(preview.finalize)
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
2753
        preview.get_preview_tree()
2754
3008.1.5 by Michael Hudson
a more precise test
2755
    def test_transform_new_file(self):
2756
        revision_tree = self.create_tree()
2757
        preview = TransformPreview(revision_tree)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
2758
        self.addCleanup(preview.finalize)
3008.1.5 by Michael Hudson
a more precise test
2759
        preview.new_file('file2', preview.root, 'content B\n', 'file2-id')
2760
        preview_tree = preview.get_preview_tree()
2761
        self.assertEqual(preview_tree.kind('file2-id'), 'file')
2762
        self.assertEqual(
2763
            preview_tree.get_file('file2-id').read(), 'content B\n')
2764
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
2765
    def test_diff_preview_tree(self):
2766
        revision_tree = self.create_tree()
2767
        preview = TransformPreview(revision_tree)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
2768
        self.addCleanup(preview.finalize)
3008.1.4 by Michael Hudson
Merge test enhancements
2769
        preview.new_file('file2', preview.root, 'content B\n', 'file2-id')
3008.1.1 by Aaron Bentley
Start work allowing previews of transforms
2770
        preview_tree = preview.get_preview_tree()
2771
        out = StringIO()
2772
        show_diff_trees(revision_tree, preview_tree, out)
3008.1.4 by Michael Hudson
Merge test enhancements
2773
        lines = out.getvalue().splitlines()
2774
        self.assertEqual(lines[0], "=== added file 'file2'")
2775
        # 3 lines of diff administrivia
2776
        self.assertEqual(lines[4], "+content B")
3008.2.1 by Aaron Bentley
Ensure conflict resolution works
2777
2778
    def test_transform_conflicts(self):
2779
        revision_tree = self.create_tree()
2780
        preview = TransformPreview(revision_tree)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
2781
        self.addCleanup(preview.finalize)
3008.2.1 by Aaron Bentley
Ensure conflict resolution works
2782
        preview.new_file('a', preview.root, 'content 2')
2783
        resolve_conflicts(preview)
2784
        trans_id = preview.trans_id_file_id('a-id')
2785
        self.assertEqual('a.moved', preview.final_name(trans_id))
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2786
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2787
    def get_tree_and_preview_tree(self):
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2788
        revision_tree = self.create_tree()
2789
        preview = TransformPreview(revision_tree)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
2790
        self.addCleanup(preview.finalize)
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2791
        a_trans_id = preview.trans_id_file_id('a-id')
2792
        preview.delete_contents(a_trans_id)
2793
        preview.create_file('b content', a_trans_id)
2794
        preview_tree = preview.get_preview_tree()
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2795
        return revision_tree, preview_tree
2796
2797
    def test_iter_changes(self):
2798
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2799
        root = revision_tree.inventory.root.file_id
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2800
        self.assertEqual([('a-id', ('a', 'a'), True, (True, True),
2801
                          (root, root), ('a', 'a'), ('file', 'file'),
2802
                          (False, False))],
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2803
                          list(preview_tree.iter_changes(revision_tree)))
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2804
3363.19.1 by Aaron Bentley
Make PreviewTree.iter_changes accept all options.
2805
    def test_include_unchanged_succeeds(self):
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2806
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
3363.19.1 by Aaron Bentley
Make PreviewTree.iter_changes accept all options.
2807
        changes = preview_tree.iter_changes(revision_tree,
2808
                                            include_unchanged=True)
2809
        root = revision_tree.inventory.root.file_id
2810
2811
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2812
2813
    def test_specific_files(self):
2814
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
3363.19.1 by Aaron Bentley
Make PreviewTree.iter_changes accept all options.
2815
        changes = preview_tree.iter_changes(revision_tree,
2816
                                            specific_files=[''])
5050.57.1 by Aaron Bentley
Make is_executable treat symlinks and directories the same across tree types.
2817
        self.assertEqual([A_ENTRY], list(changes))
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2818
3363.19.1 by Aaron Bentley
Make PreviewTree.iter_changes accept all options.
2819
    def test_want_unversioned(self):
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2820
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
3363.19.1 by Aaron Bentley
Make PreviewTree.iter_changes accept all options.
2821
        changes = preview_tree.iter_changes(revision_tree,
2822
                                            want_unversioned=True)
5050.57.1 by Aaron Bentley
Make is_executable treat symlinks and directories the same across tree types.
2823
        self.assertEqual([A_ENTRY], list(changes))
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2824
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2825
    def test_ignore_extra_trees_no_specific_files(self):
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2826
        # extra_trees is harmless without specific_files, so we'll silently
2827
        # accept it, even though we won't use it.
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2828
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2829
        preview_tree.iter_changes(revision_tree, extra_trees=[preview_tree])
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2830
2831
    def test_ignore_require_versioned_no_specific_files(self):
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2832
        # require_versioned is meaningless without specific_files.
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2833
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
2834
        preview_tree.iter_changes(revision_tree, require_versioned=False)
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2835
2836
    def test_ignore_pb(self):
3008.1.17 by Aaron Bentley
Test unused parameters of preview_tree._iter_changes
2837
        # pb could be supported, but TT.iter_changes doesn't support it.
3008.1.31 by Aaron Bentley
Split PreviewTree._iter_changes parameter tests into smaller tests
2838
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
2839
        preview_tree.iter_changes(revision_tree)
3008.1.18 by Aaron Bentley
Get supported PreviewTree functionality under test
2840
2841
    def test_kind(self):
2842
        revision_tree = self.create_tree()
2843
        preview = TransformPreview(revision_tree)
3199.1.5 by Vincent Ladeuil
Fix two more leaking tmp dirs, by reworking TransformPreview lock handling.
2844
        self.addCleanup(preview.finalize)
3008.1.18 by Aaron Bentley
Get supported PreviewTree functionality under test
2845
        preview.new_file('file', preview.root, 'contents', 'file-id')
2846
        preview.new_directory('directory', preview.root, 'dir-id')
2847
        preview_tree = preview.get_preview_tree()
2848
        self.assertEqual('file', preview_tree.kind('file-id'))
2849
        self.assertEqual('directory', preview_tree.kind('dir-id'))
2850
2851
    def test_get_file_mtime(self):
2852
        preview = self.get_empty_preview()
2853
        file_trans_id = preview.new_file('file', preview.root, 'contents',
2854
                                         'file-id')
2855
        limbo_path = preview._limbo_name(file_trans_id)
2856
        preview_tree = preview.get_preview_tree()
2857
        self.assertEqual(os.stat(limbo_path).st_mtime,
2858
                         preview_tree.get_file_mtime('file-id'))
2859
4635.1.1 by Aaron Bentley
Fix OSError with renamed files in PreviewTree.
2860
    def test_get_file_mtime_renamed(self):
2861
        work_tree = self.make_branch_and_tree('tree')
2862
        self.build_tree(['tree/file'])
2863
        work_tree.add('file', 'file-id')
2864
        preview = TransformPreview(work_tree)
2865
        self.addCleanup(preview.finalize)
2866
        file_trans_id = preview.trans_id_tree_file_id('file-id')
2867
        preview.adjust_path('renamed', preview.root, file_trans_id)
2868
        preview_tree = preview.get_preview_tree()
2869
        preview_mtime = preview_tree.get_file_mtime('file-id', 'renamed')
2870
        work_mtime = work_tree.get_file_mtime('file-id', 'file')
2871
5809.3.6 by Aaron Bentley
Fix PreviewTree.get_file_size.
2872
    def test_get_file_size(self):
2873
        work_tree = self.make_branch_and_tree('tree')
2874
        self.build_tree_contents([('tree/old', 'old')])
2875
        work_tree.add('old', 'old-id')
2876
        preview = TransformPreview(work_tree)
2877
        self.addCleanup(preview.finalize)
2878
        new_id = preview.new_file('name', preview.root, 'contents', 'new-id',
2879
                                  'executable')
2880
        tree = preview.get_preview_tree()
2881
        self.assertEqual(len('old'), tree.get_file_size('old-id'))
2882
        self.assertEqual(len('contents'), tree.get_file_size('new-id'))
2883
3008.1.18 by Aaron Bentley
Get supported PreviewTree functionality under test
2884
    def test_get_file(self):
2885
        preview = self.get_empty_preview()
2886
        preview.new_file('file', preview.root, 'contents', 'file-id')
2887
        preview_tree = preview.get_preview_tree()
2888
        tree_file = preview_tree.get_file('file-id')
2889
        try:
2890
            self.assertEqual('contents', tree_file.read())
2891
        finally:
2892
            tree_file.close()
3228.1.2 by James Henstridge
Simplify test, and move it down to be next to the other _PreviewTree tests.
2893
2894
    def test_get_symlink_target(self):
2895
        self.requireFeature(SymlinkFeature)
2896
        preview = self.get_empty_preview()
2897
        preview.new_symlink('symlink', preview.root, 'target', 'symlink-id')
2898
        preview_tree = preview.get_preview_tree()
2899
        self.assertEqual('target',
2900
                         preview_tree.get_symlink_target('symlink-id'))
3363.2.18 by Aaron Bentley
Implement correct all_file_ids for PreviewTree
2901
2902
    def test_all_file_ids(self):
2903
        tree = self.make_branch_and_tree('tree')
2904
        self.build_tree(['tree/a', 'tree/b', 'tree/c'])
2905
        tree.add(['a', 'b', 'c'], ['a-id', 'b-id', 'c-id'])
2906
        preview = TransformPreview(tree)
2907
        self.addCleanup(preview.finalize)
2908
        preview.unversion_file(preview.trans_id_file_id('b-id'))
2909
        c_trans_id = preview.trans_id_file_id('c-id')
2910
        preview.unversion_file(c_trans_id)
2911
        preview.version_file('c-id', c_trans_id)
2912
        preview_tree = preview.get_preview_tree()
2913
        self.assertEqual(set(['a-id', 'c-id', tree.get_root_id()]),
2914
                         preview_tree.all_file_ids())
3363.2.19 by Aaron Bentley
Make PreviewTree.path2id correct
2915
2916
    def test_path2id_deleted_unchanged(self):
2917
        tree = self.make_branch_and_tree('tree')
2918
        self.build_tree(['tree/unchanged', 'tree/deleted'])
2919
        tree.add(['unchanged', 'deleted'], ['unchanged-id', 'deleted-id'])
2920
        preview = TransformPreview(tree)
2921
        self.addCleanup(preview.finalize)
2922
        preview.unversion_file(preview.trans_id_file_id('deleted-id'))
2923
        preview_tree = preview.get_preview_tree()
2924
        self.assertEqual('unchanged-id', preview_tree.path2id('unchanged'))
2925
        self.assertIs(None, preview_tree.path2id('deleted'))
2926
2927
    def test_path2id_created(self):
2928
        tree = self.make_branch_and_tree('tree')
2929
        self.build_tree(['tree/unchanged'])
2930
        tree.add(['unchanged'], ['unchanged-id'])
2931
        preview = TransformPreview(tree)
2932
        self.addCleanup(preview.finalize)
2933
        preview.new_file('new', preview.trans_id_file_id('unchanged-id'),
2934
            'contents', 'new-id')
2935
        preview_tree = preview.get_preview_tree()
2936
        self.assertEqual('new-id', preview_tree.path2id('unchanged/new'))
2937
2938
    def test_path2id_moved(self):
2939
        tree = self.make_branch_and_tree('tree')
2940
        self.build_tree(['tree/old_parent/', 'tree/old_parent/child'])
2941
        tree.add(['old_parent', 'old_parent/child'],
2942
                 ['old_parent-id', 'child-id'])
2943
        preview = TransformPreview(tree)
2944
        self.addCleanup(preview.finalize)
2945
        new_parent = preview.new_directory('new_parent', preview.root,
2946
                                           'new_parent-id')
2947
        preview.adjust_path('child', new_parent,
2948
                            preview.trans_id_file_id('child-id'))
2949
        preview_tree = preview.get_preview_tree()
2950
        self.assertIs(None, preview_tree.path2id('old_parent/child'))
2951
        self.assertEqual('child-id', preview_tree.path2id('new_parent/child'))
2952
2953
    def test_path2id_renamed_parent(self):
2954
        tree = self.make_branch_and_tree('tree')
2955
        self.build_tree(['tree/old_name/', 'tree/old_name/child'])
2956
        tree.add(['old_name', 'old_name/child'],
2957
                 ['parent-id', 'child-id'])
2958
        preview = TransformPreview(tree)
2959
        self.addCleanup(preview.finalize)
2960
        preview.adjust_path('new_name', preview.root,
2961
                            preview.trans_id_file_id('parent-id'))
2962
        preview_tree = preview.get_preview_tree()
2963
        self.assertIs(None, preview_tree.path2id('old_name/child'))
2964
        self.assertEqual('child-id', preview_tree.path2id('new_name/child'))
3363.2.21 by Aaron Bentley
Implement iter_entries_by_dir
2965
2966
    def assertMatchingIterEntries(self, tt, specific_file_ids=None):
2967
        preview_tree = tt.get_preview_tree()
2968
        preview_result = list(preview_tree.iter_entries_by_dir(
2969
                              specific_file_ids))
2970
        tree = tt._tree
2971
        tt.apply()
2972
        actual_result = list(tree.iter_entries_by_dir(specific_file_ids))
2973
        self.assertEqual(actual_result, preview_result)
2974
2975
    def test_iter_entries_by_dir_new(self):
2976
        tree = self.make_branch_and_tree('tree')
2977
        tt = TreeTransform(tree)
2978
        tt.new_file('new', tt.root, 'contents', 'new-id')
2979
        self.assertMatchingIterEntries(tt)
2980
2981
    def test_iter_entries_by_dir_deleted(self):
2982
        tree = self.make_branch_and_tree('tree')
2983
        self.build_tree(['tree/deleted'])
2984
        tree.add('deleted', 'deleted-id')
2985
        tt = TreeTransform(tree)
2986
        tt.delete_contents(tt.trans_id_file_id('deleted-id'))
2987
        self.assertMatchingIterEntries(tt)
2988
2989
    def test_iter_entries_by_dir_unversioned(self):
2990
        tree = self.make_branch_and_tree('tree')
2991
        self.build_tree(['tree/removed'])
2992
        tree.add('removed', 'removed-id')
2993
        tt = TreeTransform(tree)
2994
        tt.unversion_file(tt.trans_id_file_id('removed-id'))
2995
        self.assertMatchingIterEntries(tt)
2996
2997
    def test_iter_entries_by_dir_moved(self):
2998
        tree = self.make_branch_and_tree('tree')
2999
        self.build_tree(['tree/moved', 'tree/new_parent/'])
3000
        tree.add(['moved', 'new_parent'], ['moved-id', 'new_parent-id'])
3001
        tt = TreeTransform(tree)
3002
        tt.adjust_path('moved', tt.trans_id_file_id('new_parent-id'),
3003
                       tt.trans_id_file_id('moved-id'))
3004
        self.assertMatchingIterEntries(tt)
3005
3006
    def test_iter_entries_by_dir_specific_file_ids(self):
3007
        tree = self.make_branch_and_tree('tree')
3008
        tree.set_root_id('tree-root-id')
3009
        self.build_tree(['tree/parent/', 'tree/parent/child'])
3010
        tree.add(['parent', 'parent/child'], ['parent-id', 'child-id'])
3011
        tt = TreeTransform(tree)
3012
        self.assertMatchingIterEntries(tt, ['tree-root-id', 'child-id'])
3363.2.26 by Aaron Bentley
Get symlinks working
3013
3014
    def test_symlink_content_summary(self):
3015
        self.requireFeature(SymlinkFeature)
3016
        preview = self.get_empty_preview()
3017
        preview.new_symlink('path', preview.root, 'target', 'path-id')
3018
        summary = preview.get_preview_tree().path_content_summary('path')
3019
        self.assertEqual(('symlink', None, None, 'target'), summary)
3363.2.27 by Aaron Bentley
Make path_content_summary a core API
3020
3021
    def test_missing_content_summary(self):
3022
        preview = self.get_empty_preview()
3023
        summary = preview.get_preview_tree().path_content_summary('path')
3024
        self.assertEqual(('missing', None, None, None), summary)
3025
3026
    def test_deleted_content_summary(self):
3027
        tree = self.make_branch_and_tree('tree')
3028
        self.build_tree(['tree/path/'])
3029
        tree.add('path')
3030
        preview = TransformPreview(tree)
3031
        self.addCleanup(preview.finalize)
3032
        preview.delete_contents(preview.trans_id_tree_path('path'))
3033
        summary = preview.get_preview_tree().path_content_summary('path')
3034
        self.assertEqual(('missing', None, None, None), summary)
3035
3363.2.30 by Aaron Bentley
Improve execute bit testing
3036
    def test_file_content_summary_executable(self):
3037
        preview = self.get_empty_preview()
3038
        path_id = preview.new_file('path', preview.root, 'contents', 'path-id')
3039
        preview.set_executability(True, path_id)
3040
        summary = preview.get_preview_tree().path_content_summary('path')
3041
        self.assertEqual(4, len(summary))
3042
        self.assertEqual('file', summary[0])
3043
        # size must be known
3044
        self.assertEqual(len('contents'), summary[1])
3045
        # executable
3046
        self.assertEqual(True, summary[2])
3363.2.31 by Aaron Bentley
Tweak tests
3047
        # will not have hash (not cheap to determine)
3048
        self.assertIs(None, summary[3])
3363.2.30 by Aaron Bentley
Improve execute bit testing
3049
3050
    def test_change_executability(self):
3051
        tree = self.make_branch_and_tree('tree')
3052
        self.build_tree(['tree/path'])
3053
        tree.add('path')
3054
        preview = TransformPreview(tree)
3055
        self.addCleanup(preview.finalize)
3056
        path_id = preview.trans_id_tree_path('path')
3057
        preview.set_executability(True, path_id)
3058
        summary = preview.get_preview_tree().path_content_summary('path')
3059
        self.assertEqual(True, summary[2])
3060
3363.2.27 by Aaron Bentley
Make path_content_summary a core API
3061
    def test_file_content_summary_non_exec(self):
3062
        preview = self.get_empty_preview()
3063
        preview.new_file('path', preview.root, 'contents', 'path-id')
3064
        summary = preview.get_preview_tree().path_content_summary('path')
3065
        self.assertEqual(4, len(summary))
3066
        self.assertEqual('file', summary[0])
3067
        # size must be known
3363.2.30 by Aaron Bentley
Improve execute bit testing
3068
        self.assertEqual(len('contents'), summary[1])
3363.2.27 by Aaron Bentley
Make path_content_summary a core API
3069
        # not executable
4789.15.3 by John Arbash Meinel
PreviewTree now returns False for exec bit properly.
3070
        self.assertEqual(False, summary[2])
3363.2.31 by Aaron Bentley
Tweak tests
3071
        # will not have hash (not cheap to determine)
3072
        self.assertIs(None, summary[3])
3363.2.27 by Aaron Bentley
Make path_content_summary a core API
3073
3074
    def test_dir_content_summary(self):
3075
        preview = self.get_empty_preview()
3076
        preview.new_directory('path', preview.root, 'path-id')
3077
        summary = preview.get_preview_tree().path_content_summary('path')
3078
        self.assertEqual(('directory', None, None, None), summary)
3079
3080
    def test_tree_content_summary(self):
3081
        preview = self.get_empty_preview()
3082
        path = preview.new_directory('path', preview.root, 'path-id')
3083
        preview.set_tree_reference('rev-1', path)
3084
        summary = preview.get_preview_tree().path_content_summary('path')
3085
        self.assertEqual(4, len(summary))
3086
        self.assertEqual('tree-reference', summary[0])
3363.2.33 by Aaron Bentley
Implement PreviewTree.annotate_iter
3087
3088
    def test_annotate(self):
3089
        tree = self.make_branch_and_tree('tree')
3090
        self.build_tree_contents([('tree/file', 'a\n')])
3091
        tree.add('file', 'file-id')
3092
        tree.commit('a', rev_id='one')
3093
        self.build_tree_contents([('tree/file', 'a\nb\n')])
3094
        preview = TransformPreview(tree)
3095
        self.addCleanup(preview.finalize)
3096
        file_trans_id = preview.trans_id_file_id('file-id')
3097
        preview.delete_contents(file_trans_id)
3098
        preview.create_file('a\nb\nc\n', file_trans_id)
3099
        preview_tree = preview.get_preview_tree()
3100
        expected = [
3101
            ('one', 'a\n'),
3102
            ('me:', 'b\n'),
3103
            ('me:', 'c\n'),
3104
        ]
3105
        annotation = preview_tree.annotate_iter('file-id', 'me:')
3106
        self.assertEqual(expected, annotation)
3107
3108
    def test_annotate_missing(self):
3109
        preview = self.get_empty_preview()
3110
        preview.new_file('file', preview.root, 'a\nb\nc\n', 'file-id')
3111
        preview_tree = preview.get_preview_tree()
3112
        expected = [
3113
            ('me:', 'a\n'),
3114
            ('me:', 'b\n'),
3115
            ('me:', 'c\n'),
3116
         ]
3117
        annotation = preview_tree.annotate_iter('file-id', 'me:')
3118
        self.assertEqual(expected, annotation)
3119
3363.7.3 by Aaron Bentley
Add test that annotate correctly handles renames
3120
    def test_annotate_rename(self):
3121
        tree = self.make_branch_and_tree('tree')
3122
        self.build_tree_contents([('tree/file', 'a\n')])
3123
        tree.add('file', 'file-id')
3124
        tree.commit('a', rev_id='one')
3125
        preview = TransformPreview(tree)
3126
        self.addCleanup(preview.finalize)
3127
        file_trans_id = preview.trans_id_file_id('file-id')
3128
        preview.adjust_path('newname', preview.root, file_trans_id)
3129
        preview_tree = preview.get_preview_tree()
3130
        expected = [
3131
            ('one', 'a\n'),
3132
        ]
3133
        annotation = preview_tree.annotate_iter('file-id', 'me:')
3134
        self.assertEqual(expected, annotation)
3135
3363.2.33 by Aaron Bentley
Implement PreviewTree.annotate_iter
3136
    def test_annotate_deleted(self):
3137
        tree = self.make_branch_and_tree('tree')
3138
        self.build_tree_contents([('tree/file', 'a\n')])
3139
        tree.add('file', 'file-id')
3140
        tree.commit('a', rev_id='one')
3141
        self.build_tree_contents([('tree/file', 'a\nb\n')])
3142
        preview = TransformPreview(tree)
3143
        self.addCleanup(preview.finalize)
3144
        file_trans_id = preview.trans_id_file_id('file-id')
3145
        preview.delete_contents(file_trans_id)
3146
        preview_tree = preview.get_preview_tree()
3147
        annotation = preview_tree.annotate_iter('file-id', 'me:')
3148
        self.assertIs(None, annotation)
3149
3363.2.36 by Aaron Bentley
Fix PreviewTree.stored_kind
3150
    def test_stored_kind(self):
3151
        preview = self.get_empty_preview()
3152
        preview.new_file('file', preview.root, 'a\nb\nc\n', 'file-id')
3153
        preview_tree = preview.get_preview_tree()
3154
        self.assertEqual('file', preview_tree.stored_kind('file-id'))
3363.2.37 by Aaron Bentley
Fix is_executable
3155
3156
    def test_is_executable(self):
3157
        preview = self.get_empty_preview()
3158
        preview.new_file('file', preview.root, 'a\nb\nc\n', 'file-id')
3159
        preview.set_executability(True, preview.trans_id_file_id('file-id'))
3160
        preview_tree = preview.get_preview_tree()
3161
        self.assertEqual(True, preview_tree.is_executable('file-id'))
3363.9.1 by Aaron Bentley
Implement plan_merge, refactoring various bits
3162
3571.1.1 by Aaron Bentley
Allow set/get of parent_ids in PreviewTree
3163
    def test_get_set_parent_ids(self):
3164
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
3165
        self.assertEqual([], preview_tree.get_parent_ids())
3166
        preview_tree.set_parent_ids(['rev-1'])
3167
        self.assertEqual(['rev-1'], preview_tree.get_parent_ids())
3168
3363.9.1 by Aaron Bentley
Implement plan_merge, refactoring various bits
3169
    def test_plan_file_merge(self):
3170
        work_a = self.make_branch_and_tree('wta')
3171
        self.build_tree_contents([('wta/file', 'a\nb\nc\nd\n')])
3172
        work_a.add('file', 'file-id')
3363.9.7 by Aaron Bentley
Fix up to use set_parent_ids
3173
        base_id = work_a.commit('base version')
3363.9.1 by Aaron Bentley
Implement plan_merge, refactoring various bits
3174
        tree_b = work_a.bzrdir.sprout('wtb').open_workingtree()
3175
        preview = TransformPreview(work_a)
3176
        self.addCleanup(preview.finalize)
3177
        trans_id = preview.trans_id_file_id('file-id')
3178
        preview.delete_contents(trans_id)
3179
        preview.create_file('b\nc\nd\ne\n', trans_id)
3180
        self.build_tree_contents([('wtb/file', 'a\nc\nd\nf\n')])
3181
        tree_a = preview.get_preview_tree()
3363.9.7 by Aaron Bentley
Fix up to use set_parent_ids
3182
        tree_a.set_parent_ids([base_id])
3363.9.1 by Aaron Bentley
Implement plan_merge, refactoring various bits
3183
        self.assertEqual([
3363.9.5 by Aaron Bentley
Move killed-a from top to bottom
3184
            ('killed-a', 'a\n'),
3363.9.1 by Aaron Bentley
Implement plan_merge, refactoring various bits
3185
            ('killed-b', 'b\n'),
3186
            ('unchanged', 'c\n'),
3187
            ('unchanged', 'd\n'),
3188
            ('new-a', 'e\n'),
3189
            ('new-b', 'f\n'),
3190
        ], list(tree_a.plan_file_merge('file-id', tree_b)))
3363.9.8 by Aaron Bentley
Ensure plan_file_merge works with a RevisionTree as the basis
3191
3192
    def test_plan_file_merge_revision_tree(self):
3193
        work_a = self.make_branch_and_tree('wta')
3194
        self.build_tree_contents([('wta/file', 'a\nb\nc\nd\n')])
3195
        work_a.add('file', 'file-id')
3196
        base_id = work_a.commit('base version')
3197
        tree_b = work_a.bzrdir.sprout('wtb').open_workingtree()
3198
        preview = TransformPreview(work_a.basis_tree())
3199
        self.addCleanup(preview.finalize)
3200
        trans_id = preview.trans_id_file_id('file-id')
3201
        preview.delete_contents(trans_id)
3202
        preview.create_file('b\nc\nd\ne\n', trans_id)
3203
        self.build_tree_contents([('wtb/file', 'a\nc\nd\nf\n')])
3204
        tree_a = preview.get_preview_tree()
3205
        tree_a.set_parent_ids([base_id])
3206
        self.assertEqual([
3207
            ('killed-a', 'a\n'),
3208
            ('killed-b', 'b\n'),
3209
            ('unchanged', 'c\n'),
3210
            ('unchanged', 'd\n'),
3211
            ('new-a', 'e\n'),
3212
            ('new-b', 'f\n'),
3213
        ], list(tree_a.plan_file_merge('file-id', tree_b)))
3363.9.9 by Aaron Bentley
Implement walkdirs in terms of TreeTransform
3214
3215
    def test_walkdirs(self):
3216
        preview = self.get_empty_preview()
4634.57.3 by Aaron Bentley
Fix failing test.
3217
        root = preview.new_directory('', ROOT_PARENT, 'tree-root')
3218
        # FIXME: new_directory should mark root.
4634.122.6 by John Arbash Meinel
Fix a test that used 'adjust_path' to set the root.
3219
        preview.fixup_new_roots()
3363.9.9 by Aaron Bentley
Implement walkdirs in terms of TreeTransform
3220
        preview_tree = preview.get_preview_tree()
3221
        file_trans_id = preview.new_file('a', preview.root, 'contents',
3222
                                         'a-id')
3223
        expected = [(('', 'tree-root'),
3224
                    [('a', 'a', 'file', None, 'a-id', 'file')])]
3225
        self.assertEqual(expected, list(preview_tree.walkdirs()))
3363.13.2 by Aaron Bentley
Test specific cases for PreviewTree.extras
3226
3227
    def test_extras(self):
3228
        work_tree = self.make_branch_and_tree('tree')
3229
        self.build_tree(['tree/removed-file', 'tree/existing-file',
3230
                         'tree/not-removed-file'])
3231
        work_tree.add(['removed-file', 'not-removed-file'])
3232
        preview = TransformPreview(work_tree)
3363.13.3 by Aaron Bentley
Add cleanup
3233
        self.addCleanup(preview.finalize)
3363.13.2 by Aaron Bentley
Test specific cases for PreviewTree.extras
3234
        preview.new_file('new-file', preview.root, 'contents')
3235
        preview.new_file('new-versioned-file', preview.root, 'contents',
3236
                         'new-versioned-id')
3237
        tree = preview.get_preview_tree()
3238
        preview.unversion_file(preview.trans_id_tree_path('removed-file'))
3239
        self.assertEqual(set(['new-file', 'removed-file', 'existing-file']),
3240
                         set(tree.extras()))
3363.17.1 by Aaron Bentley
Avoid inventory for merge and transform code
3241
3363.17.2 by Aaron Bentley
Add text checking
3242
    def test_merge_into_preview(self):
3363.17.1 by Aaron Bentley
Avoid inventory for merge and transform code
3243
        work_tree = self.make_branch_and_tree('tree')
3363.17.2 by Aaron Bentley
Add text checking
3244
        self.build_tree_contents([('tree/file','b\n')])
3245
        work_tree.add('file', 'file-id')
3363.17.1 by Aaron Bentley
Avoid inventory for merge and transform code
3246
        work_tree.commit('first commit')
3247
        child_tree = work_tree.bzrdir.sprout('child').open_workingtree()
3363.17.2 by Aaron Bentley
Add text checking
3248
        self.build_tree_contents([('child/file','b\nc\n')])
3363.17.1 by Aaron Bentley
Avoid inventory for merge and transform code
3249
        child_tree.commit('child commit')
3250
        child_tree.lock_write()
3251
        self.addCleanup(child_tree.unlock)
3252
        work_tree.lock_write()
3253
        self.addCleanup(work_tree.unlock)
3254
        preview = TransformPreview(work_tree)
3255
        self.addCleanup(preview.finalize)
3363.17.6 by Aaron Bentley
Improve test scenario
3256
        file_trans_id = preview.trans_id_file_id('file-id')
3257
        preview.delete_contents(file_trans_id)
3258
        preview.create_file('a\nb\n', file_trans_id)
4634.57.2 by Aaron Bentley
Fix failing test.
3259
        preview_tree = preview.get_preview_tree()
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
3260
        merger = Merger.from_revision_ids(None, preview_tree,
3363.17.1 by Aaron Bentley
Avoid inventory for merge and transform code
3261
                                          child_tree.branch.last_revision(),
3262
                                          other_branch=child_tree.branch,
3263
                                          tree_branch=work_tree.branch)
3264
        merger.merge_type = Merge3Merger
3265
        tt = merger.make_merger().make_preview_transform()
3363.17.2 by Aaron Bentley
Add text checking
3266
        self.addCleanup(tt.finalize)
3267
        final_tree = tt.get_preview_tree()
3268
        self.assertEqual('a\nb\nc\n', final_tree.get_file_text('file-id'))
3363.17.17 by Aaron Bentley
Start testing merging PreviewTree as OTHER
3269
3270
    def test_merge_preview_into_workingtree(self):
3271
        tree = self.make_branch_and_tree('tree')
4600.3.1 by Robert Collins
Set tree root ID in tree transform tests that don't care about the root id.
3272
        tree.set_root_id('TREE_ROOT')
3363.17.17 by Aaron Bentley
Start testing merging PreviewTree as OTHER
3273
        tt = TransformPreview(tree)
3274
        self.addCleanup(tt.finalize)
3275
        tt.new_file('name', tt.root, 'content', 'file-id')
3276
        tree2 = self.make_branch_and_tree('tree2')
4600.3.1 by Robert Collins
Set tree root ID in tree transform tests that don't care about the root id.
3277
        tree2.set_root_id('TREE_ROOT')
3363.17.17 by Aaron Bentley
Start testing merging PreviewTree as OTHER
3278
        merger = Merger.from_uncommitted(tree2, tt.get_preview_tree(),
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
3279
                                         None, tree.basis_tree())
3363.17.17 by Aaron Bentley
Start testing merging PreviewTree as OTHER
3280
        merger.merge_type = Merge3Merger
3281
        merger.do_merge()
3363.17.18 by Aaron Bentley
Fix is_executable for PreviewTree
3282
3363.17.21 by Aaron Bentley
Conflicts are handled when merging from preview trees
3283
    def test_merge_preview_into_workingtree_handles_conflicts(self):
3284
        tree = self.make_branch_and_tree('tree')
3285
        self.build_tree_contents([('tree/foo', 'bar')])
3286
        tree.add('foo', 'foo-id')
3287
        tree.commit('foo')
3288
        tt = TransformPreview(tree)
3289
        self.addCleanup(tt.finalize)
3290
        trans_id = tt.trans_id_file_id('foo-id')
3291
        tt.delete_contents(trans_id)
3292
        tt.create_file('baz', trans_id)
3293
        tree2 = tree.bzrdir.sprout('tree2').open_workingtree()
3294
        self.build_tree_contents([('tree2/foo', 'qux')])
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
3295
        pb = None
3363.17.21 by Aaron Bentley
Conflicts are handled when merging from preview trees
3296
        merger = Merger.from_uncommitted(tree2, tt.get_preview_tree(),
3297
                                         pb, tree.basis_tree())
3298
        merger.merge_type = Merge3Merger
3299
        merger.do_merge()
3300
5809.3.2 by Aaron Bentley
Support PreviewTree.has_filename.
3301
    def test_has_filename(self):
3302
        wt = self.make_branch_and_tree('tree')
3303
        self.build_tree(['tree/unmodified', 'tree/removed', 'tree/modified'])
3304
        tt = TransformPreview(wt)
3305
        removed_id = tt.trans_id_tree_path('removed')
3306
        tt.delete_contents(removed_id)
3307
        tt.new_file('new', tt.root, 'contents')
3308
        modified_id = tt.trans_id_tree_path('modified')
3309
        tt.delete_contents(modified_id)
3310
        tt.create_file('modified-contents', modified_id)
3311
        self.addCleanup(tt.finalize)
3312
        tree = tt.get_preview_tree()
3313
        self.assertTrue(tree.has_filename('unmodified'))
3314
        self.assertFalse(tree.has_filename('not-present'))
3315
        self.assertFalse(tree.has_filename('removed'))
3316
        self.assertTrue(tree.has_filename('new'))
3317
        self.assertTrue(tree.has_filename('modified'))
3318
3363.17.18 by Aaron Bentley
Fix is_executable for PreviewTree
3319
    def test_is_executable(self):
3320
        tree = self.make_branch_and_tree('tree')
3321
        preview = TransformPreview(tree)
3322
        self.addCleanup(preview.finalize)
3323
        preview.new_file('foo', preview.root, 'bar', 'baz-id')
3324
        preview_tree = preview.get_preview_tree()
3325
        self.assertEqual(False, preview_tree.is_executable('baz-id',
3326
                                                           'tree/foo'))
3327
        self.assertEqual(False, preview_tree.is_executable('baz-id'))
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3328
4354.4.4 by Aaron Bentley
Simplify by using CommitBuilder directly
3329
    def test_commit_preview_tree(self):
3330
        tree = self.make_branch_and_tree('tree')
3331
        rev_id = tree.commit('rev1')
3332
        tree.branch.lock_write()
3333
        self.addCleanup(tree.branch.unlock)
3334
        tt = TransformPreview(tree)
3335
        tt.new_file('file', tt.root, 'contents', 'file_id')
3336
        self.addCleanup(tt.finalize)
3337
        preview = tt.get_preview_tree()
3338
        preview.set_parent_ids([rev_id])
3339
        builder = tree.branch.get_commit_builder([rev_id])
3340
        list(builder.record_iter_changes(preview, rev_id, tt.iter_changes()))
3341
        builder.finish_inventory()
3342
        rev2_id = builder.commit('rev2')
3343
        rev2_tree = tree.branch.repository.revision_tree(rev2_id)
3344
        self.assertEqual('contents', rev2_tree.get_file_text('file_id'))
3345
4634.79.1 by Aaron Bentley
TransformPreview uses ascii-only filenames.
3346
    def test_ascii_limbo_paths(self):
4634.79.2 by Aaron Bentley
Avoid runing test on non-unicode filesystems.
3347
        self.requireFeature(tests.UnicodeFilenameFeature)
4634.79.1 by Aaron Bentley
TransformPreview uses ascii-only filenames.
3348
        branch = self.make_branch('any')
3349
        tree = branch.repository.revision_tree(_mod_revision.NULL_REVISION)
3350
        tt = TransformPreview(tree)
4789.25.7 by John Arbash Meinel
We can run the executable tests.
3351
        self.addCleanup(tt.finalize)
4634.79.1 by Aaron Bentley
TransformPreview uses ascii-only filenames.
3352
        foo_id = tt.new_directory('', ROOT_PARENT)
3353
        bar_id = tt.new_file(u'\u1234bar', foo_id, 'contents')
3354
        limbo_path = tt._limbo_name(bar_id)
3355
        self.assertEqual(limbo_path.encode('ascii', 'replace'), limbo_path)
3356
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3357
0.13.13 by Aaron Bentley
Add direct test of serialization records
3358
class FakeSerializer(object):
3359
    """Serializer implementation that simply returns the input.
3360
3361
    The input is returned in the order used by pack.ContainerPushParser.
3362
    """
3363
    @staticmethod
3364
    def bytes_record(bytes, names):
3365
        return names, bytes
3366
3367
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3368
class TestSerializeTransform(tests.TestCaseWithTransport):
3369
0.13.22 by Aaron Bentley
More unicodeness for Shelf tests
3370
    _test_needs_features = [tests.UnicodeFilenameFeature]
3371
0.13.17 by Aaron Bentley
Convert roundtrip destruction test to serialization/deserialization pair
3372
    def get_preview(self, tree=None):
3373
        if tree is None:
3374
            tree = self.make_branch_and_tree('tree')
0.13.14 by Aaron Bentley
Add deserialization test, remove roundtrip test.
3375
        tt = TransformPreview(tree)
3376
        self.addCleanup(tt.finalize)
3377
        return tt
3378
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3379
    def assertSerializesTo(self, expected, tt):
3380
        records = list(tt.serialize(FakeSerializer()))
3381
        self.assertEqual(expected, records)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3382
0.13.13 by Aaron Bentley
Add direct test of serialization records
3383
    @staticmethod
3384
    def default_attribs():
3385
        return {
0.13.15 by Aaron Bentley
Convert symlink tests to avoid roundtripping
3386
            '_id_number': 1,
0.13.13 by Aaron Bentley
Add direct test of serialization records
3387
            '_new_name': {},
3388
            '_new_parent': {},
3389
            '_new_executability': {},
3390
            '_new_id': {},
0.13.15 by Aaron Bentley
Convert symlink tests to avoid roundtripping
3391
            '_tree_path_ids': {'': 'new-0'},
0.13.13 by Aaron Bentley
Add direct test of serialization records
3392
            '_removed_id': [],
3393
            '_removed_contents': [],
3394
            '_non_present_ids': {},
3395
            }
3396
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3397
    def make_records(self, attribs, contents):
3398
        records = [
3399
            (((('attribs'),),), bencode.bencode(attribs))]
3400
        records.extend([(((n, k),), c) for n, k, c in contents])
3401
        return records
3402
0.13.13 by Aaron Bentley
Add direct test of serialization records
3403
    def creation_records(self):
3404
        attribs = self.default_attribs()
3405
        attribs['_id_number'] = 3
3406
        attribs['_new_name'] = {
3407
            'new-1': u'foo\u1234'.encode('utf-8'), 'new-2': 'qux'}
3408
        attribs['_new_id'] = {'new-1': 'baz', 'new-2': 'quxx'}
3409
        attribs['_new_parent'] = {'new-1': 'new-0', 'new-2': 'new-0'}
3410
        attribs['_new_executability'] = {'new-1': 1}
3411
        contents = [
3412
            ('new-1', 'file', 'i 1\nbar\n'),
3413
            ('new-2', 'directory', ''),
3414
            ]
3415
        return self.make_records(attribs, contents)
3416
3417
    def test_serialize_creation(self):
0.13.14 by Aaron Bentley
Add deserialization test, remove roundtrip test.
3418
        tt = self.get_preview()
0.13.13 by Aaron Bentley
Add direct test of serialization records
3419
        tt.new_file(u'foo\u1234', tt.root, 'bar', 'baz', True)
3420
        tt.new_directory('qux', tt.root, 'quxx')
0.13.21 by Aaron Bentley
Use assertSerializesTo in more places
3421
        self.assertSerializesTo(self.creation_records(), tt)
0.13.13 by Aaron Bentley
Add direct test of serialization records
3422
0.13.14 by Aaron Bentley
Add deserialization test, remove roundtrip test.
3423
    def test_deserialize_creation(self):
3424
        tt = self.get_preview()
3425
        tt.deserialize(iter(self.creation_records()))
3426
        self.assertEqual(3, tt._id_number)
3427
        self.assertEqual({'new-1': u'foo\u1234',
3428
                          'new-2': 'qux'}, tt._new_name)
3429
        self.assertEqual({'new-1': 'baz', 'new-2': 'quxx'}, tt._new_id)
3430
        self.assertEqual({'new-1': tt.root, 'new-2': tt.root}, tt._new_parent)
3431
        self.assertEqual({'baz': 'new-1', 'quxx': 'new-2'}, tt._r_new_id)
3432
        self.assertEqual({'new-1': True}, tt._new_executability)
3433
        self.assertEqual({'new-1': 'file',
3434
                          'new-2': 'directory'}, tt._new_contents)
3435
        foo_limbo = open(tt._limbo_name('new-1'), 'rb')
3436
        try:
3437
            foo_content = foo_limbo.read()
3438
        finally:
3439
            foo_limbo.close()
3440
        self.assertEqual('bar', foo_content)
3441
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3442
    def symlink_creation_records(self):
3443
        attribs = self.default_attribs()
3444
        attribs['_id_number'] = 2
3445
        attribs['_new_name'] = {'new-1': u'foo\u1234'.encode('utf-8')}
3446
        attribs['_new_parent'] = {'new-1': 'new-0'}
3447
        contents = [('new-1', 'symlink', u'bar\u1234'.encode('utf-8'))]
3448
        return self.make_records(attribs, contents)
3449
0.13.15 by Aaron Bentley
Convert symlink tests to avoid roundtripping
3450
    def test_serialize_symlink_creation(self):
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3451
        self.requireFeature(tests.SymlinkFeature)
0.13.15 by Aaron Bentley
Convert symlink tests to avoid roundtripping
3452
        tt = self.get_preview()
0.13.16 by Aaron Bentley
Add unicode symlink targets to tests
3453
        tt.new_symlink(u'foo\u1234', tt.root, u'bar\u1234')
0.13.21 by Aaron Bentley
Use assertSerializesTo in more places
3454
        self.assertSerializesTo(self.symlink_creation_records(), tt)
0.13.15 by Aaron Bentley
Convert symlink tests to avoid roundtripping
3455
3456
    def test_deserialize_symlink_creation(self):
4241.14.12 by Vincent Ladeuil
Far too many modifications for a single commit, need to restart.
3457
        self.requireFeature(tests.SymlinkFeature)
0.13.15 by Aaron Bentley
Convert symlink tests to avoid roundtripping
3458
        tt = self.get_preview()
3459
        tt.deserialize(iter(self.symlink_creation_records()))
4241.14.12 by Vincent Ladeuil
Far too many modifications for a single commit, need to restart.
3460
        abspath = tt._limbo_name('new-1')
4241.14.17 by Vincent Ladeuil
Add more tests for unicode symlinks to test_transform.
3461
        foo_content = osutils.readlink(abspath)
0.13.22 by Aaron Bentley
More unicodeness for Shelf tests
3462
        self.assertEqual(u'bar\u1234', foo_content)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3463
0.13.19 by Aaron Bentley
Clean up serialization tests
3464
    def make_destruction_preview(self):
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3465
        tree = self.make_branch_and_tree('.')
3466
        self.build_tree([u'foo\u1234', 'bar'])
3467
        tree.add([u'foo\u1234', 'bar'], ['foo-id', 'bar-id'])
0.13.19 by Aaron Bentley
Clean up serialization tests
3468
        return self.get_preview(tree)
0.13.17 by Aaron Bentley
Convert roundtrip destruction test to serialization/deserialization pair
3469
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3470
    def destruction_records(self):
3471
        attribs = self.default_attribs()
3472
        attribs['_id_number'] = 3
3473
        attribs['_removed_id'] = ['new-1']
3474
        attribs['_removed_contents'] = ['new-2']
3475
        attribs['_tree_path_ids'] = {
3476
            '': 'new-0',
3477
            u'foo\u1234'.encode('utf-8'): 'new-1',
3478
            'bar': 'new-2',
3479
            }
3480
        return self.make_records(attribs, [])
3481
0.13.17 by Aaron Bentley
Convert roundtrip destruction test to serialization/deserialization pair
3482
    def test_serialize_destruction(self):
0.13.19 by Aaron Bentley
Clean up serialization tests
3483
        tt = self.make_destruction_preview()
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3484
        foo_trans_id = tt.trans_id_tree_file_id('foo-id')
3485
        tt.unversion_file(foo_trans_id)
3486
        bar_trans_id = tt.trans_id_tree_file_id('bar-id')
3487
        tt.delete_contents(bar_trans_id)
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3488
        self.assertSerializesTo(self.destruction_records(), tt)
0.13.17 by Aaron Bentley
Convert roundtrip destruction test to serialization/deserialization pair
3489
3490
    def test_deserialize_destruction(self):
0.13.19 by Aaron Bentley
Clean up serialization tests
3491
        tt = self.make_destruction_preview()
0.13.17 by Aaron Bentley
Convert roundtrip destruction test to serialization/deserialization pair
3492
        tt.deserialize(iter(self.destruction_records()))
3493
        self.assertEqual({u'foo\u1234': 'new-1',
3494
                          'bar': 'new-2',
3495
                          '': tt.root}, tt._tree_path_ids)
3496
        self.assertEqual({'new-1': u'foo\u1234',
3497
                          'new-2': 'bar',
3498
                          tt.root: ''}, tt._tree_id_paths)
3499
        self.assertEqual(set(['new-1']), tt._removed_id)
3500
        self.assertEqual(set(['new-2']), tt._removed_contents)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3501
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3502
    def missing_records(self):
3503
        attribs = self.default_attribs()
3504
        attribs['_id_number'] = 2
3505
        attribs['_non_present_ids'] = {
3506
            'boo': 'new-1',}
3507
        return self.make_records(attribs, [])
3508
3509
    def test_serialize_missing(self):
3510
        tt = self.get_preview()
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3511
        boo_trans_id = tt.trans_id_file_id('boo')
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3512
        self.assertSerializesTo(self.missing_records(), tt)
3513
3514
    def test_deserialize_missing(self):
3515
        tt = self.get_preview()
3516
        tt.deserialize(iter(self.missing_records()))
3517
        self.assertEqual({'boo': 'new-1'}, tt._non_present_ids)
3518
3519
    def make_modification_preview(self):
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3520
        LINES_ONE = 'aa\nbb\ncc\ndd\n'
3521
        LINES_TWO = 'z\nbb\nx\ndd\n'
3522
        tree = self.make_branch_and_tree('tree')
3523
        self.build_tree_contents([('tree/file', LINES_ONE)])
3524
        tree.add('file', 'file-id')
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3525
        return self.get_preview(tree), LINES_TWO
3526
3527
    def modification_records(self):
3528
        attribs = self.default_attribs()
3529
        attribs['_id_number'] = 2
3530
        attribs['_tree_path_ids'] = {
3531
            'file': 'new-1',
3532
            '': 'new-0',}
3533
        attribs['_removed_contents'] = ['new-1']
3534
        contents = [('new-1', 'file',
3535
                     'i 1\nz\n\nc 0 1 1 1\ni 1\nx\n\nc 0 3 3 1\n')]
3536
        return self.make_records(attribs, contents)
3537
3538
    def test_serialize_modification(self):
3539
        tt, LINES = self.make_modification_preview()
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3540
        trans_id = tt.trans_id_file_id('file-id')
3541
        tt.delete_contents(trans_id)
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3542
        tt.create_file(LINES, trans_id)
3543
        self.assertSerializesTo(self.modification_records(), tt)
3544
3545
    def test_deserialize_modification(self):
3546
        tt, LINES = self.make_modification_preview()
3547
        tt.deserialize(iter(self.modification_records()))
3548
        self.assertFileEqual(LINES, tt._limbo_name('new-1'))
3549
3550
    def make_kind_change_preview(self):
3551
        LINES = 'a\nb\nc\nd\n'
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3552
        tree = self.make_branch_and_tree('tree')
3553
        self.build_tree(['tree/foo/'])
3554
        tree.add('foo', 'foo-id')
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3555
        return self.get_preview(tree), LINES
3556
3557
    def kind_change_records(self):
3558
        attribs = self.default_attribs()
3559
        attribs['_id_number'] = 2
3560
        attribs['_tree_path_ids'] = {
3561
            'foo': 'new-1',
3562
            '': 'new-0',}
3563
        attribs['_removed_contents'] = ['new-1']
3564
        contents = [('new-1', 'file',
3565
                     'i 4\na\nb\nc\nd\n\n')]
3566
        return self.make_records(attribs, contents)
3567
3568
    def test_serialize_kind_change(self):
3569
        tt, LINES = self.make_kind_change_preview()
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3570
        trans_id = tt.trans_id_file_id('foo-id')
3571
        tt.delete_contents(trans_id)
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3572
        tt.create_file(LINES, trans_id)
3573
        self.assertSerializesTo(self.kind_change_records(), tt)
3574
3575
    def test_deserialize_kind_change(self):
3576
        tt, LINES = self.make_kind_change_preview()
3577
        tt.deserialize(iter(self.kind_change_records()))
3578
        self.assertFileEqual(LINES, tt._limbo_name('new-1'))
3579
3580
    def make_add_contents_preview(self):
3581
        LINES = 'a\nb\nc\nd\n'
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3582
        tree = self.make_branch_and_tree('tree')
3583
        self.build_tree(['tree/foo'])
3584
        tree.add('foo')
3585
        os.unlink('tree/foo')
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3586
        return self.get_preview(tree), LINES
3587
3588
    def add_contents_records(self):
3589
        attribs = self.default_attribs()
3590
        attribs['_id_number'] = 2
3591
        attribs['_tree_path_ids'] = {
3592
            'foo': 'new-1',
3593
            '': 'new-0',}
3594
        contents = [('new-1', 'file',
3595
                     'i 4\na\nb\nc\nd\n\n')]
3596
        return self.make_records(attribs, contents)
3597
3598
    def test_serialize_add_contents(self):
3599
        tt, LINES = self.make_add_contents_preview()
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3600
        trans_id = tt.trans_id_tree_path('foo')
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3601
        tt.create_file(LINES, trans_id)
3602
        self.assertSerializesTo(self.add_contents_records(), tt)
3603
3604
    def test_deserialize_add_contents(self):
3605
        tt, LINES = self.make_add_contents_preview()
3606
        tt.deserialize(iter(self.add_contents_records()))
3607
        self.assertFileEqual(LINES, tt._limbo_name('new-1'))
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3608
3609
    def test_get_parents_lines(self):
3610
        LINES_ONE = 'aa\nbb\ncc\ndd\n'
3611
        LINES_TWO = 'z\nbb\nx\ndd\n'
3612
        tree = self.make_branch_and_tree('tree')
3613
        self.build_tree_contents([('tree/file', LINES_ONE)])
3614
        tree.add('file', 'file-id')
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3615
        tt = self.get_preview(tree)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3616
        trans_id = tt.trans_id_tree_path('file')
3617
        self.assertEqual((['aa\n', 'bb\n', 'cc\n', 'dd\n'],),
3618
            tt._get_parents_lines(trans_id))
3619
3620
    def test_get_parents_texts(self):
3621
        LINES_ONE = 'aa\nbb\ncc\ndd\n'
3622
        LINES_TWO = 'z\nbb\nx\ndd\n'
3623
        tree = self.make_branch_and_tree('tree')
3624
        self.build_tree_contents([('tree/file', LINES_ONE)])
3625
        tree.add('file', 'file-id')
0.13.18 by Aaron Bentley
Finish converting tests to direct serialize/deserialize tests, clean up
3626
        tt = self.get_preview(tree)
0.13.8 by Aaron Bentley
Integrate serialization into TreeTransforms
3627
        trans_id = tt.trans_id_tree_path('file')
3628
        self.assertEqual((LINES_ONE,),
3629
            tt._get_parents_texts(trans_id))
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
3630
3631
3632
class TestOrphan(tests.TestCaseWithTransport):
3633
3634
    def test_no_orphan_for_transform_preview(self):
3635
        tree = self.make_branch_and_tree('tree')
5409.7.2 by Vincent Ladeuil
Add NEWS entry, a missing test and some cleanup.
3636
        tt = transform.TransformPreview(tree)
5409.1.7 by Vincent Ladeuil
First orphaning implementation (some tests lacking).
3637
        self.addCleanup(tt.finalize)
3638
        self.assertRaises(NotImplementedError, tt.new_orphan, 'foo', 'bar')
3639
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
3640
    def _set_orphan_policy(self, wt, policy):
5409.1.24 by Vincent Ladeuil
Rename bzrlib.transform.orphan_policy to bzr.transform.orphan_policy.
3641
        wt.branch.get_config().set_user_option('bzr.transform.orphan_policy',
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
3642
                                               policy)
3643
3644
    def _prepare_orphan(self, wt):
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
3645
        self.build_tree(['dir/', 'dir/file', 'dir/foo'])
3646
        wt.add(['dir', 'dir/file'], ['dir-id', 'file-id'])
3647
        wt.commit('add dir and file ignoring foo')
5409.7.2 by Vincent Ladeuil
Add NEWS entry, a missing test and some cleanup.
3648
        tt = transform.TreeTransform(wt)
3649
        self.addCleanup(tt.finalize)
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
3650
        # dir and bar are deleted
5409.7.2 by Vincent Ladeuil
Add NEWS entry, a missing test and some cleanup.
3651
        dir_tid = tt.trans_id_tree_path('dir')
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
3652
        file_tid = tt.trans_id_tree_path('dir/file')
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
3653
        orphan_tid = tt.trans_id_tree_path('dir/foo')
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
3654
        tt.delete_contents(file_tid)
3655
        tt.unversion_file(file_tid)
5409.7.2 by Vincent Ladeuil
Add NEWS entry, a missing test and some cleanup.
3656
        tt.delete_contents(dir_tid)
3657
        tt.unversion_file(dir_tid)
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
3658
        # There should be a conflict because dir still contain foo
5409.7.2 by Vincent Ladeuil
Add NEWS entry, a missing test and some cleanup.
3659
        raw_conflicts = tt.find_conflicts()
3660
        self.assertLength(1, raw_conflicts)
3661
        self.assertEqual(('missing parent', 'new-1'), raw_conflicts[0])
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
3662
        return tt, orphan_tid
3663
3664
    def test_new_orphan_created(self):
3665
        wt = self.make_branch_and_tree('.')
5409.1.20 by Vincent Ladeuil
Revert to 'conflict' being the default orphaning policy and fix fallouts.
3666
        self._set_orphan_policy(wt, 'move')
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
3667
        tt, orphan_tid = self._prepare_orphan(wt)
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
3668
        warnings = []
3669
        def warning(*args):
3670
            warnings.append(args[0] % args[1:])
3671
        self.overrideAttr(trace, 'warning', warning)
5409.7.2 by Vincent Ladeuil
Add NEWS entry, a missing test and some cleanup.
3672
        remaining_conflicts = resolve_conflicts(tt)
5540.3.1 by Vincent Ladeuil
Fix spurious orphan reports.
3673
        self.assertEquals(['dir/foo has been orphaned in bzr-orphans'],
3674
                          warnings)
5409.7.2 by Vincent Ladeuil
Add NEWS entry, a missing test and some cleanup.
3675
        # Yeah for resolved conflicts !
3676
        self.assertLength(0, remaining_conflicts)
3677
        # We have a new orphan
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
3678
        self.assertEquals('foo.~1~', tt.final_name(orphan_tid))
5409.7.4 by Vincent Ladeuil
Take jam's review comments into account.
3679
        self.assertEquals('bzr-orphans',
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
3680
                          tt.final_name(tt.final_parent(orphan_tid)))
3681
3682
    def test_never_orphan(self):
3683
        wt = self.make_branch_and_tree('.')
5409.1.20 by Vincent Ladeuil
Revert to 'conflict' being the default orphaning policy and fix fallouts.
3684
        self._set_orphan_policy(wt, 'conflict')
5409.1.16 by Vincent Ladeuil
Add ``bzrlib.transform.orphan_policy`` and allows ``never`` to restore the previous behaviour.
3685
        tt, orphan_tid = self._prepare_orphan(wt)
3686
        remaining_conflicts = resolve_conflicts(tt)
3687
        self.assertLength(1, remaining_conflicts)
3688
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
3689
                         remaining_conflicts.pop())
3690
3691
    def test_orphan_error(self):
3692
        def bogus_orphan(tt, orphan_id, parent_id):
3693
            raise transform.OrphaningError(tt.final_name(orphan_id),
3694
                                           tt.final_name(parent_id))
3695
        transform.orphaning_registry.register('bogus', bogus_orphan,
3696
                                              'Raise an error when orphaning')
3697
        wt = self.make_branch_and_tree('.')
3698
        self._set_orphan_policy(wt, 'bogus')
3699
        tt, orphan_tid = self._prepare_orphan(wt)
3700
        remaining_conflicts = resolve_conflicts(tt)
3701
        self.assertLength(1, remaining_conflicts)
3702
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
3703
                         remaining_conflicts.pop())
5409.1.17 by Vincent Ladeuil
Ensures we fallback to the default policy if a bogus one is specified.
3704
3705
    def test_unknown_orphan_policy(self):
3706
        wt = self.make_branch_and_tree('.')
3707
        # Set a fictional policy nobody ever implemented
3708
        self._set_orphan_policy(wt, 'donttouchmypreciouuus')
3709
        tt, orphan_tid = self._prepare_orphan(wt)
3710
        warnings = []
3711
        def warning(*args):
3712
            warnings.append(args[0] % args[1:])
3713
        self.overrideAttr(trace, 'warning', warning)
3714
        remaining_conflicts = resolve_conflicts(tt)
5409.1.20 by Vincent Ladeuil
Revert to 'conflict' being the default orphaning policy and fix fallouts.
3715
        # We fallback to the default policy which create a conflict
3716
        self.assertLength(1, remaining_conflicts)
3717
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
3718
                         remaining_conflicts.pop())
3719
        self.assertLength(1, warnings)
3720
        self.assertStartsWith(warnings[0], 'donttouchmypreciouuus')