~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_transform.py

  • Committer: Jelmer Vernooij
  • Date: 2012-02-29 13:55:25 UTC
  • mto: (6437.23.22 2.5)
  • mto: This revision was merged to the branch mainline in revision 6493.
  • Revision ID: jelmer@samba.org-20120229135525-1krnrr2imulo56xj
Merge fix for bzrlib API link.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006-2011 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
17
18
import os
18
19
from StringIO import StringIO
19
20
import sys
27
28
    osutils,
28
29
    revision as _mod_revision,
29
30
    rules,
 
31
    symbol_versioning,
30
32
    tests,
 
33
    trace,
 
34
    transform,
31
35
    urlutils,
32
36
    )
33
37
from bzrlib.bzrdir import BzrDir
49
53
    ImmortalPendingDeletion,
50
54
    LockError,
51
55
    MalformedTransform,
52
 
    NoSuchFile,
53
56
    ReusingTransform,
54
57
)
55
58
from bzrlib.osutils import (
57
60
    pathjoin,
58
61
)
59
62
from bzrlib.merge import Merge3Merger, Merger
 
63
from bzrlib.mutabletree import MutableTree
60
64
from bzrlib.tests import (
 
65
    features,
 
66
    TestCaseInTempDir,
 
67
    TestSkipped,
 
68
    )
 
69
from bzrlib.tests.features import (
61
70
    HardlinkFeature,
62
71
    SymlinkFeature,
63
 
    TestCase,
64
 
    TestCaseInTempDir,
65
 
    TestSkipped,
66
 
)
 
72
    )
67
73
from bzrlib.transform import (
68
74
    build_tree,
69
75
    create_from_tree,
70
76
    cook_conflicts,
71
77
    _FileMover,
72
78
    FinalPaths,
73
 
    get_backup_name,
74
79
    resolve_conflicts,
75
80
    resolve_checkout,
76
81
    ROOT_PARENT,
91
96
        self.addCleanup(transform.finalize)
92
97
        return transform, transform.root
93
98
 
 
99
    def get_transform_for_sha1_test(self):
 
100
        trans, root = self.get_transform()
 
101
        self.wt.lock_tree_write()
 
102
        self.addCleanup(self.wt.unlock)
 
103
        contents = ['just some content\n']
 
104
        sha1 = osutils.sha_strings(contents)
 
105
        # Roll back the clock
 
106
        trans._creation_mtime = time.time() - 20.0
 
107
        return trans, root, contents, sha1
 
108
 
94
109
    def test_existing_limbo(self):
95
110
        transform, root = self.get_transform()
96
111
        limbo_name = transform._limbodir
159
174
        transform.finalize()
160
175
        transform.finalize()
161
176
 
 
177
    def test_apply_informs_tree_of_observed_sha1(self):
 
178
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
 
179
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
 
180
                                  sha1=sha1)
 
181
        calls = []
 
182
        orig = self.wt._observed_sha1
 
183
        def _observed_sha1(*args):
 
184
            calls.append(args)
 
185
            orig(*args)
 
186
        self.wt._observed_sha1 = _observed_sha1
 
187
        trans.apply()
 
188
        self.assertEqual([(None, 'file1', trans._observed_sha1s[trans_id])],
 
189
                         calls)
 
190
 
 
191
    def test_create_file_caches_sha1(self):
 
192
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
 
193
        trans_id = trans.create_path('file1', root)
 
194
        trans.create_file(contents, trans_id, sha1=sha1)
 
195
        st_val = osutils.lstat(trans._limbo_name(trans_id))
 
196
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
 
197
        self.assertEqual(o_sha1, sha1)
 
198
        self.assertEqualStat(o_st_val, st_val)
 
199
 
 
200
    def test__apply_insertions_updates_sha1(self):
 
201
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
 
202
        trans_id = trans.create_path('file1', root)
 
203
        trans.create_file(contents, trans_id, sha1=sha1)
 
204
        st_val = osutils.lstat(trans._limbo_name(trans_id))
 
205
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
 
206
        self.assertEqual(o_sha1, sha1)
 
207
        self.assertEqualStat(o_st_val, st_val)
 
208
        creation_mtime = trans._creation_mtime + 10.0
 
209
        # We fake a time difference from when the file was created until now it
 
210
        # is being renamed by using os.utime. Note that the change we actually
 
211
        # want to see is the real ctime change from 'os.rename()', but as long
 
212
        # as we observe a new stat value, we should be fine.
 
213
        os.utime(trans._limbo_name(trans_id), (creation_mtime, creation_mtime))
 
214
        trans.apply()
 
215
        new_st_val = osutils.lstat(self.wt.abspath('file1'))
 
216
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
 
217
        self.assertEqual(o_sha1, sha1)
 
218
        self.assertEqualStat(o_st_val, new_st_val)
 
219
        self.assertNotEqual(st_val.st_mtime, new_st_val.st_mtime)
 
220
 
 
221
    def test_new_file_caches_sha1(self):
 
222
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
 
223
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
 
224
                                  sha1=sha1)
 
225
        st_val = osutils.lstat(trans._limbo_name(trans_id))
 
226
        o_sha1, o_st_val = trans._observed_sha1s[trans_id]
 
227
        self.assertEqual(o_sha1, sha1)
 
228
        self.assertEqualStat(o_st_val, st_val)
 
229
 
 
230
    def test_cancel_creation_removes_observed_sha1(self):
 
231
        trans, root, contents, sha1 = self.get_transform_for_sha1_test()
 
232
        trans_id = trans.new_file('file1', root, contents, file_id='file1-id',
 
233
                                  sha1=sha1)
 
234
        self.assertTrue(trans_id in trans._observed_sha1s)
 
235
        trans.cancel_creation(trans_id)
 
236
        self.assertFalse(trans_id in trans._observed_sha1s)
 
237
 
162
238
    def test_create_files_same_timestamp(self):
163
239
        transform, root = self.get_transform()
164
240
        self.wt.lock_tree_write()
212
288
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
213
289
        self.assertRaises(ValueError, transform.fixup_new_roots)
214
290
 
 
291
    def test_retain_existing_root(self):
 
292
        tt, root = self.get_transform()
 
293
        with tt:
 
294
            tt.new_directory('', ROOT_PARENT, 'new-root-id')
 
295
            tt.fixup_new_roots()
 
296
            self.assertNotEqual('new-root-id', tt.final_file_id(tt.root))
 
297
 
 
298
    def test_retain_existing_root_added_file(self):
 
299
        tt, root = self.get_transform()
 
300
        new_trans_id = tt.new_directory('', ROOT_PARENT, 'new-root-id')
 
301
        child = tt.new_directory('child', new_trans_id, 'child-id')
 
302
        tt.fixup_new_roots()
 
303
        self.assertEqual(tt.root, tt.final_parent(child))
 
304
 
 
305
    def test_add_unversioned_root(self):
 
306
        transform, root = self.get_transform()
 
307
        new_trans_id = transform.new_directory('', ROOT_PARENT, None)
 
308
        transform.delete_contents(transform.root)
 
309
        transform.fixup_new_roots()
 
310
        self.assertNotIn(transform.root, transform._new_id)
 
311
 
 
312
    def test_remove_root_fixup(self):
 
313
        transform, root = self.get_transform()
 
314
        old_root_id = self.wt.get_root_id()
 
315
        self.assertNotEqual('new-root-id', old_root_id)
 
316
        transform.delete_contents(root)
 
317
        transform.unversion_file(root)
 
318
        transform.fixup_new_roots()
 
319
        transform.apply()
 
