~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: 2010-02-10 19:20:57 UTC
  • mfrom: (4988.10.5 jam-integration)
  • Revision ID: pqm@pqm.ubuntu.com-20100210192057-uvi7tmdubcvh9xpo
(Michal Junák) Bug #511987, support 'bzr export FILE'

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006-2010 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
26
25
    filters,
27
26
    generate_ids,
28
27
    osutils,
 
28
    progress,
29
29
    revision as _mod_revision,
30
30
    rules,
31
 
    symbol_versioning,
32
31
    tests,
33
 
    trace,
34
 
    transform,
35
32
    urlutils,
36
33
    )
37
34
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
 
)
 
35
from bzrlib.conflicts import (DuplicateEntry, DuplicateID, MissingParent,
 
36
                              UnversionedParent, ParentLoop, DeletingParent,
 
37
                              NonDirectoryParent)
47
38
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
 
)
 
39
from bzrlib.errors import (DuplicateKey, MalformedTransform, NoSuchFile,
 
40
                           ReusingTransform, CantMoveRoot,
 
41
                           PathsNotVersionedError, ExistingLimbo,
 
42
                           ExistingPendingDeletion, ImmortalLimbo,
 
43
                           ImmortalPendingDeletion, LockError)
 
44
from bzrlib.osutils import file_kind, pathjoin
62
45
from bzrlib.merge import Merge3Merger, Merger
63
46
from bzrlib.tests import (
64
 
    features,
 
47
    HardlinkFeature,
 
48
    SymlinkFeature,
 
49
    TestCase,
65
50
    TestCaseInTempDir,
66
51
    TestSkipped,
67
52
    )
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
 
)
 
53
from bzrlib.transform import (TreeTransform, ROOT_PARENT, FinalPaths,
 
54
                              resolve_conflicts, cook_conflicts,
 
55
                              build_tree, get_backup_name,
 
56
                              _FileMover, resolve_checkout,
 
57
                              TransformPreview, create_from_tree)
84
58
 
85
59
 
86
60
class TestTreeTransform(tests.TestCaseWithTransport):
95
69
        self.addCleanup(transform.finalize)
96
70
        return transform, transform.root
97
71
 
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
72
    def test_existing_limbo(self):
109
73
        transform, root = self.get_transform()
110
74
        limbo_name = transform._limbodir
137
101
        imaginary_id = transform.trans_id_tree_path('imaginary')
138
102
        imaginary_id2 = transform.trans_id_tree_path('imaginary/')
139
103
        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))
 
104
        self.assertEqual(transform.get_tree_parent(imaginary_id), root)
 
105
        self.assertEqual(transform.final_kind(root), 'directory')
 
106
        self.assertEqual(transform.final_file_id(root), self.wt.get_root_id())
143
107
        trans_id = transform.create_path('name', root)
144
108
        self.assertIs(transform.final_file_id(trans_id), None)
145
 
        self.assertIs(None, transform.final_kind(trans_id))
 
109
        self.assertRaises(NoSuchFile, transform.final_kind, trans_id)
146
110
        transform.create_file('contents', trans_id)
147
111
        transform.set_executability(True, trans_id)
148
112
        transform.version_file('my_pretties', trans_id)
173
137
        transform.finalize()
174
138
        transform.finalize()
175
139
 
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
140
    def test_create_files_same_timestamp(self):
238
141
        transform, root = self.get_transform()
239
142
        self.wt.lock_tree_write()
287
190
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
288
191
        self.assertRaises(ValueError, transform.fixup_new_roots)
289
192
 
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
193
    def test_hardlink(self):
353
194
        self.requireFeature(HardlinkFeature)
354
195
        transform, root = self.get_transform()
359
200
        trans_id = target_transform.create_path('file1', target_transform.root)
360
201
        target_transform.create_hardlink(self.wt.abspath('file1'), trans_id)
361
202
        target_transform.apply()
