~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_transform.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-12-09 02:53:42 UTC
  • mfrom: (4873.2.3 2.1.0b4-win32-test-imports)
  • Revision ID: pqm@pqm.ubuntu.com-20091209025342-sidvxfcqdgxmuz59
(jam) Get the test suite running again on Windows, (bug #492561)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
import errno
18
17
import os
19
18
from StringIO import StringIO
20
19
import sys
21
 
import time
22
20
 
23
21
from bzrlib import (
24
22
    bencode,
26
24
    filters,
27
25
    generate_ids,
28
26
    osutils,
 
27
    progress,
29
28
    revision as _mod_revision,
30
29
    rules,
31
 
    symbol_versioning,
32
30
    tests,
33
 
    trace,
34
 
    transform,
35
31
    urlutils,
36
32
    )
37
33
from bzrlib.bzrdir import BzrDir
38
 
from bzrlib.conflicts import (
39
 
    DeletingParent,
40
 
    DuplicateEntry,
41
 
    DuplicateID,
42
 
    MissingParent,
43
 
    NonDirectoryParent,
44
 
    ParentLoop,
45
 
    UnversionedParent,
46
 
)
 
34
from bzrlib.conflicts import (DuplicateEntry, DuplicateID, MissingParent,
 
35
                              UnversionedParent, ParentLoop, DeletingParent,
 
36
                              NonDirectoryParent)
47
37
from bzrlib.diff import show_diff_trees
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
 
)
 
38
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
 
39
                           ReusingTransform, CantMoveRoot,
 
40
                           PathsNotVersionedError, ExistingLimbo,
 
41
                           ExistingPendingDeletion, ImmortalLimbo,
 
42
                           ImmortalPendingDeletion, LockError)
 
43
from bzrlib.osutils import file_kind, pathjoin
62
44
from bzrlib.merge import Merge3Merger, Merger
63
45
from bzrlib.tests import (
64
 
    features,
 
46
    HardlinkFeature,
 
47
    SymlinkFeature,
 
48
    TestCase,
65
49
    TestCaseInTempDir,
66
50
    TestSkipped,
67
51
    )
68
 
from bzrlib.tests.features import (
69
 
    HardlinkFeature,
70
 
    SymlinkFeature,
71
 
    )
72
 
from bzrlib.transform import (
73
 
    build_tree,
74
 
    create_from_tree,
75
 
    cook_conflicts,
76
 
    _FileMover,
77
 
    FinalPaths,
78
 
    resolve_conflicts,
79
 
    resolve_checkout,
80
 
    ROOT_PARENT,
81
 
    TransformPreview,
82
 
    TreeTransform,
83
 
)
 
52
from bzrlib.transform import (TreeTransform, ROOT_PARENT, FinalPaths,
 
53
                              resolve_conflicts, cook_conflicts,
 
54
                              build_tree, get_backup_name,
 
55
                              _FileMover, resolve_checkout,
 
56
                              TransformPreview, create_from_tree)
84
57
 
85
58
 
86
59
class TestTreeTransform(tests.TestCaseWithTransport):
95
68
        self.addCleanup(transform.finalize)
96
69
        return transform, transform.root
97
70
 
98
 
    def get_transform_for_sha1_test(self):
99
 
        trans, root = self.get_transform()
100
 
        self.wt.lock_tree_write()
101
 
        self.addCleanup(self.wt.unlock)
102
 
        contents = ['just some content\n']
103
 
        sha1 = osutils.sha_strings(contents)
104
 
        # Roll back the clock
105
 
        trans._creation_mtime = time.time() - 20.0
106
 
        return trans, root, contents, sha1
107
 
 
108
71
    def test_existing_limbo(self):
109
72
        transform, root = self.get_transform()
110
73
        limbo_name = transform._limbodir
137
100
        imaginary_id = transform.trans_id_tree_path('imaginary')
138
101
        imaginary_id2 = transform.trans_id_tree_path('imaginary/')
139
102
        self.assertEqual(imaginary_id, imaginary_id2)
140
 
        self.assertEqual(root, transform.get_tree_parent(imaginary_id))
141
 
        self.assertEqual('directory', transform.final_kind(root))
142
 
        self.assertEqual(self.wt.get_root_id(), transform.final_file_id(root))
 
103
        self.assertEqual(transform.get_tree_parent(imaginary_id), root)
 
104
        self.assertEqual(transform.final_kind(root), 'directory')
 
105
        self.assertEqual(transform.final_file_id(root), self.wt.get_root_id())
143
106
        trans_id = transform.create_path('name', root)
144
107
        self.assertIs(transform.final_file_id(trans_id), None)
145
 
        self.assertIs(None, transform.final_kind(trans_id))
 
108
        self.assertRaises(NoSuchFile, transform.final_kind, trans_id)
146
109
        transform.create_file('contents', trans_id)
147
110
        transform.set_executability(True, trans_id)
148
111
        transform.version_file('my_pretties', trans_id)
173
136
        transform.finalize()
174
137
        transform.finalize()
175
138
 
176
 
    def test_apply_informs_tree_of_observed_sha1(self):
177
 
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
178
 
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
179
 
                                  sha1=sha1)
180
 
        calls = []
181
 
        orig = self.wt._observed_sha1
182
 
        def _observed_sha1(*args):
183
 
            calls.append(args)
184
 
            orig(*args)
185
 
        self.wt._observed_sha1 = _observed_sha1
186
 
        trans.apply()
187
 
        self.assertEqual([(None, 'file1', trans._observed_sha1s[trans_id])],
188
 
                         calls)
189
 
 
190
 
    def test_create_file_caches_sha1(self):
191
 
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
192
 
        trans_id = trans.create_path('file1', root)
193
 
        trans.create_file(contents, trans_id, sha1=sha1)
194
 
        st_val = osutils.lstat(trans._limbo_name(trans_id))
195
 
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
196
 
        self.assertEqual(o_sha1, sha1)
197
 
        self.assertEqualStat(o_st_val, st_val)
198
 
 
199
 
    def test__apply_insertions_updates_sha1(self):
200
 
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
201
 
        trans_id = trans.create_path('file1', root)
202
 
        trans.create_file(contents, trans_id, sha1=sha1)
203
 
        st_val = osutils.lstat(trans._limbo_name(trans_id))
204
 
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
205
 
        self.assertEqual(o_sha1, sha1)
206
 
        self.assertEqualStat(o_st_val, st_val)
207
 
        creation_mtime = trans._creation_mtime + 10.0
208
 
        # We fake a time difference from when the file was created until now it
209
 
        # is being renamed by using os.utime. Note that the change we actually
210
 
        # want to see is the real ctime change from 'os.rename()', but as long
211
 
        # as we observe a new stat value, we should be fine.
212
 
        os.utime(trans._limbo_name(trans_id), (creation_mtime, creation_mtime))
213
 
        trans.apply()
214
 
        new_st_val = osutils.lstat(self.wt.abspath('file1'))
215
 
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
216
 
        self.assertEqual(o_sha1, sha1)
217
 
        self.assertEqualStat(o_st_val, new_st_val)
218
 
        self.assertNotEqual(st_val.st_mtime, new_st_val.st_mtime)
219
 
 
220
 
    def test_new_file_caches_sha1(self):
221
 
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
222
 
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
223
 
                                  sha1=sha1)
224
 
        st_val = osutils.lstat(trans._limbo_name(trans_id))
225
 
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
226
 
        self.assertEqual(o_sha1, sha1)
227
 
        self.assertEqualStat(o_st_val, st_val)
228
 
 
229
 
    def test_cancel_creation_removes_observed_sha1(self):
230
 
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
231
 
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
232
 
                                  sha1=sha1)
233
 
        self.assertTrue(trans_id in trans._observed_sha1s)
234
 
        trans.cancel_creation(trans_id)
235
 
        self.assertFalse(trans_id in trans._observed_sha1s)
236
 
 
237
 
    def test_create_files_same_timestamp(self):
238
 
        transform, root = self.get_transform()
239
 
        self.wt.lock_tree_write()
240
 
        self.addCleanup(self.wt.unlock)
241
 
        # Roll back the clock, so that we know everything is being set to the
242
 
        # exact time
243
 
        transform._creation_mtime = creation_mtime = time.time() - 20.0
244
 
        transform.create_file('content-one',
245
 
                              transform.create_path('one', root))