320
        self.assertEqual(old_root_id, self.wt.get_root_id())
 
321
 
 
322
        transform, root = self.get_transform()
 
323
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'new-root-id')
 
324
        new_trans_id = transform.new_directory('', ROOT_PARENT, 'alt-root-id')
 
325
        self.assertRaises(ValueError, transform.fixup_new_roots)
 
326
 
 
327
    def test_fixup_new_roots_permits_empty_tree(self):
 
328
        transform, root = self.get_transform()
 
329
        transform.delete_contents(root)
 
330
        transform.unversion_file(root)
 
331
        transform.fixup_new_roots()
 
332
        self.assertIs(None, transform.final_kind(root))
 
333
        self.assertIs(None, transform.final_file_id(root))
 
334
 
 
335
    def test_apply_retains_root_directory(self):
 
336
        # Do not attempt to delete the physical root directory, because that
 
337
        # is impossible.
 
338
        transform, root = self.get_transform()
 
339
        with transform:
 
340
            transform.delete_contents(root)
 
341
            e = self.assertRaises(AssertionError, self.assertRaises,
 
342
                                  errors.TransformRenameFailed,
 
343
                                  transform.apply)
 
344
        self.assertContainsRe('TransformRenameFailed not raised', str(e))
 
345
 
 
346
    def test_apply_retains_file_id(self):
 
347
        transform, root = self.get_transform()
 
348
        old_root_id = transform.tree_file_id(root)
 
349
        transform.unversion_file(root)
 
350
        transform.apply()
 
351
        self.assertEqual(old_root_id, self.wt.get_root_id())
 
352
 
215
353
    def test_hardlink(self):
216
354
        self.requireFeature(HardlinkFeature)
217
355
        transform, root = self.get_transform()
222
360
        trans_id = target_transform.create_path('file1', target_transform.root)
223
361
        target_transform.create_hardlink(self.wt.abspath('file1'), trans_id)
224
362
        target_transform.apply()
225
 
        self.failUnlessExists('target/file1')
 
363
        self.assertPathExists('target/file1')
226
364
        source_stat = os.stat(self.wt.abspath('file1'))
227
365
        target_stat = os.stat('target/file1')
228
366
        self.assertEqual(source_stat, target_stat)
394
532
        transform.new_file('FiLe', transform.root, 'content')
395
533
        resolve_conflicts(transform)
396
534
        transform.apply()
397
 
        self.failUnlessExists('tree/file')
398
 
        self.failUnlessExists('tree/FiLe.moved')
 
535
        self.assertPathExists('tree/file')
 
536
        self.assertPathExists('tree/FiLe.moved')
399
537
 
400
538
    def test_resolve_checkout_case_conflict(self):
401
539
        tree = self.make_branch_and_tree('tree')
410
548
        resolve_conflicts(transform,
411
549
                          pass_func=lambda t, c: resolve_checkout(t, c, []))
412
550
        transform.apply()
413
 
        self.failUnlessExists('tree/file')
414
 
        self.failUnlessExists('tree/FiLe.moved')
 
551
        self.assertPathExists('tree/file')
 
552
        self.assertPathExists('tree/FiLe.moved')
415
553
 
416
554
    def test_apply_case_conflict(self):
417
555
        """Ensure that a transform with case conflicts can always be applied"""
425
563
        transform.new_file('dirFiLe', dir, 'content')
426
564
        resolve_conflicts(transform)
427
565
        transform.apply()
428
 
        self.failUnlessExists('tree/file')
 
566
        self.assertPathExists('tree/file')
429
567
        if not os.path.exists('tree/FiLe.moved'):
430
 
            self.failUnlessExists('tree/FiLe')
431
 
        self.failUnlessExists('tree/dir/dirfile')
 
568
            self.assertPathExists('tree/FiLe')
 
569
        self.assertPathExists('tree/dir/dirfile')
432
570
        if not os.path.exists('tree/dir/dirFiLe.moved'):
433
 
            self.failUnlessExists('tree/dir/dirFiLe')
 
571
            self.assertPathExists('tree/dir/dirFiLe')
434
572
 
435
573
    def test_case_insensitive_limbo(self):
436
574
        tree = self.make_branch_and_tree('tree')
644
782
                            'wizard2', 'behind_curtain')
645
783
 
646
784
    def test_symlinks_unicode(self):
647
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
785
        self.requireFeature(features.UnicodeFilenameFeature)