362
 
        self.assertPathExists('target/file1')
 
203
        self.failUnlessExists('target/file1')
363
204
        source_stat = os.stat(self.wt.abspath('file1'))
364
205
        target_stat = os.stat('target/file1')
365
206
        self.assertEqual(source_stat, target_stat)
531
372
        transform.new_file('FiLe', transform.root, 'content')
532
373
        resolve_conflicts(transform)
533
374
        transform.apply()
534
 
        self.assertPathExists('tree/file')
535
 
        self.assertPathExists('tree/FiLe.moved')
 
375
        self.failUnlessExists('tree/file')
 
376
        self.failUnlessExists('tree/FiLe.moved')
536
377
 
537
378
    def test_resolve_checkout_case_conflict(self):
538
379
        tree = self.make_branch_and_tree('tree')
547
388
        resolve_conflicts(transform,
548
389
                          pass_func=lambda t, c: resolve_checkout(t, c, []))
549
390
        transform.apply()
550
 
        self.assertPathExists('tree/file')
551
 
        self.assertPathExists('tree/FiLe.moved')
 
391
        self.failUnlessExists('tree/file')
 
392
        self.failUnlessExists('tree/FiLe.moved')
552
393
 
553
394
    def test_apply_case_conflict(self):
554
395
        """Ensure that a transform with case conflicts can always be applied"""
562
403
        transform.new_file('dirFiLe', dir, 'content')
563
404
        resolve_conflicts(transform)
564
405
        transform.apply()
565
 
        self.assertPathExists('tree/file')
 
406
        self.failUnlessExists('tree/file')
566
407
        if not os.path.exists('tree/FiLe.moved'):
567
 
            self.assertPathExists('tree/FiLe')
568
 
        self.assertPathExists('tree/dir/dirfile')
 
408
            self.failUnlessExists('tree/FiLe')
 
409
        self.failUnlessExists('tree/dir/dirfile')
569
410
        if not os.path.exists('tree/dir/dirFiLe.moved'):
570
 
            self.assertPathExists('tree/dir/dirFiLe')
 
411
            self.failUnlessExists('tree/dir/dirFiLe')
571
412
 
572
413
    def test_case_insensitive_limbo(self):
573
414
        tree = self.make_branch_and_tree('tree')
781
622
                            'wizard2', 'behind_curtain')
782
623
 
783
624
    def test_symlinks_unicode(self):
784
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
625
        self.requireFeature(tests.UnicodeFilenameFeature)
785
626
        self._test_symlinks(u'\N{Euro Sign}wizard',
786
627
                            u'wizard-targ\N{Euro Sign}t',
787
628
                            u'\N{Euro Sign}wizard2',
875
716
        raw_conflicts = resolve_conflicts(tt)
876
717
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
877
718
        tt.finalize()
878
 
        conflicts_s = [unicode(c) for c in cooked_conflicts]
 
719
        conflicts_s = [str(c) for c in cooked_conflicts]
879
720
        self.assertEqual(len(cooked_conflicts), len(conflicts_s))
880
721
        self.assertEqual(conflicts_s[0], 'Conflict adding file dorothy.  '
881
722
                                         'Moved existing file to '
894
735
                                         ' versioned, but has versioned'
895
736
                                         ' children.  Versioned directory.')
896
737
        self.assertEqual(conflicts_s[6], 'Conflict moving oz/emeraldcity into'
897
 
                                         ' oz/emeraldcity. Cancelled move.')
 
738
                                         ' oz/emeraldcity.  Cancelled move.')
898
739
 
899
740
    def prepare_wrong_parent_kind(self):
900
741
        tt, root = self.get_transform()
951
792
        self.assertIs(None, self.wt.path2id('parent'))
952
793
        self.assertIs(None, self.wt.path2id('parent.new'))
953
794
 
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
795
    def test_moving_versioned_directories(self):
970
796
        create, root = self.get_transform()
