~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_diff.py

  • Committer: Ian Clatworthy
  • Date: 2007-08-13 14:33:10 UTC
  • mto: (2733.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 2734.
  • Revision ID: ian.clatworthy@internode.on.net-20070813143310-twhj4la0qnupvze8
Added Quick Start Summary

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
import os
18
 
import os.path
19
18
from cStringIO import StringIO
20
19
import errno
21
20
import subprocess
22
 
import sys
23
21
from tempfile import TemporaryFile
24
22
 
25
 
from bzrlib import tests
26
 
from bzrlib.diff import (
27
 
    DiffFromTool,
28
 
    DiffPath,
29
 
    DiffSymlink,
30
 
    DiffTree,
31
 
    DiffText,
32
 
    external_diff,
33
 
    internal_diff,
34
 
    show_diff_trees,
35
 
    )
36
 
from bzrlib.errors import BinaryFile, NoDiff, ExecutableMissing
 
23
from bzrlib.diff import internal_diff, external_diff, show_diff_trees
 
24
from bzrlib.errors import BinaryFile, NoDiff
37
25
import bzrlib.osutils as osutils
38
 
import bzrlib.revision as _mod_revision
39
 
import bzrlib.transform as transform
40
26
import bzrlib.patiencediff
41
 
import bzrlib._patiencediff_py
42
27
from bzrlib.tests import (Feature, TestCase, TestCaseWithTransport,
43
28
                          TestCaseInTempDir, TestSkipped)
44
29
 
45
30
 
46
 
class _AttribFeature(Feature):
47
 
 
48
 
    def _probe(self):
49
 
        if (sys.platform not in ('cygwin', 'win32')):
50
 
            return False
51
 
        try:
52
 
            proc = subprocess.Popen(['attrib', '.'], stdout=subprocess.PIPE)
53
 
        except OSError, e:
54
 
            return False
55
 
        return (0 == proc.wait())
56
 
 
57
 
    def feature_name(self):
58
 
        return 'attrib Windows command-line tool'
59
 
 
60
 
AttribFeature = _AttribFeature()
61
 
 
62
 
 
63
 
class _CompiledPatienceDiffFeature(Feature):
64
 
 
65
 
    def _probe(self):
66
 
        try:
67
 
            import bzrlib._patiencediff_c
68
 
        except ImportError:
69
 
            return False
70
 
        return True
71
 
 
72
 
    def feature_name(self):
73
 
        return 'bzrlib._patiencediff_c'
74
 
 
75
 
CompiledPatienceDiffFeature = _CompiledPatienceDiffFeature()
76
 
 
 
31
class _UnicodeFilename(Feature):
 
32
    """Does the filesystem support Unicode filenames?"""
 
33
 
 
34
    def _probe(self):
 
35
        try:
 
36
            os.stat(u'\u03b1')
 
37
        except UnicodeEncodeError:
 
38
            return False
 
39
        except (IOError, OSError):
 
40
            # The filesystem allows the Unicode filename but the file doesn't
 
41
            # exist.
 
42
            return True
 
43
        else:
 
44
            # The filesystem allows the Unicode filename and the file exists,
 
45
            # for some reason.
 
46
            return True
 
47
 
 
48
UnicodeFilename = _UnicodeFilename()
 
49
 
 
50
 
 
51
class TestUnicodeFilename(TestCase):
 
52
 
 
53
    def test_probe_passes(self):
 
54
        """UnicodeFilename._probe passes."""
 
55
        # We can't test much more than that because the behaviour depends
 
56
        # on the platform.
 
57
        UnicodeFilename._probe()
 
58
        
77
59
 
78
60
def udiff_lines(old, new, allow_binary=False):
79
61
    output = StringIO()
184
166
                              StringIO(), diff_opts=['-u'])
185
167
        finally:
186
168
            os.environ['PATH'] = orig_path
187
 
 
 
169
        
188
170
    def test_internal_diff_default(self):
189
171
        # Default internal diff encoding is utf8
190
172
        output = StringIO()
233
215
                          ]
234
216
                          , lines)
235
217
 
236
 
    def test_internal_diff_no_content(self):
237
 
        output = StringIO()
238
 
        internal_diff(u'old', [], u'new', [], output)
239
 
        self.assertEqual('', output.getvalue())
240
 
 
241
 
    def test_internal_diff_no_changes(self):
242
 
        output = StringIO()
243
 
        internal_diff(u'old', ['text\n', 'contents\n'],
244
 
                      u'new', ['text\n', 'contents\n'],
245
 
                      output)
246
 
        self.assertEqual('', output.getvalue())
247
 
 
248
218
    def test_internal_diff_returns_bytes(self):
249
219
        import StringIO
250
220
        output = StringIO.StringIO()
355
325
+file2 contents at rev 3
356
326
 