648
786
        self._test_symlinks(u'\N{Euro Sign}wizard',
649
787
                            u'wizard-targ\N{Euro Sign}t',
650
788
                            u'\N{Euro Sign}wizard2',
738
876
        raw_conflicts = resolve_conflicts(tt)
739
877
        cooked_conflicts = cook_conflicts(raw_conflicts, tt)
740
878
        tt.finalize()
741
 
        conflicts_s = [str(c) for c in cooked_conflicts]
 
879
        conflicts_s = [unicode(c) for c in cooked_conflicts]
742
880
        self.assertEqual(len(cooked_conflicts), len(conflicts_s))
743
881
        self.assertEqual(conflicts_s[0], 'Conflict adding file dorothy.  '
744
882
                                         'Moved existing file to '
814
952
        self.assertIs(None, self.wt.path2id('parent'))
815
953
        self.assertIs(None, self.wt.path2id('parent.new'))
816
954
 
 
955
    def test_resolve_conflicts_missing_parent(self):
 
956
        wt = self.make_branch_and_tree('.')
 
957
        tt = TreeTransform(wt)
 
958
        self.addCleanup(tt.finalize)
 
959
        parent = tt.trans_id_file_id('parent-id')
 
960
        tt.new_file('file', parent, 'Contents')
 
961
        raw_conflicts = resolve_conflicts(tt)
 
962
        # Since the directory doesn't exist it's seen as 'missing'.  So
 
963
        # 'resolve_conflicts' create a conflict asking for it to be created.
 
964
        self.assertLength(1, raw_conflicts)
 
965
        self.assertEqual(('missing parent', 'Created directory', 'new-1'),
 
966
                         raw_conflicts.pop())
 
967
        # apply fail since the missing directory doesn't exist
 
968
        self.assertRaises(errors.NoFinalPath, tt.apply)
 
969
 
817
970
    def test_moving_versioned_directories(self):
818
971
        create, root = self.get_transform()
819
972
        kansas = create.new_directory('kansas', root, 'kansas-id')
853
1006
        rename.apply()
854
1007
 
855
1008
    def test_rename_fails(self):
 
1009
        self.requireFeature(features.not_running_as_root)
856
1010
        # see https://bugs.launchpad.net/bzr/+bug/491763
857
1011
        create, root_id = self.get_transform()
858
1012
        first_dir = create.new_directory('first-dir', root_id, 'first-id')
880
1034
        # On windows looks like:
881
1035
        # "Failed to rename .../work/myfile to 
882
1036
        # .../work/.bzr/checkout/limbo/new-1: [Errno 13] Permission denied"
883
 
        # The strerror will vary per OS and language so it's not checked here
884
 
        self.assertContainsRe(str(e),
885
 
            "Failed to rename .*(first-dir.newname:|myfile)")
 
1037
        # This test isn't concerned with exactly what the error looks like,
 
1038
        # and the strerror will vary across OS and locales, but the assert
 
1039
        # that the exeception attributes are what we expect
 
1040
        self.assertEqual(e.errno, errno.EACCES)
 
1041
        if os.name == "posix":
 
1042
            self.assertEndsWith(e.to_path, "/first-dir/newname")
 
1043
        else:
 
1044
            self.assertEqual(os.path.basename(e.from_path), "myfile")
886
1045
 
887
1046
    def test_set_executability_order(self):
888
1047
        """Ensure that executability behaves the same, no matter what order.
1161
1320
        parent2 = transform.new_directory('parent2', root)
1162
1321
        transform.adjust_path('child1', parent2, child1)
1163
1322
        transform.apply()
1164
 
        self.failIfExists(self.wt.abspath('parent1/child1'))
1165
 
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
 
1323
        self.assertPathDoesNotExist(self.wt.abspath('parent1/child1'))
 
1324
        self.assertPathExists(self.wt.abspath('parent2/child1'))
1166
1325
        # rename limbo/new-1 => parent1, rename limbo/new-3 => parent2
1167
1326
        # no rename for child1 (counting only renames during apply)
1168
 
        self.failUnlessEqual(2, transform.rename_count)
 
1327
        self.assertEqual(2, transform.rename_count)
1169
1328
 
1170
1329
    def test_cancel_parent(self):
1171
1330
        """Cancelling a parent doesn't cause deletion of a non-empty directory
1194
1353
        parent2 = transform.new_directory('parent2', root)
1195
1354
        transform.adjust_path('child1', parent2, child1)
1196
1355
        transform.apply()
1197
 
        self.failIfExists(self.wt.abspath('parent1'))
1198
 
        self.failUnlessExists(self.wt.abspath('parent2/child1'))
 
1356
        self.assertPathDoesNotExist(self.wt.abspath('parent1'))
 
1357
        self.assertPathExists(self.wt.abspath('parent2/child1'))
1199
1358
        # rename limbo/new-3 => parent2, rename limbo/new-2 => child1
1200
 
        self.failUnlessEqual(2, transform.rename_count)
 
1359
        self.assertEqual(2, transform.rename_count)
1201
1360
 
1202
1361
    def test_adjust_and_cancel(self):
1203
1362
        """Make sure adjust_path keeps track of limbo children properly"""
1236
1395
        child = transform.new_directory('child', parent)
1237
1396
        transform.adjust_path('parent', root, parent)
1238
1397
        transform.apply()
1239
 
        self.failUnlessExists(self.wt.abspath('parent/child'))
 
1398
        self.assertPathExists(self.wt.abspath('parent/child'))
1240
1399
        self.assertEqual(1, transform.rename_count)
1241
1400
 
1242
1401
    def test_reuse_name(self):
1318
1477
        # The rename will fail because the target directory is not empty (but
1319
1478
        # raises FileExists anyway).
1320
1479
        err = self.assertRaises(errors.FileExists, tt_helper)
1321
 
        self.assertContainsRe(str(err),
1322
 
            "^File exists: .+/baz")
 
1480
        self.assertEndsWith(err.path, "/baz")
1323
1481
 
1324
1482
    def test_two_directories_clash(self):
1325
1483
        def tt_helper():
1337
1495
                wt.unlock()
1338
1496
                raise
1339
1497
        err = self.assertRaises(errors.FileExists, tt_helper)
1340
 
        self.assertContainsRe(str(err),
1341
 
            "^File exists: .+/foo")
 
1498
        self.assertEndsWith(err.path, "/foo")
1342
1499
 
1343
1500
    def test_two_directories_clash_finalize(self):
1344
1501
        def tt_helper():
1356
1513
                tt.finalize()
1357
1514
                raise
1358
1515
        err = self.assertRaises(errors.FileExists, tt_helper)
1359
 
        self.assertContainsRe(str(err),
1360
 
            "^File exists: .+/foo")
 
1516
        self.assertEndsWith(err.path, "/foo")
1361
1517
 
1362
1518
    def test_file_to_directory(self):
1363
1519
        wt = self.make_branch_and_tree('.')
1373
1529
        tt.create_file(["aa\n"], bar_trans_id)
1374
1530
        tt.version_file("bar-1", bar_trans_id)
1375
1531
        tt.apply()
1376
 
        self.failUnlessExists("foo/bar")
 
1532
        self.assertPathExists("foo/bar")
1377
1533
        wt.lock_read()
1378
1534
        try:
1379
1535
            self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1396
1552
        tt.delete_contents(foo_trans_id)
1397
1553
        tt.create_symlink("bar", foo_trans_id)
1398
1554
        tt.apply()
1399
 
        self.failUnlessExists("foo")
 
1555
        self.assertPathExists("foo")
1400
1556
        wt.lock_read()
1401
1557
        self.addCleanup(wt.unlock)
1402
1558
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1415
1571
        tt.delete_versioned(bar_trans_id)
1416
1572
        tt.create_file(["aa\n"], foo_trans_id)
1417
1573
        tt.apply()
1418
 
        self.failUnlessExists("foo")
 
1574
        self.assertPathExists("foo")
1419
1575
        wt.lock_read()
1420
1576
        self.addCleanup(wt.unlock)
1421
1577
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1436
1592
        self.build_tree(['baz'])
1437
1593
        tt.create_hardlink("baz", foo_trans_id)
1438
1594
        tt.apply()
1439
 
        self.failUnlessExists("foo")
1440
 
        self.failUnlessExists("baz")
 
1595
        self.assertPathExists("foo")
 
1596
        self.assertPathExists("baz")
1441
1597
        wt.lock_read()
1442
1598
        self.addCleanup(wt.unlock)
1443
1599
        self.assertEqual(wt.inventory.get_file_kind(wt.path2id("foo")),
1505
1661
    return template % ('<' * 7, tree, '=' * 7, merge, '>' * 7)
1506
1662
 
1507
1663
 
 
1664
class TestInventoryAltered(tests.TestCaseWithTransport):
 
1665
 
 
1666
    def test_inventory_altered_unchanged(self):
 
1667
        tree = self.make_branch_and_tree('tree')
 
1668
        self.build_tree(['tree/foo'])
 
1669
        tree.add('foo', 'foo-id')
 
1670
        with TransformPreview(tree) as tt:
 
1671
            self.assertEqual([], tt._inventory_altered())
 
1672
 
 
1673
    def test_inventory_altered_changed_parent_id(self):
 
1674
        tree = self.make_branch_and_tree('tree')
 
1675
        self.build_tree(['tree/foo'])
 
1676
        tree.add('foo', 'foo-id')
 
1677
        with TransformPreview(tree) as tt:
 
1678
            tt.unversion_file(tt.root)
 
1679
            tt.version_file('new-id', tt.root)
 
1680
            foo_trans_id = tt.trans_id_tree_file_id('foo-id')
 
1681
            foo_tuple = ('foo', foo_trans_id)
 
1682
            root_tuple = ('', tt.root)
 
1683
            self.assertEqual([root_tuple, foo_tuple], tt._inventory_altered())
 
1684
 
 
1685
    def test_inventory_altered_noop_changed_parent_id(self):
 
1686
        tree = self.make_branch_and_tree('tree')
 
1687
        self.build_tree(['tree/foo'])
 
1688
        tree.add('foo', 'foo-id')
 
1689
        with TransformPreview(tree) as tt:
 
1690
            tt.unversion_file(tt.root)
 
1691
            tt.version_file(tree.get_root_id(), tt.root)
 
1692
            foo_trans_id = tt.trans_id_tree_file_id('foo-id')
 
1693
            self.assertEqual([], tt._inventory_altered())
 
1694
 
 
1695
 
1508
1696
class TestTransformMerge(TestCaseInTempDir):
1509
1697
 
1510
1698
    def test_text_merge(self):
1577
1765
        merge_modified = this.wt.merge_modified()
1578
1766
        self.assertSubset(merge_modified, modified)
1579
1767
        self.assertEqual(len(merge_modified), len(modified))
1580
 
        file(this.wt.id2abspath('a'), 'wb').write('booga')
 
1768
        with file(this.wt.id2abspath('a'), 'wb') as f: f.write('booga')
1581
1769
        modified.pop(0)
1582
1770
        merge_modified = this.wt.merge_modified()
1583
1771
        self.assertSubset(merge_modified, modified)
1699
1887
        os.mkdir('a')
1700
1888
        a = BzrDir.create_standalone_workingtree('a')
1701
1889
        os.mkdir('a/foo')
1702
 
        file('a/foo/bar', 'wb').write('contents')
 
1890
        with file('a/foo/bar', 'wb') as f: f.write('contents')
1703
1891
        os.symlink('a/foo/bar', 'a/foo/baz')
1704
1892
        a.add(['foo', 'foo/bar', 'foo/baz'])
1705
1893
        a.commit('initial commit')
1720
1908
        tree.add_reference(subtree)
1721
1909
        tree.commit('a revision')
1722
1910
        tree.branch.create_checkout('target')
1723
 
        self.failUnlessExists('target')
1724
 
        self.failUnlessExists('target/subtree')
 
1911
        self.assertPathExists('target')
 
1912
        self.assertPathExists('target/subtree')
1725
1913
 
1726
1914
    def test_file_conflict_handling(self):
1727
1915
        """Ensure that when building trees, conflict handling is done"""
1774
1962
        source.commit('added file')
1775
1963
        build_tree(source.basis_tree(), target)
1776
1964
        self.assertEqual([], target.conflicts())
1777
 
        self.failUnlessExists('target/dir1/file')
 
1965
        self.assertPathExists('target/dir1/file')
1778
1966
 
1779
1967
        # Ensure contents are merged
1780
1968
        target = self.make_branch_and_tree('target2')
1781
1969
        self.build_tree(['target2/dir1/', 'target2/dir1/file2'])
1782
1970
        build_tree(source.basis_tree(), target)
1783
1971
        self.assertEqual([], target.conflicts())
1784
 
        self.failUnlessExists('target2/dir1/file2')
1785
 
        self.failUnlessExists('target2/dir1/file')
 
1972
        self.assertPathExists('target2/dir1/file2')
 
1973
        self.assertPathExists('target2/dir1/file')
1786
1974
 
1787
1975
        # Ensure new contents are suppressed for existing branches
1788
1976
        target = self.make_branch_and_tree('target3')
1789
1977
        self.make_branch('target3/dir1')
1790
1978
        self.build_tree(['target3/dir1/file2'])
1791
1979
        build_tree(source.basis_tree(), target)
1792
 
        self.failIfExists('target3/dir1/file')
1793
 
        self.failUnlessExists('target3/dir1/file2')
1794
 
        self.failUnlessExists('target3/dir1.diverted/file')
 
1980
        self.assertPathDoesNotExist('target3/dir1/file')
 
1981
        self.assertPathExists('target3/dir1/file2')
 
1982
        self.assertPathExists('target3/dir1.diverted/file')
1795
1983
        self.assertEqual([DuplicateEntry('Diverted to',
1796
1984
            'dir1.diverted', 'dir1', 'new-dir1', None)],
1797
1985
            target.conflicts())
1800
1988
        self.build_tree(['target4/dir1/'])
1801
1989
        self.make_branch('target4/dir1/file')
1802
1990
        build_tree(source.basis_tree(), target)
1803
 
        self.failUnlessExists('target4/dir1/file')
 
1991
        self.assertPathExists('target4/dir1/file')
1804
1992
        self.assertEqual('directory', file_kind('target4/dir1/file'))
1805
 
        self.failUnlessExists('target4/dir1/file.diverted')
 
1993
        self.assertPathExists('target4/dir1/file.diverted')
1806
1994
        self.assertEqual([DuplicateEntry('Diverted to',
1807
1995
            'dir1/file.diverted', 'dir1/file', 'new-file', None)],
1808
1996
            target.conflicts())
1876
2064
        self.addCleanup(target.unlock)
1877
2065
        self.assertEqual([], list(target.iter_changes(revision_tree)))
1878
2066
 
 
2067
    def test_build_tree_accelerator_tree_observes_sha1(self):
 
2068
        source = self.create_ab_tree()
 
2069
        sha1 = osutils.sha_string('A')
 
2070
        target = self.make_branch_and_tree('target')
 
2071
        target.lock_write()
 
2072
        self.addCleanup(target.unlock)
 
2073
        state = target.current_dirstate()
 
2074
        state._cutoff_time = time.time() + 60
 
2075
        build_tree(source.basis_tree(), target, source)
 
2076
        entry = state._get_entry(0, path_utf8='file1')
 
2077
        self.assertEqual(sha1, entry[1][0][1])
 
2078
 
1879
2079
    def test_build_tree_accelerator_tree_missing_file(self):
1880
2080
        source = self.create_ab_tree()
1881
2081
        os.unlink('source/file1')
2024
2224
        self.assertEqualStat(source_stat, target_stat)
2025
2225
 
2026
2226
    def test_case_insensitive_build_tree_inventory(self):
2027
 
        if (tests.CaseInsensitiveFilesystemFeature.available()
2028
 
            or tests.CaseInsCasePresFilenameFeature.available()):
 
2227
        if (features.CaseInsensitiveFilesystemFeature.available()
 
2228
            or features.CaseInsCasePresFilenameFeature.available()):
2029
2229
            raise tests.UnavailableFeature('Fully case sensitive filesystem')
2030
2230
        source = self.make_branch_and_tree('source')
2031
2231
        self.build_tree(['source/file', 'source/FILE'])
2039
2239
        self.assertEqual('file.moved', target.id2path('lower-id'))
2040
2240
        self.assertEqual('FILE', target.id2path('upper-id'))
2041
2241
 
 
2242
    def test_build_tree_observes_sha(self):
 
2243
        source = self.make_branch_and_tree('source')
 
2244
        self.build_tree(['source/file1', 'source/dir/', 'source/dir/file2'])
 
2245
        source.add(['file1', 'dir', 'dir/file2'],
 
2246
                   ['file1-id', 'dir-id', 'file2-id'])
 
2247
        source.commit('new files')
 
2248
        target = self.make_branch_and_tree('target')
 
2249
        target.lock_write()
 
2250
        self.addCleanup(target.unlock)
 
2251
        # We make use of the fact that DirState caches its cutoff time. So we
 
2252
        # set the 'safe' time to one minute in the future.
 
2253
        state = target.current_dirstate()
 
2254
        state._cutoff_time = time.time() + 60
 
2255
        build_tree(source.basis_tree(), target)
 
2256
        entry1_sha = osutils.sha_file_by_name('source/file1')
 
2257
        entry2_sha = osutils.sha_file_by_name('source/dir/file2')
 
2258
        # entry[1] is the state information, entry[1][0] is the state of the
 
2259
        # working tree, entry[1][0][1] is the sha value for the current working
 
2260
        # tree
 
2261
        entry1 = state._get_entry(0, path_utf8='file1')
 
2262
        self.assertEqual(entry1_sha, entry1[1][0][1])
 
2263
        # The 'size' field must also be set.
 
2264
        self.assertEqual(25, entry1[1][0][2])
 
2265
        entry1_state = entry1[1][0]
 
2266
        entry2 = state._get_entry(0, path_utf8='dir/file2')
 
2267
        self.assertEqual(entry2_sha, entry2[1][0][1])
 
2268
        self.assertEqual(29, entry2[1][0][2])
 
2269
        entry2_state = entry2[1][0]
 
2270
        # Now, make sure that we don't have to re-read the content. The
 
2271
        # packed_stat should match exactly.
 
2272
        self.assertEqual(entry1_sha, target.get_file_sha1('file1-id', 'file1'))
 
2273
        self.assertEqual(entry2_sha,
 
2274
                         target.get_file_sha1('file2-id', 'dir/file2'))
 
2275
        self.assertEqual(entry1_state, entry1[1][0])
 
2276
        self.assertEqual(entry2_state, entry2[1][0])
 
2277
 
2042
2278
 
2043
2279
class TestCommitTransform(tests.TestCaseWithTransport):
2044
2280
 
2178
2414
        self.assertEqual('tree', revision.properties['branch-nick'])
2179
2415
 
2180
2416
 
2181
 
class MockTransform(object):
2182
 
 
2183
 
    def has_named_child(self, by_parent, parent_id, name):
2184
 
        for child_id in by_parent[parent_id]:
2185
 
            if child_id == '0':
2186
 
                if name == "name~":
2187
 
                    return True
2188
 
            elif name == "name.~%s~" % child_id:
2189
 
                return True
2190
 
        return False
2191
 
 
2192
 
 
2193
 
class MockEntry(object):
2194
 
    def __init__(self):
2195
 
        object.__init__(self)
2196
 
        self.name = "name"
2197
 
 
2198
 
 
2199
 
class TestGetBackupName(TestCase):
2200
 
    def test_get_backup_name(self):
 
2417
class TestBackupName(tests.TestCase):
 
2418
 
 
2419
    def test_deprecations(self):
 
2420
        class MockTransform(object):
 
2421
 
 
2422
            def has_named_child(self, by_parent, parent_id, name):
 
2423
                return name in by_parent.get(parent_id, [])
 
2424
 
 
2425
        class MockEntry(object):
 
2426
 
 
2427
            def __init__(self):
 
2428
                object.__init__(self)
 
2429
                self.name = "name"
 
2430
 
2201
2431
        tt = MockTransform()
2202
 
        name = get_backup_name(MockEntry(), {'a':[]}, 'a', tt)
2203
 
        self.assertEqual(name, 'name.~1~')
2204
 
        name = get_backup_name(MockEntry(), {'a':['1']}, 'a', tt)
2205
 
        self.assertEqual(name, 'name.~2~')
2206
 
        name = get_backup_name(MockEntry(), {'a':['2']}, 'a', tt)
2207
 
        self.assertEqual(name, 'name.~1~')
2208
 
        name = get_backup_name(MockEntry(), {'a':['2'], 'b':[]}, 'b', tt)
2209
 
        self.assertEqual(name, 'name.~1~')
2210
 
        name = get_backup_name(MockEntry(), {'a':['1', '2', '3']}, 'a', tt)
2211
 
        self.assertEqual(name, 'name.~4~')
 
2432
        name1 = self.applyDeprecated(
 
2433
            symbol_versioning.deprecated_in((2, 3, 0)),
 
2434
            transform.get_backup_name, MockEntry(), {'a':[]}, 'a', tt)
 
2435
        self.assertEqual('name.~1~', name1)
 
2436
        name2 = self.applyDeprecated(
 
2437
            symbol_versioning.deprecated_in((2, 3, 0)),
 
2438
            transform._get_backup_name, 'name', {'a':['name.~1~']}, 'a', tt)
 
2439
        self.assertEqual('name.~2~', name2)
2212
2440
 
2213
2441
 
2214
2442
class TestFileMover(tests.TestCaseWithTransport):
2217
2445
        self.build_tree(['a/', 'a/b', 'c/', 'c/d'])
2218
2446
        mover = _FileMover()
2219
2447
        mover.rename('a', 'q')
2220
 
        self.failUnlessExists('q')
2221
 
        self.failIfExists('a')
2222
 
        self.failUnlessExists('q/b')
2223
 
        self.failUnlessExists('c')
2224
 
        self.failUnlessExists('c/d')
 
2448
        self.assertPathExists('q')
 
2449
        self.assertPathDoesNotExist('a')
 
2450
        self.assertPathExists('q/b')
 
2451
        self.assertPathExists('c')
 
2452
        self.assertPathExists('c/d')
2225
2453
 
2226
2454
    def test_pre_delete_rollback(self):
2227
2455
        self.build_tree(['a/'])
2228
2456
        mover = _FileMover()
2229
2457
        mover.pre_delete('a', 'q')
2230
 
        self.failUnlessExists('q')
2231
 
        self.failIfExists('a')
 
2458
        self.assertPathExists('q')
 
2459
        self.assertPathDoesNotExist('a')
2232
2460
        mover.rollback()
2233
 
        self.failIfExists('q')
2234
 
        self.failUnlessExists('a')
 
2461
        self.assertPathDoesNotExist('q')
 
2462
        self.assertPathExists('a')
2235
2463
 
2236
2464
    def test_apply_deletions(self):
2237
2465
        self.build_tree(['a/', 'b/'])
2238
2466
        mover = _FileMover()
2239
2467
        mover.pre_delete('a', 'q')
2240
2468
        mover.pre_delete('b', 'r')
2241
 
        self.failUnlessExists('q')
2242
 
        self.failUnlessExists('r')
2243
 
        self.failIfExists('a')
2244
 
        self.failIfExists('b')
 
2469
        self.assertPathExists('q')
 
2470
        self.assertPathExists('r')
 
2471
        self.assertPathDoesNotExist('a')
 
2472
        self.assertPathDoesNotExist('b')
2245
2473
        mover.apply_deletions()
2246
 
        self.failIfExists('q')
2247
 
        self.failIfExists('r')
2248
 
        self.failIfExists('a')
2249
 
        self.failIfExists('b')
 
2474
        self.assertPathDoesNotExist('q')
 
2475
        self.assertPathDoesNotExist('r')
 
2476
        self.assertPathDoesNotExist('a')
 
2477
        self.assertPathDoesNotExist('b')
2250
2478
 
2251
2479
    def test_file_mover_rollback(self):
2252
2480
        self.build_tree(['a/', 'a/b', 'c/', 'c/d/', 'c/e/'])
2257
2485
            mover.rename('a', 'c')
2258
2486
        except errors.FileExists, e:
2259
2487
            mover.rollback()
2260
 
        self.failUnlessExists('a')
2261
 
        self.failUnlessExists('c/d')
 
2488
        self.assertPathExists('a')
 
2489
        self.assertPathExists('c/d')
2262
2490
 
2263
2491
 
2264
2492
class Bogus(Exception):
2294
2522
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2295
2523
        self.assertRaises(Bogus, tt.apply,
2296
2524
                          _mover=self.ExceptionFileMover(bad_source='a'))
2297
 
        self.failUnlessExists('a')
2298
 
        self.failUnlessExists('a/b')
 
2525
        self.assertPathExists('a')
 
2526
        self.assertPathExists('a/b')
2299
2527
        tt.apply()
2300
 
        self.failUnlessExists('c')
2301
 
        self.failUnlessExists('c/d')
 
2528
        self.assertPathExists('c')
 
2529
        self.assertPathExists('c/d')
2302
2530
 
2303
2531
    def test_rollback_rename_into_place(self):
2304
2532
        tree = self.make_branch_and_tree('.')
2310
2538
        tt.adjust_path('d', a_id, tt.trans_id_tree_path('a/b'))
2311
2539
        self.assertRaises(Bogus, tt.apply,
2312
2540
                          _mover=self.ExceptionFileMover(bad_target='c/d'))
2313
 
        self.failUnlessExists('a')
2314
 
        self.failUnlessExists('a/b')
 
2541
        self.assertPathExists('a')
 
2542
        self.assertPathExists('a/b')
2315
2543
        tt.apply()
2316
 
        self.failUnlessExists('c')
2317
 
        self.failUnlessExists('c/d')
 
2544
        self.assertPathExists('c')
 
2545
        self.assertPathExists('c/d')
2318
2546
 
2319
2547
    def test_rollback_deletion(self):
2320
2548
        tree = self.make_branch_and_tree('.')
2326
2554
        tt.adjust_path('d', tt.root, tt.trans_id_tree_path('a/b'))
2327
2555
        self.assertRaises(Bogus, tt.apply,
2328
2556
                          _mover=self.ExceptionFileMover(bad_target='d'))
2329
 
        self.failUnlessExists('a')
2330
 
        self.failUnlessExists('a/b')
2331
 
 
2332
 
    def test_resolve_no_parent(self):
 
2557
        self.assertPathExists('a')
 
2558
        self.assertPathExists('a/b')
 
2559
 
 
2560
 
 
2561
class TestFinalizeRobustness(tests.TestCaseWithTransport):
 
2562
    """Ensure treetransform creation errors can be safely cleaned up after"""
 
2563
 
 
2564
    def _override_globals_in_method(self, instance, method_name, globals):
 
2565
        """Replace method on instance with one with updated globals"""
 
2566
        import types
 
2567
        func = getattr(instance, method_name).im_func
 
2568
        new_globals = dict(func.func_globals)
 
2569
        new_globals.update(globals)
 
2570
        new_func = types.FunctionType(func.func_code, new_globals,
 
2571
            func.func_name, func.func_defaults)
 
2572
        setattr(instance, method_name,
 
2573
            types.MethodType(new_func, instance, instance.__class__))
 
2574
        self.addCleanup(delattr, instance, method_name)
 
2575
 
 
2576
    @staticmethod
 
2577
    def _fake_open_raises_before(name, mode):
 
2578
        """Like open() but raises before doing anything"""
 
2579
        raise RuntimeError
 
2580
 
 
2581
    @staticmethod
 
2582
    def _fake_open_raises_after(name, mode):
 
2583
        """Like open() but raises after creating file without returning"""
 
2584
        open(name, mode).close()
 
2585
        raise RuntimeError
 
2586
 
 
2587
    def create_transform_and_root_trans_id(self):
 
2588
        """Setup a transform creating a file in limbo"""
 
2589
        tree = self.make_branch_and_tree('.')
 
2590
        tt = TreeTransform(tree)
 
2591
        return tt, tt.create_path("a", tt.root)
 
2592
 
 
2593
    def create_transform_and_subdir_trans_id(self):
 
2594
        """Setup a transform creating a directory containing a file in limbo"""
 
2595
        tree = self.make_branch_and_tree('.')
 
2596
        tt = TreeTransform(tree)
 
2597
        d_trans_id = tt.create_path("d", tt.root)
 
2598
        tt.create_directory(d_trans_id)
 
2599
        f_trans_id = tt.create_path("a", d_trans_id)
 
2600
        tt.adjust_path("a", d_trans_id, f_trans_id)
 
2601
        return tt, f_trans_id
 
2602
 
 
2603
    def test_root_create_file_open_raises_before_creation(self):
 
2604
        tt, trans_id = self.create_transform_and_root_trans_id()
 
2605
        self._override_globals_in_method(tt, "create_file",
 
2606
            {"open": self._fake_open_raises_before})
 
2607
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
 
2608
        path = tt._limbo_name(trans_id)
 
2609
        self.assertPathDoesNotExist(path)
 
2610
        tt.finalize()
 
2611
        self.assertPathDoesNotExist(tt._limbodir)
 
2612
 
 
2613
    def test_root_create_file_open_raises_after_creation(self):
 
2614
        tt, trans_id = self.create_transform_and_root_trans_id()
 
2615
        self._override_globals_in_method(tt, "create_file",
 
2616
            {"open": self._fake_open_raises_after})
 
2617
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
 
2618
        path = tt._limbo_name(trans_id)
 
2619
        self.assertPathExists(path)
 
2620
        tt.finalize()
 
2621
        self.assertPathDoesNotExist(path)
 
2622
        self.assertPathDoesNotExist(tt._limbodir)
 
2623
 
 
2624
    def test_subdir_create_file_open_raises_before_creation(self):
 
2625
        tt, trans_id = self.create_transform_and_subdir_trans_id()
 
2626
        self._override_globals_in_method(tt, "create_file",
 
2627
            {"open": self._fake_open_raises_before})
 
2628
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
 
2629
        path = tt._limbo_name(trans_id)
 
2630
        self.assertPathDoesNotExist(path)
 
2631
        tt.finalize()
 
2632
        self.assertPathDoesNotExist(tt._limbodir)
 
2633
 
 
2634
    def test_subdir_create_file_open_raises_after_creation(self):
 
2635
        tt, trans_id = self.create_transform_and_subdir_trans_id()
 
2636
        self._override_globals_in_method(tt, "create_file",
 
2637
            {"open": self._fake_open_raises_after})
 
2638
        self.assertRaises(RuntimeError, tt.create_file, ["contents"], trans_id)
 
2639
        path = tt._limbo_name(trans_id)
 
2640
        self.assertPathExists(path)
 
2641
        tt.finalize()
 
2642
        self.assertPathDoesNotExist(path)
 
2643
        self.assertPathDoesNotExist(tt._limbodir)
 
2644
 
 
2645
    def test_rename_in_limbo_rename_raises_after_rename(self):
 
2646
        tt, trans_id = self.create_transform_and_root_trans_id()
 
2647
        parent1 = tt.new_directory('parent1', tt.root)
 
2648
        child1 = tt.new_file('child1', parent1, 'contents')
 
2649
        parent2 = tt.new_directory('parent2', tt.root)
 
2650
 
 
2651
        class FakeOSModule(object):
 
2652
            def rename(self, old, new):
 
2653
                os.rename(old, new)
 
2654
                raise RuntimeError
 
2655
        self._override_globals_in_method(tt, "_rename_in_limbo",
 
2656
            {"os": FakeOSModule()})
 
2657
        self.assertRaises(
 
2658
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
 
2659
        path = osutils.pathjoin(tt._limbo_name(parent2), "child1")
 
2660
        self.assertPathExists(path)
 
2661
        tt.finalize()
 
2662
        self.assertPathDoesNotExist(path)
 
2663
        self.assertPathDoesNotExist(tt._limbodir)
 
2664
 
 
2665
    def test_rename_in_limbo_rename_raises_before_rename(self):
 
2666
        tt, trans_id = self.create_transform_and_root_trans_id()
 
2667
        parent1 = tt.new_directory('parent1', tt.root)
 
2668
        child1 = tt.new_file('child1', parent1, 'contents')
 
2669
        parent2 = tt.new_directory('parent2', tt.root)
 
2670
 
 
2671
        class FakeOSModule(object):
 
2672
            def rename(self, old, new):
 
2673
                raise RuntimeError
 
2674
        self._override_globals_in_method(tt, "_rename_in_limbo",
 
2675
            {"os": FakeOSModule()})
 
2676
        self.assertRaises(
 
2677
            RuntimeError, tt.adjust_path, "child1", parent2, child1)
 
2678
        path = osutils.pathjoin(tt._limbo_name(parent1), "child1")
 
2679
        self.assertPathExists(path)
 
2680
        tt.finalize()
 
2681
        self.assertPathDoesNotExist(path)
 
2682
        self.assertPathDoesNotExist(tt._limbodir)
 
2683
 
 
2684
 
 
2685
class TestTransformMissingParent(tests.TestCaseWithTransport):
 
2686
 
 
2687
    def make_tt_with_versioned_dir(self):
2333
2688
        wt = self.make_branch_and_tree('.')
 
2689
        self.build_tree(['dir/',])
 
2690
        wt.add(['dir'], ['dir-id'])
 
2691
        wt.commit('Create dir')
2334
2692
        tt = TreeTransform(wt)
2335
2693
        self.addCleanup(tt.finalize)
2336
 
        parent = tt.trans_id_file_id('parent-id')
2337
 
        tt.new_file('file', parent, 'Contents')
2338
 
        resolve_conflicts(tt)
 
2694
        return wt, tt
 
2695
 
 
2696
    def test_resolve_create_parent_for_versioned_file(self):
 
2697
        wt, tt = self.make_tt_with_versioned_dir()
 
2698
        dir_tid = tt.trans_id_tree_file_id('dir-id')
 
2699
        file_tid = tt.new_file('file', dir_tid, 'Contents', file_id='file-id')
 
2700
        tt.delete_contents(dir_tid)
 
2701
        tt.unversion_file(dir_tid)
 
2702
        conflicts = resolve_conflicts(tt)
 
2703
        # one conflict for the missing directory, one for the unversioned
 
2704
        # parent
 
2705
        self.assertLength(2, conflicts)
 
2706
 
 
2707
    def test_non_versioned_file_create_conflict(self):
 
2708
        wt, tt = self.make_tt_with_versioned_dir()
 
2709
        dir_tid = tt.trans_id_tree_file_id('dir-id')
 
2710
        tt.new_file('file', dir_tid, 'Contents')
 
2711
        tt.delete_contents(dir_tid)
 
2712
        tt.unversion_file(dir_tid)
 
2713
        conflicts = resolve_conflicts(tt)
 
2714
        # no conflicts or rather: orphaning 'file' resolve the 'dir' conflict
 
2715
        self.assertLength(1, conflicts)
 
2716
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
 
2717
                         conflicts.pop())
2339
2718
 
2340
2719
 
2341
2720
A_ENTRY = ('a-id', ('a', 'a'), True, (True, True),
2342
2721
                  ('TREE_ROOT', 'TREE_ROOT'), ('a', 'a'), ('file', 'file'),
2343
2722
                  (False, False))
2344
2723
ROOT_ENTRY = ('TREE_ROOT', ('', ''), False, (True, True), (None, None),
2345
 
              ('', ''), ('directory', 'directory'), (False, None))
 
2724
              ('', ''), ('directory', 'directory'), (False, False))
2346
2725
 
2347
2726
 
2348
2727
class TestTransformPreview(tests.TestCaseWithTransport):
2435
2814
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2436
2815
        changes = preview_tree.iter_changes(revision_tree,
2437
2816
                                            specific_files=[''])
2438
 
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
 
2817
        self.assertEqual([A_ENTRY], list(changes))
2439
2818
 
2440
2819
    def test_want_unversioned(self):
2441
2820
        revision_tree, preview_tree = self.get_tree_and_preview_tree()
2442
2821
        changes = preview_tree.iter_changes(revision_tree,
2443
2822
                                            want_unversioned=True)
2444
 
        self.assertEqual([ROOT_ENTRY, A_ENTRY], list(changes))
 
2823
        self.assertEqual([A_ENTRY], list(changes))
2445
2824
 
2446
2825
    def test_ignore_extra_trees_no_specific_files(self):
2447
2826
        # extra_trees is harmless without specific_files, so we'll silently
2490
2869
        preview_mtime = preview_tree.get_file_mtime('file-id', 'renamed')
2491
2870
        work_mtime = work_tree.get_file_mtime('file-id', 'file')
2492
2871
 
 
2872
    def test_get_file_size(self):
 
2873
        work_tree = self.make_branch_and_tree('tree')
 
2874
        self.build_tree_contents([('tree/old', 'old')])
 
2875
        work_tree.add('old', 'old-id')
 
2876
        preview = TransformPreview(work_tree)
 
2877
        self.addCleanup(preview.finalize)
 
2878
        new_id = preview.new_file('name', preview.root, 'contents', 'new-id',
 
2879
                                  'executable')
 
2880
        tree = preview.get_preview_tree()
 
2881
        self.assertEqual(len('old'), tree.get_file_size('old-id'))
 
2882
        self.assertEqual(len('contents'), tree.get_file_size('new-id'))
 
2883
 
2493
2884
    def test_get_file(self):
2494
2885
        preview = self.get_empty_preview()
2495
2886
        preview.new_file('file', preview.root, 'contents', 'file-id')
2907
3298
        merger.merge_type = Merge3Merger
2908
3299
        merger.do_merge()
2909
3300
 
 
3301
    def test_has_filename(self):
 
3302
        wt = self.make_branch_and_tree('tree')
 
3303
        self.build_tree(['tree/unmodified', 'tree/removed', 'tree/modified'])
 
3304
        tt = TransformPreview(wt)
 
3305
        removed_id = tt.trans_id_tree_path('removed')
 
3306
        tt.delete_contents(removed_id)
 
3307
        tt.new_file('new', tt.root, 'contents')
 
3308
        modified_id = tt.trans_id_tree_path('modified')
 
3309
        tt.delete_contents(modified_id)
 
3310
        tt.create_file('modified-contents', modified_id)
 
3311
        self.addCleanup(tt.finalize)
 
3312
        tree = tt.get_preview_tree()
 
3313
        self.assertTrue(tree.has_filename('unmodified'))
 
3314
        self.assertFalse(tree.has_filename('not-present'))
 
3315
        self.assertFalse(tree.has_filename('removed'))
 
3316
        self.assertTrue(tree.has_filename('new'))
 
3317
        self.assertTrue(tree.has_filename('modified'))
 
3318
 
2910
3319
    def test_is_executable(self):
2911
3320
        tree = self.make_branch_and_tree('tree')
2912
3321
        preview = TransformPreview(tree)
2935
3344
        self.assertEqual('contents', rev2_tree.get_file_text('file_id'))
2936
3345
 
2937
3346
    def test_ascii_limbo_paths(self):
2938
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
3347
        self.requireFeature(features.UnicodeFilenameFeature)
2939
3348
        branch = self.make_branch('any')
2940
3349
        tree = branch.repository.revision_tree(_mod_revision.NULL_REVISION)
2941
3350
        tt = TransformPreview(tree)
2958
3367
 
2959
3368
class TestSerializeTransform(tests.TestCaseWithTransport):
2960
3369
 
2961
 
    _test_needs_features = [tests.UnicodeFilenameFeature]
 
3370
    _test_needs_features = [features.UnicodeFilenameFeature]
2962
3371
 
2963
3372
    def get_preview(self, tree=None):
2964
3373
        if tree is None:
3039
3448
        return self.make_records(attribs, contents)
3040
3449
 
3041
3450
    def test_serialize_symlink_creation(self):
3042
 
        self.requireFeature(tests.SymlinkFeature)
 
3451
        self.requireFeature(features.SymlinkFeature)
3043
3452
        tt = self.get_preview()
3044
3453
        tt.new_symlink(u'foo\u1234', tt.root, u'bar\u1234')
3045
3454
        self.assertSerializesTo(self.symlink_creation_records(), tt)
3046
3455
 
3047
3456
    def test_deserialize_symlink_creation(self):
3048
 
        self.requireFeature(tests.SymlinkFeature)
 
3457
        self.requireFeature(features.SymlinkFeature)
3049
3458
        tt = self.get_preview()
3050
3459
        tt.deserialize(iter(self.symlink_creation_records()))
3051
3460
        abspath = tt._limbo_name('new-1')
3218
3627
        trans_id = tt.trans_id_tree_path('file')
3219
3628
        self.assertEqual((LINES_ONE,),
3220
3629
            tt._get_parents_texts(trans_id))
 
3630
 
 
3631
 
 
3632
class TestOrphan(tests.TestCaseWithTransport):
 
3633
 
 
3634
    def test_no_orphan_for_transform_preview(self):
 
3635
        tree = self.make_branch_and_tree('tree')
 
3636
        tt = transform.TransformPreview(tree)
 
3637
        self.addCleanup(tt.finalize)
 
3638
        self.assertRaises(NotImplementedError, tt.new_orphan, 'foo', 'bar')
 
3639
 
 
3640
    def _set_orphan_policy(self, wt, policy):
 
3641
        wt.branch.get_config().set_user_option('bzr.transform.orphan_policy',
 
3642
                                               policy)
 
3643
 
 
3644
    def _prepare_orphan(self, wt):
 
3645
        self.build_tree(['dir/', 'dir/file', 'dir/foo'])
 
3646
        wt.add(['dir', 'dir/file'], ['dir-id', 'file-id'])
 
3647
        wt.commit('add dir and file ignoring foo')
 
3648
        tt = transform.TreeTransform(wt)
 
3649
        self.addCleanup(tt.finalize)
 
3650
        # dir and bar are deleted
 
3651
        dir_tid = tt.trans_id_tree_path('dir')
 
3652
        file_tid = tt.trans_id_tree_path('dir/file')
 
3653
        orphan_tid = tt.trans_id_tree_path('dir/foo')
 
3654
        tt.delete_contents(file_tid)
 
3655
        tt.unversion_file(file_tid)
 
3656
        tt.delete_contents(dir_tid)
 
3657
        tt.unversion_file(dir_tid)
 
3658
        # There should be a conflict because dir still contain foo
 
3659
        raw_conflicts = tt.find_conflicts()
 
3660
        self.assertLength(1, raw_conflicts)
 
3661
        self.assertEqual(('missing parent', 'new-1'), raw_conflicts[0])
 
3662
        return tt, orphan_tid
 
3663
 
 
3664
    def test_new_orphan_created(self):
 
3665
        wt = self.make_branch_and_tree('.')
 
3666
        self._set_orphan_policy(wt, 'move')
 
3667
        tt, orphan_tid = self._prepare_orphan(wt)
 
3668
        warnings = []
 
3669
        def warning(*args):
 
3670
            warnings.append(args[0] % args[1:])
 
3671
        self.overrideAttr(trace, 'warning', warning)
 
3672
        remaining_conflicts = resolve_conflicts(tt)
 
3673
        self.assertEquals(['dir/foo has been orphaned in bzr-orphans'],
 
3674
                          warnings)
 
3675
        # Yeah for resolved conflicts !
 
3676
        self.assertLength(0, remaining_conflicts)
 
3677
        # We have a new orphan
 
3678
        self.assertEquals('foo.~1~', tt.final_name(orphan_tid))
 
3679
        self.assertEquals('bzr-orphans',
 
3680
                          tt.final_name(tt.final_parent(orphan_tid)))
 
3681
 
 
3682
    def test_never_orphan(self):
 
3683
        wt = self.make_branch_and_tree('.')
 
3684
        self._set_orphan_policy(wt, 'conflict')
 
3685
        tt, orphan_tid = self._prepare_orphan(wt)
 
3686
        remaining_conflicts = resolve_conflicts(tt)
 
3687
        self.assertLength(1, remaining_conflicts)
 
3688
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
 
3689
                         remaining_conflicts.pop())
 
3690
 
 
3691
    def test_orphan_error(self):
 
3692
        def bogus_orphan(tt, orphan_id, parent_id):
 
3693
            raise transform.OrphaningError(tt.final_name(orphan_id),
 
3694
                                           tt.final_name(parent_id))
 
3695
        transform.orphaning_registry.register('bogus', bogus_orphan,
 
3696
                                              'Raise an error when orphaning')
 
3697
        wt = self.make_branch_and_tree('.')
 
3698
        self._set_orphan_policy(wt, 'bogus')
 
3699
        tt, orphan_tid = self._prepare_orphan(wt)
 
3700
        remaining_conflicts = resolve_conflicts(tt)
 
3701
        self.assertLength(1, remaining_conflicts)
 
3702
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
 
3703
                         remaining_conflicts.pop())
 
