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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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.transform as transform
39
import bzrlib.patiencediff
40
import bzrlib._patiencediff_py
41
from bzrlib.tests import (Feature, TestCase, TestCaseWithTransport,
42
TestCaseInTempDir, TestSkipped)
45
class _AttribFeature(Feature):
48
if (sys.platform not in ('cygwin', 'win32')):
51
proc = subprocess.Popen(['attrib', '.'], stdout=subprocess.PIPE)
54
return (0 == proc.wait())
56
def feature_name(self):
57
return 'attrib Windows command-line tool'
59
AttribFeature = _AttribFeature()
62
class _CompiledPatienceDiffFeature(Feature):
66
import bzrlib._patiencediff_c
71
def feature_name(self):
72
return 'bzrlib._patiencediff_c'
74
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
77
45
def udiff_lines(old, new, allow_binary=False):
78
46
output = StringIO()
79
internal_diff('old', old, 'new', new, output, allow_binary)
47
diff.internal_diff('old', old, 'new', new, output, allow_binary)
81
49
return output.readlines()
86
54
# StringIO has no fileno, so it tests a different codepath
87
55
output = StringIO()
89
output = TemporaryFile()
57
output = tempfile.TemporaryFile()
91
external_diff('old', old, 'new', new, output, diff_opts=['-u'])
93
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')
95
63
lines = output.readlines()
100
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):
102
93
def test_add_nl(self):
103
94
"""diff generates a valid diff for patches that add a newline"""
104
95
lines = udiff_lines(['boo'], ['boo\n'])
105
96
self.check_patch(lines)
106
self.assertEquals(lines[4], '\\ No newline at end of file\n')
97
self.assertEqual(lines[4], '\\ No newline at end of file\n')
107
98
## "expected no-nl, got %r" % lines[4]
109
100
def test_add_nl_2(self):
122
113
lines = udiff_lines(['boo\n'], ['boo'])
123
114
self.check_patch(lines)
124
self.assertEquals(lines[5], '\\ No newline at end of file\n')
115
self.assertEqual(lines[5], '\\ No newline at end of file\n')
125
116
## "expected no-nl, got %r" % lines[5]
127
118
def check_patch(self, lines):
128
self.assert_(len(lines) > 1)
119
self.assertTrue(len(lines) > 1)
129
120
## "Not enough lines for a file header for patch:\n%s" % "".join(lines)
130
self.assert_(lines[0].startswith ('---'))
121
self.assertTrue(lines[0].startswith ('---'))
131
122
## 'No orig line for patch:\n%s' % "".join(lines)
132
self.assert_(lines[1].startswith ('+++'))
123
self.assertTrue(lines[1].startswith ('+++'))
133
124
## 'No mod line for patch:\n%s' % "".join(lines)
134
self.assert_(len(lines) > 2)
125
self.assertTrue(len(lines) > 2)
135
126
## "No hunks for patch:\n%s" % "".join(lines)
136
self.assert_(lines[2].startswith('@@'))
127
self.assertTrue(lines[2].startswith('@@'))
137
128
## "No hunk header for patch:\n%s" % "".join(lines)
138
self.assert_('@@' in lines[2][2:])
129
self.assertTrue('@@' in lines[2][2:])
139
130
## "Unterminated hunk header for patch:\n%s" % "".join(lines)
141
132
def test_binary_lines(self):
142
self.assertRaises(BinaryFile, udiff_lines, [1023 * 'a' + '\x00'], [])
143
self.assertRaises(BinaryFile, udiff_lines, [], [1023 * 'a' + '\x00'])
144
udiff_lines([1023 * 'a' + '\x00'], [], allow_binary=True)
145
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)
147
140
def test_external_diff(self):
148
141
lines = external_udiff_lines(['boo\n'], ['goo\n'])
158
151
self.check_patch(lines)
160
153
def test_external_diff_binary_lang_c(self):
162
154
for lang in ('LANG', 'LC_ALL', 'LANGUAGE'):
163
old_env[lang] = osutils.set_or_unset_env(lang, 'C')
165
lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
166
# Older versions of diffutils say "Binary files", newer
167
# versions just say "Files".
168
self.assertContainsRe(lines[0],
169
'(Binary f|F)iles old and new differ\n')
170
self.assertEquals(lines[1:], ['\n'])
172
for lang, old_val in old_env.iteritems():
173
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'])
175
162
def test_no_external_diff(self):
176
163
"""Check that NoDiff is raised when diff is not available"""
177
# Use os.environ['PATH'] to make sure no 'diff' command is available
178
orig_path = os.environ['PATH']
180
os.environ['PATH'] = ''
181
self.assertRaises(NoDiff, external_diff,
182
'old', ['boo\n'], 'new', ['goo\n'],
183
StringIO(), diff_opts=['-u'])
185
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'])
187
171
def test_internal_diff_default(self):
188
172
# Default internal diff encoding is utf8
189
173
output = StringIO()
190
internal_diff(u'old_\xb5', ['old_text\n'],
191
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)
192
176
lines = output.getvalue().splitlines(True)
193
177
self.check_patch(lines)
194
self.assertEquals(['--- old_\xc2\xb5\n',
178
self.assertEqual(['--- old_\xc2\xb5\n',
195
179
'+++ new_\xc3\xa5\n',
196
180
'@@ -1,1 +1,1 @@\n',
235
219
def test_internal_diff_no_content(self):
236
220
output = StringIO()
237
internal_diff(u'old', [], u'new', [], output)
221
diff.internal_diff(u'old', [], u'new', [], output)
238
222
self.assertEqual('', output.getvalue())
240
224
def test_internal_diff_no_changes(self):
241
225
output = StringIO()
242
internal_diff(u'old', ['text\n', 'contents\n'],
243
u'new', ['text\n', 'contents\n'],
226
diff.internal_diff(u'old', ['text\n', 'contents\n'],
227
u'new', ['text\n', 'contents\n'],
245
229
self.assertEqual('', output.getvalue())
247
231
def test_internal_diff_returns_bytes(self):
249
233
output = StringIO.StringIO()
250
internal_diff(u'old_\xb5', ['old_text\n'],
251
u'new_\xe5', ['new_text\n'], output)
252
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,
253
237
'internal_diff should return bytestrings')
256
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):
258
305
def test_external_diff_binary(self):
259
306
"""The output when using external diff should use diff's i18n error"""
261
308
lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
263
310
cmd = ['diff', '-u', '--binary', 'old', 'new']
264
open('old', 'wb').write('\x00foobar\n')
265
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')
266
313
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
267
314
stdin=subprocess.PIPE)
268
315
out, err = pipe.communicate()
269
# Diff returns '2' on Binary files.
270
self.assertEqual(2, pipe.returncode)
271
316
# We should output whatever diff tells us, plus a trailing newline
272
317
self.assertEqual(out.splitlines(True) + ['\n'], lines)
275
class TestShowDiffTreesHelper(TestCaseWithTransport):
276
"""Has a helper for running show_diff_trees"""
278
def get_diff(self, tree1, tree2, specific_files=None, working_tree=None):
280
if working_tree is not None:
281
extra_trees = (working_tree,)
284
show_diff_trees(tree1, tree2, output, specific_files=specific_files,
285
extra_trees=extra_trees, old_label='old/',
287
return output.getvalue()
290
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):
293
336
super(TestDiffDates, self).setUp()
446
488
tree.rename_one('dir', 'other')
447
489
self.build_tree_contents([('tree/other/file', 'new contents\n')])
448
diff = self.get_diff(tree.basis_tree(), tree)
449
self.assertContainsRe(diff, "=== renamed directory 'dir' => 'other'\n")
450
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")
451
493
# XXX: This is technically incorrect, because it used to be at another
452
494
# location. What to do?
453
self.assertContainsRe(diff, '--- old/dir/file\t')
454
self.assertContainsRe(diff, '\\+\\+\\+ new/other/file\t')
455
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'
458
500
def test_renamed_directory(self):
459
501
"""Test when only a directory is only renamed."""
522
564
tree.rename_one('c', 'new-c')
523
565
tree.rename_one('d', 'new-d')
525
diff = self.get_diff(tree.basis_tree(), tree)
527
self.assertContainsRe(diff, r"file 'a'.*\(properties changed:.*\+x to -x.*\)")
528
self.assertContainsRe(diff, r"file 'b'.*\(properties changed:.*-x to \+x.*\)")
529
self.assertContainsRe(diff, r"file 'c'.*\(properties changed:.*\+x to -x.*\)")
530
self.assertContainsRe(diff, r"file 'd'.*\(properties changed:.*-x to \+x.*\)")
531
self.assertNotContainsRe(diff, r"file 'e'")
532
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'")
535
580
def test_binary_unicode_filenames(self):
536
581
"""Test that contents of files are *not* encoded in UTF-8 when there
537
582
is a binary file in the diff.
539
584
# See https://bugs.launchpad.net/bugs/110092.
540
self.requireFeature(tests.UnicodeFilenameFeature)
585
self.requireFeature(features.UnicodeFilenameFeature)
542
587
# This bug isn't triggered with cStringIO.
543
588
from StringIO import StringIO
551
596
tree.add([alpha], ['file-id'])
552
597
tree.add([omega], ['file-id-2'])
553
598
diff_content = StringIO()
554
show_diff_trees(tree.basis_tree(), tree, diff_content)
555
diff = diff_content.getvalue()
556
self.assertContainsRe(diff, r"=== added file '%s'" % alpha_utf8)
557
self.assertContainsRe(
558
diff, "Binary files a/%s.*and b/%s.* differ\n" % (alpha_utf8, alpha_utf8))
559
self.assertContainsRe(diff, r"=== added file '%s'" % omega_utf8)
560
self.assertContainsRe(diff, r"--- a/%s" % (omega_utf8,))
561
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,))
563
608
def test_unicode_filename(self):
564
609
"""Test when the filename are unicode."""
565
self.requireFeature(tests.UnicodeFilenameFeature)
610
self.requireFeature(features.UnicodeFilenameFeature)
567
612
alpha, omega = u'\u03b1', u'\u03c9'
568
613
autf8, outf8 = alpha.encode('utf8'), omega.encode('utf8')
583
628
tree.add(['add_'+alpha], ['file-id'])
584
629
self.build_tree_contents([('tree/mod_'+alpha, 'contents_mod\n')])
586
diff = self.get_diff(tree.basis_tree(), tree)
587
self.assertContainsRe(diff,
631
d = get_diff_as_string(tree.basis_tree(), tree)
632
self.assertContainsRe(d,
588
633
"=== renamed file 'ren_%s' => 'ren_%s'\n"%(autf8, outf8))
589
self.assertContainsRe(diff, "=== added file 'add_%s'"%autf8)
590
self.assertContainsRe(diff, "=== modified file 'mod_%s'"%autf8)
591
self.assertContainsRe(diff, "=== removed file 'del_%s'"%autf8)
594
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):
596
684
def diff(self, file_id, old_path, new_path, old_kind, new_kind):
597
685
self.to_file.write('was: ')
657
745
self.assertContainsRe(self.differ.to_file.getvalue(), '\+contents')
659
747
def test_diff_symlink(self):
660
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
748
differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
661
749
differ.diff_symlink('old target', None)
662
750
self.assertEqual("=== target was 'old target'\n",
663
751
differ.to_file.getvalue())
665
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
753
differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
666
754
differ.diff_symlink(None, 'new target')
667
755
self.assertEqual("=== target is 'new target'\n",
668
756
differ.to_file.getvalue())
670
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
758
differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
671
759
differ.diff_symlink('old target', 'new target')
672
760
self.assertEqual("=== target changed 'old target' => 'new target'\n",
673
761
differ.to_file.getvalue())
760
848
'.*a-file(.|\n)*b-file')
763
class TestPatienceDiffLib(TestCase):
851
class TestPatienceDiffLib(tests.TestCase):
766
854
super(TestPatienceDiffLib, self).setUp()
767
self._unique_lcs = bzrlib._patiencediff_py.unique_lcs_py
768
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
769
857
self._PatienceSequenceMatcher = \
770
bzrlib._patiencediff_py.PatienceSequenceMatcher_py
858
_patiencediff_py.PatienceSequenceMatcher_py
772
860
def test_diff_unicode_string(self):
773
861
a = ''.join([unichr(i) for i in range(4000, 4500, 3)])
774
862
b = ''.join([unichr(i) for i in range(4300, 4800, 2)])
775
863
sm = self._PatienceSequenceMatcher(None, a, b)
776
864
mb = sm.get_matching_blocks()
777
self.assertEquals(35, len(mb))
865
self.assertEqual(35, len(mb))
779
867
def test_unique_lcs(self):
780
868
unique_lcs = self._unique_lcs
781
self.assertEquals(unique_lcs('', ''), [])
782
self.assertEquals(unique_lcs('', 'a'), [])
783
self.assertEquals(unique_lcs('a', ''), [])
784
self.assertEquals(unique_lcs('a', 'a'), [(0,0)])
785
self.assertEquals(unique_lcs('a', 'b'), [])
786
self.assertEquals(unique_lcs('ab', 'ab'), [(0,0), (1,1)])
787
self.assertEquals(unique_lcs('abcde', 'cdeab'), [(2,0), (3,1), (4,2)])
788
self.assertEquals(unique_lcs('cdeab', 'abcde'), [(0,2), (1,3), (2,4)])
789
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),
791
self.assertEquals(unique_lcs('acbac', 'abc'), [(2,1)])
879
self.assertEqual(unique_lcs('acbac', 'abc'), [(2,1)])
793
881
def test_recurse_matches(self):
794
882
def test_one(a, b, matches):
795
883
test_matches = []
796
884
self._recurse_matches(
797
885
a, b, 0, 0, len(a), len(b), test_matches, 10)
798
self.assertEquals(test_matches, matches)
886
self.assertEqual(test_matches, matches)
800
888
test_one(['a', '', 'b', '', 'c'], ['a', 'a', 'b', 'c', 'c'],
801
889
[(0, 0), (2, 2), (4, 4)])
1128
1216
, list(unified_diff(txt_a, txt_b,
1129
1217
sequencematcher=psm)))
1219
def test_patience_unified_diff_with_dates(self):
1220
txt_a = ['hello there\n',
1222
'how are you today?\n']
1223
txt_b = ['hello there\n',
1224
'how are you today?\n']
1225
unified_diff = patiencediff.unified_diff
1226
psm = self._PatienceSequenceMatcher
1227
self.assertEqual(['--- a\t2008-08-08\n',
1228
'+++ b\t2008-09-09\n',
1229
'@@ -1,3 +1,2 @@\n',
1232
' how are you today?\n'
1234
, list(unified_diff(txt_a, txt_b,
1235
fromfile='a', tofile='b',
1236
fromfiledate='2008-08-08',
1237
tofiledate='2008-09-09',
1238
sequencematcher=psm)))
1132
1241
class TestPatienceDiffLib_c(TestPatienceDiffLib):
1134
_test_needs_features = [CompiledPatienceDiffFeature]
1243
_test_needs_features = [features.compiled_patiencediff_feature]
1136
1245
def setUp(self):
1137
1246
super(TestPatienceDiffLib_c, self).setUp()
1138
import bzrlib._patiencediff_c
1139
self._unique_lcs = bzrlib._patiencediff_c.unique_lcs_c
1140
self._recurse_matches = bzrlib._patiencediff_c.recurse_matches_c
1247
from bzrlib import _patiencediff_c
1248
self._unique_lcs = _patiencediff_c.unique_lcs_c
1249
self._recurse_matches = _patiencediff_c.recurse_matches_c
1141
1250
self._PatienceSequenceMatcher = \
1142
bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1251
_patiencediff_c.PatienceSequenceMatcher_c
1144
1253
def test_unhashable(self):
1145
1254
"""We should get a proper exception here."""
1206
1315
, list(unified_diff_files('a2', 'b2')))
1208
1317
# And the patience diff
1209
self.assertEquals(['--- a2 \n',
1211
'@@ -4,6 +4,11 @@\n',
1224
, list(unified_diff_files('a2', 'b2',
1225
sequencematcher=psm)))
1318
self.assertEqual(['--- a2\n',
1320
'@@ -4,6 +4,11 @@\n',
1332
list(unified_diff_files('a2', 'b2',
1333
sequencematcher=psm)))
1228
1336
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
1230
_test_needs_features = [CompiledPatienceDiffFeature]
1338
_test_needs_features = [features.compiled_patiencediff_feature]
1232
1340
def setUp(self):
1233
1341
super(TestPatienceDiffLibFiles_c, self).setUp()
1234
import bzrlib._patiencediff_c
1342
from bzrlib import _patiencediff_c
1235
1343
self._PatienceSequenceMatcher = \
1236
bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1239
class TestUsingCompiledIfAvailable(TestCase):
1344
_patiencediff_c.PatienceSequenceMatcher_c
1347
class TestUsingCompiledIfAvailable(tests.TestCase):
1241
1349
def test_PatienceSequenceMatcher(self):
1242
if CompiledPatienceDiffFeature.available():
1350
if features.compiled_patiencediff_feature.available():
1243
1351
from bzrlib._patiencediff_c import PatienceSequenceMatcher_c
1244
1352
self.assertIs(PatienceSequenceMatcher_c,
1245
bzrlib.patiencediff.PatienceSequenceMatcher)
1353
patiencediff.PatienceSequenceMatcher)
1247
1355
from bzrlib._patiencediff_py import PatienceSequenceMatcher_py
1248
1356
self.assertIs(PatienceSequenceMatcher_py,
1249
bzrlib.patiencediff.PatienceSequenceMatcher)
1357
patiencediff.PatienceSequenceMatcher)
1251
1359
def test_unique_lcs(self):
1252
if CompiledPatienceDiffFeature.available():
1360
if features.compiled_patiencediff_feature.available():
1253
1361
from bzrlib._patiencediff_c import unique_lcs_c
1254
1362
self.assertIs(unique_lcs_c,
1255
bzrlib.patiencediff.unique_lcs)
1363
patiencediff.unique_lcs)
1257
1365
from bzrlib._patiencediff_py import unique_lcs_py
1258
1366
self.assertIs(unique_lcs_py,
1259
bzrlib.patiencediff.unique_lcs)
1367
patiencediff.unique_lcs)
1261
1369
def test_recurse_matches(self):
1262
if CompiledPatienceDiffFeature.available():
1370
if features.compiled_patiencediff_feature.available():
1263
1371
from bzrlib._patiencediff_c import recurse_matches_c
1264
1372
self.assertIs(recurse_matches_c,
1265
bzrlib.patiencediff.recurse_matches)
1373
patiencediff.recurse_matches)
1267
1375
from bzrlib._patiencediff_py import recurse_matches_py
1268
1376
self.assertIs(recurse_matches_py,
1269
bzrlib.patiencediff.recurse_matches)
1272
class TestDiffFromTool(TestCaseWithTransport):
1377
patiencediff.recurse_matches)
1380
class TestDiffFromTool(tests.TestCaseWithTransport):
1274
1382
def test_from_string(self):
1275
diff_obj = DiffFromTool.from_string('diff', None, None, None)
1383
diff_obj = diff.DiffFromTool.from_string('diff', None, None, None)
1276
1384
self.addCleanup(diff_obj.finish)
1277
self.assertEqual(['diff', '%(old_path)s', '%(new_path)s'],
1385
self.assertEqual(['diff', '@old_path', '@new_path'],
1278
1386
diff_obj.command_template)
1280
1388
def test_from_string_u5(self):
1281
diff_obj = DiffFromTool.from_string('diff -u\\ 5', None, None, None)
1389
diff_obj = diff.DiffFromTool.from_string('diff "-u 5"',
1282
1391
self.addCleanup(diff_obj.finish)
1283
self.assertEqual(['diff', '-u 5', '%(old_path)s', '%(new_path)s'],
1392
self.assertEqual(['diff', '-u 5', '@old_path', '@new_path'],
1284
1393
diff_obj.command_template)
1285
1394
self.assertEqual(['diff', '-u 5', 'old-path', 'new-path'],
1286
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'))
1288
1407
def test_execute(self):
1289
1408
output = StringIO()
1290
diff_obj = DiffFromTool(['python', '-c',
1291
'print "%(old_path)s %(new_path)s"'],
1409
diff_obj = diff.DiffFromTool(['python', '-c',
1410
'print "@old_path @new_path"'],
1293
1412
self.addCleanup(diff_obj.finish)
1294
1413
diff_obj._execute('old', 'new')
1295
1414
self.assertEqual(output.getvalue().rstrip(), 'old new')
1297
def test_excute_missing(self):
1298
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'],
1300
1419
self.addCleanup(diff_obj.finish)
1301
e = self.assertRaises(ExecutableMissing, diff_obj._execute, 'old',
1420
e = self.assertRaises(errors.ExecutableMissing, diff_obj._execute,
1303
1422
self.assertEqual('a-tool-which-is-unlikely-to-exist could not be found'
1304
1423
' on this machine', str(e))
1306
1425
def test_prepare_files_creates_paths_readable_by_windows_tool(self):
1307
self.requireFeature(AttribFeature)
1426
self.requireFeature(features.AttribFeature)
1308
1427
output = StringIO()
1309
1428
tree = self.make_branch_and_tree('tree')
1310
1429
self.build_tree_contents([('tree/file', 'content')])
1312
1431
tree.commit('old tree')
1313
1432
tree.lock_read()
1314
1433
self.addCleanup(tree.unlock)
1315
diff_obj = DiffFromTool(['python', '-c',
1316
'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)
1318
1440
diff_obj._prepare_files('file-id', 'file', 'file')
1319
self.assertReadableByAttrib(diff_obj._root, 'old\\file', r'old\\file')
1320
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$')
1322
1448
def assertReadableByAttrib(self, cwd, relpath, regex):
1323
1449
proc = subprocess.Popen(['attrib', relpath],
1324
1450
stdout=subprocess.PIPE,
1327
result = proc.stdout.read()
1328
self.assertContainsRe(result, regex)
1452
(result, err) = proc.communicate()
1453
self.assertContainsRe(result.replace('\r\n', '\n'), regex)
1330
1455
def test_prepare_files(self):
1331
1456
output = StringIO()
1344
1470
self.addCleanup(old_tree.unlock)
1345
1471
tree.lock_read()
1346
1472
self.addCleanup(tree.unlock)
1347
diff_obj = DiffFromTool(['python', '-c',
1348
'print "%(old_path)s %(new_path)s"'],
1349
old_tree, tree, output)
1473
diff_obj = diff.DiffFromTool(['python', '-c',
1474
'print "@old_path @new_path"'],
1475
old_tree, tree, output)
1350
1476
self.addCleanup(diff_obj.finish)
1351
1477
self.assertContainsRe(diff_obj._root, 'bzr-diff-[^/]*')
1352
1478
old_path, new_path = diff_obj._prepare_files('file-id', 'oldname',
1354
1480
self.assertContainsRe(old_path, 'old/oldname$')
1355
self.assertEqual(0, os.stat(old_path).st_mtime)
1356
self.assertContainsRe(new_path, 'new/newname$')
1481
self.assertEqual(315532800, os.stat(old_path).st_mtime)
1482
self.assertContainsRe(new_path, 'tree/newname$')
1357
1483
self.assertFileEqual('oldcontent', old_path)
1358
1484
self.assertFileEqual('newcontent', new_path)
1359
1485
if osutils.host_os_dereferences_symlinks():
1360
1486
self.assertTrue(os.path.samefile('tree/newname', new_path))
1361
1487
# make sure we can create files with the same parent directories
1362
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)