246
 
        time.sleep(1) # *ugly*
247
 
        transform.create_file('content-two',
248
 
                              transform.create_path('two', root))
249
 
        transform.apply()
250
 
        fo, st1 = self.wt.get_file_with_stat(None, path='one', filtered=False)
251
 
        fo.close()
252
 
        fo, st2 = self.wt.get_file_with_stat(None, path='two', filtered=False)
253
 
        fo.close()
254
 
        # We only guarantee 2s resolution
255
 
        self.assertTrue(abs(creation_mtime - st1.st_mtime) < 2.0,
256
 
            "%s != %s within 2 seconds" % (creation_mtime, st1.st_mtime))
257
 
        # But if we have more than that, all files should get the same result
258
 
        self.assertEqual(st1.st_mtime, st2.st_mtime)
259
 
 
260
 
    def test_change_root_id(self):
261
 
        transform, root = self.get_transform()
262
 
        self.assertNotEqual('new-root-id', self.wt.get_root_id())
263
 
        transform.new_directory('', ROOT_PARENT, 'new-root-id')
264
 
        transform.delete_contents(root)
265
 
        transform.unversion_file(root)
266
 
        transform.fixup_new_roots()
267
 
        transform.apply()
268
 
        self.assertEqual('new-root-id', self.wt.get_root_id())
269
 
 
270
 
    def test_change_root_id_add_files(self):
271
 
        transform, root = self.get_transform()
272
 
        self.assertNotEqual('new-root-id', self.wt.get_root_id())
273
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
274
 
        transform.new_file('file', new_trans_id, ['new-contents\n'],
275
 
                           'new-file-id')
276
 
        transform.delete_contents(root)
277
 
        transform.unversion_file(root)
278
 
        transform.fixup_new_roots()
279
 
        transform.apply()
280
 
        self.assertEqual('new-root-id', self.wt.get_root_id())
281
 
        self.assertEqual('new-file-id', self.wt.path2id('file'))
282
 
        self.assertFileEqual('new-contents\n', self.wt.abspath('file'))
283
 
 
284
 
    def test_add_two_roots(self):
285
 
        transform, root = self.get_transform()
286
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
287
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
288
 
        self.assertRaises(ValueError, transform.fixup_new_roots)
289
 
 
290
 
    def test_retain_existing_root(self):
291
 
        tt, root = self.get_transform()
292
 
        with tt:
293
 
            tt.new_directory('', ROOT_PARENT, 'new-root-id')
294
 
            tt.fixup_new_roots()
295
 
            self.assertNotEqual('new-root-id', tt.final_file_id(tt.root))
296
 
 
297
 
    def test_retain_existing_root_added_file(self):
298
 
        tt, root = self.get_transform()
299
 
        new_trans_id = tt.new_directory('', ROOT_PARENT, 'new-root-id')
300
 
        child = tt.new_directory('child', new_trans_id, 'child-id')
301
 
        tt.fixup_new_roots()
302
 
        self.assertEqual(tt.root, tt.final_parent(child))
303
 
 
304
 
    def test_add_unversioned_root(self):
305
 
        transform, root = self.get_transform()
306
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, None)
307
 
        transform.delete_contents(transform.root)
308
 
        transform.fixup_new_roots()
309
 
        self.assertNotIn(transform.root, transform._new_id)
310
 
 
311
 
    def test_remove_root_fixup(self):
312
 
        transform, root = self.get_transform()
313
 
        old_root_id = self.wt.get_root_id()
314
 
        self.assertNotEqual('new-root-id', old_root_id)
315
 
        transform.delete_contents(root)
316
 
        transform.unversion_file(root)
317
 
        transform.fixup_new_roots()
318
 
        transform.apply()
319
 
        self.assertEqual(old_root_id, self.wt.get_root_id())
320
 
 
321
 
        transform, root = self.get_transform()
322
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
323
 
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
324
 
        self.assertRaises(ValueError, transform.fixup_new_roots)
325
 
 
326
 
    def test_fixup_new_roots_permits_empty_tree(self):
327
 
        transform, root = self.get_transform()
328
 
        transform.delete_contents(root)
329
 
        transform.unversion_file(root)
330
 
        transform.fixup_new_roots()
331
 
        self.assertIs(None, transform.final_kind(root))
332
 
        self.assertIs(None, transform.final_file_id(root))
333
 
 
334
 
    def test_apply_retains_root_directory(self):
335
 
        # Do not attempt to delete the physical root directory, because that
336
 
        # is impossible.
337
 
        transform, root = self.get_transform()
338
 
        with transform:
339
 
            transform.delete_contents(root)
340
 
            e = self.assertRaises(AssertionError, self.assertRaises,
341
 
                                  errors.TransformRenameFailed,
342
 
                                  transform.apply)
343
 
        self.assertContainsRe('TransformRenameFailed not raised', str(e))
344
 
 
345
 
    def test_apply_retains_file_id(self):
346
 
        transform, root = self.get_transform()
347
 
        old_root_id = transform.tree_file_id(root)
348
 
        transform.unversion_file(root)
349
 
        transform.apply()
350
 
        self.assertEqual(old_root_id, self.wt.get_root_id())
351
 
 
352
139
    def test_hardlink(self):
353
140
        self.requireFeature(HardlinkFeature)
354
141
        transform, root = self.get_transform()
359
146
        trans_id = target_transform.create_path('file1', target_transform.root)
360
147
        target_transform.create_hardlink(self.wt.abspath('file1'), trans_id)
361
148
        target_transform.apply()
362
 
        self.assertPathExists('target/file1')
 
149
        self.failUnlessExists('target/file1')
363
150
        source_stat = os.stat(self.wt.abspath('file1'))
364
151
        target_stat = os.stat('target/file1')
365
152
        self.assertEqual(source_stat, target_stat)
531
318
        transform.new_file('FiLe', transform.root, 'content')
532
319
        resolve_conflicts(transform)
533
320
        transform.apply()
534
 
        self.assertPathExists('tree/file')
535
 
        self.assertPathExists('tree/FiLe.moved')
 
321
        self.failUnlessExists('tree/file')
 
322
        self.failUnlessExists('tree/FiLe.moved')
536
323
 
537
324
    def test_resolve_checkout_case_conflict(self):
538
325
        tree = self.make_branch_and_tree('tree')
547
334
        resolve_conflicts(transform,
548
335
                          pass_func=lambda t, c: resolve_checkout(t, c, []))
549
336
        transform.apply()
550
 
        self.assertPathExists('tree/file')
551
 
        self.assertPathExists('tree/FiLe.moved')
 
337
        self.failUnlessExists('tree/file')
 
338
        self.failUnlessExists('tree/FiLe.moved')
552
339
 
553
340
    def test_apply_case_conflict(self):
554
341
        """Ensure that a transform with case conflicts can always be applied"""
562
349
        transform.new_file('dirFiLe', dir, 'content')
563
350
        resolve_conflicts(transform)
564
351
        transform.apply()
565
 
        self.assertPathExists('tree/file')
 
352
        self.failUnlessExists('tree/file')
566
353
        if not os.path.exists('tree/FiLe.moved'):
567
 
            self.assertPathExists('tree/FiLe')
568
 
        self.assertPathExists('tree/dir/dirfile')
 
354
            self.failUnlessExists('tree/FiLe')
 
355
        self.failUnlessExists('tree/dir/dirfile')
569
356
        if not os.path.exists('tree/dir/dirFiLe.moved'):
570
 
            self.assertPathExists('tree/dir/dirFiLe')
 
357
            self.failUnlessExists('tree/dir/dirFiLe')
571
358
 
572
359
    def test_case_insensitive_limbo(self):
573
360
        tree = self.make_branch_and_tree('tree')
781
568
                            'wizard2', 'behind_curtain')
782
569
 
783
570
    def test_symlinks_unicode(self):
784
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
571
        self.requireFeature(tests.UnicodeFilenameFeature)