3704
 
 
3705
    def test_unknown_orphan_policy(self):
 
3706
        wt = self.make_branch_and_tree('.')
 
3707
        # Set a fictional policy nobody ever implemented
 
3708
        self._set_orphan_policy(wt, 'donttouchmypreciouuus')
 
3709
        tt, orphan_tid = self._prepare_orphan(wt)
 
3710
        warnings = []
 
3711
        def warning(*args):
 
3712
            warnings.append(args[0] % args[1:])
 
3713
        self.overrideAttr(trace, 'warning', warning)
 
3714
        remaining_conflicts = resolve_conflicts(tt)
 
3715
        # We fallback to the default policy which create a conflict
 
3716
        self.assertLength(1, remaining_conflicts)
 
3717
        self.assertEqual(('deleting parent', 'Not deleting', 'new-1'),
 
3718
                         remaining_conflicts.pop())
 
3719
        self.assertLength(1, warnings)
 
3720
        self.assertStartsWith(warnings[0], 'donttouchmypreciouuus')
 
3721
 
 
3722
 
 
3723
class TestTransformHooks(tests.TestCaseWithTransport):
 
3724
 
 
3725
    def setUp(self):
 
3726
        super(TestTransformHooks, self).setUp()
 
3727
        self.wt = self.make_branch_and_tree('.')
 