971
797
        kansas = create.new_directory('kansas', root, 'kansas-id')
1004
830
        rename.set_executability(True, myfile)
1005
831
        rename.apply()
1006
832
 
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
833
    def test_set_executability_order(self):
1046
834
        """Ensure that executability behaves the same, no matter what order.
1047
835
 
1319
1107
        parent2 = transform.new_directory('parent2', root)
1320
1108
        transform.adjust_path('child1', parent2, child1)
1321
1109
        transform.apply()
1322
 
        self.assertPathDoesNotExist(self.wt.abspath('parent1/child1'))
1323
 
        self.assertPathExists(self.wt.abspath('parent2/child1'))
 
1110
        self.failIfExists(self.wt.abspath('parent1/child1'))
 
1111
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
1324
1112
        # rename limbo/new-1 => parent1, rename limbo/new-3 => parent2
1325
1113
        # no rename for child1 (counting only renames during apply)
1326
 
        self.assertEqual(2, transform.rename_count)
 
1114
        self.failUnlessEqual(2, transform.rename_count)
1327
1115
 
1328
1116
    def test_cancel_parent(self):
1329
1117
        """Cancelling a parent doesn't cause deletion of a non-empty directory
1352
1140
        parent2 = transform.new_directory('parent2', root)
1353
1141
        transform.adjust_path('child1', parent2, child1)
1354
1142
        transform.apply()
1355
 
        self.assertPathDoesNotExist(self.wt.abspath('parent1'))
1356
 
        self.assertPathExists(self.wt.abspath('parent2/child1'))
 
1143
        self.failIfExists(self.wt.abspath('parent1'))
 
1144
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
1357
1145
        # rename limbo/new-3 => parent2, rename limbo/new-2 => child1
1358
 
        self.assertEqual(2, transform.rename_count)
 
1146
        self.failUnlessEqual(2, transform.rename_count)
1359
1147
 
1360
1148
    def test_adjust_and_cancel(self):
1361
1149
        """Make sure adjust_path keeps track of limbo children properly"""
1394
1182
        child = transform.new_directory('child', parent)
1395
1183
        transform.adjust_path('parent', root, parent)
1396
1184
        transform.apply()
1397
 
        self.assertPathExists(self.wt.abspath('parent/child'))
 
1185
        self.failUnlessExists(self.wt.abspath('parent/child'))
1398
1186
        self.assertEqual(1, transform.rename_count)
1399
1187
 
1400
1188
    def test_reuse_name(self):
1531
1319
        tt.create_file(["aa\n"], bar_trans_id)
1532
1320
        tt.version_file("bar-1", bar_trans_id)
1533
1321
        tt.apply()
1534
 
        self.assertPathExists("foo/bar")
 
1322
        self.failUnlessExists("foo/bar")
1535
1323
        wt.lock_read()
1536
1324
        try:
1537
1325
            self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1554
1342
        tt.delete_contents(foo_trans_id)
1555
1343
        tt.create_symlink("bar", foo_trans_id)
1556
1344
        tt.apply()
1557
 
        self.assertPathExists("foo")
 
1345
        self.failUnlessExists("foo")
1558
1346
        wt.lock_read()
1559
1347
        self.addCleanup(wt.unlock)
1560
1348
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1573
1361
        tt.delete_versioned(bar_trans_id)
1574
1362
        tt.create_file(["aa\n"], foo_trans_id)
1575
1363
        tt.apply()
1576
 
        self.assertPathExists("foo")
 
1364
        self.failUnlessExists("foo")
1577
1365
        wt.lock_read()
1578
1366
        self.addCleanup(wt.unlock)
1579
1367
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1594
1382
        self.build_tree(['baz'])
1595
1383
        tt.create_hardlink("baz", foo_trans_id)
1596
1384
        tt.apply()
1597
 
        self.assertPathExists("foo")
1598
 
        self.assertPathExists("baz")
 
1385
        self.failUnlessExists("foo")
 