785
572
        self._test_symlinks(u'\N{Euro Sign}wizard',
786
573
                            u'wizard-targ\N{Euro Sign}t',
787
574
                            u'\N{Euro Sign}wizard2',
875
662
        raw_conflicts = resolve_conflicts(tt)
876
663
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
877
664
        tt.finalize()
878
 
        conflicts_s = [unicode(c) for c in cooked_conflicts]
 
665
        conflicts_s = [str(c) for c in cooked_conflicts]
879
666
        self.assertEqual(len(cooked_conflicts), len(conflicts_s))
880
667
        self.assertEqual(conflicts_s[0], 'Conflict adding file dorothy.  '
881
668
                                         'Moved existing file to '
894
681
                                         ' versioned, but has versioned'
895
682
                                         ' children.  Versioned directory.')
896
683
        self.assertEqual(conflicts_s[6], 'Conflict moving oz/emeraldcity into'
897
 
                                         ' oz/emeraldcity. Cancelled move.')
 
684
                                         ' oz/emeraldcity.  Cancelled move.')
898
685
 
899
686
    def prepare_wrong_parent_kind(self):
900
687
        tt, root = self.get_transform()
951
738
        self.assertIs(None, self.wt.path2id('parent'))
952
739
        self.assertIs(None, self.wt.path2id('parent.new'))
953
740
 
954
 
    def test_resolve_conflicts_missing_parent(self):
955
 
        wt = self.make_branch_and_tree('.')
956
 
        tt = TreeTransform(wt)
957
 
        self.addCleanup(tt.finalize)
958
 
        parent = tt.trans_id_file_id('parent-id')
959
 
        tt.new_file('file', parent, 'Contents')
960
 
        raw_conflicts = resolve_conflicts(tt)
961
 
        # Since the directory doesn't exist it's seen as 'missing'.  So
962
 
        # 'resolve_conflicts' create a conflict asking for it to be created.
963
 
        self.assertLength(1, raw_conflicts)
964
 
        self.assertEqual(('missing parent', 'Created directory', 'new-1'),
965
 
                         raw_conflicts.pop())
966
 
        # apply fail since the missing directory doesn't exist
967
 
        self.assertRaises(errors.NoFinalPath, tt.apply)
968
 
 
969
741
    def test_moving_versioned_directories(self):
970
742
        create, root = self.get_transform()
971
743
        kansas = create.new_directory('kansas', root, 'kansas-id')
986
758
        create.apply()
987
759
        transform, root = self.get_transform()
988
760
        transform.adjust_root_path('oldroot', fun)
989
 
        new_root = transform.trans_id_tree_path('')
 
761
        new_root=transform.trans_id_tree_path('')
990
762
        transform.version_file('new-root', new_root)
991
763
        transform.apply()
992
764
 
1004
776
        rename.set_executability(True, myfile)
1005
777
        rename.apply()
1006
778
 
1007
 
    def test_rename_fails(self):
1008
 
        self.requireFeature(features.not_running_as_root)
1009
 
        # see https://bugs.launchpad.net/bzr/+bug/491763
1010
 
        create, root_id = self.get_transform()
1011
 
        first_dir = create.new_directory('first-dir', root_id, 'first-id')
1012
 
        myfile = create.new_file('myfile', root_id, 'myfile-text',
1013
 
                                 'myfile-id')
1014
 
        create.apply()
1015
 
        if os.name == "posix" and sys.platform != "cygwin":
1016
 
            # posix filesystems fail on renaming if the readonly bit is set
1017
 
            osutils.make_readonly(self.wt.abspath('first-dir'))
1018
 
        elif os.name == "nt":
1019
 
            # windows filesystems fail on renaming open files
1020
 
            self.addCleanup(file(self.wt.abspath('myfile')).close)
1021
 
        else:
1022
 
            self.skip("Don't know how to force a permissions error on rename")
1023
 
        # now transform to rename
1024
 
        rename_transform, root_id = self.get_transform()
1025
 
        file_trans_id = rename_transform.trans_id_file_id('myfile-id')
1026
 
        dir_id = rename_transform.trans_id_file_id('first-id')
1027
 
        rename_transform.adjust_path('newname', dir_id, file_trans_id)
1028
 
        e = self.assertRaises(errors.TransformRenameFailed,
1029
 
            rename_transform.apply)
1030
 
        # On nix looks like: 
1031
 
        # "Failed to rename .../work/.bzr/checkout/limbo/new-1
1032
 
        # to .../first-dir/newname: [Errno 13] Permission denied"
1033
 
        # On windows looks like:
1034
 
        # "Failed to rename .../work/myfile to 
1035
 
        # .../work/.bzr/checkout/limbo/new-1: [Errno 13] Permission denied"
1036
 
        # This test isn't concerned with exactly what the error looks like,
1037
 
        # and the strerror will vary across OS and locales, but the assert
1038
 
        # that the exeception attributes are what we expect
1039
 
        self.assertEqual(e.errno, errno.EACCES)
1040
 
        if os.name == "posix":
1041
 
            self.assertEndsWith(e.to_path, "/first-dir/newname")
1042
 
        else:
1043
 
            self.assertEqual(os.path.basename(e.from_path), "myfile")
1044
 
 
1045
779
    def test_set_executability_order(self):
1046
780
        """Ensure that executability behaves the same, no matter what order.
1047
781
 
1319
1053
        parent2 = transform.new_directory('parent2', root)
1320
1054
        transform.adjust_path('child1', parent2, child1)
1321
1055
        transform.apply()
1322
 
        self.assertPathDoesNotExist(self.wt.abspath('parent1/child1'))
1323
 
        self.assertPathExists(self.wt.abspath('parent2/child1'))
 
1056
        self.failIfExists(self.wt.abspath('parent1/child1'))
 
1057
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
1324
1058
        # rename limbo/new-1 => parent1, rename limbo/new-3 => parent2
1325
1059
        # no rename for child1 (counting only renames during apply)
1326
 
        self.assertEqual(2, transform.rename_count)
 
1060
        self.failUnlessEqual(2, transform.rename_count)
1327
1061
 
1328
1062
    def test_cancel_parent(self):
1329
1063
        """Cancelling a parent doesn't cause deletion of a non-empty directory
1352
1086
        parent2 = transform.new_directory('parent2', root)
1353
1087
        transform.adjust_path('child1', parent2, child1)
1354
1088
        transform.apply()
1355
 
        self.assertPathDoesNotExist(self.wt.abspath('parent1'))
1356
 
        self.assertPathExists(self.wt.abspath('parent2/child1'))
 
1089
        self.failIfExists(self.wt.abspath('parent1'))
 
1090
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
1357
1091
        # rename limbo/new-3 => parent2, rename limbo/new-2 => child1
1358
 
        self.assertEqual(2, transform.rename_count)
 
1092
        self.failUnlessEqual(2, transform.rename_count)
1359
1093
 
1360
1094
    def test_adjust_and_cancel(self):
1361
1095
        """Make sure adjust_path keeps track of limbo children properly"""
1394
1128
        child = transform.new_directory('child', parent)
1395
1129
        transform.adjust_path('parent', root, parent)
1396
1130
        transform.apply()
1397
 
        self.assertPathExists(self.wt.abspath('parent/child'))
 
1131
        self.failUnlessExists(self.wt.abspath('parent/child'))
1398
1132
        self.assertEqual(1, transform.rename_count)
1399
1133
 
1400
1134
    def test_reuse_name(self):
1531
1265
        tt.create_file(["aa\n"], bar_trans_id)
1532
1266
        tt.version_file("bar-1", bar_trans_id)
1533
1267
        tt.apply()
1534
 
        self.assertPathExists("foo/bar")
 
1268
        self.failUnlessExists("foo/bar")
1535
1269
        wt.lock_read()
1536
1270
        try:
1537
1271
            self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1554
1288
        tt.delete_contents(foo_trans_id)
1555
1289
        tt.create_symlink("bar", foo_trans_id)
1556
1290
        tt.apply()
1557
 
        self.assertPathExists("foo")
 
1291
        self.failUnlessExists("foo")
1558
1292
        wt.lock_read()
1559
1293
        self.addCleanup(wt.unlock)
1560
1294
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1573
1307
        tt.delete_versioned(bar_trans_id)
1574
1308
        tt.create_file(["aa\n"], foo_trans_id)
1575
1309
        tt.apply()
1576
 
        self.assertPathExists("foo")
 
1310
        self.failUnlessExists("foo")
1577
1311
        wt.lock_read()
1578
1312
        self.addCleanup(wt.unlock)
1579
1313
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1594
1328
        self.build_tree(['baz'])
1595
1329
        tt.create_hardlink("baz", foo_trans_id)
1596
1330
        tt.apply()
1597
 
        self.assertPathExists("foo")
1598
 
        self.assertPathExists("baz")
 