3728
        os.chdir('..')
 
3729
 
 
3730
    def get_transform(self):
 
3731
        transform = TreeTransform(self.wt)
 
3732
        self.addCleanup(transform.finalize)
 
3733
        return transform, transform.root
 
3734
 
 
3735
    def test_pre_commit_hooks(self):
 
3736
        calls = []
 
3737
        def record_pre_transform(tree, tt):
 
3738
            calls.append((tree, tt))
 
3739
        MutableTree.hooks.install_named_hook('pre_transform',
 
3740
            record_pre_transform, "Pre transform")
 
3741
        transform, root = self.get_transform()
 
3742
        old_root_id = transform.tree_file_id(root)
 
3743
        transform.apply()
 
3744
        self.assertEqual(old_root_id, self.wt.get_root_id())
 
3745
        self.assertEquals([(self.wt, transform)], calls)
 
3746
 
 
3747
    def test_post_commit_hooks(self):
 
3748
        calls = []
 
3749
        def record_post_transform(tree, tt):
 
3750
            calls.append((tree, tt))
 
3751
        MutableTree.hooks.install_named_hook('post_transform',
 
3752
            record_post_transform, "Post transform")
 
3753
        transform, root = self.get_transform()
 
3754
        old_root_id = transform.tree_file_id(root)
 
3755
        transform.apply()
 
3756
        self.assertEqual(old_root_id, self.wt.get_root_id())
 
3757
        self.assertEquals([(self.wt, transform)], calls)