34
from bzrlib.tests import (
35
from bzrlib.symbol_versioning import deprecated_in
36
from bzrlib.tests import features
38
37
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
40
class _AttribFeature(tests.Feature):
43
if (sys.platform not in ('cygwin', 'win32')):
46
proc = subprocess.Popen(['attrib', '.'], stdout=subprocess.PIPE)
49
return (0 == proc.wait())
51
def feature_name(self):
52
return 'attrib Windows command-line tool'
54
AttribFeature = _AttribFeature()
57
compiled_patiencediff_feature = tests.ModuleAvailableFeature(
58
'bzrlib._patiencediff_c')
45
61
def udiff_lines(old, new, allow_binary=False):
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
84
class TestDiff(tests.TestCase):
93
86
def test_add_nl(self):
94
87
"""diff generates a valid diff for patches that add a newline"""
95
88
lines = udiff_lines(['boo'], ['boo\n'])
96
89
self.check_patch(lines)
97
self.assertEqual(lines[4], '\\ No newline at end of file\n')
90
self.assertEquals(lines[4], '\\ No newline at end of file\n')
98
91
## "expected no-nl, got %r" % lines[4]
100
93
def test_add_nl_2(self):
113
106
lines = udiff_lines(['boo\n'], ['boo'])
114
107
self.check_patch(lines)
115
self.assertEqual(lines[5], '\\ No newline at end of file\n')
108
self.assertEquals(lines[5], '\\ No newline at end of file\n')
116
109
## "expected no-nl, got %r" % lines[5]
118
111
def check_patch(self, lines):
119
self.assertTrue(len(lines) > 1)
112
self.assert_(len(lines) > 1)
120
113
## "Not enough lines for a file header for patch:\n%s" % "".join(lines)
121
self.assertTrue(lines[0].startswith ('---'))
114
self.assert_(lines[0].startswith ('---'))
122
115
## 'No orig line for patch:\n%s' % "".join(lines)
123
self.assertTrue(lines[1].startswith ('+++'))
116
self.assert_(lines[1].startswith ('+++'))
124
117
## 'No mod line for patch:\n%s' % "".join(lines)
125
self.assertTrue(len(lines) > 2)
118
self.assert_(len(lines) > 2)
126
119
## "No hunks for patch:\n%s" % "".join(lines)
127
self.assertTrue(lines[2].startswith('@@'))
120
self.assert_(lines[2].startswith('@@'))
128
121
## "No hunk header for patch:\n%s" % "".join(lines)
129
self.assertTrue('@@' in lines[2][2:])
122
self.assert_('@@' in lines[2][2:])
130
123
## "Unterminated hunk header for patch:\n%s" % "".join(lines)
132
125
def test_binary_lines(self):
151
144
self.check_patch(lines)
153
146
def test_external_diff_binary_lang_c(self):
154
148
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'])
149
old_env[lang] = osutils.set_or_unset_env(lang, 'C')
151
lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
152
# Older versions of diffutils say "Binary files", newer
153
# versions just say "Files".
154
self.assertContainsRe(lines[0],
155
'(Binary f|F)iles old and new differ\n')
156
self.assertEquals(lines[1:], ['\n'])
158
for lang, old_val in old_env.iteritems():
159
osutils.set_or_unset_env(lang, old_val)
162
161
def test_no_external_diff(self):
163
162
"""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'])
163
# Use os.environ['PATH'] to make sure no 'diff' command is available
164
orig_path = os.environ['PATH']
166
os.environ['PATH'] = ''
167
self.assertRaises(errors.NoDiff, diff.external_diff,
168
'old', ['boo\n'], 'new', ['goo\n'],
169
StringIO(), diff_opts=['-u'])
171
os.environ['PATH'] = orig_path
171
173
def test_internal_diff_default(self):
172
174
# Default internal diff encoding is utf8
233
235
output = StringIO.StringIO()
234
236
diff.internal_diff(u'old_\xb5', ['old_text\n'],
235
237
u'new_\xe5', ['new_text\n'], output)
236
self.assertIsInstance(output.getvalue(), str,
238
self.failUnless(isinstance(output.getvalue(), str),
237
239
'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
242
class TestDiffFiles(tests.TestCaseInTempDir):
308
247
lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
310
249
cmd = ['diff', '-u', '--binary', 'old', 'new']
311
with open('old', 'wb') as f: f.write('\x00foobar\n')
312
with open('new', 'wb') as f: f.write('foo\x00bar\n')
250
open('old', 'wb').write('\x00foobar\n')
251
open('new', 'wb').write('foo\x00bar\n')
313
252
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
314
253
stdin=subprocess.PIPE)
315
254
out, err = pipe.communicate()
255
# Diff returns '2' on Binary files.
256
self.assertEqual(2, pipe.returncode)
316
257
# We should output whatever diff tells us, plus a trailing newline
317
258
self.assertEqual(out.splitlines(True) + ['\n'], lines)
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):
261
class TestShowDiffTreesHelper(tests.TestCaseWithTransport):
262
"""Has a helper for running show_diff_trees"""
264
def get_diff(self, tree1, tree2, specific_files=None, working_tree=None):
266
if working_tree is not None:
267
extra_trees = (working_tree,)
270
diff.show_diff_trees(tree1, tree2, output,
271
specific_files=specific_files,
272
extra_trees=extra_trees, old_label='old/',
274
return output.getvalue()
277
class TestDiffDates(TestShowDiffTreesHelper):
336
280
super(TestDiffDates, self).setUp()
451
395
self.wt.rename_one('file1', 'dir1/file1')
452
396
old_tree = self.b.repository.revision_tree('rev-1')
453
397
new_tree = self.b.repository.revision_tree('rev-4')
454
out = get_diff_as_string(old_tree, new_tree, specific_files=['dir1'],
398
out = self.get_diff(old_tree, new_tree, specific_files=['dir1'],
455
399
working_tree=self.wt)
456
400
self.assertContainsRe(out, 'file1\t')
457
out = get_diff_as_string(old_tree, new_tree, specific_files=['dir2'],
401
out = self.get_diff(old_tree, new_tree, specific_files=['dir2'],
458
402
working_tree=self.wt)
459
403
self.assertNotContainsRe(out, 'file1\t')
462
class TestShowDiffTrees(tests.TestCaseWithTransport):
407
class TestShowDiffTrees(TestShowDiffTreesHelper):
463
408
"""Direct tests for show_diff_trees"""
465
410
def test_modified_file(self):
862
807
b = ''.join([unichr(i) for i in range(4300, 4800, 2)])
863
808
sm = self._PatienceSequenceMatcher(None, a, b)
864
809
mb = sm.get_matching_blocks()
865
self.assertEqual(35, len(mb))
810
self.assertEquals(35, len(mb))
867
812
def test_unique_lcs(self):
868
813
unique_lcs = self._unique_lcs
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),
814
self.assertEquals(unique_lcs('', ''), [])
815
self.assertEquals(unique_lcs('', 'a'), [])
816
self.assertEquals(unique_lcs('a', ''), [])
817
self.assertEquals(unique_lcs('a', 'a'), [(0,0)])
818
self.assertEquals(unique_lcs('a', 'b'), [])
819
self.assertEquals(unique_lcs('ab', 'ab'), [(0,0), (1,1)])
820
self.assertEquals(unique_lcs('abcde', 'cdeab'), [(2,0), (3,1), (4,2)])
821
self.assertEquals(unique_lcs('cdeab', 'abcde'), [(0,2), (1,3), (2,4)])
822
self.assertEquals(unique_lcs('abXde', 'abYde'), [(0,0), (1,1),
879
self.assertEqual(unique_lcs('acbac', 'abc'), [(2,1)])
824
self.assertEquals(unique_lcs('acbac', 'abc'), [(2,1)])
881
826
def test_recurse_matches(self):
882
827
def test_one(a, b, matches):
883
828
test_matches = []
884
829
self._recurse_matches(
885
830
a, b, 0, 0, len(a), len(b), test_matches, 10)
886
self.assertEqual(test_matches, matches)
831
self.assertEquals(test_matches, matches)
888
833
test_one(['a', '', 'b', '', 'c'], ['a', 'a', 'b', 'c', 'c'],
889
834
[(0, 0), (2, 2), (4, 4)])
1315
1260
, list(unified_diff_files('a2', 'b2')))
1317
1262
# And the patience diff
1318
self.assertEqual(['--- a2\n',
1320
'@@ -4,6 +4,11 @@\n',
1332
list(unified_diff_files('a2', 'b2',
1333
sequencematcher=psm)))
1263
self.assertEquals(['--- a2\n',
1265
'@@ -4,6 +4,11 @@\n',
1278
, list(unified_diff_files('a2', 'b2',
1279
sequencematcher=psm)))
1336
1282
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
1338
_test_needs_features = [features.compiled_patiencediff_feature]
1284
_test_needs_features = [compiled_patiencediff_feature]
1340
1286
def setUp(self):
1341
1287
super(TestPatienceDiffLibFiles_c, self).setUp()
1488
1434
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
1437
class TestGetTreesAndBranchesToDiffLocked(tests.TestCaseWithTransport):
1533
1439
def call_gtabtd(self, path_list, revision_specs, old_url, new_url):
1534
"""Call get_trees_and_branches_to_diff_locked."""
1440
"""Call get_trees_and_branches_to_diff_locked. Overridden by
1441
TestGetTreesAndBranchesToDiff.
1535
1443
return diff.get_trees_and_branches_to_diff_locked(
1536
1444
path_list, revision_specs, old_url, new_url, self.addCleanup)
1574
1482
self.assertEqual(tree.branch.base, new_branch.base)
1575
1483
self.assertIs(None, specific_files)
1576
1484
self.assertEqual(tree.basedir, extra_trees[0].basedir)
1487
class TestGetTreesAndBranchesToDiff(TestGetTreesAndBranchesToDiffLocked):
1488
"""Apply the tests for get_trees_and_branches_to_diff_locked to the
1489
deprecated get_trees_and_branches_to_diff function.
1492
def call_gtabtd(self, path_list, revision_specs, old_url, new_url):
1493
return self.applyDeprecated(
1494
deprecated_in((2, 2, 0)), diff.get_trees_and_branches_to_diff,
1495
path_list, revision_specs, old_url, new_url)