1331
        self.failUnlessExists("foo")
 
1332
        self.failUnlessExists("baz")
1599
1333
        wt.lock_read()
1600
1334
        self.addCleanup(wt.unlock)
1601
1335
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1663
1397
    return template % ('<' * 7, tree, '=' * 7, merge, '>' * 7)
1664
1398
 
1665
1399
 
1666
 
class TestInventoryAltered(tests.TestCaseWithTransport):
1667
 
 
1668
 
    def test_inventory_altered_unchanged(self):
1669
 
        tree = self.make_branch_and_tree('tree')
1670
 
        self.build_tree(['tree/foo'])
1671
 
        tree.add('foo', 'foo-id')
1672
 
        with TransformPreview(tree) as tt:
1673
 
            self.assertEqual([], tt._inventory_altered())
1674
 
 
1675
 
    def test_inventory_altered_changed_parent_id(self):
1676
 
        tree = self.make_branch_and_tree('tree')
1677
 
        self.build_tree(['tree/foo'])
1678
 
        tree.add('foo', 'foo-id')
1679
 
        with TransformPreview(tree) as tt:
1680
 
            tt.unversion_file(tt.root)
1681
 
            tt.version_file('new-id', tt.root)
1682
 
            foo_trans_id = tt.trans_id_tree_file_id('foo-id')
1683
 
            foo_tuple = ('foo', foo_trans_id)
1684
 
            root_tuple = ('', tt.root)
1685
 
            self.assertEqual([root_tuple, foo_tuple], tt._inventory_altered())
1686
 
 
1687
 
    def test_inventory_altered_noop_changed_parent_id(self):
1688
 
        tree = self.make_branch_and_tree('tree')
1689
 
        self.build_tree(['tree/foo'])
1690
 
        tree.add('foo', 'foo-id')
1691
 
        with TransformPreview(tree) as tt:
1692
 
            tt.unversion_file(tt.root)
1693
 
            tt.version_file(tree.get_root_id(), tt.root)
1694
 
            foo_trans_id = tt.trans_id_tree_file_id('foo-id')
1695
 
            self.assertEqual([], tt._inventory_altered())
1696
 
 
1697
 
 
1698
1400
class TestTransformMerge(TestCaseInTempDir):
1699
1401
 
1700
1402
    def test_text_merge(self):
1910
1612
        tree.add_reference(subtree)
1911
1613
        tree.commit('a revision')
1912
1614
        tree.branch.create_checkout('target')
1913
 
        self.assertPathExists('target')
1914
 
        self.assertPathExists('target/subtree')
 
1615
        self.failUnlessExists('target')
 
1616
        self.failUnlessExists('target/subtree')
1915
1617
 
1916
1618
    def test_file_conflict_handling(self):
1917
1619
        """Ensure that when building trees, conflict handling is done"""
1964
1666
        source.commit('added file')
1965
1667
        build_tree(source.basis_tree(), target)
1966
1668
        self.assertEqual([], target.conflicts())
1967
 
        self.assertPathExists('target/dir1/file')
 
1669
        self.failUnlessExists('target/dir1/file')
1968
1670
 
1969
1671
        # Ensure contents are merged
1970
1672
        target = self.make_branch_and_tree('target2')
1971
1673
        self.build_tree(['target2/dir1/', 'target2/dir1/file2'])
1972
1674
        build_tree(source.basis_tree(), target)
1973
1675
        self.assertEqual([], target.conflicts())
1974
 
        self.assertPathExists('target2/dir1/file2')
1975
 
        self.assertPathExists('target2/dir1/file')
 
1676
        self.failUnlessExists('target2/dir1/file2')
 
1677
        self.failUnlessExists('target2/dir1/file')
1976
1678
 
1977
1679
        # Ensure new contents are suppressed for existing branches
1978
1680
        target = self.make_branch_and_tree('target3')
1979
1681
        self.make_branch('target3/dir1')
1980
1682
        self.build_tree(['target3/dir1/file2'])
1981
1683
        build_tree(source.basis_tree(), target)
1982
 
        self.assertPathDoesNotExist('target3/dir1/file')
1983
 
        self.assertPathExists('target3/dir1/file2')
1984
 
        self.assertPathExists('target3/dir1.diverted/file')
 
1684
        self.failIfExists('target3/dir1/file')
 
1685
        self.failUnlessExists('target3/dir1/file2')
 
1686
        self.failUnlessExists('target3/dir1.diverted/file')
1985
1687
        self.assertEqual([DuplicateEntry('Diverted to',
1986
1688
            'dir1.diverted', 'dir1', 'new-dir1', None)],
1987
1689
            target.conflicts())
1990
1692
        self.build_tree(['target4/dir1/'])
1991
1693
        self.make_branch('target4/dir1/file')
1992
1694
        build_tree(source.basis_tree(), target)
1993
 
        self.assertPathExists('target4/dir1/file')
 
1695
        self.failUnlessExists('target4/dir1/file')
1994
1696
        self.assertEqual('directory', file_kind('target4/dir1/file'))
1995
 
        self.assertPathExists('target4/dir1/file.diverted')
 
1697
        self.failUnlessExists('target4/dir1/file.diverted')
1996
1698
        self.assertEqual([DuplicateEntry('Diverted to',
1997
1699
            'dir1/file.diverted', 'dir1/file', 'new-file', None)],
1998
1700
            target.conflicts())
2066
1768
        self.addCleanup(target.unlock)
2067
1769
        self.assertEqual([], list(target.iter_changes(revision_tree)))
2068
1770
 
2069
 
    def test_build_tree_accelerator_tree_observes_sha1(self):
2070
 
        source = self.create_ab_tree()
2071
 
        sha1 = osutils.sha_string('A')
2072
 
        target = self.make_branch_and_tree('target')
2073
 
        target.lock_write()
2074
 
        self.addCleanup(target.unlock)
2075
 
        state = target.current_dirstate()
2076
 
        state._cutoff_time = time.time() + 60
2077
 
        build_tree(source.basis_tree(), target, source)
2078
 
        entry = state._get_entry(0, path_utf8='file1')
2079
 
        self.assertEqual(sha1, entry[1][0][1])
2080
 
 
2081
1771
    def test_build_tree_accelerator_tree_missing_file(self):
2082
1772
        source = self.create_ab_tree()
2083
1773
        os.unlink('source/file1')
2179
1869
        self.assertTrue(source.is_executable('file1-id'))
2180
1870
 
2181
1871
    def install_rot13_content_filter(self, pattern):
2182
 
        # We could use
2183
 
        # self.addCleanup(filters._reset_registry, filters._reset_registry())
2184
 
        # below, but that looks a bit... hard to read even if it's exactly
2185
 
        # the same thing.
2186
1872
        original_registry = filters._reset_registry()
2187
1873
        def restore_registry():
2188
1874
            filters._reset_registry(original_registry)
2226
1912
        self.assertEqualStat(source_stat, target_stat)
2227
1913
 
2228
1914
    def test_case_insensitive_build_tree_inventory(self):
2229
 
        if (features.CaseInsensitiveFilesystemFeature.available()
2230
 
            or features.CaseInsCasePresFilenameFeature.available()):
 
1915
        if (tests.CaseInsensitiveFilesystemFeature.available()
 
1916
            or tests.CaseInsCasePresFilenameFeature.available()):
2231
1917
            raise tests.UnavailableFeature('Fully case sensitive filesystem')
2232
1918
        source = self.make_branch_and_tree('source')
2233
1919
        self.build_tree(['source/file', 'source/FILE'])
2241
1927
        self.assertEqual('file.moved', target.id2path('lower-id'))
2242
1928
        self.assertEqual('FILE', target.id2path('upper-id'))
2243
1929
 
2244
 
    def test_build_tree_observes_sha(self):
2245
 
        source = self.make_branch_and_tree('source')
2246
 
        self.build_tree(['source/file1', 'source/dir/', 'source/dir/file2'])
2247
 
        source.add(['file1', 'dir', 'dir/file2'],
2248
 
                   ['file1-id', 'dir-id', 'file2-id'])
2249
 
        source.commit('new files')
2250
 
        target = self.make_branch_and_tree('target')
2251
 
        target.lock_write()
2252
 
        self.addCleanup(target.unlock)
2253
 
        # We make use of the fact that DirState caches its cutoff time. So we
2254
 
        # set the 'safe' time to one minute in the future.
