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
18
19
from cStringIO import StringIO
23
from tempfile import TemporaryFile
28
revision as _mod_revision,
25
from bzrlib import tests
26
from bzrlib.diff import (
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
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()
45
77
def udiff_lines(old, new, allow_binary=False):
46
78
output = StringIO()
47
diff.internal_diff('old', old, 'new', new, output, allow_binary)
79
internal_diff('old', old, 'new', new, output, allow_binary)
49
81
return output.readlines()
54
86
# StringIO has no fileno, so it tests a different codepath
55
87
output = StringIO()
57
output = tempfile.TemporaryFile()
89
output = TemporaryFile()
59
diff.external_diff('old', old, 'new', new, output, diff_opts=['-u'])
61
raise tests.TestSkipped('external "diff" not present to test')
91
external_diff('old', old, 'new', new, output, diff_opts=['-u'])
93
raise TestSkipped('external "diff" not present to test')
63
95
lines = output.readlines()
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):
100
class TestDiff(TestCase):
93
102
def test_add_nl(self):
94
103
"""diff generates a valid diff for patches that add a newline"""
95
104
lines = udiff_lines(['boo'], ['boo\n'])
96
105
self.check_patch(lines)
97
self.assertEqual(lines[4], '\\ No newline at end of file\n')
106
self.assertEquals(lines[4], '\\ No newline at end of file\n')
98
107
## "expected no-nl, got %r" % lines[4]
100
109
def test_add_nl_2(self):
113
122
lines = udiff_lines(['boo\n'], ['boo'])
114
123
self.check_patch(lines)
115
self.assertEqual(lines[5], '\\ No newline at end of file\n')
124
self.assertEquals(lines[5], '\\ No newline at end of file\n')
116
125
## "expected no-nl, got %r" % lines[5]
118
127
def check_patch(self, lines):
119
self.assertTrue(len(lines) > 1)
128
self.assert_(len(lines) > 1)
120
129
## "Not enough lines for a file header for patch:\n%s" % "".join(lines)
121
self.assertTrue(lines[0].startswith ('---'))
130
self.assert_(lines[0].startswith ('---'))
122
131
## 'No orig line for patch:\n%s' % "".join(lines)
123
self.assertTrue(lines[1].startswith ('+++'))
132
self.assert_(lines[1].startswith ('+++'))
124
133
## 'No mod line for patch:\n%s' % "".join(lines)
125
self.assertTrue(len(lines) > 2)
134
self.assert_(len(lines) > 2)
126
135
## "No hunks for patch:\n%s" % "".join(lines)
127
self.assertTrue(lines[2].startswith('@@'))
136
self.assert_(lines[2].startswith('@@'))
128
137
## "No hunk header for patch:\n%s" % "".join(lines)
129
self.assertTrue('@@' in lines[2][2:])
138
self.assert_('@@' in lines[2][2:])
130
139
## "Unterminated hunk header for patch:\n%s" % "".join(lines)
132
141
def test_binary_lines(self):
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)
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)
140
147
def test_external_diff(self):
141
148
lines = external_udiff_lines(['boo\n'], ['goo\n'])
151
158
self.check_patch(lines)
153
160
def test_external_diff_binary_lang_c(self):
154
162
for lang in ('LANG', 'LC_ALL', 'LANGUAGE'):
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'])
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)
162
175
def test_no_external_diff(self):
163
176
"""Check that NoDiff is raised when diff is not available"""
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'])
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
171
187
def test_internal_diff_default(self):
172
188
# Default internal diff encoding is utf8
173
189
output = StringIO()
174
diff.internal_diff(u'old_\xb5', ['old_text\n'],
175
u'new_\xe5', ['new_text\n'], output)
190
internal_diff(u'old_\xb5', ['old_text\n'],
191
u'new_\xe5', ['new_text\n'], output)
176
192
lines = output.getvalue().splitlines(True)
177
193
self.check_patch(lines)
178
self.assertEqual(['--- old_\xc2\xb5\n',
194
self.assertEquals(['--- old_\xc2\xb5\n',
179
195
'+++ new_\xc3\xa5\n',
180
196
'@@ -1,1 +1,1 @@\n',
219
235
def test_internal_diff_no_content(self):
220
236
output = StringIO()
221
diff.internal_diff(u'old', [], u'new', [], output)
237
internal_diff(u'old', [], u'new', [], output)
222
238
self.assertEqual('', output.getvalue())
224
240
def test_internal_diff_no_changes(self):
225
241
output = StringIO()
226
diff.internal_diff(u'old', ['text\n', 'contents\n'],
227
u'new', ['text\n', 'contents\n'],
242
internal_diff(u'old', ['text\n', 'contents\n'],
243
u'new', ['text\n', 'contents\n'],
229
245
self.assertEqual('', output.getvalue())
231
247
def test_internal_diff_returns_bytes(self):
233
249
output = StringIO.StringIO()
234
diff.internal_diff(u'old_\xb5', ['old_text\n'],
235
u'new_\xe5', ['new_text\n'], output)
236
self.assertIsInstance(output.getvalue(), str,
250
internal_diff(u'old_\xb5', ['old_text\n'],
251
u'new_\xe5', ['new_text\n'], output)
252
self.failUnless(isinstance(output.getvalue(), str),
237
253
'internal_diff should return bytestrings')
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):
256
class TestDiffFiles(TestCaseInTempDir):
305
258
def test_external_diff_binary(self):
306
259
"""The output when using external diff should use diff's i18n error"""
319
272
self.assertEqual(out.splitlines(True) + ['\n'], lines)
322
def get_diff_as_string(tree1, tree2, specific_files=None, working_tree=None):
324
if working_tree is not None:
325
extra_trees = (working_tree,)
328
diff.show_diff_trees(tree1, tree2, output,
329
specific_files=specific_files,
330
extra_trees=extra_trees, old_label='old/',
332
return output.getvalue()
335
class TestDiffDates(tests.TestCaseWithTransport):
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):
338
293
super(TestDiffDates, self).setUp()
490
446
tree.rename_one('dir', 'other')
491
447
self.build_tree_contents([('tree/other/file', 'new contents\n')])
492
d = get_diff_as_string(tree.basis_tree(), tree)
493
self.assertContainsRe(d, "=== renamed directory 'dir' => 'other'\n")
494
self.assertContainsRe(d, "=== modified file 'other/file'\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")
495
451
# XXX: This is technically incorrect, because it used to be at another
496
452
# location. What to do?
497
self.assertContainsRe(d, '--- old/dir/file\t')
498
self.assertContainsRe(d, '\\+\\+\\+ new/other/file\t')
499
self.assertContainsRe(d, '-contents\n'
453
self.assertContainsRe(diff, '--- old/dir/file\t')
454
self.assertContainsRe(diff, '\\+\\+\\+ new/other/file\t')
455
self.assertContainsRe(diff, '-contents\n'
502
458
def test_renamed_directory(self):
503
459
"""Test when only a directory is only renamed."""
566
522
tree.rename_one('c', 'new-c')
567
523
tree.rename_one('d', 'new-d')
569
d = get_diff_as_string(tree.basis_tree(), tree)
571
self.assertContainsRe(d, r"file 'a'.*\(properties changed:"
573
self.assertContainsRe(d, r"file 'b'.*\(properties changed:"
575
self.assertContainsRe(d, r"file 'c'.*\(properties changed:"
577
self.assertContainsRe(d, r"file 'd'.*\(properties changed:"
579
self.assertNotContainsRe(d, r"file 'e'")
580
self.assertNotContainsRe(d, r"file 'f'")
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'")
582
535
def test_binary_unicode_filenames(self):
583
536
"""Test that contents of files are *not* encoded in UTF-8 when there
584
537
is a binary file in the diff.
586
539
# See https://bugs.launchpad.net/bugs/110092.
587
self.requireFeature(features.UnicodeFilenameFeature)
540
self.requireFeature(tests.UnicodeFilenameFeature)
589
542
# This bug isn't triggered with cStringIO.
590
543
from StringIO import StringIO
598
551
tree.add([alpha], ['file-id'])
599
552
tree.add([omega], ['file-id-2'])
600
553
diff_content = StringIO()
601
diff.show_diff_trees(tree.basis_tree(), tree, diff_content)
602
d = diff_content.getvalue()
603
self.assertContainsRe(d, r"=== added file '%s'" % alpha_utf8)
604
self.assertContainsRe(d, "Binary files a/%s.*and b/%s.* differ\n"
605
% (alpha_utf8, alpha_utf8))
606
self.assertContainsRe(d, r"=== added file '%s'" % omega_utf8)
607
self.assertContainsRe(d, r"--- a/%s" % (omega_utf8,))
608
self.assertContainsRe(d, r"\+\+\+ b/%s" % (omega_utf8,))
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,))
610
563
def test_unicode_filename(self):
611
564
"""Test when the filename are unicode."""
612
self.requireFeature(features.UnicodeFilenameFeature)
565
self.requireFeature(tests.UnicodeFilenameFeature)
614
567
alpha, omega = u'\u03b1', u'\u03c9'
615
568
autf8, outf8 = alpha.encode('utf8'), omega.encode('utf8')
630
583
tree.add(['add_'+alpha], ['file-id'])
631
584
self.build_tree_contents([('tree/mod_'+alpha, 'contents_mod\n')])
633
d = get_diff_as_string(tree.basis_tree(), tree)
634
self.assertContainsRe(d,
586
diff = self.get_diff(tree.basis_tree(), tree)
587
self.assertContainsRe(diff,
635
588
"=== renamed file 'ren_%s' => 'ren_%s'\n"%(autf8, outf8))
636
self.assertContainsRe(d, "=== added file 'add_%s'"%autf8)
637
self.assertContainsRe(d, "=== modified file 'mod_%s'"%autf8)
638
self.assertContainsRe(d, "=== removed file 'del_%s'"%autf8)
640
def test_unicode_filename_path_encoding(self):
641
"""Test for bug #382699: unicode filenames on Windows should be shown
644
self.requireFeature(features.UnicodeFilenameFeature)
645
# The word 'test' in Russian
646
_russian_test = u'\u0422\u0435\u0441\u0442'
647
directory = _russian_test + u'/'
648
test_txt = _russian_test + u'.txt'
649
u1234 = u'\u1234.txt'
651
tree = self.make_branch_and_tree('.')
652
self.build_tree_contents([
657
tree.add([test_txt, u1234, directory])
660
diff.show_diff_trees(tree.basis_tree(), tree, sio,
661
path_encoding='cp1251')
663
output = subst_dates(sio.getvalue())
665
=== added directory '%(directory)s'
666
=== added file '%(test_txt)s'
667
--- a/%(test_txt)s\tYYYY-MM-DD HH:MM:SS +ZZZZ
668
+++ b/%(test_txt)s\tYYYY-MM-DD HH:MM:SS +ZZZZ
672
=== added file '?.txt'
673
--- a/?.txt\tYYYY-MM-DD HH:MM:SS +ZZZZ
674
+++ b/?.txt\tYYYY-MM-DD HH:MM:SS +ZZZZ
678
''' % {'directory': _russian_test.encode('cp1251'),
679
'test_txt': test_txt.encode('cp1251'),
681
self.assertEqualDiff(output, shouldbe)
684
class DiffWasIs(diff.DiffPath):
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):
686
596
def diff(self, file_id, old_path, new_path, old_kind, new_kind):
687
597
self.to_file.write('was: ')
747
657
self.assertContainsRe(self.differ.to_file.getvalue(), '\+contents')
749
659
def test_diff_symlink(self):
750
differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
660
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
751
661
differ.diff_symlink('old target', None)
752
662
self.assertEqual("=== target was 'old target'\n",
753
663
differ.to_file.getvalue())
755
differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
665
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
756
666
differ.diff_symlink(None, 'new target')
757
667
self.assertEqual("=== target is 'new target'\n",
758
668
differ.to_file.getvalue())
760
differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
670
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
761
671
differ.diff_symlink('old target', 'new target')
762
672
self.assertEqual("=== target changed 'old target' => 'new target'\n",
763
673
differ.to_file.getvalue())
850
760
'.*a-file(.|\n)*b-file')
853
class TestPatienceDiffLib(tests.TestCase):
763
class TestPatienceDiffLib(TestCase):
856
766
super(TestPatienceDiffLib, self).setUp()
857
self._unique_lcs = _patiencediff_py.unique_lcs_py
858
self._recurse_matches = _patiencediff_py.recurse_matches_py
767
self._unique_lcs = bzrlib._patiencediff_py.unique_lcs_py
768
self._recurse_matches = bzrlib._patiencediff_py.recurse_matches_py
859
769
self._PatienceSequenceMatcher = \
860
_patiencediff_py.PatienceSequenceMatcher_py
862
def test_diff_unicode_string(self):
863
a = ''.join([unichr(i) for i in range(4000, 4500, 3)])
864
b = ''.join([unichr(i) for i in range(4300, 4800, 2)])
865
sm = self._PatienceSequenceMatcher(None, a, b)
866
mb = sm.get_matching_blocks()
867
self.assertEqual(35, len(mb))
770
bzrlib._patiencediff_py.PatienceSequenceMatcher_py
869
772
def test_unique_lcs(self):
870
773
unique_lcs = self._unique_lcs
871
self.assertEqual(unique_lcs('', ''), [])
872
self.assertEqual(unique_lcs('', 'a'), [])
873
self.assertEqual(unique_lcs('a', ''), [])
874
self.assertEqual(unique_lcs('a', 'a'), [(0,0)])
875
self.assertEqual(unique_lcs('a', 'b'), [])
876
self.assertEqual(unique_lcs('ab', 'ab'), [(0,0), (1,1)])
877
self.assertEqual(unique_lcs('abcde', 'cdeab'), [(2,0), (3,1), (4,2)])
878
self.assertEqual(unique_lcs('cdeab', 'abcde'), [(0,2), (1,3), (2,4)])
879
self.assertEqual(unique_lcs('abXde', 'abYde'), [(0,0), (1,1),
774
self.assertEquals(unique_lcs('', ''), [])
775
self.assertEquals(unique_lcs('', 'a'), [])
776
self.assertEquals(unique_lcs('a', ''), [])
777
self.assertEquals(unique_lcs('a', 'a'), [(0,0)])
778
self.assertEquals(unique_lcs('a', 'b'), [])
779
self.assertEquals(unique_lcs('ab', 'ab'), [(0,0), (1,1)])
780
self.assertEquals(unique_lcs('abcde', 'cdeab'), [(2,0), (3,1), (4,2)])
781
self.assertEquals(unique_lcs('cdeab', 'abcde'), [(0,2), (1,3), (2,4)])
782
self.assertEquals(unique_lcs('abXde', 'abYde'), [(0,0), (1,1),
881
self.assertEqual(unique_lcs('acbac', 'abc'), [(2,1)])
784
self.assertEquals(unique_lcs('acbac', 'abc'), [(2,1)])
883
786
def test_recurse_matches(self):
884
787
def test_one(a, b, matches):
885
788
test_matches = []
886
789
self._recurse_matches(
887
790
a, b, 0, 0, len(a), len(b), test_matches, 10)
888
self.assertEqual(test_matches, matches)
791
self.assertEquals(test_matches, matches)
890
793
test_one(['a', '', 'b', '', 'c'], ['a', 'a', 'b', 'c', 'c'],
891
794
[(0, 0), (2, 2), (4, 4)])
1218
1121
, list(unified_diff(txt_a, txt_b,
1219
1122
sequencematcher=psm)))
1221
def test_patience_unified_diff_with_dates(self):
1222
txt_a = ['hello there\n',
1224
'how are you today?\n']
1225
txt_b = ['hello there\n',
1226
'how are you today?\n']
1227
unified_diff = patiencediff.unified_diff
1228
psm = self._PatienceSequenceMatcher
1229
self.assertEqual(['--- a\t2008-08-08\n',
1230
'+++ b\t2008-09-09\n',
1231
'@@ -1,3 +1,2 @@\n',
1234
' how are you today?\n'
1236
, list(unified_diff(txt_a, txt_b,
1237
fromfile='a', tofile='b',
1238
fromfiledate='2008-08-08',
1239
tofiledate='2008-09-09',
1240
sequencematcher=psm)))
1243
1125
class TestPatienceDiffLib_c(TestPatienceDiffLib):
1245
_test_needs_features = [features.compiled_patiencediff_feature]
1127
_test_needs_features = [CompiledPatienceDiffFeature]
1247
1129
def setUp(self):
1248
1130
super(TestPatienceDiffLib_c, self).setUp()
1249
from bzrlib import _patiencediff_c
1250
self._unique_lcs = _patiencediff_c.unique_lcs_c
1251
self._recurse_matches = _patiencediff_c.recurse_matches_c
1131
import bzrlib._patiencediff_c
1132
self._unique_lcs = bzrlib._patiencediff_c.unique_lcs_c
1133
self._recurse_matches = bzrlib._patiencediff_c.recurse_matches_c
1252
1134
self._PatienceSequenceMatcher = \
1253
_patiencediff_c.PatienceSequenceMatcher_c
1135
bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1255
1137
def test_unhashable(self):
1256
1138
"""We should get a proper exception here."""
1317
1199
, list(unified_diff_files('a2', 'b2')))
1319
1201
# And the patience diff
1320
self.assertEqual(['--- a2\n',
1322
'@@ -4,6 +4,11 @@\n',
1334
list(unified_diff_files('a2', 'b2',
1335
sequencematcher=psm)))
1202
self.assertEquals(['--- a2 \n',
1204
'@@ -4,6 +4,11 @@\n',
1217
, list(unified_diff_files('a2', 'b2',
1218
sequencematcher=psm)))
1338
1221
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
1340
_test_needs_features = [features.compiled_patiencediff_feature]
1223
_test_needs_features = [CompiledPatienceDiffFeature]
1342
1225
def setUp(self):
1343
1226
super(TestPatienceDiffLibFiles_c, self).setUp()
1344
from bzrlib import _patiencediff_c
1227
import bzrlib._patiencediff_c
1345
1228
self._PatienceSequenceMatcher = \
1346
_patiencediff_c.PatienceSequenceMatcher_c
1349
class TestUsingCompiledIfAvailable(tests.TestCase):
1229
bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1232
class TestUsingCompiledIfAvailable(TestCase):
1351
1234
def test_PatienceSequenceMatcher(self):
1352
if features.compiled_patiencediff_feature.available():
1235
if CompiledPatienceDiffFeature.available():
1353
1236
from bzrlib._patiencediff_c import PatienceSequenceMatcher_c
1354
1237
self.assertIs(PatienceSequenceMatcher_c,
1355
patiencediff.PatienceSequenceMatcher)
1238
bzrlib.patiencediff.PatienceSequenceMatcher)
1357
1240
from bzrlib._patiencediff_py import PatienceSequenceMatcher_py
1358
1241
self.assertIs(PatienceSequenceMatcher_py,
1359
patiencediff.PatienceSequenceMatcher)
1242
bzrlib.patiencediff.PatienceSequenceMatcher)
1361
1244
def test_unique_lcs(self):
1362
if features.compiled_patiencediff_feature.available():
1245
if CompiledPatienceDiffFeature.available():
1363
1246
from bzrlib._patiencediff_c import unique_lcs_c
1364
1247
self.assertIs(unique_lcs_c,
1365
patiencediff.unique_lcs)
1248
bzrlib.patiencediff.unique_lcs)
1367
1250
from bzrlib._patiencediff_py import unique_lcs_py
1368
1251
self.assertIs(unique_lcs_py,
1369
patiencediff.unique_lcs)
1252
bzrlib.patiencediff.unique_lcs)
1371
1254
def test_recurse_matches(self):
1372
if features.compiled_patiencediff_feature.available():
1255
if CompiledPatienceDiffFeature.available():
1373
1256
from bzrlib._patiencediff_c import recurse_matches_c
1374
1257
self.assertIs(recurse_matches_c,
1375
patiencediff.recurse_matches)
1258
bzrlib.patiencediff.recurse_matches)
1377
1260
from bzrlib._patiencediff_py import recurse_matches_py
1378
1261
self.assertIs(recurse_matches_py,
1379
patiencediff.recurse_matches)
1382
class TestDiffFromTool(tests.TestCaseWithTransport):
1262
bzrlib.patiencediff.recurse_matches)
1265
class TestDiffFromTool(TestCaseWithTransport):
1384
1267
def test_from_string(self):
1385
diff_obj = diff.DiffFromTool.from_string('diff', None, None, None)
1268
diff_obj = DiffFromTool.from_string('diff', None, None, None)
1386
1269
self.addCleanup(diff_obj.finish)
1387
self.assertEqual(['diff', '@old_path', '@new_path'],
1270
self.assertEqual(['diff', '%(old_path)s', '%(new_path)s'],
1388
1271
diff_obj.command_template)
1390
1273
def test_from_string_u5(self):
1391
diff_obj = diff.DiffFromTool.from_string('diff "-u 5"',
1274
diff_obj = DiffFromTool.from_string('diff -u\\ 5', None, None, None)
1393
1275
self.addCleanup(diff_obj.finish)
1394
self.assertEqual(['diff', '-u 5', '@old_path', '@new_path'],
1276
self.assertEqual(['diff', '-u 5', '%(old_path)s', '%(new_path)s'],
1395
1277
diff_obj.command_template)
1396
1278
self.assertEqual(['diff', '-u 5', 'old-path', 'new-path'],
1397
1279
diff_obj._get_command('old-path', 'new-path'))
1399
def test_from_string_path_with_backslashes(self):
1400
self.requireFeature(features.backslashdir_feature)
1401
tool = 'C:\\Tools\\Diff.exe'
1402
diff_obj = diff.DiffFromTool.from_string(tool, None, None, None)
1403
self.addCleanup(diff_obj.finish)
1404
self.assertEqual(['C:\\Tools\\Diff.exe', '@old_path', '@new_path'],
1405
diff_obj.command_template)
1406
self.assertEqual(['C:\\Tools\\Diff.exe', 'old-path', 'new-path'],
1407
diff_obj._get_command('old-path', 'new-path'))
1409
1281
def test_execute(self):
1410
1282
output = StringIO()
1411
diff_obj = diff.DiffFromTool(['python', '-c',
1412
'print "@old_path @new_path"'],
1283
diff_obj = DiffFromTool(['python', '-c',
1284
'print "%(old_path)s %(new_path)s"'],
1414
1286
self.addCleanup(diff_obj.finish)
1415
1287
diff_obj._execute('old', 'new')
1416
1288
self.assertEqual(output.getvalue().rstrip(), 'old new')
1418
def test_execute_missing(self):
1419
diff_obj = diff.DiffFromTool(['a-tool-which-is-unlikely-to-exist'],
1290
def test_excute_missing(self):
1291
diff_obj = DiffFromTool(['a-tool-which-is-unlikely-to-exist'],
1421
1293
self.addCleanup(diff_obj.finish)
1422
e = self.assertRaises(errors.ExecutableMissing, diff_obj._execute,
1294
e = self.assertRaises(ExecutableMissing, diff_obj._execute, 'old',
1424
1296
self.assertEqual('a-tool-which-is-unlikely-to-exist could not be found'
1425
1297
' on this machine', str(e))
1427
1299
def test_prepare_files_creates_paths_readable_by_windows_tool(self):
1428
self.requireFeature(features.AttribFeature)
1300
self.requireFeature(AttribFeature)
1429
1301
output = StringIO()
1430
1302
tree = self.make_branch_and_tree('tree')
1431
1303
self.build_tree_contents([('tree/file', 'content')])
1433
1305
tree.commit('old tree')
1434
1306
tree.lock_read()
1435
1307
self.addCleanup(tree.unlock)
1436
basis_tree = tree.basis_tree()
1437
basis_tree.lock_read()
1438
self.addCleanup(basis_tree.unlock)
1439
diff_obj = diff.DiffFromTool(['python', '-c',
1440
'print "@old_path @new_path"'],
1441
basis_tree, tree, output)
1308
diff_obj = DiffFromTool(['python', '-c',
1309
'print "%(old_path)s %(new_path)s"'],
1442
1311
diff_obj._prepare_files('file-id', 'file', 'file')
1443
# The old content should be readonly
1444
self.assertReadableByAttrib(diff_obj._root, 'old\\file',
1446
# The new content should use the tree object, not a 'new' file anymore
1447
self.assertEndsWith(tree.basedir, 'work/tree')
1448
self.assertReadableByAttrib(tree.basedir, 'file', r'work\\tree\\file$')
1312
self.assertReadableByAttrib(diff_obj._root, 'old\\file', r'old\\file')
1313
self.assertReadableByAttrib(diff_obj._root, 'new\\file', r'new\\file')
1450
1315
def assertReadableByAttrib(self, cwd, relpath, regex):
1451
1316
proc = subprocess.Popen(['attrib', relpath],
1452
1317
stdout=subprocess.PIPE,
1454
(result, err) = proc.communicate()
1455
self.assertContainsRe(result.replace('\r\n', '\n'), regex)
1320
result = proc.stdout.read()
1321
self.assertContainsRe(result, regex)
1457
1323
def test_prepare_files(self):
1458
1324
output = StringIO()
1472
1337
self.addCleanup(old_tree.unlock)
1473
1338
tree.lock_read()
1474
1339
self.addCleanup(tree.unlock)
1475
diff_obj = diff.DiffFromTool(['python', '-c',
1476
'print "@old_path @new_path"'],
1477
old_tree, tree, output)
1340
diff_obj = DiffFromTool(['python', '-c',
1341
'print "%(old_path)s %(new_path)s"'],
1342
old_tree, tree, output)
1478
1343
self.addCleanup(diff_obj.finish)
1479
1344
self.assertContainsRe(diff_obj._root, 'bzr-diff-[^/]*')
1480
1345
old_path, new_path = diff_obj._prepare_files('file-id', 'oldname',
1482
1347
self.assertContainsRe(old_path, 'old/oldname$')
1483
self.assertEqual(315532800, os.stat(old_path).st_mtime)
1484
self.assertContainsRe(new_path, 'tree/newname$')
1348
self.assertEqual(0, os.stat(old_path).st_mtime)
1349
self.assertContainsRe(new_path, 'new/newname$')
1485
1350
self.assertFileEqual('oldcontent', old_path)
1486
1351
self.assertFileEqual('newcontent', new_path)
1487
1352
if osutils.host_os_dereferences_symlinks():
1488
1353
self.assertTrue(os.path.samefile('tree/newname', new_path))
1489
1354
# make sure we can create files with the same parent directories
1490
1355
diff_obj._prepare_files('file2-id', 'oldname2', 'newname2')
1493
class TestDiffFromToolEncodedFilename(tests.TestCaseWithTransport):
1495
def test_encodable_filename(self):
1496
# Just checks file path for external diff tool.
1497
# We cannot change CPython's internal encoding used by os.exec*.
1498
diffobj = diff.DiffFromTool(['dummy', '@old_path', '@new_path'],
1500
for _, scenario in EncodingAdapter.encoding_scenarios:
1501
encoding = scenario['encoding']
1502
dirname = scenario['info']['directory']
1503
filename = scenario['info']['filename']
1505
self.overrideAttr(diffobj, '_fenc', lambda: encoding)
1506
relpath = dirname + u'/' + filename
1507
fullpath = diffobj._safe_filename('safe', relpath)
1508
self.assertEqual(fullpath,
1509
fullpath.encode(encoding).decode(encoding))
1510
self.assertTrue(fullpath.startswith(diffobj._root + '/safe'))
1512
def test_unencodable_filename(self):
1513
diffobj = diff.DiffFromTool(['dummy', '@old_path', '@new_path'],
1515
for _, scenario in EncodingAdapter.encoding_scenarios:
1516
encoding = scenario['encoding']
1517
dirname = scenario['info']['directory']
1518
filename = scenario['info']['filename']
1520
if encoding == 'iso-8859-1':
1521
encoding = 'iso-8859-2'
1523
encoding = 'iso-8859-1'
1525
self.overrideAttr(diffobj, '_fenc', lambda: encoding)
1526
relpath = dirname + u'/' + filename
1527
fullpath = diffobj._safe_filename('safe', relpath)
1528
self.assertEqual(fullpath,
1529
fullpath.encode(encoding).decode(encoding))
1530
self.assertTrue(fullpath.startswith(diffobj._root + '/safe'))
1533
class TestGetTreesAndBranchesToDiffLocked(tests.TestCaseWithTransport):
1535
def call_gtabtd(self, path_list, revision_specs, old_url, new_url):
1536
"""Call get_trees_and_branches_to_diff_locked."""
1537
return diff.get_trees_and_branches_to_diff_locked(
1538
path_list, revision_specs, old_url, new_url, self.addCleanup)
1540
def test_basic(self):
1541
tree = self.make_branch_and_tree('tree')
1542
(old_tree, new_tree,
1543
old_branch, new_branch,
1544
specific_files, extra_trees) = self.call_gtabtd(
1545
['tree'], None, None, None)
1547
self.assertIsInstance(old_tree, revisiontree.RevisionTree)
1548
self.assertEqual(_mod_revision.NULL_REVISION,
1549
old_tree.get_revision_id())
1550
self.assertEqual(tree.basedir, new_tree.basedir)
1551
self.assertEqual(tree.branch.base, old_branch.base)
1552
self.assertEqual(tree.branch.base, new_branch.base)
1553
self.assertIs(None, specific_files)
1554
self.assertIs(None, extra_trees)
1556
def test_with_rev_specs(self):
1557
tree = self.make_branch_and_tree('tree')
1558
self.build_tree_contents([('tree/file', 'oldcontent')])
1559
tree.add('file', 'file-id')
1560
tree.commit('old tree', timestamp=0, rev_id="old-id")
1561
self.build_tree_contents([('tree/file', 'newcontent')])
1562
tree.commit('new tree', timestamp=0, rev_id="new-id")
1564
revisions = [revisionspec.RevisionSpec.from_string('1'),
1565
revisionspec.RevisionSpec.from_string('2')]
1566
(old_tree, new_tree,
1567
old_branch, new_branch,
1568
specific_files, extra_trees) = self.call_gtabtd(
1569
['tree'], revisions, None, None)
1571
self.assertIsInstance(old_tree, revisiontree.RevisionTree)
1572
self.assertEqual("old-id", old_tree.get_revision_id())
1573
self.assertIsInstance(new_tree, revisiontree.RevisionTree)
1574
self.assertEqual("new-id", new_tree.get_revision_id())
1575
self.assertEqual(tree.branch.base, old_branch.base)
1576
self.assertEqual(tree.branch.base, new_branch.base)
1577
self.assertIs(None, specific_files)
1578
self.assertEqual(tree.basedir, extra_trees[0].basedir)