357
327
''')
358
 
 
 
328
        
359
329
    def test_diff_add_files(self):
360
 
        tree1 = self.b.repository.revision_tree(_mod_revision.NULL_REVISION)
 
330
        tree1 = self.b.repository.revision_tree(None)
361
331
        tree2 = self.b.repository.revision_tree('rev-1')
362
332
        output = self.get_diff(tree1, tree2)
363
333
        # the files have the epoch time stamp for the tree in which
397
367
        self.wt.rename_one('file1', 'file1b')
398
368
        old_tree = self.b.repository.revision_tree('rev-1')
399
369
        new_tree = self.b.repository.revision_tree('rev-4')
400
 
        out = self.get_diff(old_tree, new_tree, specific_files=['file1b'],
 
370
        out = self.get_diff(old_tree, new_tree, specific_files=['file1b'], 
401
371
                            working_tree=self.wt)
402
372
        self.assertContainsRe(out, 'file1\t')
403
373
 
409
379
        self.wt.rename_one('file1', 'dir1/file1')
410
380
        old_tree = self.b.repository.revision_tree('rev-1')
411
381
        new_tree = self.b.repository.revision_tree('rev-4')
412
 
        out = self.get_diff(old_tree, new_tree, specific_files=['dir1'],
 
382
        out = self.get_diff(old_tree, new_tree, specific_files=['dir1'], 
413
383
                            working_tree=self.wt)
414
384
        self.assertContainsRe(out, 'file1\t')
415
 
        out = self.get_diff(old_tree, new_tree, specific_files=['dir2'],
 
385
        out = self.get_diff(old_tree, new_tree, specific_files=['dir2'], 
416
386
                            working_tree=self.wt)
417
387
        self.assertNotContainsRe(out, 'file1\t')
418
388
 
500
470
        self.assertContainsRe(diff, '-contents\n'
501
471
                                    '\\+new contents\n')
502
472
 
503
 
 
504
 
    def test_internal_diff_exec_property(self):
505
 
        tree = self.make_branch_and_tree('tree')
506
 
 
507
 
        tt = transform.TreeTransform(tree)
508
 
        tt.new_file('a', tt.root, 'contents\n', 'a-id', True)
509
 
        tt.new_file('b', tt.root, 'contents\n', 'b-id', False)
510
 
        tt.new_file('c', tt.root, 'contents\n', 'c-id', True)
511
 
        tt.new_file('d', tt.root, 'contents\n', 'd-id', False)
512
 
        tt.new_file('e', tt.root, 'contents\n', 'control-e-id', True)
513
 
        tt.new_file('f', tt.root, 'contents\n', 'control-f-id', False)
514
 
        tt.apply()
515
 
        tree.commit('one', rev_id='rev-1')
516
 
 
517
 
        tt = transform.TreeTransform(tree)
518
 
        tt.set_executability(False, tt.trans_id_file_id('a-id'))
519
 
        tt.set_executability(True, tt.trans_id_file_id('b-id'))
520
 
        tt.set_executability(False, tt.trans_id_file_id('c-id'))
521
 
        tt.set_executability(True, tt.trans_id_file_id('d-id'))
522
 
        tt.apply()
523
 
        tree.rename_one('c', 'new-c')
524
 
        tree.rename_one('d', 'new-d')
525
 
 
526
 
        diff = self.get_diff(tree.basis_tree(), tree)
527
 
 
528
 
        self.assertContainsRe(diff, r"file 'a'.*\(properties changed:.*\+x to -x.*\)")
529
 
        self.assertContainsRe(diff, r"file 'b'.*\(properties changed:.*-x to \+x.*\)")
530
 
        self.assertContainsRe(diff, r"file 'c'.*\(properties changed:.*\+x to -x.*\)")
531
 
        self.assertContainsRe(diff, r"file 'd'.*\(properties changed:.*-x to \+x.*\)")
532
 
        self.assertNotContainsRe(diff, r"file 'e'")
533
 
        self.assertNotContainsRe(diff, r"file 'f'")
534
 
 
535
 
 
536
473
    def test_binary_unicode_filenames(self):
537
474
        """Test that contents of files are *not* encoded in UTF-8 when there
538
475
        is a binary file in the diff.
539
476
        """
540
477
        # See https://bugs.launchpad.net/bugs/110092.
541
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
478
        self.requireFeature(UnicodeFilename)
542
479
 
543
480
        # This bug isn't triggered with cStringIO.
544
481
        from StringIO import StringIO
561
498
        self.assertContainsRe(diff, r"--- a/%s" % (omega_utf8,))
562
499
        self.assertContainsRe(diff, r"\+\+\+ b/%s" % (omega_utf8,))
563
500
 
564
 
    def test_unicode_filename(self):
565
 
        """Test when the filename are unicode."""
566
 
        self.requireFeature(tests.UnicodeFilenameFeature)
567
 
 
568
 
        alpha, omega = u'\u03b1', u'\u03c9'
569
 
        autf8, outf8 = alpha.encode('utf8'), omega.encode('utf8')
570
 
 
571
 
        tree = self.make_branch_and_tree('tree')
572
 
        self.build_tree_contents([('tree/ren_'+alpha, 'contents\n')])
573
 
        tree.add(['ren_'+alpha], ['file-id-2'])
574
 
        self.build_tree_contents([('tree/del_'+alpha, 'contents\n')])
575
 
        tree.add(['del_'+alpha], ['file-id-3'])
576
 
        self.build_tree_contents([('tree/mod_'+alpha, 'contents\n')])
577
 
        tree.add(['mod_'+alpha], ['file-id-4'])
578
 
 
579
 
        tree.commit('one', rev_id='rev-1')
580
 
 
581
 
        tree.rename_one('ren_'+alpha, 'ren_'+omega)
582
 
        tree.remove('del_'+alpha)
583
 
        self.build_tree_contents([('tree/add_'+alpha, 'contents\n')])
584
 
        tree.add(['add_'+alpha], ['file-id'])
585
 
        self.build_tree_contents([('tree/mod_'+alpha, 'contents_mod\n')])
586
 
 
587
 
        diff = self.get_diff(tree.basis_tree(), tree)
588
 
        self.assertContainsRe(diff,
589
 
                "=== renamed file 'ren_%s' => 'ren_%s'\n"%(autf8, outf8))
590
 
        self.assertContainsRe(diff, "=== added file 'add_%s'"%autf8)
591
 
        self.assertContainsRe(diff, "=== modified file 'mod_%s'"%autf8)
592
 
        self.assertContainsRe(diff, "=== removed file 'del_%s'"%autf8)
593
 
 
594
 
 
595
 
class DiffWasIs(DiffPath):
596
 
 
597
 
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
598
 
        self.to_file.write('was: ')
599
 
        self.to_file.write(self.old_tree.get_file(file_id).read())
600
 
        self.to_file.write('is: ')
601
 
        self.to_file.write(self.new_tree.get_file(file_id).read())
602
 
        pass
603
 
 
604
 
 
605
 
class TestDiffTree(TestCaseWithTransport):
606
 
 
607
 
    def setUp(self):
608
 
        TestCaseWithTransport.setUp(self)
609
 
        self.old_tree = self.make_branch_and_tree('old-tree')
610
 
        self.old_tree.lock_write()
611
 
        self.addCleanup(self.old_tree.unlock)
612
 
        self.new_tree = self.make_branch_and_tree('new-tree')
613
 
        self.new_tree.lock_write()
614
 
        self.addCleanup(self.new_tree.unlock)
615
 
        self.differ = DiffTree(self.old_tree, self.new_tree, StringIO())
616
 
 
617
 
    def test_diff_text(self):
618
 
        self.build_tree_contents([('old-tree/olddir/',),
619
 
                                  ('old-tree/olddir/oldfile', 'old\n')])
620
 
        self.old_tree.add('olddir')
621
 
        self.old_tree.add('olddir/oldfile', 'file-id')
622
 
        self.build_tree_contents([('new-tree/newdir/',),
623
 
                                  ('new-tree/newdir/newfile', 'new\n')])
624
 
        self.new_tree.add('newdir')
625
 
        self.new_tree.add('newdir/newfile', 'file-id')
626
 
        differ = DiffText(self.old_tree, self.new_tree, StringIO())
627
 
        differ.diff_text('file-id', None, 'old label', 'new label')
628
 
        self.assertEqual(
629
 
            '--- old label\n+++ new label\n@@ -1,1 +0,0 @@\n-old\n\n',
630
 
            differ.to_file.getvalue())
631
 
        differ.to_file.seek(0)
632
 
        differ.diff_text(None, 'file-id', 'old label', 'new label')
633
 
        self.assertEqual(
634
 
            '--- old label\n+++ new label\n@@ -0,0 +1,1 @@\n+new\n\n',
635
 
            differ.to_file.getvalue())
636
 
        differ.to_file.seek(0)
637
 
        differ.diff_text('file-id', 'file-id', 'old label', 'new label')
638
 
        self.assertEqual(
639
 
            '--- old label\n+++ new label\n@@ -1,1 +1,1 @@\n-old\n+new\n\n',
640
 
            differ.to_file.getvalue())
641
 
 
642
 
    def test_diff_deletion(self):
643
 
        self.build_tree_contents([('old-tree/file', 'contents'),
644
 
                                  ('new-tree/file', 'contents')])
645
 
        self.old_tree.add('file', 'file-id')
646
 
        self.new_tree.add('file', 'file-id')
647
 
        os.unlink('new-tree/file')
648
 
        self.differ.show_diff(None)
649
 
        self.assertContainsRe(self.differ.to_file.getvalue(), '-contents')
650
 
 
651
 
    def test_diff_creation(self):
652
 
        self.build_tree_contents([('old-tree/file', 'contents'),
653
 
                                  ('new-tree/file', 'contents')])
654
 
        self.old_tree.add('file', 'file-id')
655
 
        self.new_tree.add('file', 'file-id')
656
 
        os.unlink('old-tree/file')
657
 
        self.differ.show_diff(None)
658
 
        self.assertContainsRe(self.differ.to_file.getvalue(), '\+contents')
659
 
 
660
 
    def test_diff_symlink(self):
661
 
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
662
 
        differ.diff_symlink('old target', None)
663
 
        self.assertEqual("=== target was 'old target'\n",
664
 
                         differ.to_file.getvalue())
665
 
 
666
 
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
667
 
        differ.diff_symlink(None, 'new target')
668
 
        self.assertEqual("=== target is 'new target'\n",
669
 
                         differ.to_file.getvalue())
670
 
 
671
 
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
672
 
        differ.diff_symlink('old target', 'new target')
673
 
        self.assertEqual("=== target changed 'old target' => 'new target'\n",
674
 
                         differ.to_file.getvalue())
675
 
 
676
 
    def test_diff(self):
677
 
        self.build_tree_contents([('old-tree/olddir/',),
678
 
                                  ('old-tree/olddir/oldfile', 'old\n')])
679
 
        self.old_tree.add('olddir')
680
 
        self.old_tree.add('olddir/oldfile', 'file-id')
681
 
        self.build_tree_contents([('new-tree/newdir/',),
682
 
                                  ('new-tree/newdir/newfile', 'new\n')])
683
 
        self.new_tree.add('newdir')
684
 
        self.new_tree.add('newdir/newfile', 'file-id')
685
 
        self.differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
686
 
        self.assertContainsRe(
687
 
            self.differ.to_file.getvalue(),
688
 
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
689
 
             ' \@\@\n-old\n\+new\n\n')
690
 
 
691
 
    def test_diff_kind_change(self):
692
 
        self.requireFeature(tests.SymlinkFeature)
693
 
        self.build_tree_contents([('old-tree/olddir/',),
694
 
                                  ('old-tree/olddir/oldfile', 'old\n')])
695
 
        self.old_tree.add('olddir')
696
 
        self.old_tree.add('olddir/oldfile', 'file-id')
697
 
        self.build_tree(['new-tree/newdir/'])
698
 
        os.symlink('new', 'new-tree/newdir/newfile')
699
 
        self.new_tree.add('newdir')
700
 
        self.new_tree.add('newdir/newfile', 'file-id')
701
 
        self.differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
702
 
        self.assertContainsRe(
703
 
            self.differ.to_file.getvalue(),
704
 
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+0,0'
705
 
             ' \@\@\n-old\n\n')
706
 
        self.assertContainsRe(self.differ.to_file.getvalue(),
707
 
                              "=== target is u'new'\n")
708
 
 
709
 
    def test_diff_directory(self):
710
 
        self.build_tree(['new-tree/new-dir/'])
711
 
        self.new_tree.add('new-dir', 'new-dir-id')
712
 
        self.differ.diff('new-dir-id', None, 'new-dir')
713
 
        self.assertEqual(self.differ.to_file.getvalue(), '')
714
 
 
715
 
    def create_old_new(self):
716
 
        self.build_tree_contents([('old-tree/olddir/',),
717
 
                                  ('old-tree/olddir/oldfile', 'old\n')])
718
 
        self.old_tree.add('olddir')
719
 
        self.old_tree.add('olddir/oldfile', 'file-id')
720
 
        self.build_tree_contents([('new-tree/newdir/',),
721
 
                                  ('new-tree/newdir/newfile', 'new\n')])
722
 
        self.new_tree.add('newdir')
723
 
        self.new_tree.add('newdir/newfile', 'file-id')
724
 
 
725
 
    def test_register_diff(self):
726
 
        self.create_old_new()
727
 
        old_diff_factories = DiffTree.diff_factories
728
 
        DiffTree.diff_factories=old_diff_factories[:]
729
 
        DiffTree.diff_factories.insert(0, DiffWasIs.from_diff_tree)
730
 
        try:
731
 
            differ = DiffTree(self.old_tree, self.new_tree, StringIO())
732
 
        finally:
733
 
            DiffTree.diff_factories = old_diff_factories
734
 
        differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
735
 
        self.assertNotContainsRe(
736
 
            differ.to_file.getvalue(),
737
 
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
738
 
             ' \@\@\n-old\n\+new\n\n')
739
 
        self.assertContainsRe(differ.to_file.getvalue(),
740
 
                              'was: old\nis: new\n')
741
 
 
742
 
    def test_extra_factories(self):
743
 
        self.create_old_new()
744
 
        differ = DiffTree(self.old_tree, self.new_tree, StringIO(),
745
 
                            extra_factories=[DiffWasIs.from_diff_tree])
746
 
        differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
747
 
        self.assertNotContainsRe(
748
 
            differ.to_file.getvalue(),
749
 
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
750
 
             ' \@\@\n-old\n\+new\n\n')
751
 
        self.assertContainsRe(differ.to_file.getvalue(),
752
 
                              'was: old\nis: new\n')
753
 
 
754
 
    def test_alphabetical_order(self):
755
 
        self.build_tree(['new-tree/a-file'])
756
 
        self.new_tree.add('a-file')
757
 
        self.build_tree(['old-tree/b-file'])
758
 
        self.old_tree.add('b-file')
759
 
        self.differ.show_diff(None)
760
 
        self.assertContainsRe(self.differ.to_file.getvalue(),
761
 
            '.*a-file(.|\n)*b-file')
762
 
 
763
501
 
764
502
class TestPatienceDiffLib(TestCase):
765
503
 
766
 
    def setUp(self):
767
 
        super(TestPatienceDiffLib, self).setUp()
768
 
        self._unique_lcs = bzrlib._patiencediff_py.unique_lcs_py
769
 
        self._recurse_matches = bzrlib._patiencediff_py.recurse_matches_py
770
 
        self._PatienceSequenceMatcher = \
771
 
            bzrlib._patiencediff_py.PatienceSequenceMatcher_py
772
 
 
773
 
    def test_diff_unicode_string(self):
774
 
        a = ''.join([unichr(i) for i in range(4000, 4500, 3)])
775
 
        b = ''.join([unichr(i) for i in range(4300, 4800, 2)])
776
 
        sm = self._PatienceSequenceMatcher(None, a, b)
777
 
        mb = sm.get_matching_blocks()
778
 
        self.assertEquals(35, len(mb))
779
 
 
780
504
    def test_unique_lcs(self):
781
 
        unique_lcs = self._unique_lcs
 
505
        unique_lcs = bzrlib.patiencediff.unique_lcs
782
506
        self.assertEquals(unique_lcs('', ''), [])
783
 
        self.assertEquals(unique_lcs('', 'a'), [])
784
 
        self.assertEquals(unique_lcs('a', ''), [])
785
507
        self.assertEquals(unique_lcs('a', 'a'), [(0,0)])
786
508
        self.assertEquals(unique_lcs('a', 'b'), [])
787
509
        self.assertEquals(unique_lcs('ab', 'ab'), [(0,0), (1,1)])
788
510
        self.assertEquals(unique_lcs('abcde', 'cdeab'), [(2,0), (3,1), (4,2)])
789
511
        self.assertEquals(unique_lcs('cdeab', 'abcde'), [(0,2), (1,3), (2,4)])
790
 
        self.assertEquals(unique_lcs('abXde', 'abYde'), [(0,0), (1,1),
 
512
        self.assertEquals(unique_lcs('abXde', 'abYde'), [(0,0), (1,1), 
791
513
                                                         (3,3), (4,4)])
792
514
        self.assertEquals(unique_lcs('acbac', 'abc'), [(2,1)])
793
515
 
794
516
    def test_recurse_matches(self):
795
517
        def test_one(a, b, matches):
796
518
            test_matches = []
797
 
            self._recurse_matches(
798
 
                a, b, 0, 0, len(a), len(b), test_matches, 10)
 
519
            bzrlib.patiencediff.recurse_matches(a, b, 0, 0, len(a), len(b),
 
520
                test_matches, 10)
799
521
            self.assertEquals(test_matches, matches)
800
522
 
801
523
        test_one(['a', '', 'b', '', 'c'], ['a', 'a', 'b', 'c', 'c'],
802
524
                 [(0, 0), (2, 2), (4, 4)])
803
525
        test_one(['a', 'c', 'b', 'a', 'c'], ['a', 'b', 'c'],
804
526
                 [(0, 0), (2, 1), (4, 2)])
805
 
        # Even though 'bc' is not unique globally, and is surrounded by
806
 
        # non-matching lines, we should still match, because they are locally
807
 
        # unique
808
 
        test_one('abcdbce', 'afbcgdbce', [(0,0), (1, 2), (2, 3), (3, 5),
809
 
                                          (4, 6), (5, 7), (6, 8)])
810
527
 
811
 
        # recurse_matches doesn't match non-unique
 
528
        # recurse_matches doesn't match non-unique 
812
529
        # lines surrounded by bogus text.
813
530
        # The update has been done in patiencediff.SequenceMatcher instead
814
531
 
818
535
        # This is what it currently gives:
819
536
        test_one('aBccDe', 'abccde', [(0,0), (5,5)])
820
537
 
821
 
    def assertDiffBlocks(self, a, b, expected_blocks):
822
 
        """Check that the sequence matcher returns the correct blocks.
823
 
 
824
 
        :param a: A sequence to match
825
 
        :param b: Another sequence to match
826
 
        :param expected_blocks: The expected output, not including the final
827
 
            matching block (len(a), len(b), 0)
828
 
        """
829
 
        matcher = self._PatienceSequenceMatcher(None, a, b)
830
 
        blocks = matcher.get_matching_blocks()
831
 
        last = blocks.pop()
832
 
        self.assertEqual((len(a), len(b), 0), last)
833
 
        self.assertEqual(expected_blocks, blocks)
834
 
 
835
538
    def test_matching_blocks(self):
 
539
        def chk_blocks(a, b, expected_blocks):
 
540
            # difflib always adds a signature of the total
 
541
            # length, with no matching entries at the end
 
542
            s = bzrlib.patiencediff.PatienceSequenceMatcher(None, a, b)
 
543
            blocks = s.get_matching_blocks()
 
544
            self.assertEquals((len(a), len(b), 0), blocks[-1])
 
545
            self.assertEquals(expected_blocks, blocks[:-1])
 
546
 
836
547
        # Some basic matching tests
837
 
        self.assertDiffBlocks('', '', [])
838
 
        self.assertDiffBlocks([], [], [])
839
 
        self.assertDiffBlocks('abc', '', [])
840
 
        self.assertDiffBlocks('', 'abc', [])
841
 
        self.assertDiffBlocks('abcd', 'abcd', [(0, 0, 4)])
842
 
        self.assertDiffBlocks('abcd', 'abce', [(0, 0, 3)])
843
 
        self.assertDiffBlocks('eabc', 'abce', [(1, 0, 3)])
844
 
        self.assertDiffBlocks('eabce', 'abce', [(1, 0, 4)])
845
 
        self.assertDiffBlocks('abcde', 'abXde', [(0, 0, 2), (3, 3, 2)])
846
 
        self.assertDiffBlocks('abcde', 'abXYZde', [(0, 0, 2), (3, 5, 2)])
847
 
        self.assertDiffBlocks('abde', 'abXYZde', [(0, 0, 2), (2, 5, 2)])
848
 
        # This may check too much, but it checks to see that
 
548
        chk_blocks('', '', [])
 
549
        chk_blocks([], [], [])
 
550
        chk_blocks('abcd', 'abcd', [(0, 0, 4)])
 
551
        chk_blocks('abcd', 'abce', [(0, 0, 3)])
 
552
        chk_blocks('eabc', 'abce', [(1, 0, 3)])
 
553
        chk_blocks('eabce', 'abce', [(1, 0, 4)])
 
554
        chk_blocks('abcde', 'abXde', [(0, 0, 2), (3, 3, 2)])
 
555
        chk_blocks('abcde', 'abXYZde', [(0, 0, 2), (3, 5, 2)])
 
556
        chk_blocks('abde', 'abXYZde', [(0, 0, 2), (2, 5, 2)])
 
557
        # This may check too much, but it checks to see that 
849
558
        # a copied block stays attached to the previous section,
850
559
        # not the later one.
851
560
        # difflib would tend to grab the trailing longest match
852
561
        # which would make the diff not look right
853
 
        self.assertDiffBlocks('abcdefghijklmnop', 'abcdefxydefghijklmnop',
854
 
                              [(0, 0, 6), (6, 11, 10)])
 
562
        chk_blocks('abcdefghijklmnop', 'abcdefxydefghijklmnop',
 
563
                   [(0, 0, 6), (6, 11, 10)])
855
564
 
856
565
        # make sure it supports passing in lists
857
 
        self.assertDiffBlocks(
 
566
        chk_blocks(
858
567
                   ['hello there\n',
859
568
                    'world\n',
860
569
                    'how are you today?\n'],
864
573
 
865
574
        # non unique lines surrounded by non-matching lines
866
575
        # won't be found
867
 
        self.assertDiffBlocks('aBccDe', 'abccde', [(0,0,1), (5,5,1)])
 
576
        chk_blocks('aBccDe', 'abccde', [(0,0,1), (5,5,1)])
868
577
 
869
578
        # But they only need to be locally unique
870
 
        self.assertDiffBlocks('aBcDec', 'abcdec', [(0,0,1), (2,2,1), (4,4,2)])
 
579
        chk_blocks('aBcDec', 'abcdec', [(0,0,1), (2,2,1), (4,4,2)])
871
580
 
872
581
        # non unique blocks won't be matched
873
 
        self.assertDiffBlocks('aBcdEcdFg', 'abcdecdfg', [(0,0,1), (8,8,1)])
 
582
        chk_blocks('aBcdEcdFg', 'abcdecdfg', [(0,0,1), (8,8,1)])
874
583
 
875
584
        # but locally unique ones will
876
 
        self.assertDiffBlocks('aBcdEeXcdFg', 'abcdecdfg', [(0,0,1), (2,2,2),
 
585
        chk_blocks('aBcdEeXcdFg', 'abcdecdfg', [(0,0,1), (2,2,2),
877
586
                                              (5,4,1), (7,5,2), (10,8,1)])
878
587
 
879
 
        self.assertDiffBlocks('abbabbXd', 'cabbabxd', [(7,7,1)])
880
 
        self.assertDiffBlocks('abbabbbb', 'cabbabbc', [])
881
 
        self.assertDiffBlocks('bbbbbbbb', 'cbbbbbbc', [])
882
 
 
883
 
    def test_matching_blocks_tuples(self):
884
 
        # Some basic matching tests
885
 
        self.assertDiffBlocks([], [], [])
886
 
        self.assertDiffBlocks([('a',), ('b',), ('c,')], [], [])
887
 
        self.assertDiffBlocks([], [('a',), ('b',), ('c,')], [])
888
 
        self.assertDiffBlocks([('a',), ('b',), ('c,')],
889
 
                              [('a',), ('b',), ('c,')],
890
 
                              [(0, 0, 3)])
891
 
        self.assertDiffBlocks([('a',), ('b',), ('c,')],
892
 
                              [('a',), ('b',), ('d,')],
893
 
                              [(0, 0, 2)])
894
 
        self.assertDiffBlocks([('d',), ('b',), ('c,')],
895
 
                              [('a',), ('b',), ('c,')],
896
 
                              [(1, 1, 2)])
897
 
        self.assertDiffBlocks([('d',), ('a',), ('b',), ('c,')],
898
 
                              [('a',), ('b',), ('c,')],
899
 
                              [(1, 0, 3)])
900
 
        self.assertDiffBlocks([('a', 'b'), ('c', 'd'), ('e', 'f')],
901
 
                              [('a', 'b'), ('c', 'X'), ('e', 'f')],
902
 
                              [(0, 0, 1), (2, 2, 1)])
903
 
        self.assertDiffBlocks([('a', 'b'), ('c', 'd'), ('e', 'f')],
904
 
                              [('a', 'b'), ('c', 'dX'), ('e', 'f')],
905
 
                              [(0, 0, 1), (2, 2, 1)])
 
588
        chk_blocks('abbabbXd', 'cabbabxd', [(7,7,1)])
 
589
        chk_blocks('abbabbbb', 'cabbabbc', [])
 
590
        chk_blocks('bbbbbbbb', 'cbbbbbbc', [])
906
591
 
907
592
    def test_opcodes(self):
908
593
        def chk_ops(a, b, expected_codes):
909
 
            s = self._PatienceSequenceMatcher(None, a, b)
 
594
            s = bzrlib.patiencediff.PatienceSequenceMatcher(None, a, b)
910
595
            self.assertEquals(expected_codes, s.get_opcodes())
911
596
 
912
597
        chk_ops('', '', [])
913
598
        chk_ops([], [], [])
914
 
        chk_ops('abc', '', [('delete', 0,3, 0,0)])
915
 
        chk_ops('', 'abc', [('insert', 0,0, 0,3)])
916
599
        chk_ops('abcd', 'abcd', [('equal',    0,4, 0,4)])
917
600
        chk_ops('abcd', 'abce', [('equal',   0,3, 0,3),
918
601
                                 ('replace', 3,4, 3,4)
951
634
                 ('delete', 1,2, 1,1),
952
635
                 ('equal',  2,3, 1,2),
953
636
                ])
954
 
        chk_ops('aBccDe', 'abccde',
 
637
        chk_ops('aBccDe', 'abccde', 
955
638
                [('equal',   0,1, 0,1),
956
639
                 ('replace', 1,5, 1,5),
957
640
                 ('equal',   5,6, 5,6),
958
641
                ])
959
 
        chk_ops('aBcDec', 'abcdec',
 
642
        chk_ops('aBcDec', 'abcdec', 
960
643
                [('equal',   0,1, 0,1),
961
644
                 ('replace', 1,2, 1,2),
962
645
                 ('equal',   2,3, 2,3),
963
646
                 ('replace', 3,4, 3,4),
964
647
                 ('equal',   4,6, 4,6),
965
648
                ])
966
 
        chk_ops('aBcdEcdFg', 'abcdecdfg',
 
649
        chk_ops('aBcdEcdFg', 'abcdecdfg', 
967
650
                [('equal',   0,1, 0,1),
968
651
                 ('replace', 1,8, 1,8),
969
652
                 ('equal',   8,9, 8,9)
970
653
                ])
971
 
        chk_ops('aBcdEeXcdFg', 'abcdecdfg',
 
654
        chk_ops('aBcdEeXcdFg', 'abcdecdfg', 
972
655
                [('equal',   0,1, 0,1),
973
656
                 ('replace', 1,2, 1,2),
974
657
                 ('equal',   2,4, 2,4),
980
663
                 ('equal',   10,11, 8,9)
981
664
                ])
982
665
 
983
 
    def test_grouped_opcodes(self):
984
 
        def chk_ops(a, b, expected_codes, n=3):
985
 
            s = self._PatienceSequenceMatcher(None, a, b)
986
 
            self.assertEquals(expected_codes, list(s.get_grouped_opcodes(n)))
987
 
 
988
 
        chk_ops('', '', [])
989
 
        chk_ops([], [], [])
990
 
        chk_ops('abc', '', [[('delete', 0,3, 0,0)]])
991
 
        chk_ops('', 'abc', [[('insert', 0,0, 0,3)]])
992
 
        chk_ops('abcd', 'abcd', [])
993
 
        chk_ops('abcd', 'abce', [[('equal',   0,3, 0,3),
994
 
                                  ('replace', 3,4, 3,4)
995
 
                                 ]])
996
 
        chk_ops('eabc', 'abce', [[('delete', 0,1, 0,0),
997
 
                                 ('equal',  1,4, 0,3),
998
 
                                 ('insert', 4,4, 3,4)
999
 
                                ]])
1000
 
        chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
1001
 
                [[('equal',  3,6, 3,6),
1002
 
                  ('insert', 6,6, 6,11),
1003
 
                  ('equal',  6,9, 11,14)
1004
 
                  ]])
1005
 
        chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
1006
 
                [[('equal',  2,6, 2,6),
1007
 
                  ('insert', 6,6, 6,11),
1008
 
                  ('equal',  6,10, 11,15)
1009
 
                  ]], 4)
1010
 
        chk_ops('Xabcdef', 'abcdef',
1011
 
                [[('delete', 0,1, 0,0),
1012
 
                  ('equal',  1,4, 0,3)
1013
 
                  ]])
1014
 
        chk_ops('abcdef', 'abcdefX',
1015
 
                [[('equal',  3,6, 3,6),
1016
 
                  ('insert', 6,6, 6,7)
1017
 
                  ]])
1018
 
 
1019
 
 
1020
666
    def test_multiple_ranges(self):
1021
667
        # There was an earlier bug where we used a bad set of ranges,
1022
668
        # this triggers that specific bug, to make sure it doesn't regress
1023
 
        self.assertDiffBlocks('abcdefghijklmnop',
1024
 
                              'abcXghiYZQRSTUVWXYZijklmnop',
1025
 
                              [(0, 0, 3), (6, 4, 3), (9, 20, 7)])
1026
 
 
1027
 
        self.assertDiffBlocks('ABCd efghIjk  L',
1028
 
                              'AxyzBCn mo pqrstuvwI1 2  L',
1029
 
                              [(0,0,1), (1, 4, 2), (9, 19, 1), (12, 23, 3)])
 
669
        def chk_blocks(a, b, expected_blocks):
 
670
            # difflib always adds a signature of the total
 
671
            # length, with no matching entries at the end
 
672
            s = bzrlib.patiencediff.PatienceSequenceMatcher(None, a, b)
 
673
            blocks = s.get_matching_blocks()
 
674
            x = blocks.pop()
 
675
            self.assertEquals(x, (len(a), len(b), 0))
 
676
            self.assertEquals(expected_blocks, blocks)
 
677
 
 
678
        chk_blocks('abcdefghijklmnop'
 
679
                 , 'abcXghiYZQRSTUVWXYZijklmnop'
 
680
                 , [(0, 0, 3), (6, 4, 3), (9, 20, 7)])
 
681
 
 
682
        chk_blocks('ABCd efghIjk  L'
 
683
                 , 'AxyzBCn mo pqrstuvwI1 2  L'
 
684
                 , [(0,0,1), (1, 4, 2), (9, 19, 1), (12, 23, 3)])
1030
685
 
1031
686
        # These are rot13 code snippets.
1032
 
        self.assertDiffBlocks('''\
 