2255
 
        state = target.current_dirstate()
2256
 
        state._cutoff_time = time.time() + 60
2257
 
        build_tree(source.basis_tree(), target)
2258
 
        entry1_sha = osutils.sha_file_by_name('source/file1')
2259
 
        entry2_sha = osutils.sha_file_by_name('source/dir/file2')
2260
 
        # entry[1] is the state information, entry[1][0] is the state of the
2261
 
        # working tree, entry[1][0][1] is the sha value for the current working
2262
 
        # tree
2263
 
        entry1 = state._get_entry(0, path_utf8='file1')
2264
 
        self.assertEqual(entry1_sha, entry1[1][0][1])
2265
 
        # The 'size' field must also be set.
2266
 
        self.assertEqual(25, entry1[1][0][2])
2267
 
        entry1_state = entry1[1][0]
2268
 
        entry2 = state._get_entry(0, path_utf8='dir/file2')
2269
 
        self.assertEqual(entry2_sha, entry2[1][0][1])
2270
 
        self.assertEqual(29, entry2[1][0][2])
2271
 
        entry2_state = entry2[1][0]
2272
 
        # Now, make sure that we don't have to re-read the content. The
2273
 
        # packed_stat should match exactly.
2274
 
        self.assertEqual(entry1_sha, target.get_file_sha1('file1-id', 'file1'))
2275
 
        self.assertEqual(entry2_sha,
2276
 
                         target.get_file_sha1('file2-id', 'dir/file2'))
2277
 
        self.assertEqual(entry1_state, entry1[1][0])
2278
 
        self.assertEqual(entry2_state, entry2[1][0])
2279
 
 
2280
1930
 
2281
1931
class TestCommitTransform(tests.TestCaseWithTransport):
2282
1932
 
2383
2033
        self.assertRaises(errors.MalformedTransform, tt.commit, branch,
2384
2034
                          'message')
2385
2035
 
2386
 
    def test_commit_rich_revision_data(self):
2387
 
        branch, tt = self.get_branch_and_transform()
2388
 
        rev_id = tt.commit(branch, 'message', timestamp=1, timezone=43201,
2389
 
                           committer='me <me@example.com>',
2390
 
                           revprops={'foo': 'bar'}, revision_id='revid-1',
2391
 
                           authors=['Author1 <author1@example.com>',
2392
 
                              'Author2 <author2@example.com>',
2393
 
                               ])
2394
 
        self.assertEqual('revid-1', rev_id)
2395
 
        revision = branch.repository.get_revision(rev_id)
2396
 
        self.assertEqual(1, revision.timestamp)
2397
 
        self.assertEqual(43201, revision.timezone)
2398
 
        self.assertEqual('me <me@example.com>', revision.committer)
2399
 
        self.assertEqual(['Author1 <author1@example.com>',
2400
 
                          'Author2 <author2@example.com>'],
2401
 
                         revision.get_apparent_authors())
2402
 
        del revision.properties['authors']
2403
 
        self.assertEqual({'foo': 'bar',
2404
 
                          'branch-nick': 'tree'},
2405
 
                         revision.properties)
2406
 
 
2407
 
    def test_no_explicit_revprops(self):
2408
 
        branch, tt = self.get_branch_and_transform()
2409
 
        rev_id = tt.commit(branch, 'message', authors=[
2410
 
            'Author1 <author1@example.com>',
2411
 
            'Author2 <author2@example.com>', ])
2412
 
        revision = branch.repository.get_revision(rev_id)
2413
 
        self.assertEqual(['Author1 <author1@example.com>',
2414
 
                          'Author2 <author2@example.com>'],
2415
 
                         revision.get_apparent_authors())
2416
 
        self.assertEqual('tree', revision.properties['branch-nick'])
2417
 
 
2418
 
 
2419
 
class TestBackupName(tests.TestCase):
2420
 
 
2421
 
    def test_deprecations(self):
2422
 
        class MockTransform(object):
2423
 
 
2424
 
            def has_named_child(self, by_parent, parent_id, name):
2425
 
                return name in by_parent.get(parent_id, [])
2426
 
 
2427
 
        class MockEntry(object):
2428
 
 
2429
 
            def __init__(self):
2430
 
                object.__init__(self)
2431
 
                self.name = "name"
2432
 
 
 
2036
 
 
2037
class MockTransform(object):
 
2038
 
 
2039
    def has_named_child(self, by_parent, parent_id, name):
 
2040
        for child_id in by_parent[parent_id]:
 
2041
            if child_id == '0':
 
2042
                if name == "name~":
 
2043
                    return True
 
2044
            elif name == "name.~%s~" % child_id:
 
2045
                return True
 
2046
        return False
 
2047
 
 
2048
 
 
2049
class MockEntry(object):
 
2050
    def __init__(self):
 
2051
        object.__init__(self)
 
2052
        self.name = "name"
 
2053
 
 
2054
 
 
2055
class TestGetBackupName(TestCase):
 
2056
    def test_get_backup_name(self):
2433
2057
        tt = MockTransform()
2434
 
        name1 = self.applyDeprecated(
2435
 
            symbol_versioning.deprecated_in((2, 3, 0)),
2436
 
            transform.get_backup_name, MockEntry(), {'a':[]}, 'a', tt)
2437
 
        self.assertEqual('name.~1~', name1)
2438
 
        name2 = self.applyDeprecated(
2439
 
            symbol_versioning.deprecated_in((2, 3, 0)),
2440
 
            transform._get_backup_name, 'name', {'a':['name.~1~']}, 'a', tt)
2441
 
        self.assertEqual('name.~2~', name2)
 
2058
        name = get_backup_name(MockEntry(), {'a':[]}, 'a', tt)
 
2059
        self.assertEqual(name, 'name.~1~')
 
2060
        name = get_backup_name(MockEntry(), {'a':['1']}, 'a', tt)
 
2061
        self.assertEqual(name, 'name.~2~')
 
2062
        name = get_backup_name(MockEntry(), {'a':['2']}, 'a', tt)
 
2063
        self.assertEqual(name, 'name.~1~')
 
2064
        name = get_backup_name(MockEntry(), {'a':['2'], 'b':[]}, 'b', tt)
 
2065
        self.assertEqual(name, 'name.~1~')
 
2066
        name = get_backup_name(MockEntry(), {'a':['1', '2', '3']}, 'a', tt)
 
2067
        self.assertEqual(name, 'name.~4~')
2442
2068
 
2443
2069
 
2444
2070
class TestFileMover(tests.TestCaseWithTransport):
2447
2073
        self.build_tree(['a/', 'a/b', 'c/', 'c/d'])
2448
2074
        mover = _FileMover()
2449
2075
        mover.rename('a', 'q')
2450
 
        self.assertPathExists('q')
2451
 
        self.assertPathDoesNotExist('a')
2452
 
        self.assertPathExists('q/b')
2453
 
        self.assertPathExists('c')
2454
 
        self.assertPathExists('c/d')
 
2076
        self.failUnlessExists('q')
 
2077
        self.failIfExists('a')
 
2078
        self.failUnlessExists('q/b')
 
2079
        self.failUnlessExists('c')
 
2080
        self.failUnlessExists('c/d')
2455
2081
 
2456
2082
    def test_pre_delete_rollback(self):
2457
2083
        self.build_tree(['a/'])
2458
2084
        mover = _FileMover()
2459
2085
        mover.pre_delete('a', 'q')
2460
 
        self.assertPathExists('q')
2461
 
        self.assertPathDoesNotExist('a')
 
2086
        self.failUnlessExists('q')
 
2087
        self.failIfExists('a')
2462
2088
        mover.rollback()
2463
 
        self.assertPathDoesNotExist('q')
2464
 
        self.assertPathExists('a')
 
2089
        self.failIfExists('q')
 
2090
        self.failUnlessExists('a')
2465
2091
 
2466
2092
    def test_apply_deletions(self):
2467
2093
        self.build_tree(['a/', 'b/'])
2468
2094
        mover = _FileMover()
2469
2095
        mover.pre_delete('a', 'q')
2470
2096
        mover.pre_delete('b', 'r')
2471
 
        self.assertPathExists('q')
2472
 
        self.assertPathExists('r')
2473
 
        self.assertPathDoesNotExist('a')
2474
 
        self.assertPathDoesNotExist('b')
 
2097
        self.failUnlessExists('q')
 
