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