687
        chk_blocks('''\
1033
688
    trg nqqrq jura lbh nqq n svyr va gur qverpgbel.
1034
689
    """
1035
690
    gnxrf_netf = ['svyr*']
1036
691
    gnxrf_bcgvbaf = ['ab-erphefr']
1037
 
 
 
692
  
1038
693
    qrs eha(frys, svyr_yvfg, ab_erphefr=Snyfr):
1039
694
        sebz omeyvo.nqq vzcbeg fzneg_nqq, nqq_ercbegre_cevag, nqq_ercbegre_ahyy
1040
695
        vs vf_dhvrg():
1048
703
'''.splitlines(True), '''\
1049
704
    trg nqqrq jura lbh nqq n svyr va gur qverpgbel.
1050
705
 
1051
 
    --qel-eha jvyy fubj juvpu svyrf jbhyq or nqqrq, ohg abg npghnyyl
 
706
    --qel-eha jvyy fubj juvpu svyrf jbhyq or nqqrq, ohg abg npghnyyl 
1052
707
    nqq gurz.
1053
708
    """
1054
709
    gnxrf_netf = ['svyr*']
1082
737
        txt_b = ['hello there\n',
1083
738
                 'how are you today?\n']
1084
739
        unified_diff = bzrlib.patiencediff.unified_diff
1085
 
        psm = self._PatienceSequenceMatcher
1086
 
        self.assertEquals(['--- \n',
1087
 
                           '+++ \n',
 
740
        psm = bzrlib.patiencediff.PatienceSequenceMatcher
 
741
        self.assertEquals([ '---  \n',
 
742
                           '+++  \n',
1088
743
                           '@@ -1,3 +1,2 @@\n',
1089
744
                           ' hello there\n',
1090
745
                           '-world\n',
1095
750
        txt_a = map(lambda x: x+'\n', 'abcdefghijklmnop')
1096
751
        txt_b = map(lambda x: x+'\n', 'abcdefxydefghijklmnop')
1097
752
        # This is the result with LongestCommonSubstring matching
1098
 
        self.assertEquals(['--- \n',
1099
 
                           '+++ \n',
 
753
        self.assertEquals(['---  \n',
 
754
                           '+++  \n',
1100
755
                           '@@ -1,6 +1,11 @@\n',
1101
756
                           ' a\n',
1102
757
                           ' b\n',
1111
766
                           ' f\n']
1112
767
                          , list(unified_diff(txt_a, txt_b)))
1113
768
        # And the patience diff
1114
 
        self.assertEquals(['--- \n',
1115
 
                           '+++ \n',
 
769
        self.assertEquals(['---  \n',
 
770
                           '+++  \n',
1116
771
                           '@@ -4,6 +4,11 @@\n',
1117
772
                           ' d\n',
1118
773
                           ' e\n',
1129
784
                          , list(unified_diff(txt_a, txt_b,
1130
785
                                 sequencematcher=psm)))
1131
786
 
1132
 
    def test_patience_unified_diff_with_dates(self):
1133
 
        txt_a = ['hello there\n',
1134
 
                 'world\n',
1135
 
                 'how are you today?\n']
1136
 
        txt_b = ['hello there\n',
1137
 
                 'how are you today?\n']
1138
 
        unified_diff = bzrlib.patiencediff.unified_diff
1139
 
        psm = self._PatienceSequenceMatcher
1140
 
        self.assertEquals(['--- a\t2008-08-08\n',
1141
 
                           '+++ b\t2008-09-09\n',
1142
 
                           '@@ -1,3 +1,2 @@\n',
1143
 
                           ' hello there\n',
1144
 
                           '-world\n',
1145
 
                           ' how are you today?\n'
1146
 
                          ]
1147
 
                          , list(unified_diff(txt_a, txt_b,
1148
 
                                 fromfile='a', tofile='b',
1149
 
                                 fromfiledate='2008-08-08',
1150
 
                                 tofiledate='2008-09-09',
1151
 
                                 sequencematcher=psm)))
1152
 
 
1153
 
 
1154
 
class TestPatienceDiffLib_c(TestPatienceDiffLib):
1155
 
 
1156
 
    _test_needs_features = [CompiledPatienceDiffFeature]
1157
 
 
1158
 
    def setUp(self):
1159
 
        super(TestPatienceDiffLib_c, self).setUp()
1160
 
        import bzrlib._patiencediff_c
1161
 
        self._unique_lcs = bzrlib._patiencediff_c.unique_lcs_c
1162
 
        self._recurse_matches = bzrlib._patiencediff_c.recurse_matches_c
1163
 
        self._PatienceSequenceMatcher = \
1164
 
            bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1165
 
 
1166
 
    def test_unhashable(self):
1167
 
        """We should get a proper exception here."""
1168
 
        # We need to be able to hash items in the sequence, lists are
1169
 
        # unhashable, and thus cannot be diffed
1170
 
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1171
 
                                         None, [[]], [])
1172
 
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1173
 
                                         None, ['valid', []], [])
1174
 
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1175
 
                                         None, ['valid'], [[]])
1176
 
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1177
 
                                         None, ['valid'], ['valid', []])
1178
 
 
1179
787
 
1180
788
class TestPatienceDiffLibFiles(TestCaseInTempDir):
1181
789
 
1182
 
    def setUp(self):
1183
 
        super(TestPatienceDiffLibFiles, self).setUp()
1184
 
        self._PatienceSequenceMatcher = \
1185
 
            bzrlib._patiencediff_py.PatienceSequenceMatcher_py
1186
 
 
1187
790
    def test_patience_unified_diff_files(self):
1188
791
        txt_a = ['hello there\n',
1189
792
                 'world\n',
1194
797
        open('b1', 'wb').writelines(txt_b)
1195
798
 
1196
799
        unified_diff_files = bzrlib.patiencediff.unified_diff_files
1197
 
        psm = self._PatienceSequenceMatcher
1198
 
        self.assertEquals(['--- a1\n',
1199
 
                           '+++ b1\n',
 
800
        psm = bzrlib.patiencediff.PatienceSequenceMatcher
 
801
        self.assertEquals(['--- a1 \n',
 
802
                           '+++ b1 \n',
1200
803
                           '@@ -1,3 +1,2 @@\n',
1201
804
                           ' hello there\n',
1202
805
                           '-world\n',
1211
814
        open('b2', 'wb').writelines(txt_b)
1212
815
 
1213
816
        # This is the result with LongestCommonSubstring matching
1214
 
        self.assertEquals(['--- a2\n',
1215
 
                           '+++ b2\n',
 
817
        self.assertEquals(['--- a2 \n',
 
818
                           '+++ b2 \n',
1216
819
                           '@@ -1,6 +1,11 @@\n',
1217
820
                           ' a\n',
1218
821
                           ' b\n',
1228
831
                          , list(unified_diff_files('a2', 'b2')))
1229
832
 
1230
833
        # And the patience diff
1231
 
        self.assertEquals(['--- a2\n',
1232
 
                           '+++ b2\n',
 
834
        self.assertEquals(['--- a2 \n',
 
835
                           '+++ b2 \n',
1233
836
                           '@@ -4,6 +4,11 @@\n',
1234
837
                           ' d\n',
1235
838
                           ' e\n',
1245
848
                          ]
1246
849
                          , list(unified_diff_files('a2', 'b2',
1247
850
                                 sequencematcher=psm)))
1248
 
 
1249
 
 
1250
 
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
1251
 
 
1252
 
    _test_needs_features = [CompiledPatienceDiffFeature]
1253
 
 
1254
 
    def setUp(self):
1255
 
        super(TestPatienceDiffLibFiles_c, self).setUp()
1256
 
        import bzrlib._patiencediff_c
1257
 
        self._PatienceSequenceMatcher = \
1258
 
            bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1259
 
 
1260
 
 
1261
 
class TestUsingCompiledIfAvailable(TestCase):
1262
 
 
1263
 
    def test_PatienceSequenceMatcher(self):
1264
 
        if CompiledPatienceDiffFeature.available():
1265
 
            from bzrlib._patiencediff_c import PatienceSequenceMatcher_c
1266
 
            self.assertIs(PatienceSequenceMatcher_c,
1267
 
                          bzrlib.patiencediff.PatienceSequenceMatcher)
1268
 
        else:
1269
 
            from bzrlib._patiencediff_py import PatienceSequenceMatcher_py
1270
 
            self.assertIs(PatienceSequenceMatcher_py,
1271
 
                          bzrlib.patiencediff.PatienceSequenceMatcher)
1272
 
 
1273
 
    def test_unique_lcs(self):
1274
 
        if CompiledPatienceDiffFeature.available():
1275
 
            from bzrlib._patiencediff_c import unique_lcs_c
1276
 
            self.assertIs(unique_lcs_c,
1277
 
                          bzrlib.patiencediff.unique_lcs)
1278
 
        else:
1279
 
            from bzrlib._patiencediff_py import unique_lcs_py
1280
 
            self.assertIs(unique_lcs_py,
1281
 
                          bzrlib.patiencediff.unique_lcs)
1282
 
 
1283
 
    def test_recurse_matches(self):
1284
 
        if CompiledPatienceDiffFeature.available():
1285
 
            from bzrlib._patiencediff_c import recurse_matches_c
1286
 
            self.assertIs(recurse_matches_c,
1287
 
                          bzrlib.patiencediff.recurse_matches)
1288
 
        else:
1289
 
            from bzrlib._patiencediff_py import recurse_matches_py
1290
 
            self.assertIs(recurse_matches_py,
1291
 
                          bzrlib.patiencediff.recurse_matches)
1292
 
 
1293
 
 
1294
 
class TestDiffFromTool(TestCaseWithTransport):
1295
 
 
1296
 
    def test_from_string(self):
1297
 
        diff_obj = DiffFromTool.from_string('diff', None, None, None)
1298
 
        self.addCleanup(diff_obj.finish)
1299
 
        self.assertEqual(['diff', '%(old_path)s', '%(new_path)s'],
1300
 
            diff_obj.command_template)
1301
 
 
1302
 
    def test_from_string_u5(self):
1303
 
        diff_obj = DiffFromTool.from_string('diff -u\\ 5', None, None, None)
1304
 
        self.addCleanup(diff_obj.finish)
1305
 
        self.assertEqual(['diff', '-u 5', '%(old_path)s', '%(new_path)s'],
1306
 
                         diff_obj.command_template)
1307
 
        self.assertEqual(['diff', '-u 5', 'old-path', 'new-path'],
1308
 
                         diff_obj._get_command('old-path', 'new-path'))
1309
 
 
1310
 
    def test_execute(self):
1311
 
        output = StringIO()
1312
 
        diff_obj = DiffFromTool(['python', '-c',
1313
 
                                 'print "%(old_path)s %(new_path)s"'],
1314
 
                                None, None, output)
1315
 
        self.addCleanup(diff_obj.finish)
1316
 
        diff_obj._execute('old', 'new')
1317
 
        self.assertEqual(output.getvalue().rstrip(), 'old new')
1318
 
 
1319
 
    def test_excute_missing(self):
1320
 
        diff_obj = DiffFromTool(['a-tool-which-is-unlikely-to-exist'],
1321
 
                                None, None, None)
1322
 
        self.addCleanup(diff_obj.finish)
1323
 
        e = self.assertRaises(ExecutableMissing, diff_obj._execute, 'old',
1324
 
                              'new')
1325
 
        self.assertEqual('a-tool-which-is-unlikely-to-exist could not be found'
1326
 
                         ' on this machine', str(e))
1327
 
 
1328
 
    def test_prepare_files_creates_paths_readable_by_windows_tool(self):
1329
 
        self.requireFeature(AttribFeature)
1330
 
        output = StringIO()
1331
 
        tree = self.make_branch_and_tree('tree')
1332
 
        self.build_tree_contents([('tree/file', 'content')])
1333
 
        tree.add('file', 'file-id')
1334
 
        tree.commit('old tree')
1335
 
        tree.lock_read()
1336
 
        self.addCleanup(tree.unlock)
1337
 
        diff_obj = DiffFromTool(['python', '-c',
1338
 
                                 'print "%(old_path)s %(new_path)s"'],
1339
 
                                tree, tree, output)
1340
 
        diff_obj._prepare_files('file-id', 'file', 'file')
1341
 
        self.assertReadableByAttrib(diff_obj._root, 'old\\file', r'old\\file')
1342
 
        self.assertReadableByAttrib(diff_obj._root, 'new\\file', r'new\\file')
1343
 
 
1344
 
    def assertReadableByAttrib(self, cwd, relpath, regex):
1345
 
        proc = subprocess.Popen(['attrib', relpath],
1346
 
                                stdout=subprocess.PIPE,
1347
 
                                cwd=cwd)
1348
 
        proc.wait()
1349
 
        result = proc.stdout.read()
1350
 
        self.assertContainsRe(result, regex)
1351
 
 
1352
 
    def test_prepare_files(self):
1353
 
        output = StringIO()
1354
 
        tree = self.make_branch_and_tree('tree')
1355
 
        self.build_tree_contents([('tree/oldname', 'oldcontent')])
1356
 
        self.build_tree_contents([('tree/oldname2', 'oldcontent2')])
1357
 
        tree.add('oldname', 'file-id')
1358
 
        tree.add('oldname2', 'file2-id')
1359
 
        tree.commit('old tree', timestamp=0)
1360
 
        tree.rename_one('oldname', 'newname')
1361
 
        tree.rename_one('oldname2', 'newname2')
1362
 
        self.build_tree_contents([('tree/newname', 'newcontent')])
1363
 
        self.build_tree_contents([('tree/newname2', 'newcontent2')])
1364
 
        old_tree = tree.basis_tree()
1365
 
        old_tree.lock_read()
1366
 
        self.addCleanup(old_tree.unlock)
1367
 
        tree.lock_read()
1368
 
        self.addCleanup(tree.unlock)
1369
 
        diff_obj = DiffFromTool(['python', '-c',
1370
 
                                 'print "%(old_path)s %(new_path)s"'],
1371
 
                                old_tree, tree, output)
1372
 
        self.addCleanup(diff_obj.finish)
1373
 
        self.assertContainsRe(diff_obj._root, 'bzr-diff-[^/]*')
1374
 
        old_path, new_path = diff_obj._prepare_files('file-id', 'oldname',
1375
 
                                                     'newname')
1376
 
        self.assertContainsRe(old_path, 'old/oldname$')
1377
 
        self.assertEqual(0, os.stat(old_path).st_mtime)
1378
 
        self.assertContainsRe(new_path, 'new/newname$')
1379
 
        self.assertFileEqual('oldcontent', old_path)
1380
 
        self.assertFileEqual('newcontent', new_path)
1381
 
        if osutils.host_os_dereferences_symlinks():
1382
 
            self.assertTrue(os.path.samefile('tree/newname', new_path))
1383
 
        # make sure we can create files with the same parent directories
1384
 
        diff_obj._prepare_files('file2-id', 'oldname2', 'newname2')