2098
        self.failUnlessExists('r')
 
2099
        self.failIfExists('a')
 
2100
        self.failIfExists('b')
2475
2101
        mover.apply_deletions()
2476
 
        self.assertPathDoesNotExist('q')
2477
 
        self.assertPathDoesNotExist('r')
2478
 
        self.assertPathDoesNotExist('a')
2479
 
        self.assertPathDoesNotExist('b')
 
2102
        self.failIfExists('q')
 
2103
        self.failIfExists('r')
 
2104
        self.failIfExists('a')
 
2105
        self.failIfExists('b')
2480
2106
 
2481
2107
    def test_file_mover_rollback(self):
2482
2108
        self.build_tree(['a/', 'a/b', 'c/', 'c/d/', 'c/e/'])
2487
2113
            mover.rename('a', 'c')
2488
2114
        except errors.FileExists, e:
2489
2115
            mover.rollback()
2490
 
        self.assertPathExists('a')
2491
 
        self.assertPathExists('c/d')
 
2116
        self.failUnlessExists('a')
 
2117
        self.failUnlessExists('c/d')
2492
2118
 
2493
2119
 
2494
2120
class Bogus(Exception):
2524
2150
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2525
2151
        self.assertRaises(Bogus, tt.apply,
2526
2152
                          _mover=self.ExceptionFileMover(bad_source='a'))
2527
 
        self.assertPathExists('a')
2528
 
        self.assertPathExists('a/b')
 
2153
        self.failUnlessExists('a')
 
2154
        self.failUnlessExists('a/b')
2529
2155
        tt.apply()
2530
 
        self.assertPathExists('c')
2531
 
        self.assertPathExists('c/d')
 
2156
        self.failUnlessExists('c')
 
2157
        self.failUnlessExists('c/d')
2532
2158
 
2533
2159
    def test_rollback_rename_into_place(self):
2534
2160
        tree = self.make_branch_and_tree('.')
2540
2166
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2541
2167
        self.assertRaises(Bogus, tt.apply,
2542
2168
                          _mover=self.ExceptionFileMover(bad_target='c/d'))
2543
 
        self.assertPathExists('a')
2544
 
        self.assertPathExists('a/b')
 
2169
        self.failUnlessExists('a')
 
2170
        self.failUnlessExists('a/b')
2545
2171
        tt.apply()
2546
 
        self.assertPathExists('c')
2547
 
        self.assertPathExists('c/d')
 
2172
        self.failUnlessExists('c')
 
2173
        self.failUnlessExists('c/d')
2548
2174
 
2549
2175
    def test_rollback_deletion(self):
2550
2176
        tree = self.make_branch_and_tree('.')
2556
2182
        tt.adjust_path('d', tt.root, tt.trans_id_tree_path('a/b'))
2557
2183
        self.assertRaises(Bogus, tt.apply,
2558
2184
                          _mover=self.ExceptionFileMover(bad_target='d'))
2559
 
        self.assertPathExists('a')
2560
 
        self.assertPathExists('a/b')
2561
 
 
2562
 
 
2563
 
class TestFinalizeRobustness(tests.TestCaseWithTransport):
2564
 
    """Ensure treetransform creation errors can be safely cleaned up after"""
2565
 
 
2566
 
    def _override_globals_in_method(self, instance, method_name, globals):
2567
 
        """Replace method on instance with one with updated globals"""
2568
 
        import types
2569
 
        func = getattr(instance, method_name).im_func
2570
 
        new_globals = dict(func.func_globals)
2571
 
        new_globals.update(globals)
2572
 
        new_func = types.FunctionType(func.func_code, new_globals,
2573
 
            func.func_name, func.func_defaults)
2574
 
        setattr(instance, method_name,
2575
 
            types.MethodType(new_func, instance, instance.__class__))
2576
 
        self.addCleanup(delattr, instance, method_name)
2577
 
 
2578
 
    @staticmethod
2579
 
    def _fake_open_raises_before(name, mode):
2580
 
        """Like open() but raises before doing anything"""
2581
 
        raise RuntimeError
2582
 
 
2583
 
    @staticmethod
2584
 
    def _fake_open_raises_after(name, mode):
2585
 
        """Like open() but raises after creating file without returning"""
2586
 
        open(name, mode).close()
2587
 
        raise RuntimeError
2588
 
 
2589
 
    def create_transform_and_root_trans_id(self):
2590
 
        """Setup a transform creating a file in limbo"""
2591
 
        tree = self.make_branch_and_tree('.')
2592
 
        tt = TreeTransform(tree)
2593
 
        return tt, tt.create_path("a", tt.root)
2594
 
 
2595
 
    def create_transform_and_subdir_trans_id(self):
2596
 
        """Setup a transform creating a directory containing a file in limbo"""
2597
 
        tree = self.make_branch_and_tree('.')
2598
 
        tt = TreeTransform(tree)
2599
 
        d_trans_id = tt.create_path("d", tt.root)
2600
 
        tt.create_directory(d_trans_id)
2601
 
        f_trans_id = tt.create_path("a", d_trans_id)
2602
 
        tt.adjust_path("a", d_trans_id, f_trans_id)
2603
 
        return tt, f_trans_id
2604
 
 
2605
 
    def test_root_create_file_open_raises_before_creation(self):
2606
 
        tt, trans_id = self.create_transform_and_root_trans_id()
2607
 
        self._override_globals_in_method(tt, "create_file",
2608
 
            {"open": self._fake_open_raises_before})
2609
 
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2610
 
        path = tt._limbo_name(trans_id)
2611
 
        self.assertPathDoesNotExist(path)
2612
 
        tt.finalize()
2613
 
        self.assertPathDoesNotExist(tt._limbodir)
2614
 
 
2615
 
    def test_root_create_file_open_raises_after_creation(self):
2616
 
        tt, trans_id = self.create_transform_and_root_trans_id()
2617
 
        self._override_globals_in_method(tt, "create_file",
2618
 
            {"open": self._fake_open_raises_after})
2619
 
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2620
 
        path = tt._limbo_name(trans_id)
2621
 
        self.assertPathExists(path)
2622
 
        tt.finalize()
2623
 
        self.assertPathDoesNotExist(path)
2624
 
        self.assertPathDoesNotExist(tt._limbodir)
2625
 
 
2626
 
    def test_subdir_create_file_open_raises_before_creation(self):
2627
 
        tt, trans_id = self.create_transform_and_subdir_trans_id()
2628
 
        self._override_globals_in_method(tt, "create_file",
2629
 
            {"open": self._fake_open_raises_before})
2630
 
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2631
 
        path = tt._limbo_name(trans_id)
2632
 
        self.assertPathDoesNotExist(path)
2633
 
        tt.finalize()
2634
 
        self.assertPathDoesNotExist(tt._limbodir)
2635
 
 
2636
 
    def test_subdir_create_file_open_raises_after_creation(self):
2637
 
        tt, trans_id = self.create_transform_and_subdir_trans_id()
2638
 
        self._override_globals_in_method(tt, "create_file",
2639
 
            {"open": self._fake_open_raises_after})
2640
 
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
2641
 
        path = tt._limbo_name(trans_id)
2642
 
        self.assertPathExists(path)
2643
 
        tt.finalize()
2644
 
        self.assertPathDoesNotExist(path)
2645
 
        self.assertPathDoesNotExist(tt._limbodir)
2646
 
 
2647
 
    def test_rename_in_limbo_rename_raises_after_rename(self):
2648
 
        tt, trans_id = self.create_transform_and_root_trans_id()
2649
 
        parent1 = tt.new_directory('parent1', tt.root)
2650
 
        child1 = tt.new_file('child1', parent1, 'contents')
2651
 
        parent2 = tt.new_directory('parent2', tt.root)
2652
 
 
2653
 
        class FakeOSModule(object):
2654
 
            def rename(self, old, new):
2655
 
                os.rename(old, new)
2656
 
                raise RuntimeError
2657
 
        self._override_globals_in_method(tt, "_rename_in_limbo",
2658
 
            {"os": FakeOSModule()})
