/brz/remove-bazaar

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