1386
        self.failUnlessExists("baz")
1599
1387
        wt.lock_read()
1600
1388
        self.addCleanup(wt.unlock)
1601
1389
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1663
1451
    return template % ('<' * 7, tree, '=' * 7, merge, '>' * 7)
1664
1452
 
1665
1453
 
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
1454
class TestTransformMerge(TestCaseInTempDir):
1699
1455
 
1700
1456
    def test_text_merge(self):
1910
1666
        tree.add_reference(subtree)
1911
1667
        tree.commit('a revision')
1912
1668
        tree.branch.create_checkout('target')
1913
 
        self.assertPathExists('target')
1914
 
        self.assertPathExists('target/subtree')
 
1669
        self.failUnlessExists('target')
 
1670
        self.failUnlessExists('target/subtree')
1915
1671
 
1916
1672
    def test_file_conflict_handling(self):
1917
1673
        """Ensure that when building trees, conflict handling is done"""
1964
1720
        source.commit('added file')
1965
1721
        build_tree(source.basis_tree(), target)
1966
1722
        self.assertEqual([], target.conflicts())
1967
 
        self.assertPathExists('target/dir1/file')
 
1723
        self.failUnlessExists('target/dir1/file')
1968
1724
 
1969
1725
        # Ensure contents are merged
1970
1726
        target = self.make_branch_and_tree('target2')
1971
1727
        self.build_tree(['target2/dir1/', 'target2/dir1/file2'])
1972
1728
        build_tree(source.basis_tree(), target)
1973
1729
        self.assertEqual([], target.conflicts())
1974
 
        self.assertPathExists('target2/dir1/file2')
1975
 
        self.assertPathExists('target2/dir1/file')
 
1730
        self.failUnlessExists('target2/dir1/file2')
 
1731
        self.failUnlessExists('target2/dir1/file')
1976
1732
 
1977
1733
        # Ensure new contents are suppressed for existing branches
1978
1734
        target = self.make_branch_and_tree('target3')
1979
1735
        self.make_branch('target3/dir1')
1980
1736
        self.build_tree(['target3/dir1/file2'])
1981
1737
        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')
 
1738
        self.failIfExists('target3/dir1/file')
 
1739
        self.failUnlessExists('target3/dir1/file2')
 
1740
        self.failUnlessExists('target3/dir1.diverted/file')
1985
1741
        self.assertEqual([DuplicateEntry('Diverted to',
1986
1742
            'dir1.diverted', 'dir1', 'new-dir1', None)],
1987
1743
            target.conflicts())
1990
1746
        self.build_tree(['target4/dir1/'])
1991
1747
        self.make_branch('target4/dir1/file')
1992
1748
        build_tree(source.basis_tree(), target)
1993
 
        self.assertPathExists('target4/dir1/file')
 
1749
        self.failUnlessExists('target4/dir1/file')
1994
1750
        self.assertEqual('directory', file_kind('target4/dir1/file'))
1995
 
        self.assertPathExists('target4/dir1/file.diverted')
 
1751
        self.failUnlessExists('target4/dir1/file.diverted')
1996
1752
        self.assertEqual([DuplicateEntry('Diverted to',
1997
1753
            'dir1/file.diverted', 'dir1/file', 'new-file', None)],
1998
1754
            target.conflicts())
2066
1822
        self.addCleanup(target.unlock)
2067
1823
        self.assertEqual([], list(target.iter_changes(revision_tree)))
2068
1824
 
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
1825
    def test_build_tree_accelerator_tree_missing_file(self):
2082
1826
        source = self.create_ab_tree()
2083
1827
        os.unlink('source/file1')
2226
1970
        self.assertEqualStat(source_stat, target_stat)
2227
1971
 
2228
1972
    def test_case_insensitive_build_tree_inventory(self):
2229
 
        if (features.CaseInsensitiveFilesystemFeature.available()
2230
 
            or features.CaseInsCasePresFilenameFeature.available()):
 