2659
 
        self.assertRaises(
2660
 
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
2661
 
        path = osutils.pathjoin(tt._limbo_name(parent2), "child1")
2662
 
        self.assertPathExists(path)
2663
 
        tt.finalize()
2664
 
        self.assertPathDoesNotExist(path)
2665
 
        self.assertPathDoesNotExist(tt._limbodir)
2666
 
 
2667
 
    def test_rename_in_limbo_rename_raises_before_rename(self):
2668
 
        tt, trans_id = self.create_transform_and_root_trans_id()
2669
 
        parent1 = tt.new_directory('parent1', tt.root)
2670
 
        child1 = tt.new_file('child1', parent1, 'contents')
2671
 
        parent2 = tt.new_directory('parent2', tt.root)
2672
 
 
2673
 
        class FakeOSModule(object):
2674
 
            def rename(self, old, new):
2675
 
                raise RuntimeError
2676
 
        self._override_globals_in_method(tt, "_rename_in_limbo",
2677
 
            {"os": FakeOSModule()})
2678
 
        self.assertRaises(
2679
 
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
2680
 
        path = osutils.pathjoin(tt._limbo_name(parent1), "child1")
2681
 
        self.assertPathExists(path)
2682
 
        tt.finalize()
2683
 
        self.assertPathDoesNotExist(path)
2684
 
        self.assertPathDoesNotExist(tt._limbodir)
2685
 
 
2686
 
 
2687
 
class TestTransformMissingParent(tests.TestCaseWithTransport):
2688
 
 
2689
 
    def make_tt_with_versioned_dir(self):
 
2185
        self.failUnlessExists('a')
 
2186
        self.failUnlessExists('a/b')
 
2187
 
 
2188
    def test_resolve_no_parent(self):
2690
2189
        wt = self.make_branch_and_tree('.')
2691
 
        self.build_tree(['dir/',])
2692
 
        wt.add(['dir'], ['dir-id'])
2693
 
        wt.commit('Create dir')
2694
2190
        tt = TreeTransform(wt)
2695
2191
        self.addCleanup(tt.finalize)
2696
 
        return wt, tt
2697
 
 
2698
 
    def test_resolve_create_parent_for_versioned_file(self):
2699
 
        wt, tt = self.make_tt_with_versioned_dir()
2700
 
        dir_tid = tt.trans_id_tree_file_id('dir-id')
2701
 
        file_tid = tt.new_file('file', dir_tid, 'Contents', file_id='file-id')
2702
 
        tt.delete_contents(dir_tid)
2703
 
        tt.unversion_file(dir_tid)
2704
 
        conflicts = resolve_conflicts(tt)
2705
 
        # one conflict for the missing directory, one for the unversioned
2706
 
        # parent
2707
 
        self.assertLength(2, conflicts)
2708
 
 
2709
 
    def test_non_versioned_file_create_conflict(self):
2710
 
        wt, tt = self.make_tt_with_versioned_dir()
2711
 
        dir_tid = tt.trans_id_tree_file_id('dir-id')
2712
 
        tt.new_file('file', dir_tid, 'Contents')
2713
 
        tt.delete_contents(dir_tid)
2714
 
        tt.unversion_file(dir_tid)
2715
 
        conflicts = resolve_conflicts(tt)
2716
 
        # no conflicts or rather: orphaning 'file' resolve the 'dir' conflict
2717
 
        self.assertLength(1, conflicts)
2718
 
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
2719
 
                         conflicts.pop())
 
2192
        parent = tt.trans_id_file_id('parent-id')
 
2193
        tt.new_file('file', parent, 'Contents')
 
2194
        resolve_conflicts(tt)
2720
2195
 
2721
2196
 
2722
2197
A_ENTRY = ('a-id', ('a', 'a'), True, (True, True),
2723
2198
                  ('TREE_ROOT', 'TREE_ROOT'), ('a', 'a'), ('file', 'file'),
2724
2199
                  (False, False))
2725
2200
ROOT_ENTRY = ('TREE_ROOT', ('', ''), False, (True, True), (None, None),
2726
 
              ('', ''), ('directory', 'directory'), (False, False))
 
2201
              ('', ''), ('directory', 'directory'), (False, None))
2727
2202
 
2728
2203
 
2729
2204
class TestTransformPreview(tests.TestCaseWithTransport):
2816
2291
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2817
2292
        changes = preview_tree.iter_changes(revision_tree,
2818
2293
                                            specific_files=[''])
2819
 
        self.assertEqual([A_ENTRY], list(changes))
 
2294
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2820
2295
 
2821
2296
    def test_want_unversioned(self):
2822
2297
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2823
2298
        changes = preview_tree.iter_changes(revision_tree,
2824
2299
                                            want_unversioned=True)
2825
 
        self.assertEqual([A_ENTRY], list(changes))
 
2300
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2826
2301
 
2827
2302
    def test_ignore_extra_trees_no_specific_files(self):
2828
2303
        # extra_trees is harmless without specific_files, so we'll silently
2838
2313
    def test_ignore_pb(self):
2839
2314
        # pb could be supported, but TT.iter_changes doesn't support it.
2840
2315
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2841
 
        preview_tree.iter_changes(revision_tree)
 
2316
        preview_tree.iter_changes(revision_tree, pb=progress.DummyProgress())
2842
2317
 
2843
2318
    def test_kind(self):
2844
2319
        revision_tree = self.create_tree()
2871
2346
        preview_mtime = preview_tree.get_file_mtime('file-id', 'renamed')
2872
2347
        work_mtime = work_tree.get_file_mtime('file-id', 'file')
2873
2348
 
2874
 
    def test_get_file_size(self):
2875
 
        work_tree = self.make_branch_and_tree('tree')
2876
 
        self.build_tree_contents([('tree/old', 'old')])
2877
 
        work_tree.add('old', 'old-id')
2878
 
        preview = TransformPreview(work_tree)
2879
 
        self.addCleanup(preview.finalize)
2880
 
        new_id = preview.new_file('name', preview.root, 'contents', 'new-id',
2881
 
                                  'executable')
2882
 
        tree = preview.get_preview_tree()
2883
 
        self.assertEqual(len('old'), tree.get_file_size('old-id'))
2884
 
        self.assertEqual(len('contents'), tree.get_file_size('new-id'))
2885
 
 
2886
2349
    def test_get_file(self):
2887
2350
        preview = self.get_empty_preview()
2888
2351
        preview.new_file('file', preview.root, 'contents', 'file-id')
3218
2681
        preview = self.get_empty_preview()
3219
2682
        root = preview.new_directory('', ROOT_PARENT, 'tree-root')
3220
2683
        # FIXME: new_directory should mark root.
3221
 
        preview.fixup_new_roots()
 
2684
        preview.adjust_path('', ROOT_PARENT, root)
3222
2685
        preview_tree = preview.get_preview_tree()
3223
2686
        file_trans_id = preview.new_file('a', preview.root, 'contents',
3224
2687
                                         'a-id')
3258
2721
        file_trans_id = preview.trans_id_file_id('file-id')
3259
2722
        preview.delete_contents(file_trans_id)
3260
2723
        preview.create_file('a\nb\n', file_trans_id)
 
2724
        pb = progress.DummyProgress()
3261
2725
        preview_tree = preview.get_preview_tree()
3262
 
        merger = Merger.from_revision_ids(None, preview_tree,
 
2726
        merger = Merger.from_revision_ids(pb, preview_tree,
3263
2727
                                          child_tree.branch.last_revision(),
3264
2728
                                          other_branch=child_tree.branch,
3265
2729
                                          tree_branch=work_tree.branch)
3277
2741
        tt.new_file('name', tt.root, 'content', 'file-id')
3278
2742
        tree2 = self.make_branch_and_tree('tree2')
3279
2743
        tree2.set_root_id('TREE_ROOT')
 
2744
        pb = progress.DummyProgress()
3280
2745
        merger = Merger.from_uncommitted(tree2, tt.get_preview_tree(),
3281
 
                                         None, tree.basis_tree())
 
2746
                                         pb, tree.basis_tree())
3282
2747
        merger.merge_type = Merge3Merger
3283
2748
        merger.do_merge()
3284
2749
 
3294
2759
        tt.create_file('baz', trans_id)
3295
2760
        tree2 = tree.bzrdir.sprout('tree2').open_workingtree()
3296
2761
        self.build_tree_contents([('tree2/foo', 'qux')])
3297
 
        pb = None
 
2762
        pb = progress.DummyProgress()
3298
2763
        merger = Merger.from_uncommitted(tree2, tt.get_preview_tree(),
3299
2764
                                         pb, tree.basis_tree())
3300
2765
        merger.merge_type = Merge3Merger
