/brz/remove-bazaar

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