1973
        if (tests.CaseInsensitiveFilesystemFeature.available()
 
1974
            or tests.CaseInsCasePresFilenameFeature.available()):
2231
1975
            raise tests.UnavailableFeature('Fully case sensitive filesystem')
2232
1976
        source = self.make_branch_and_tree('source')
2233
1977
        self.build_tree(['source/file', 'source/FILE'])
2241
1985
        self.assertEqual('file.moved', target.id2path('lower-id'))
2242
1986
        self.assertEqual('FILE', target.id2path('upper-id'))
2243
1987
 
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
1988
 
2281
1989
class TestCommitTransform(tests.TestCaseWithTransport):
2282
1990
 
2383
2091
        self.assertRaises(errors.MalformedTransform, tt.commit, branch,
2384
2092
                          'message')
2385
2093
 
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
 
 
 
2094
 
 
2095
class MockTransform(object):
 
2096
 
 
2097
    def has_named_child(self, by_parent, parent_id, name):
 
2098
        for child_id in by_parent[parent_id]:
 
2099
            if child_id == '0':
 
2100
                if name == "name~":
 
2101
                    return True
 
2102
            elif name == "name.~%s~" % child_id:
 
2103
                return True
 
2104
        return False
 
2105
 
 
2106
 
 
2107
class MockEntry(object):
 
2108
    def __init__(self):
 
2109
        object.__init__(self)
 
2110
        self.name = "name"
 
2111
 
 
2112
 
 
2113
class TestGetBackupName(TestCase):
 
2114
    def test_get_backup_name(self):
2433
2115
        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)
 
2116
        name = get_backup_name(MockEntry(), {'a':[]}, 'a', tt)
 
2117
        self.assertEqual(name, 'name.~1~')
 
2118
        name = get_backup_name(MockEntry(), {'a':['1']}, 'a', tt)
 
2119
        self.assertEqual(name, 'name.~2~')
 
2120
        name = get_backup_name(MockEntry(), {'a':['2']}, 'a', tt)
 
2121
        self.assertEqual(name, 'name.~1~')
 
2122
        name = get_backup_name(MockEntry(), {'a':['2'], 'b':[]}, 'b', tt)
 
2123
        self.assertEqual(name, 'name.~1~')
 
2124
        name = get_backup_name(MockEntry(), {'a':['1', '2', '3']}, 'a', tt)
 
2125
        self.assertEqual(name, 'name.~4~')
2442
2126
 
2443
2127
 
2444
2128
class TestFileMover(tests.TestCaseWithTransport):
2447
2131
        self.build_tree(['a/', 'a/b', 'c/', 'c/d'])
2448
2132
        mover = _FileMover()
2449
2133
        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')
 
2134
        self.failUnlessExists('q')
 
2135
        self.failIfExists('a')
 
2136
        self.failUnlessExists('q/b')
 
2137
        self.failUnlessExists('c')
 
2138
        self.failUnlessExists('c/d')
2455
2139
 
2456
2140
    def test_pre_delete_rollback(self):
2457
2141
        self.build_tree(['a/'])
2458
2142
        mover = _FileMover()
2459
2143
        mover.pre_delete('a', 'q')
2460
 
        self.assertPathExists('q')
2461
 
        self.assertPathDoesNotExist('a')
 
2144
        self.failUnlessExists('q')
 
2145
        self.failIfExists('a')
2462
2146
        mover.rollback()
2463
 
        self.assertPathDoesNotExist('q')
2464
 
        self.assertPathExists('a')
 
2147
        self.failIfExists('q')
 
2148
        self.failUnlessExists('a')
2465
2149
 
2466
2150
    def test_apply_deletions(self):
2467
2151
        self.build_tree(['a/', 'b/'])
2468
2152
        mover = _FileMover()
2469
2153
        mover.pre_delete('a', 'q')
2470
2154
        mover.pre_delete('b', 'r')