3301
2766
        merger.do_merge()
3302
2767
 
3303
 
    def test_has_filename(self):
3304
 
        wt = self.make_branch_and_tree('tree')
3305
 
        self.build_tree(['tree/unmodified', 'tree/removed', 'tree/modified'])
3306
 
        tt = TransformPreview(wt)
3307
 
        removed_id = tt.trans_id_tree_path('removed')
3308
 
        tt.delete_contents(removed_id)
3309
 
        tt.new_file('new', tt.root, 'contents')
3310
 
        modified_id = tt.trans_id_tree_path('modified')
3311
 
        tt.delete_contents(modified_id)
3312
 
        tt.create_file('modified-contents', modified_id)
3313
 
        self.addCleanup(tt.finalize)
3314
 
        tree = tt.get_preview_tree()
3315
 
        self.assertTrue(tree.has_filename('unmodified'))
3316
 
        self.assertFalse(tree.has_filename('not-present'))
3317
 
        self.assertFalse(tree.has_filename('removed'))
3318
 
        self.assertTrue(tree.has_filename('new'))
3319
 
        self.assertTrue(tree.has_filename('modified'))
3320
 
 
3321
2768
    def test_is_executable(self):
3322
2769
        tree = self.make_branch_and_tree('tree')
3323
2770
        preview = TransformPreview(tree)
3346
2793
        self.assertEqual('contents', rev2_tree.get_file_text('file_id'))
3347
2794
 
3348
2795
    def test_ascii_limbo_paths(self):
3349
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
2796
        self.requireFeature(tests.UnicodeFilenameFeature)
3350
2797
        branch = self.make_branch('any')
3351
2798
        tree = branch.repository.revision_tree(_mod_revision.NULL_REVISION)
3352
2799
        tt = TransformPreview(tree)
3369
2816
 
3370
2817
class TestSerializeTransform(tests.TestCaseWithTransport):
3371
2818
 
3372
 
    _test_needs_features = [features.UnicodeFilenameFeature]
 
2819
    _test_needs_features = [tests.UnicodeFilenameFeature]
3373
2820
 
3374
2821
    def get_preview(self, tree=None):
3375
2822
        if tree is None:
3450
2897
        return self.make_records(attribs, contents)
3451
2898
 
3452
2899
    def test_serialize_symlink_creation(self):
3453
 
        self.requireFeature(features.SymlinkFeature)
 
2900
        self.requireFeature(tests.SymlinkFeature)
3454
2901
        tt = self.get_preview()
3455
2902
        tt.new_symlink(u'foo\u1234', tt.root, u'bar\u1234')
3456
2903
        self.assertSerializesTo(self.symlink_creation_records(), tt)
3457
2904
 
3458
2905
    def test_deserialize_symlink_creation(self):
3459
 
        self.requireFeature(features.SymlinkFeature)
 
2906
        self.requireFeature(tests.SymlinkFeature)
3460
2907
        tt = self.get_preview()
3461
2908
        tt.deserialize(iter(self.symlink_creation_records()))
3462
2909
        abspath = tt._limbo_name('new-1')
3629
3076
        trans_id = tt.trans_id_tree_path('file')
3630
3077
        self.assertEqual((LINES_ONE,),
3631
3078
            tt._get_parents_texts(trans_id))
3632
 
 
3633
 
 
3634
 
class TestOrphan(tests.TestCaseWithTransport):
3635
 
 
3636
 
    def test_no_orphan_for_transform_preview(self):
3637
 
        tree = self.make_branch_and_tree('tree')
3638
 
        tt = transform.TransformPreview(tree)
3639
 
        self.addCleanup(tt.finalize)
3640
 
        self.assertRaises(NotImplementedError, tt.new_orphan, 'foo', 'bar')
3641
 
 
3642
 
    def _set_orphan_policy(self, wt, policy):
3643
 
        wt.branch.get_config().set_user_option('bzr.transform.orphan_policy',
3644
 
                                               policy)
3645
 
 
3646
 
    def _prepare_orphan(self, wt):
3647
 
        self.build_tree(['dir/', 'dir/file', 'dir/foo'])
3648
 
        wt.add(['dir', 'dir/file'], ['dir-id', 'file-id'])
3649
 
        wt.commit('add dir and file ignoring foo')
3650
 
        tt = transform.TreeTransform(wt)
3651
 
        self.addCleanup(tt.finalize)
3652
 
        # dir and bar are deleted
3653
 
        dir_tid = tt.trans_id_tree_path('dir')
3654
 
        file_tid = tt.trans_id_tree_path('dir/file')
3655
 
        orphan_tid = tt.trans_id_tree_path('dir/foo')
3656
 
        tt.delete_contents(file_tid)
3657
 
        tt.unversion_file(file_tid)
3658
 
        tt.delete_contents(dir_tid)
3659
 
        tt.unversion_file(dir_tid)
3660
 
        # There should be a conflict because dir still contain foo
3661
 
        raw_conflicts = tt.find_conflicts()
3662
 
        self.assertLength(1, raw_conflicts)
3663
 
        self.assertEqual(('missing parent', 'new-1'), raw_conflicts[0])
3664
 
        return tt, orphan_tid
3665
 
 
3666
 
    def test_new_orphan_created(self):
3667
 
        wt = self.make_branch_and_tree('.')
3668
 
        self._set_orphan_policy(wt, 'move')
3669
 
        tt, orphan_tid = self._prepare_orphan(wt)
3670
 
        warnings = []
3671
 
        def warning(*args):
3672
 
            warnings.append(args[0] % args[1:])
3673
 
        self.overrideAttr(trace, 'warning', warning)
3674
 
        remaining_conflicts = resolve_conflicts(tt)
3675
 
        self.assertEquals(['dir/foo has been orphaned in bzr-orphans'],
3676
 
                          warnings)
3677
 
        # Yeah for resolved conflicts !
3678
 
        self.assertLength(0, remaining_conflicts)
3679
 
        # We have a new orphan
3680
 
        self.assertEquals('foo.~1~', tt.final_name(orphan_tid))
3681
 
        self.assertEquals('bzr-orphans',
3682
 
                          tt.final_name(tt.final_parent(orphan_tid)))
3683
 
 
3684
 
    def test_never_orphan(self):
3685
 
        wt = self.make_branch_and_tree('.')
3686
 
        self._set_orphan_policy(wt, 'conflict')
3687
 
        tt, orphan_tid = self._prepare_orphan(wt)
3688
 
        remaining_conflicts = resolve_conflicts(tt)
3689
 
        self.assertLength(1, remaining_conflicts)
3690
 
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
3691
 
                         remaining_conflicts.pop())
3692
 
 
3693
 
    def test_orphan_error(self):
3694
 
        def bogus_orphan(tt, orphan_id, parent_id):
3695
 
            raise transform.OrphaningError(tt.final_name(orphan_id),
3696
 
                                           tt.final_name(parent_id))
3697
 
        transform.orphaning_registry.register('bogus', bogus_orphan,
3698
 
                                              'Raise an error when orphaning')
3699
 
        wt = self.make_branch_and_tree('.')
3700
 
        self._set_orphan_policy(wt, 'bogus')
3701
 
        tt, orphan_tid = self._prepare_orphan(wt)
3702
 
        remaining_conflicts = resolve_conflicts(tt)
3703
 
        self.assertLength(1, remaining_conflicts)
3704
 
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
3705
 
                         remaining_conflicts.pop())
3706
 
 
3707
 
    def test_unknown_orphan_policy(self):
3708
 
        wt = self.make_branch_and_tree('.')
3709
 
        # Set a fictional policy nobody ever implemented
3710
 
        self._set_orphan_policy(wt, 'donttouchmypreciouuus')
3711
 
        tt, orphan_tid = self._prepare_orphan(wt)
3712
 
        warnings = []
3713
 
        def warning(*args):
3714
 
            warnings.append(args[0] % args[1:])
3715
 
        self.overrideAttr(trace, 'warning', warning)
3716
 
        remaining_conflicts = resolve_conflicts(tt)
3717
 
        # We fallback to the default policy which create a conflict
3718
 
        self.assertLength(1, remaining_conflicts)
3719
 
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
3720
 
                         remaining_conflicts.pop())
3721
 
        self.assertLength(1, warnings)
3722
 
        self.assertStartsWith(warnings[0], 'donttouchmypreciouuus')