15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
18
from cStringIO import StringIO
23
from tempfile import TemporaryFile
25
from bzrlib import tests
26
from bzrlib.diff import (
28
revision as _mod_revision,
36
from bzrlib.errors import BinaryFile, NoDiff, ExecutableMissing
37
import bzrlib.osutils as osutils
38
import bzrlib.revision as _mod_revision
39
import bzrlib.transform as transform
40
import bzrlib.patiencediff
41
import bzrlib._patiencediff_py
42
from bzrlib.tests import (Feature, TestCase, TestCaseWithTransport,
43
TestCaseInTempDir, TestSkipped)
46
class _AttribFeature(Feature):
49
if (sys.platform not in ('cygwin', 'win32')):
52
proc = subprocess.Popen(['attrib', '.'], stdout=subprocess.PIPE)
55
return (0 == proc.wait())
57
def feature_name(self):
58
return 'attrib Windows command-line tool'
60
AttribFeature = _AttribFeature()
63
class _CompiledPatienceDiffFeature(Feature):
67
import bzrlib._patiencediff_c
72
def feature_name(self):
73
return 'bzrlib._patiencediff_c'
75
CompiledPatienceDiffFeature = _CompiledPatienceDiffFeature()
34
from bzrlib.tests import (
38
from bzrlib.tests.blackbox.test_diff import subst_dates
39
from bzrlib.tests.scenarios import load_tests_apply_scenarios
42
load_tests = load_tests_apply_scenarios
78
45
def udiff_lines(old, new, allow_binary=False):
79
46
output = StringIO()
80
internal_diff('old', old, 'new', new, output, allow_binary)
47
diff.internal_diff('old', old, 'new', new, output, allow_binary)
82
49
return output.readlines()
87
54
# StringIO has no fileno, so it tests a different codepath
88
55
output = StringIO()
90
output = TemporaryFile()
57
output = tempfile.TemporaryFile()
92
external_diff('old', old, 'new', new, output, diff_opts=['-u'])
94
raise TestSkipped('external "diff" not present to test')
59
diff.external_diff('old', old, 'new', new, output, diff_opts=['-u'])
61
raise tests.TestSkipped('external "diff" not present to test')
96
63
lines = output.readlines()
101
class TestDiff(TestCase):
68
class TestDiffOptions(tests.TestCase):
70
def test_unified_added(self):
71
"""Check for default style '-u' only if no other style specified
74
# Verify that style defaults to unified, id est '-u' appended
75
# to option list, in the absence of an alternative style.
76
self.assertEqual(['-a', '-u'], diff.default_style_unified(['-a']))
79
class TestDiffOptionsScenarios(tests.TestCase):
81
scenarios = [(s, dict(style=s)) for s in diff.style_option_list]
82
style = None # Set by load_tests_apply_scenarios from scenarios
84
def test_unified_not_added(self):
85
# Verify that for all valid style options, '-u' is not
86
# appended to option list.
87
ret_opts = diff.default_style_unified(diff_opts=["%s" % (self.style,)])
88
self.assertEqual(["%s" % (self.style,)], ret_opts)
91
class TestDiff(tests.TestCase):
103
93
def test_add_nl(self):
104
94
"""diff generates a valid diff for patches that add a newline"""
105
95
lines = udiff_lines(['boo'], ['boo\n'])
106
96
self.check_patch(lines)
107
self.assertEquals(lines[4], '\\ No newline at end of file\n')
97
self.assertEqual(lines[4], '\\ No newline at end of file\n')
108
98
## "expected no-nl, got %r" % lines[4]
110
100
def test_add_nl_2(self):
123
113
lines = udiff_lines(['boo\n'], ['boo'])
124
114
self.check_patch(lines)
125
self.assertEquals(lines[5], '\\ No newline at end of file\n')
115
self.assertEqual(lines[5], '\\ No newline at end of file\n')
126
116
## "expected no-nl, got %r" % lines[5]
128
118
def check_patch(self, lines):
129
self.assert_(len(lines) > 1)
119
self.assertTrue(len(lines) > 1)
130
120
## "Not enough lines for a file header for patch:\n%s" % "".join(lines)
131
self.assert_(lines[0].startswith ('---'))
121
self.assertTrue(lines[0].startswith ('---'))
132
122
## 'No orig line for patch:\n%s' % "".join(lines)
133
self.assert_(lines[1].startswith ('+++'))
123
self.assertTrue(lines[1].startswith ('+++'))
134
124
## 'No mod line for patch:\n%s' % "".join(lines)
135
self.assert_(len(lines) > 2)
125
self.assertTrue(len(lines) > 2)
136
126
## "No hunks for patch:\n%s" % "".join(lines)
137
self.assert_(lines[2].startswith('@@'))
127
self.assertTrue(lines[2].startswith('@@'))
138
128
## "No hunk header for patch:\n%s" % "".join(lines)
139
self.assert_('@@' in lines[2][2:])
129
self.assertTrue('@@' in lines[2][2:])
140
130
## "Unterminated hunk header for patch:\n%s" % "".join(lines)
142
132
def test_binary_lines(self):
143
self.assertRaises(BinaryFile, udiff_lines, [1023 * 'a' + '\x00'], [])
144
self.assertRaises(BinaryFile, udiff_lines, [], [1023 * 'a' + '\x00'])
145
udiff_lines([1023 * 'a' + '\x00'], [], allow_binary=True)
146
udiff_lines([], [1023 * 'a' + '\x00'], allow_binary=True)
134
uni_lines = [1023 * 'a' + '\x00']
135
self.assertRaises(errors.BinaryFile, udiff_lines, uni_lines , empty)
136
self.assertRaises(errors.BinaryFile, udiff_lines, empty, uni_lines)
137
udiff_lines(uni_lines , empty, allow_binary=True)
138
udiff_lines(empty, uni_lines, allow_binary=True)
148
140
def test_external_diff(self):
149
141
lines = external_udiff_lines(['boo\n'], ['goo\n'])
159
151
self.check_patch(lines)
161
153
def test_external_diff_binary_lang_c(self):
163
154
for lang in ('LANG', 'LC_ALL', 'LANGUAGE'):
164
old_env[lang] = osutils.set_or_unset_env(lang, 'C')
166
lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
167
# Older versions of diffutils say "Binary files", newer
168
# versions just say "Files".
169
self.assertContainsRe(lines[0],
170
'(Binary f|F)iles old and new differ\n')
171
self.assertEquals(lines[1:], ['\n'])
173
for lang, old_val in old_env.iteritems():
174
osutils.set_or_unset_env(lang, old_val)
155
self.overrideEnv(lang, 'C')
156
lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
157
# Older versions of diffutils say "Binary files", newer
158
# versions just say "Files".
159
self.assertContainsRe(lines[0], '(Binary f|F)iles old and new differ\n')
160
self.assertEqual(lines[1:], ['\n'])
176
162
def test_no_external_diff(self):
177
163
"""Check that NoDiff is raised when diff is not available"""
178
# Use os.environ['PATH'] to make sure no 'diff' command is available
179
orig_path = os.environ['PATH']
181
os.environ['PATH'] = ''
182
self.assertRaises(NoDiff, external_diff,
183
'old', ['boo\n'], 'new', ['goo\n'],
184
StringIO(), diff_opts=['-u'])
186
os.environ['PATH'] = orig_path
164
# Make sure no 'diff' command is available
165
# XXX: Weird, using None instead of '' breaks the test -- vila 20101216
166
self.overrideEnv('PATH', '')
167
self.assertRaises(errors.NoDiff, diff.external_diff,
168
'old', ['boo\n'], 'new', ['goo\n'],
169
StringIO(), diff_opts=['-u'])
188
171
def test_internal_diff_default(self):
189
172
# Default internal diff encoding is utf8
190
173
output = StringIO()
191
internal_diff(u'old_\xb5', ['old_text\n'],
192
u'new_\xe5', ['new_text\n'], output)
174
diff.internal_diff(u'old_\xb5', ['old_text\n'],
175
u'new_\xe5', ['new_text\n'], output)
193
176
lines = output.getvalue().splitlines(True)
194
177
self.check_patch(lines)
195
self.assertEquals(['--- old_\xc2\xb5\n',
178
self.assertEqual(['--- old_\xc2\xb5\n',
196
179
'+++ new_\xc3\xa5\n',
197
180
'@@ -1,1 +1,1 @@\n',
236
219
def test_internal_diff_no_content(self):
237
220
output = StringIO()
238
internal_diff(u'old', [], u'new', [], output)
221
diff.internal_diff(u'old', [], u'new', [], output)
239
222
self.assertEqual('', output.getvalue())
241
224
def test_internal_diff_no_changes(self):
242
225
output = StringIO()
243
internal_diff(u'old', ['text\n', 'contents\n'],
244
u'new', ['text\n', 'contents\n'],
226
diff.internal_diff(u'old', ['text\n', 'contents\n'],
227
u'new', ['text\n', 'contents\n'],
246
229
self.assertEqual('', output.getvalue())
248
231
def test_internal_diff_returns_bytes(self):
250
233
output = StringIO.StringIO()
251
internal_diff(u'old_\xb5', ['old_text\n'],
252
u'new_\xe5', ['new_text\n'], output)
253
self.failUnless(isinstance(output.getvalue(), str),
234
diff.internal_diff(u'old_\xb5', ['old_text\n'],
235
u'new_\xe5', ['new_text\n'], output)
236
self.assertIsInstance(output.getvalue(), str,
254
237
'internal_diff should return bytestrings')
257
class TestDiffFiles(TestCaseInTempDir):
239
def test_internal_diff_default_context(self):
241
diff.internal_diff('old', ['same_text\n','same_text\n','same_text\n',
242
'same_text\n','same_text\n','old_text\n'],
243
'new', ['same_text\n','same_text\n','same_text\n',
244
'same_text\n','same_text\n','new_text\n'], output)
245
lines = output.getvalue().splitlines(True)
246
self.check_patch(lines)
247
self.assertEqual(['--- old\n',
259
def test_internal_diff_no_context(self):
261
diff.internal_diff('old', ['same_text\n','same_text\n','same_text\n',
262
'same_text\n','same_text\n','old_text\n'],
263
'new', ['same_text\n','same_text\n','same_text\n',
264
'same_text\n','same_text\n','new_text\n'], output,
266
lines = output.getvalue().splitlines(True)
267
self.check_patch(lines)
268
self.assertEqual(['--- old\n',
277
def test_internal_diff_more_context(self):
279
diff.internal_diff('old', ['same_text\n','same_text\n','same_text\n',
280
'same_text\n','same_text\n','old_text\n'],
281
'new', ['same_text\n','same_text\n','same_text\n',
282
'same_text\n','same_text\n','new_text\n'], output,
284
lines = output.getvalue().splitlines(True)
285
self.check_patch(lines)
286
self.assertEqual(['--- old\n',
303
class TestDiffFiles(tests.TestCaseInTempDir):
259
305
def test_external_diff_binary(self):
260
306
"""The output when using external diff should use diff's i18n error"""
262
308
lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
264
310
cmd = ['diff', '-u', '--binary', 'old', 'new']
265
open('old', 'wb').write('\x00foobar\n')
266
open('new', 'wb').write('foo\x00bar\n')
311
with open('old', 'wb') as f: f.write('\x00foobar\n')
312
with open('new', 'wb') as f: f.write('foo\x00bar\n')
267
313
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
268
314
stdin=subprocess.PIPE)
269
315
out, err = pipe.communicate()
270
# Diff returns '2' on Binary files.
271
self.assertEqual(2, pipe.returncode)
272
316
# We should output whatever diff tells us, plus a trailing newline
273
317
self.assertEqual(out.splitlines(True) + ['\n'], lines)
276
class TestShowDiffTreesHelper(TestCaseWithTransport):
277
"""Has a helper for running show_diff_trees"""
279
def get_diff(self, tree1, tree2, specific_files=None, working_tree=None):
281
if working_tree is not None:
282
extra_trees = (working_tree,)
285
show_diff_trees(tree1, tree2, output, specific_files=specific_files,
286
extra_trees=extra_trees, old_label='old/',
288
return output.getvalue()
291
class TestDiffDates(TestShowDiffTreesHelper):
320
def get_diff_as_string(tree1, tree2, specific_files=None, working_tree=None):
322
if working_tree is not None:
323
extra_trees = (working_tree,)
326
diff.show_diff_trees(tree1, tree2, output,
327
specific_files=specific_files,
328
extra_trees=extra_trees, old_label='old/',
330
return output.getvalue()
333
class TestDiffDates(tests.TestCaseWithTransport):
294
336
super(TestDiffDates, self).setUp()
447
488
tree.rename_one('dir', 'other')
448
489
self.build_tree_contents([('tree/other/file', 'new contents\n')])
449
diff = self.get_diff(tree.basis_tree(), tree)
450
self.assertContainsRe(diff, "=== renamed directory 'dir' => 'other'\n")
451
self.assertContainsRe(diff, "=== modified file 'other/file'\n")
490
d = get_diff_as_string(tree.basis_tree(), tree)
491
self.assertContainsRe(d, "=== renamed directory 'dir' => 'other'\n")
492
self.assertContainsRe(d, "=== modified file 'other/file'\n")
452
493
# XXX: This is technically incorrect, because it used to be at another
453
494
# location. What to do?
454
self.assertContainsRe(diff, '--- old/dir/file\t')
455
self.assertContainsRe(diff, '\\+\\+\\+ new/other/file\t')
456
self.assertContainsRe(diff, '-contents\n'
495
self.assertContainsRe(d, '--- old/dir/file\t')
496
self.assertContainsRe(d, '\\+\\+\\+ new/other/file\t')
497
self.assertContainsRe(d, '-contents\n'
459
500
def test_renamed_directory(self):
460
501
"""Test when only a directory is only renamed."""
523
564
tree.rename_one('c', 'new-c')
524
565
tree.rename_one('d', 'new-d')
526
diff = self.get_diff(tree.basis_tree(), tree)
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'")
567
d = get_diff_as_string(tree.basis_tree(), tree)
569
self.assertContainsRe(d, r"file 'a'.*\(properties changed:"
571
self.assertContainsRe(d, r"file 'b'.*\(properties changed:"
573
self.assertContainsRe(d, r"file 'c'.*\(properties changed:"
575
self.assertContainsRe(d, r"file 'd'.*\(properties changed:"
577
self.assertNotContainsRe(d, r"file 'e'")
578
self.assertNotContainsRe(d, r"file 'f'")
536
580
def test_binary_unicode_filenames(self):
537
581
"""Test that contents of files are *not* encoded in UTF-8 when there
538
582
is a binary file in the diff.
540
584
# See https://bugs.launchpad.net/bugs/110092.
541
self.requireFeature(tests.UnicodeFilenameFeature)
585
self.requireFeature(features.UnicodeFilenameFeature)
543
587
# This bug isn't triggered with cStringIO.
544
588
from StringIO import StringIO
552
596
tree.add([alpha], ['file-id'])
553
597
tree.add([omega], ['file-id-2'])
554
598
diff_content = StringIO()
555
show_diff_trees(tree.basis_tree(), tree, diff_content)
556
diff = diff_content.getvalue()
557
self.assertContainsRe(diff, r"=== added file '%s'" % alpha_utf8)
558
self.assertContainsRe(
559
diff, "Binary files a/%s.*and b/%s.* differ\n" % (alpha_utf8, alpha_utf8))
560
self.assertContainsRe(diff, r"=== added file '%s'" % omega_utf8)
561
self.assertContainsRe(diff, r"--- a/%s" % (omega_utf8,))
562
self.assertContainsRe(diff, r"\+\+\+ b/%s" % (omega_utf8,))
599
diff.show_diff_trees(tree.basis_tree(), tree, diff_content)
600
d = diff_content.getvalue()
601
self.assertContainsRe(d, r"=== added file '%s'" % alpha_utf8)
602
self.assertContainsRe(d, "Binary files a/%s.*and b/%s.* differ\n"
603
% (alpha_utf8, alpha_utf8))
604
self.assertContainsRe(d, r"=== added file '%s'" % omega_utf8)
605
self.assertContainsRe(d, r"--- a/%s" % (omega_utf8,))
606
self.assertContainsRe(d, r"\+\+\+ b/%s" % (omega_utf8,))
564
608
def test_unicode_filename(self):
565
609
"""Test when the filename are unicode."""
566
self.requireFeature(tests.UnicodeFilenameFeature)
610
self.requireFeature(features.UnicodeFilenameFeature)
568
612
alpha, omega = u'\u03b1', u'\u03c9'
569
613
autf8, outf8 = alpha.encode('utf8'), omega.encode('utf8')
584
628
tree.add(['add_'+alpha], ['file-id'])
585
629
self.build_tree_contents([('tree/mod_'+alpha, 'contents_mod\n')])
587
diff = self.get_diff(tree.basis_tree(), tree)
588
self.assertContainsRe(diff,
631
d = get_diff_as_string(tree.basis_tree(), tree)
632
self.assertContainsRe(d,
589
633
"=== 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)
595
class DiffWasIs(DiffPath):
634
self.assertContainsRe(d, "=== added file 'add_%s'"%autf8)
635
self.assertContainsRe(d, "=== modified file 'mod_%s'"%autf8)
636
self.assertContainsRe(d, "=== removed file 'del_%s'"%autf8)
638
def test_unicode_filename_path_encoding(self):
639
"""Test for bug #382699: unicode filenames on Windows should be shown
642
self.requireFeature(features.UnicodeFilenameFeature)
643
# The word 'test' in Russian
644
_russian_test = u'\u0422\u0435\u0441\u0442'
645
directory = _russian_test + u'/'
646
test_txt = _russian_test + u'.txt'
647
u1234 = u'\u1234.txt'
649
tree = self.make_branch_and_tree('.')
650
self.build_tree_contents([
655
tree.add([test_txt, u1234, directory])
658
diff.show_diff_trees(tree.basis_tree(), tree, sio,
659
path_encoding='cp1251')
661
output = subst_dates(sio.getvalue())
663
=== added directory '%(directory)s'
664
=== added file '%(test_txt)s'
665
--- a/%(test_txt)s\tYYYY-MM-DD HH:MM:SS +ZZZZ
666
+++ b/%(test_txt)s\tYYYY-MM-DD HH:MM:SS +ZZZZ
670
=== added file '?.txt'
671
--- a/?.txt\tYYYY-MM-DD HH:MM:SS +ZZZZ
672
+++ b/?.txt\tYYYY-MM-DD HH:MM:SS +ZZZZ
676
''' % {'directory': _russian_test.encode('cp1251'),
677
'test_txt': test_txt.encode('cp1251'),
679
self.assertEqualDiff(output, shouldbe)
682
class DiffWasIs(diff.DiffPath):
597
684
def diff(self, file_id, old_path, new_path, old_kind, new_kind):
598
685
self.to_file.write('was: ')
658
745
self.assertContainsRe(self.differ.to_file.getvalue(), '\+contents')
660
747
def test_diff_symlink(self):
661
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
748
differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
662
749
differ.diff_symlink('old target', None)
663
750
self.assertEqual("=== target was 'old target'\n",
664
751
differ.to_file.getvalue())
666
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
753
differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
667
754
differ.diff_symlink(None, 'new target')
668
755
self.assertEqual("=== target is 'new target'\n",
669
756
differ.to_file.getvalue())
671
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
758
differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
672
759
differ.diff_symlink('old target', 'new target')
673
760
self.assertEqual("=== target changed 'old target' => 'new target'\n",
674
761
differ.to_file.getvalue())
761
848
'.*a-file(.|\n)*b-file')
764
class TestPatienceDiffLib(TestCase):
851
class TestPatienceDiffLib(tests.TestCase):
767
854
super(TestPatienceDiffLib, self).setUp()
768
self._unique_lcs = bzrlib._patiencediff_py.unique_lcs_py
769
self._recurse_matches = bzrlib._patiencediff_py.recurse_matches_py
855
self._unique_lcs = _patiencediff_py.unique_lcs_py
856
self._recurse_matches = _patiencediff_py.recurse_matches_py
770
857
self._PatienceSequenceMatcher = \
771
bzrlib._patiencediff_py.PatienceSequenceMatcher_py
858
_patiencediff_py.PatienceSequenceMatcher_py
773
860
def test_diff_unicode_string(self):
774
861
a = ''.join([unichr(i) for i in range(4000, 4500, 3)])
775
862
b = ''.join([unichr(i) for i in range(4300, 4800, 2)])
776
863
sm = self._PatienceSequenceMatcher(None, a, b)
777
864
mb = sm.get_matching_blocks()
778
self.assertEquals(35, len(mb))
865
self.assertEqual(35, len(mb))
780
867
def test_unique_lcs(self):
781
868
unique_lcs = self._unique_lcs
782
self.assertEquals(unique_lcs('', ''), [])
783
self.assertEquals(unique_lcs('', 'a'), [])
784
self.assertEquals(unique_lcs('a', ''), [])
785
self.assertEquals(unique_lcs('a', 'a'), [(0,0)])
786
self.assertEquals(unique_lcs('a', 'b'), [])
787
self.assertEquals(unique_lcs('ab', 'ab'), [(0,0), (1,1)])
788
self.assertEquals(unique_lcs('abcde', 'cdeab'), [(2,0), (3,1), (4,2)])
789
self.assertEquals(unique_lcs('cdeab', 'abcde'), [(0,2), (1,3), (2,4)])
790
self.assertEquals(unique_lcs('abXde', 'abYde'), [(0,0), (1,1),
869
self.assertEqual(unique_lcs('', ''), [])
870
self.assertEqual(unique_lcs('', 'a'), [])
871
self.assertEqual(unique_lcs('a', ''), [])
872
self.assertEqual(unique_lcs('a', 'a'), [(0,0)])
873
self.assertEqual(unique_lcs('a', 'b'), [])
874
self.assertEqual(unique_lcs('ab', 'ab'), [(0,0), (1,1)])
875
self.assertEqual(unique_lcs('abcde', 'cdeab'), [(2,0), (3,1), (4,2)])
876
self.assertEqual(unique_lcs('cdeab', 'abcde'), [(0,2), (1,3), (2,4)])
877
self.assertEqual(unique_lcs('abXde', 'abYde'), [(0,0), (1,1),
792
self.assertEquals(unique_lcs('acbac', 'abc'), [(2,1)])
879
self.assertEqual(unique_lcs('acbac', 'abc'), [(2,1)])
794
881
def test_recurse_matches(self):
795
882
def test_one(a, b, matches):
796
883
test_matches = []
797
884
self._recurse_matches(
798
885
a, b, 0, 0, len(a), len(b), test_matches, 10)
799
self.assertEquals(test_matches, matches)
886
self.assertEqual(test_matches, matches)
801
888
test_one(['a', '', 'b', '', 'c'], ['a', 'a', 'b', 'c', 'c'],
802
889
[(0, 0), (2, 2), (4, 4)])
1228
1315
, list(unified_diff_files('a2', 'b2')))
1230
1317
# And the patience diff
1231
self.assertEquals(['--- a2\n',
1233
'@@ -4,6 +4,11 @@\n',
1246
, list(unified_diff_files('a2', 'b2',
1247
sequencematcher=psm)))
1318
self.assertEqual(['--- a2\n',
1320
'@@ -4,6 +4,11 @@\n',
1332
list(unified_diff_files('a2', 'b2',
1333
sequencematcher=psm)))
1250
1336
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
1252
_test_needs_features = [CompiledPatienceDiffFeature]
1338
_test_needs_features = [features.compiled_patiencediff_feature]
1254
1340
def setUp(self):
1255
1341
super(TestPatienceDiffLibFiles_c, self).setUp()
1256
import bzrlib._patiencediff_c
1342
from bzrlib import _patiencediff_c
1257
1343
self._PatienceSequenceMatcher = \
1258
bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1261
class TestUsingCompiledIfAvailable(TestCase):
1344
_patiencediff_c.PatienceSequenceMatcher_c
1347
class TestUsingCompiledIfAvailable(tests.TestCase):
1263
1349
def test_PatienceSequenceMatcher(self):
1264
if CompiledPatienceDiffFeature.available():
1350
if features.compiled_patiencediff_feature.available():
1265
1351
from bzrlib._patiencediff_c import PatienceSequenceMatcher_c
1266
1352
self.assertIs(PatienceSequenceMatcher_c,
1267
bzrlib.patiencediff.PatienceSequenceMatcher)
1353
patiencediff.PatienceSequenceMatcher)
1269
1355
from bzrlib._patiencediff_py import PatienceSequenceMatcher_py
1270
1356
self.assertIs(PatienceSequenceMatcher_py,
1271
bzrlib.patiencediff.PatienceSequenceMatcher)
1357
patiencediff.PatienceSequenceMatcher)
1273
1359
def test_unique_lcs(self):
1274
if CompiledPatienceDiffFeature.available():
1360
if features.compiled_patiencediff_feature.available():
1275
1361
from bzrlib._patiencediff_c import unique_lcs_c
1276
1362
self.assertIs(unique_lcs_c,
1277
bzrlib.patiencediff.unique_lcs)
1363
patiencediff.unique_lcs)
1279
1365
from bzrlib._patiencediff_py import unique_lcs_py
1280
1366
self.assertIs(unique_lcs_py,
1281
bzrlib.patiencediff.unique_lcs)
1367
patiencediff.unique_lcs)
1283
1369
def test_recurse_matches(self):
1284
if CompiledPatienceDiffFeature.available():
1370
if features.compiled_patiencediff_feature.available():
1285
1371
from bzrlib._patiencediff_c import recurse_matches_c
1286
1372
self.assertIs(recurse_matches_c,
1287
bzrlib.patiencediff.recurse_matches)
1373
patiencediff.recurse_matches)
1289
1375
from bzrlib._patiencediff_py import recurse_matches_py
1290
1376
self.assertIs(recurse_matches_py,
1291
bzrlib.patiencediff.recurse_matches)
1294
class TestDiffFromTool(TestCaseWithTransport):
1377
patiencediff.recurse_matches)
1380
class TestDiffFromTool(tests.TestCaseWithTransport):
1296
1382
def test_from_string(self):
1297
diff_obj = DiffFromTool.from_string('diff', None, None, None)
1383
diff_obj = diff.DiffFromTool.from_string('diff', None, None, None)
1298
1384
self.addCleanup(diff_obj.finish)
1299
self.assertEqual(['diff', '%(old_path)s', '%(new_path)s'],
1385
self.assertEqual(['diff', '@old_path', '@new_path'],
1300
1386
diff_obj.command_template)
1302
1388
def test_from_string_u5(self):
1303
diff_obj = DiffFromTool.from_string('diff -u\\ 5', None, None, None)
1389
diff_obj = diff.DiffFromTool.from_string('diff "-u 5"',
1304
1391
self.addCleanup(diff_obj.finish)
1305
self.assertEqual(['diff', '-u 5', '%(old_path)s', '%(new_path)s'],
1392
self.assertEqual(['diff', '-u 5', '@old_path', '@new_path'],
1306
1393
diff_obj.command_template)
1307
1394
self.assertEqual(['diff', '-u 5', 'old-path', 'new-path'],
1308
1395
diff_obj._get_command('old-path', 'new-path'))
1397
def test_from_string_path_with_backslashes(self):
1398
self.requireFeature(features.backslashdir_feature)
1399
tool = 'C:\\Tools\\Diff.exe'
1400
diff_obj = diff.DiffFromTool.from_string(tool, None, None, None)
1401
self.addCleanup(diff_obj.finish)
1402
self.assertEqual(['C:\\Tools\\Diff.exe', '@old_path', '@new_path'],
1403
diff_obj.command_template)
1404
self.assertEqual(['C:\\Tools\\Diff.exe', 'old-path', 'new-path'],
1405
diff_obj._get_command('old-path', 'new-path'))
1310
1407
def test_execute(self):
1311
1408
output = StringIO()
1312
diff_obj = DiffFromTool(['python', '-c',
1313
'print "%(old_path)s %(new_path)s"'],
1409
diff_obj = diff.DiffFromTool(['python', '-c',
1410
'print "@old_path @new_path"'],
1315
1412
self.addCleanup(diff_obj.finish)
1316
1413
diff_obj._execute('old', 'new')
1317
1414
self.assertEqual(output.getvalue().rstrip(), 'old new')
1319
def test_excute_missing(self):
1320
diff_obj = DiffFromTool(['a-tool-which-is-unlikely-to-exist'],
1416
def test_execute_missing(self):
1417
diff_obj = diff.DiffFromTool(['a-tool-which-is-unlikely-to-exist'],
1322
1419
self.addCleanup(diff_obj.finish)
1323
e = self.assertRaises(ExecutableMissing, diff_obj._execute, 'old',
1420
e = self.assertRaises(errors.ExecutableMissing, diff_obj._execute,
1325
1422
self.assertEqual('a-tool-which-is-unlikely-to-exist could not be found'
1326
1423
' on this machine', str(e))
1328
1425
def test_prepare_files_creates_paths_readable_by_windows_tool(self):
1329
self.requireFeature(AttribFeature)
1426
self.requireFeature(features.AttribFeature)
1330
1427
output = StringIO()
1331
1428
tree = self.make_branch_and_tree('tree')
1332
1429
self.build_tree_contents([('tree/file', 'content')])
1334
1431
tree.commit('old tree')
1335
1432
tree.lock_read()
1336
1433
self.addCleanup(tree.unlock)
1337
diff_obj = DiffFromTool(['python', '-c',
1338
'print "%(old_path)s %(new_path)s"'],
1434
basis_tree = tree.basis_tree()
1435
basis_tree.lock_read()
1436
self.addCleanup(basis_tree.unlock)
1437
diff_obj = diff.DiffFromTool(['python', '-c',
1438
'print "@old_path @new_path"'],
1439
basis_tree, tree, output)
1340
1440
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')
1441
# The old content should be readonly
1442
self.assertReadableByAttrib(diff_obj._root, 'old\\file',
1444
# The new content should use the tree object, not a 'new' file anymore
1445
self.assertEndsWith(tree.basedir, 'work/tree')
1446
self.assertReadableByAttrib(tree.basedir, 'file', r'work\\tree\\file$')
1344
1448
def assertReadableByAttrib(self, cwd, relpath, regex):
1345
1449
proc = subprocess.Popen(['attrib', relpath],
1346
1450
stdout=subprocess.PIPE,
1349
result = proc.stdout.read()
1350
self.assertContainsRe(result, regex)
1452
(result, err) = proc.communicate()
1453
self.assertContainsRe(result.replace('\r\n', '\n'), regex)
1352
1455
def test_prepare_files(self):
1353
1456
output = StringIO()
1366
1470
self.addCleanup(old_tree.unlock)
1367
1471
tree.lock_read()
1368
1472
self.addCleanup(tree.unlock)
1369
diff_obj = DiffFromTool(['python', '-c',
1370
'print "%(old_path)s %(new_path)s"'],
1371
old_tree, tree, output)
1473
diff_obj = diff.DiffFromTool(['python', '-c',
1474
'print "@old_path @new_path"'],
1475
old_tree, tree, output)
1372
1476
self.addCleanup(diff_obj.finish)
1373
1477
self.assertContainsRe(diff_obj._root, 'bzr-diff-[^/]*')
1374
1478
old_path, new_path = diff_obj._prepare_files('file-id', 'oldname',
1376
1480
self.assertContainsRe(old_path, 'old/oldname$')
1377
self.assertEqual(0, os.stat(old_path).st_mtime)
1378
self.assertContainsRe(new_path, 'new/newname$')
1481
self.assertEqual(315532800, os.stat(old_path).st_mtime)
1482
self.assertContainsRe(new_path, 'tree/newname$')
1379
1483
self.assertFileEqual('oldcontent', old_path)
1380
1484
self.assertFileEqual('newcontent', new_path)
1381
1485
if osutils.host_os_dereferences_symlinks():
1382
1486
self.assertTrue(os.path.samefile('tree/newname', new_path))
1383
1487
# make sure we can create files with the same parent directories
1384
1488
diff_obj._prepare_files('file2-id', 'oldname2', 'newname2')
1491
class TestDiffFromToolEncodedFilename(tests.TestCaseWithTransport):
1493
def test_encodable_filename(self):
1494
# Just checks file path for external diff tool.
1495
# We cannot change CPython's internal encoding used by os.exec*.
1496
diffobj = diff.DiffFromTool(['dummy', '@old_path', '@new_path'],
1498
for _, scenario in EncodingAdapter.encoding_scenarios:
1499
encoding = scenario['encoding']
1500
dirname = scenario['info']['directory']
1501
filename = scenario['info']['filename']
1503
self.overrideAttr(diffobj, '_fenc', lambda: encoding)
1504
relpath = dirname + u'/' + filename
1505
fullpath = diffobj._safe_filename('safe', relpath)
1506
self.assertEqual(fullpath,
1507
fullpath.encode(encoding).decode(encoding))
1508
self.assertTrue(fullpath.startswith(diffobj._root + '/safe'))
1510
def test_unencodable_filename(self):
1511
diffobj = diff.DiffFromTool(['dummy', '@old_path', '@new_path'],
1513
for _, scenario in EncodingAdapter.encoding_scenarios:
1514
encoding = scenario['encoding']
1515
dirname = scenario['info']['directory']
1516
filename = scenario['info']['filename']
1518
if encoding == 'iso-8859-1':
1519
encoding = 'iso-8859-2'
1521
encoding = 'iso-8859-1'
1523
self.overrideAttr(diffobj, '_fenc', lambda: encoding)
1524
relpath = dirname + u'/' + filename
1525
fullpath = diffobj._safe_filename('safe', relpath)
1526
self.assertEqual(fullpath,
1527
fullpath.encode(encoding).decode(encoding))
1528
self.assertTrue(fullpath.startswith(diffobj._root + '/safe'))
1531
class TestGetTreesAndBranchesToDiffLocked(tests.TestCaseWithTransport):
1533
def call_gtabtd(self, path_list, revision_specs, old_url, new_url):
1534
"""Call get_trees_and_branches_to_diff_locked."""
1535
return diff.get_trees_and_branches_to_diff_locked(
1536
path_list, revision_specs, old_url, new_url, self.addCleanup)
1538
def test_basic(self):
1539
tree = self.make_branch_and_tree('tree')
1540
(old_tree, new_tree,
1541
old_branch, new_branch,
1542
specific_files, extra_trees) = self.call_gtabtd(
1543
['tree'], None, None, None)
1545
self.assertIsInstance(old_tree, revisiontree.RevisionTree)
1546
self.assertEqual(_mod_revision.NULL_REVISION,
1547
old_tree.get_revision_id())
1548
self.assertEqual(tree.basedir, new_tree.basedir)
1549
self.assertEqual(tree.branch.base, old_branch.base)
1550
self.assertEqual(tree.branch.base, new_branch.base)
1551
self.assertIs(None, specific_files)
1552
self.assertIs(None, extra_trees)
1554
def test_with_rev_specs(self):
1555
tree = self.make_branch_and_tree('tree')
1556
self.build_tree_contents([('tree/file', 'oldcontent')])
1557
tree.add('file', 'file-id')
1558
tree.commit('old tree', timestamp=0, rev_id="old-id")
1559
self.build_tree_contents([('tree/file', 'newcontent')])
1560
tree.commit('new tree', timestamp=0, rev_id="new-id")
1562
revisions = [revisionspec.RevisionSpec.from_string('1'),
1563
revisionspec.RevisionSpec.from_string('2')]
1564
(old_tree, new_tree,
1565
old_branch, new_branch,
1566
specific_files, extra_trees) = self.call_gtabtd(
1567
['tree'], revisions, None, None)
1569
self.assertIsInstance(old_tree, revisiontree.RevisionTree)
1570
self.assertEqual("old-id", old_tree.get_revision_id())
1571
self.assertIsInstance(new_tree, revisiontree.RevisionTree)
1572
self.assertEqual("new-id", new_tree.get_revision_id())
1573
self.assertEqual(tree.branch.base, old_branch.base)
1574
self.assertEqual(tree.branch.base, new_branch.base)
1575
self.assertIs(None, specific_files)
1576
self.assertEqual(tree.basedir, extra_trees[0].basedir)