2471
 
        self.assertPathExists('q')
2472
 
        self.assertPathExists('r')
2473
 
        self.assertPathDoesNotExist('a')
2474
 
        self.assertPathDoesNotExist('b')
 
2155
        self.failUnlessExists('q')
 
2156
        self.failUnlessExists('r')
 
2157
        self.failIfExists('a')
 
2158
        self.failIfExists('b')
2475
2159
        mover.apply_deletions()
2476
 
        self.assertPathDoesNotExist('q')
2477
 
        self.assertPathDoesNotExist('r')
2478
 
        self.assertPathDoesNotExist('a')
2479
 
        self.assertPathDoesNotExist('b')
 
2160
        self.failIfExists('q')
 
2161
        self.failIfExists('r')
 
2162
        self.failIfExists('a')
 
2163
        self.failIfExists('b')
2480
2164
 
2481
2165
    def test_file_mover_rollback(self):
2482
2166
        self.build_tree(['a/', 'a/b', 'c/', 'c/d/', 'c/e/'])
2487
2171
            mover.rename('a', 'c')
2488
2172
        except errors.FileExists, e:
2489
2173
            mover.rollback()
2490
 
        self.assertPathExists('a')
2491
 
        self.assertPathExists('c/d')
 
2174
        self.failUnlessExists('a')
 
2175
        self.failUnlessExists('c/d')
2492
2176
 
2493
2177
 
2494
2178
class Bogus(Exception):
2524
2208
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2525
2209
        self.assertRaises(Bogus, tt.apply,
2526
2210
                          _mover=self.ExceptionFileMover(bad_source='a'))
2527
 
        self.assertPathExists('a')
2528
 
        self.assertPathExists('a/b')
 
2211
        self.failUnlessExists('a')
 
2212
        self.failUnlessExists('a/b')
2529
2213
        tt.apply()
2530
 
        self.assertPathExists('c')
2531
 
        self.assertPathExists('c/d')
 
2214
        self.failUnlessExists('c')
 
2215
        self.failUnlessExists('c/d')
2532
2216
 
2533
2217
    def test_rollback_rename_into_place(self):
2534
2218
        tree = self.make_branch_and_tree('.')
2540
2224
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2541
2225
        self.assertRaises(Bogus, tt.apply,
2542
2226
                          _mover=self.ExceptionFileMover(bad_target='c/d'))
2543
 
        self.assertPathExists('a')
2544
 
        self.assertPathExists('a/b')
 
2227
        self.failUnlessExists('a')
 
2228
        self.failUnlessExists('a/b')
2545
2229
        tt.apply()
2546
 
        self.assertPathExists('c')
2547
 
        self.assertPathExists('c/d')
 
2230
        self.failUnlessExists('c')
 
2231
        self.failUnlessExists('c/d')
2548
2232
 
2549
2233
    def test_rollback_deletion(self):
2550
2234
        tree = self.make_branch_and_tree('.')
2556
2240
        tt.adjust_path('d', tt.root, tt.trans_id_tree_path('a/b'))
2557
2241
        self.assertRaises(Bogus, tt.apply,
2558
2242
                          _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):
 
2243
        self.failUnlessExists('a')
 
2244
        self.failUnlessExists('a/b')
 
2245
 
 
2246
    def test_resolve_no_parent(self):
2690
2247
        wt = self.make_branch_and_tree('.')
2691
 
        self.build_tree(['dir/',])
2692
 
        wt.add(['dir'], ['dir-id'])
2693
 
        wt.commit('Create dir')
2694
2248
        tt = TreeTransform(wt)
2695
2249
        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())
 
2250
        parent = tt.trans_id_file_id('parent-id')
 
2251
        tt.new_file('file', parent, 'Contents')
 
2252
        resolve_conflicts(tt)
2720
2253
 
2721
2254
 
2722
2255
A_ENTRY = ('a-id', ('a', 'a'), True, (True, True),
2723
2256
                  ('TREE_ROOT', 'TREE_ROOT'), ('a', 'a'), ('file', 'file'),
2724
2257
                  (False, False))
2725
2258
ROOT_ENTRY = ('TREE_ROOT', ('', ''), False, (True, True), (None, None),
2726
 
              ('', ''), ('directory', 'directory'), (False, False))
 
2259
              ('', ''), ('directory', 'directory'), (False, None))
2727
2260
 
2728
2261
 
2729
2262
class TestTransformPreview(tests.TestCaseWithTransport):
2816
2349
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2817
2350
        changes = preview_tree.iter_changes(revision_tree,
2818
2351
                                            specific_files=[''])
2819
 
        self.assertEqual([A_ENTRY], list(changes))
 
2352
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2820
2353
 
2821
2354
    def test_want_unversioned(self):
2822
2355
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2823
2356
        changes = preview_tree.iter_changes(revision_tree,
2824
2357
                                            want_unversioned=True)
2825
 
        self.assertEqual([A_ENTRY], list(changes))
 
2358
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
2826
2359
 
2827
2360
    def test_ignore_extra_trees_no_specific_files(self):
2828
2361
        # extra_trees is harmless without specific_files, so we'll silently
2871
2404
        preview_mtime = preview_tree.get_file_mtime('file-id', 'renamed')
2872
2405
        work_mtime = work_tree.get_file_mtime('file-id', 'file')
2873
2406
 
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
2407
    def test_get_file(self):
2887
2408
        preview = self.get_empty_preview()
2888
2409
        preview.new_file('file', preview.root, 'contents', 'file-id')
3300
2821
        merger.merge_type = Merge3Merger
3301
2822
        merger.do_merge()
3302
2823
 
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
2824
    def test_is_executable(self):
3322
2825
        tree = self.make_branch_and_tree('tree')
3323
2826
        preview = TransformPreview(tree)
3346
2849
        self.assertEqual('contents', rev2_tree.get_file_text('file_id'))
3347
2850
 
3348
2851
    def test_ascii_limbo_paths(self):
3349
 
        self.requireFeature(features.UnicodeFilenameFeature)
 
2852
        self.requireFeature(tests.UnicodeFilenameFeature)
3350
2853
        branch = self.make_branch('any')
3351
2854
        tree = branch.repository.revision_tree(_mod_revision.NULL_REVISION)
3352
2855
        tt = TransformPreview(tree)
3369
2872
 
3370
2873
class TestSerializeTransform(tests.TestCaseWithTransport):
3371
2874
 
3372
 
    _test_needs_features = [features.UnicodeFilenameFeature]
 
2875
    _test_needs_features = [tests.UnicodeFilenameFeature]
3373
2876
 
3374
2877
    def get_preview(self, tree=None):
3375
2878
        if tree is None:
3450
2953
        return self.make_records(attribs, contents)
3451
2954
 
3452
2955
    def test_serialize_symlink_creation(self):
3453
 
        self.requireFeature(features.SymlinkFeature)
 
2956
        self.requireFeature(tests.SymlinkFeature)
3454
2957
        tt = self.get_preview()
3455
2958
        tt.new_symlink(u'foo\u1234', tt.root, u'bar\u1234')
3456
2959
        self.assertSerializesTo(self.symlink_creation_records(), tt)
3457
2960
 
3458
2961
    def test_deserialize_symlink_creation(self):
3459
 
        self.requireFeature(features.SymlinkFeature)
 
2962
        self.requireFeature(tests.SymlinkFeature)
3460
2963
        tt = self.get_preview()
3461
2964
        tt.deserialize(iter(self.symlink_creation_records()))
3462
2965
        abspath = tt._limbo_name('new-1')
3629
3132
        trans_id = tt.trans_id_tree_path('file')
3630
3133
        self.assertEqual((LINES_ONE,),
3631
3134
            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')