1
from bzrlib.selftest import TestCase
2
from bzrlib.diff import internal_diff
1
# Copyright (C) 2005, 2006 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
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
3
19
from cStringIO import StringIO
4
def udiff_lines(old, new):
23
from tempfile import TemporaryFile
25
from bzrlib import tests
26
from bzrlib.diff import (
35
get_trees_and_branches_to_diff,
37
from bzrlib.errors import BinaryFile, NoDiff, ExecutableMissing
38
import bzrlib.osutils as osutils
39
import bzrlib.revision as _mod_revision
40
import bzrlib.transform as transform
41
import bzrlib.patiencediff
42
import bzrlib._patiencediff_py
43
from bzrlib.tests import (Feature, TestCase, TestCaseWithTransport,
44
TestCaseInTempDir, TestSkipped)
45
from bzrlib.revisiontree import RevisionTree
46
from bzrlib.revisionspec import RevisionSpec
49
class _AttribFeature(Feature):
52
if (sys.platform not in ('cygwin', 'win32')):
55
proc = subprocess.Popen(['attrib', '.'], stdout=subprocess.PIPE)
58
return (0 == proc.wait())
60
def feature_name(self):
61
return 'attrib Windows command-line tool'
63
AttribFeature = _AttribFeature()
66
class _CompiledPatienceDiffFeature(Feature):
70
import bzrlib._patiencediff_c
75
def feature_name(self):
76
return 'bzrlib._patiencediff_c'
78
CompiledPatienceDiffFeature = _CompiledPatienceDiffFeature()
81
def udiff_lines(old, new, allow_binary=False):
6
internal_diff('old', old, 'new', new, output)
83
internal_diff('old', old, 'new', new, output, allow_binary)
8
85
return output.readlines()
10
def check_patch(lines):
11
assert len(lines) > 1, \
12
"Not enough lines for a file header for patch:\n%s" % "".join(lines)
13
assert lines[0].startswith ('---'), \
14
'No orig line for patch:\n%s' % "".join(lines)
15
assert lines[1].startswith ('+++'), \
16
'No mod line for patch:\n%s' % "".join(lines)
17
assert len(lines) > 2, \
18
"No hunks for patch:\n%s" % "".join(lines)
19
assert lines[2].startswith('@@'),\
20
"No hunk header for patch:\n%s" % "".join(lines)
21
assert '@@' in lines[2][2:], \
22
"Unterminated hunk header for patch:\n%s" % "".join(lines)
88
def external_udiff_lines(old, new, use_stringio=False):
90
# StringIO has no fileno, so it tests a different codepath
93
output = TemporaryFile()
95
external_diff('old', old, 'new', new, output, diff_opts=['-u'])
97
raise TestSkipped('external "diff" not present to test')
99
lines = output.readlines()
24
104
class TestDiff(TestCase):
25
106
def test_add_nl(self):
26
107
"""diff generates a valid diff for patches that add a newline"""
27
108
lines = udiff_lines(['boo'], ['boo\n'])
29
assert lines[4] == '\\ No newline at end of file\n', \
30
"expected no-nl, got %r" % lines[4]
109
self.check_patch(lines)
110
self.assertEquals(lines[4], '\\ No newline at end of file\n')
111
## "expected no-nl, got %r" % lines[4]
32
113
def test_add_nl_2(self):
33
114
"""diff generates a valid diff for patches that change last line and
36
117
lines = udiff_lines(['boo'], ['goo\n'])
38
assert lines[4] == '\\ No newline at end of file\n', \
39
"expected no-nl, got %r" % lines[4]
118
self.check_patch(lines)
119
self.assertEquals(lines[4], '\\ No newline at end of file\n')
120
## "expected no-nl, got %r" % lines[4]
41
122
def test_remove_nl(self):
42
123
"""diff generates a valid diff for patches that change last line and
45
126
lines = udiff_lines(['boo\n'], ['boo'])
47
assert lines[5] == '\\ No newline at end of file\n', \
48
"expected no-nl, got %r" % lines[5]
127
self.check_patch(lines)
128
self.assertEquals(lines[5], '\\ No newline at end of file\n')
129
## "expected no-nl, got %r" % lines[5]
131
def check_patch(self, lines):
132
self.assert_(len(lines) > 1)
133
## "Not enough lines for a file header for patch:\n%s" % "".join(lines)
134
self.assert_(lines[0].startswith ('---'))
135
## 'No orig line for patch:\n%s' % "".join(lines)
136
self.assert_(lines[1].startswith ('+++'))
137
## 'No mod line for patch:\n%s' % "".join(lines)
138
self.assert_(len(lines) > 2)
139
## "No hunks for patch:\n%s" % "".join(lines)
140
self.assert_(lines[2].startswith('@@'))
141
## "No hunk header for patch:\n%s" % "".join(lines)
142
self.assert_('@@' in lines[2][2:])
143
## "Unterminated hunk header for patch:\n%s" % "".join(lines)
145
def test_binary_lines(self):
146
self.assertRaises(BinaryFile, udiff_lines, [1023 * 'a' + '\x00'], [])
147
self.assertRaises(BinaryFile, udiff_lines, [], [1023 * 'a' + '\x00'])
148
udiff_lines([1023 * 'a' + '\x00'], [], allow_binary=True)
149
udiff_lines([], [1023 * 'a' + '\x00'], allow_binary=True)
151
def test_external_diff(self):
152
lines = external_udiff_lines(['boo\n'], ['goo\n'])
153
self.check_patch(lines)
154
self.assertEqual('\n', lines[-1])
156
def test_external_diff_no_fileno(self):
157
# Make sure that we can handle not having a fileno, even
158
# if the diff is large
159
lines = external_udiff_lines(['boo\n']*10000,
162
self.check_patch(lines)
164
def test_external_diff_binary_lang_c(self):
166
for lang in ('LANG', 'LC_ALL', 'LANGUAGE'):
167
old_env[lang] = osutils.set_or_unset_env(lang, 'C')
169
lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
170
# Older versions of diffutils say "Binary files", newer
171
# versions just say "Files".
172
self.assertContainsRe(lines[0],
173
'(Binary f|F)iles old and new differ\n')
174
self.assertEquals(lines[1:], ['\n'])
176
for lang, old_val in old_env.iteritems():
177
osutils.set_or_unset_env(lang, old_val)
179
def test_no_external_diff(self):
180
"""Check that NoDiff is raised when diff is not available"""
181
# Use os.environ['PATH'] to make sure no 'diff' command is available
182
orig_path = os.environ['PATH']
184
os.environ['PATH'] = ''
185
self.assertRaises(NoDiff, external_diff,
186
'old', ['boo\n'], 'new', ['goo\n'],
187
StringIO(), diff_opts=['-u'])
189
os.environ['PATH'] = orig_path
191
def test_internal_diff_default(self):
192
# Default internal diff encoding is utf8
194
internal_diff(u'old_\xb5', ['old_text\n'],
195
u'new_\xe5', ['new_text\n'], output)
196
lines = output.getvalue().splitlines(True)
197
self.check_patch(lines)
198
self.assertEquals(['--- old_\xc2\xb5\n',
199
'+++ new_\xc3\xa5\n',
207
def test_internal_diff_utf8(self):
209
internal_diff(u'old_\xb5', ['old_text\n'],
210
u'new_\xe5', ['new_text\n'], output,
211
path_encoding='utf8')
212
lines = output.getvalue().splitlines(True)
213
self.check_patch(lines)
214
self.assertEquals(['--- old_\xc2\xb5\n',
215
'+++ new_\xc3\xa5\n',
223
def test_internal_diff_iso_8859_1(self):
225
internal_diff(u'old_\xb5', ['old_text\n'],
226
u'new_\xe5', ['new_text\n'], output,
227
path_encoding='iso-8859-1')
228
lines = output.getvalue().splitlines(True)
229
self.check_patch(lines)
230
self.assertEquals(['--- old_\xb5\n',
239
def test_internal_diff_no_content(self):
241
internal_diff(u'old', [], u'new', [], output)
242
self.assertEqual('', output.getvalue())
244
def test_internal_diff_no_changes(self):
246
internal_diff(u'old', ['text\n', 'contents\n'],
247
u'new', ['text\n', 'contents\n'],
249
self.assertEqual('', output.getvalue())
251
def test_internal_diff_returns_bytes(self):
253
output = StringIO.StringIO()
254
internal_diff(u'old_\xb5', ['old_text\n'],
255
u'new_\xe5', ['new_text\n'], output)
256
self.failUnless(isinstance(output.getvalue(), str),
257
'internal_diff should return bytestrings')
260
class TestDiffFiles(TestCaseInTempDir):
262
def test_external_diff_binary(self):
263
"""The output when using external diff should use diff's i18n error"""
264
# Make sure external_diff doesn't fail in the current LANG
265
lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
267
cmd = ['diff', '-u', '--binary', 'old', 'new']
268
open('old', 'wb').write('\x00foobar\n')
269
open('new', 'wb').write('foo\x00bar\n')
270
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
271
stdin=subprocess.PIPE)
272
out, err = pipe.communicate()
273
# Diff returns '2' on Binary files.
274
self.assertEqual(2, pipe.returncode)
275
# We should output whatever diff tells us, plus a trailing newline
276
self.assertEqual(out.splitlines(True) + ['\n'], lines)
279
class TestShowDiffTreesHelper(TestCaseWithTransport):
280
"""Has a helper for running show_diff_trees"""
282
def get_diff(self, tree1, tree2, specific_files=None, working_tree=None):
284
if working_tree is not None:
285
extra_trees = (working_tree,)
288
show_diff_trees(tree1, tree2, output, specific_files=specific_files,
289
extra_trees=extra_trees, old_label='old/',
291
return output.getvalue()
294
class TestDiffDates(TestShowDiffTreesHelper):
297
super(TestDiffDates, self).setUp()
298
self.wt = self.make_branch_and_tree('.')
299
self.b = self.wt.branch
300
self.build_tree_contents([
301
('file1', 'file1 contents at rev 1\n'),
302
('file2', 'file2 contents at rev 1\n')
304
self.wt.add(['file1', 'file2'])
306
message='Revision 1',
307
timestamp=1143849600, # 2006-04-01 00:00:00 UTC
310
self.build_tree_contents([('file1', 'file1 contents at rev 2\n')])
312
message='Revision 2',
313
timestamp=1143936000, # 2006-04-02 00:00:00 UTC
316
self.build_tree_contents([('file2', 'file2 contents at rev 3\n')])
318
message='Revision 3',
319
timestamp=1144022400, # 2006-04-03 00:00:00 UTC
322
self.wt.remove(['file2'])
324
message='Revision 4',
325
timestamp=1144108800, # 2006-04-04 00:00:00 UTC
328
self.build_tree_contents([
329
('file1', 'file1 contents in working tree\n')
331
# set the date stamps for files in the working tree to known values
332
os.utime('file1', (1144195200, 1144195200)) # 2006-04-05 00:00:00 UTC
334
def test_diff_rev_tree_working_tree(self):
335
output = self.get_diff(self.wt.basis_tree(), self.wt)
336
# note that the date for old/file1 is from rev 2 rather than from
337
# the basis revision (rev 4)
338
self.assertEqualDiff(output, '''\
339
=== modified file 'file1'
340
--- old/file1\t2006-04-02 00:00:00 +0000
341
+++ new/file1\t2006-04-05 00:00:00 +0000
343
-file1 contents at rev 2
344
+file1 contents in working tree
348
def test_diff_rev_tree_rev_tree(self):
349
tree1 = self.b.repository.revision_tree('rev-2')
350
tree2 = self.b.repository.revision_tree('rev-3')
351
output = self.get_diff(tree1, tree2)
352
self.assertEqualDiff(output, '''\
353
=== modified file 'file2'
354
--- old/file2\t2006-04-01 00:00:00 +0000
355
+++ new/file2\t2006-04-03 00:00:00 +0000
357
-file2 contents at rev 1
358
+file2 contents at rev 3
362
def test_diff_add_files(self):
363
tree1 = self.b.repository.revision_tree(_mod_revision.NULL_REVISION)
364
tree2 = self.b.repository.revision_tree('rev-1')
365
output = self.get_diff(tree1, tree2)
366
# the files have the epoch time stamp for the tree in which
368
self.assertEqualDiff(output, '''\
369
=== added file 'file1'
370
--- old/file1\t1970-01-01 00:00:00 +0000
371
+++ new/file1\t2006-04-01 00:00:00 +0000
373
+file1 contents at rev 1
375
=== added file 'file2'
376
--- old/file2\t1970-01-01 00:00:00 +0000
377
+++ new/file2\t2006-04-01 00:00:00 +0000
379
+file2 contents at rev 1
383
def test_diff_remove_files(self):
384
tree1 = self.b.repository.revision_tree('rev-3')
385
tree2 = self.b.repository.revision_tree('rev-4')
386
output = self.get_diff(tree1, tree2)
387
# the file has the epoch time stamp for the tree in which
389
self.assertEqualDiff(output, '''\
390
=== removed file 'file2'
391
--- old/file2\t2006-04-03 00:00:00 +0000
392
+++ new/file2\t1970-01-01 00:00:00 +0000
394
-file2 contents at rev 3
398
def test_show_diff_specified(self):
399
"""A working tree filename can be used to identify a file"""
400
self.wt.rename_one('file1', 'file1b')
401
old_tree = self.b.repository.revision_tree('rev-1')
402
new_tree = self.b.repository.revision_tree('rev-4')
403
out = self.get_diff(old_tree, new_tree, specific_files=['file1b'],
404
working_tree=self.wt)
405
self.assertContainsRe(out, 'file1\t')
407
def test_recursive_diff(self):
408
"""Children of directories are matched"""
411
self.wt.add(['dir1', 'dir2'])
412
self.wt.rename_one('file1', 'dir1/file1')
413
old_tree = self.b.repository.revision_tree('rev-1')
414
new_tree = self.b.repository.revision_tree('rev-4')
415
out = self.get_diff(old_tree, new_tree, specific_files=['dir1'],
416
working_tree=self.wt)
417
self.assertContainsRe(out, 'file1\t')
418
out = self.get_diff(old_tree, new_tree, specific_files=['dir2'],
419
working_tree=self.wt)
420
self.assertNotContainsRe(out, 'file1\t')
424
class TestShowDiffTrees(TestShowDiffTreesHelper):
425
"""Direct tests for show_diff_trees"""
427
def test_modified_file(self):
428
"""Test when a file is modified."""
429
tree = self.make_branch_and_tree('tree')
430
self.build_tree_contents([('tree/file', 'contents\n')])
431
tree.add(['file'], ['file-id'])
432
tree.commit('one', rev_id='rev-1')
434
self.build_tree_contents([('tree/file', 'new contents\n')])
435
diff = self.get_diff(tree.basis_tree(), tree)
436
self.assertContainsRe(diff, "=== modified file 'file'\n")
437
self.assertContainsRe(diff, '--- old/file\t')
438
self.assertContainsRe(diff, '\\+\\+\\+ new/file\t')
439
self.assertContainsRe(diff, '-contents\n'
442
def test_modified_file_in_renamed_dir(self):
443
"""Test when a file is modified in a renamed directory."""
444
tree = self.make_branch_and_tree('tree')
445
self.build_tree(['tree/dir/'])
446
self.build_tree_contents([('tree/dir/file', 'contents\n')])
447
tree.add(['dir', 'dir/file'], ['dir-id', 'file-id'])
448
tree.commit('one', rev_id='rev-1')
450
tree.rename_one('dir', 'other')
451
self.build_tree_contents([('tree/other/file', 'new contents\n')])
452
diff = self.get_diff(tree.basis_tree(), tree)
453
self.assertContainsRe(diff, "=== renamed directory 'dir' => 'other'\n")
454
self.assertContainsRe(diff, "=== modified file 'other/file'\n")
455
# XXX: This is technically incorrect, because it used to be at another
456
# location. What to do?
457
self.assertContainsRe(diff, '--- old/dir/file\t')
458
self.assertContainsRe(diff, '\\+\\+\\+ new/other/file\t')
459
self.assertContainsRe(diff, '-contents\n'
462
def test_renamed_directory(self):
463
"""Test when only a directory is only renamed."""
464
tree = self.make_branch_and_tree('tree')
465
self.build_tree(['tree/dir/'])
466
self.build_tree_contents([('tree/dir/file', 'contents\n')])
467
tree.add(['dir', 'dir/file'], ['dir-id', 'file-id'])
468
tree.commit('one', rev_id='rev-1')
470
tree.rename_one('dir', 'newdir')
471
diff = self.get_diff(tree.basis_tree(), tree)
472
# Renaming a directory should be a single "you renamed this dir" even
473
# when there are files inside.
474
self.assertEqual("=== renamed directory 'dir' => 'newdir'\n", diff)
476
def test_renamed_file(self):
477
"""Test when a file is only renamed."""
478
tree = self.make_branch_and_tree('tree')
479
self.build_tree_contents([('tree/file', 'contents\n')])
480
tree.add(['file'], ['file-id'])
481
tree.commit('one', rev_id='rev-1')
483
tree.rename_one('file', 'newname')
484
diff = self.get_diff(tree.basis_tree(), tree)
485
self.assertContainsRe(diff, "=== renamed file 'file' => 'newname'\n")
486
# We shouldn't have a --- or +++ line, because there is no content
488
self.assertNotContainsRe(diff, '---')
490
def test_renamed_and_modified_file(self):
491
"""Test when a file is only renamed."""
492
tree = self.make_branch_and_tree('tree')
493
self.build_tree_contents([('tree/file', 'contents\n')])
494
tree.add(['file'], ['file-id'])
495
tree.commit('one', rev_id='rev-1')
497
tree.rename_one('file', 'newname')
498
self.build_tree_contents([('tree/newname', 'new contents\n')])
499
diff = self.get_diff(tree.basis_tree(), tree)
500
self.assertContainsRe(diff, "=== renamed file 'file' => 'newname'\n")
501
self.assertContainsRe(diff, '--- old/file\t')
502
self.assertContainsRe(diff, '\\+\\+\\+ new/newname\t')
503
self.assertContainsRe(diff, '-contents\n'
507
def test_internal_diff_exec_property(self):
508
tree = self.make_branch_and_tree('tree')
510
tt = transform.TreeTransform(tree)
511
tt.new_file('a', tt.root, 'contents\n', 'a-id', True)
512
tt.new_file('b', tt.root, 'contents\n', 'b-id', False)
513
tt.new_file('c', tt.root, 'contents\n', 'c-id', True)
514
tt.new_file('d', tt.root, 'contents\n', 'd-id', False)
515
tt.new_file('e', tt.root, 'contents\n', 'control-e-id', True)
516
tt.new_file('f', tt.root, 'contents\n', 'control-f-id', False)
518
tree.commit('one', rev_id='rev-1')
520
tt = transform.TreeTransform(tree)
521
tt.set_executability(False, tt.trans_id_file_id('a-id'))
522
tt.set_executability(True, tt.trans_id_file_id('b-id'))
523
tt.set_executability(False, tt.trans_id_file_id('c-id'))
524
tt.set_executability(True, tt.trans_id_file_id('d-id'))
526
tree.rename_one('c', 'new-c')
527
tree.rename_one('d', 'new-d')
529
diff = self.get_diff(tree.basis_tree(), tree)
531
self.assertContainsRe(diff, r"file 'a'.*\(properties changed:.*\+x to -x.*\)")
532
self.assertContainsRe(diff, r"file 'b'.*\(properties changed:.*-x to \+x.*\)")
533
self.assertContainsRe(diff, r"file 'c'.*\(properties changed:.*\+x to -x.*\)")
534
self.assertContainsRe(diff, r"file 'd'.*\(properties changed:.*-x to \+x.*\)")
535
self.assertNotContainsRe(diff, r"file 'e'")
536
self.assertNotContainsRe(diff, r"file 'f'")
539
def test_binary_unicode_filenames(self):
540
"""Test that contents of files are *not* encoded in UTF-8 when there
541
is a binary file in the diff.
543
# See https://bugs.launchpad.net/bugs/110092.
544
self.requireFeature(tests.UnicodeFilenameFeature)
546
# This bug isn't triggered with cStringIO.
547
from StringIO import StringIO
548
tree = self.make_branch_and_tree('tree')
549
alpha, omega = u'\u03b1', u'\u03c9'
550
alpha_utf8, omega_utf8 = alpha.encode('utf8'), omega.encode('utf8')
551
self.build_tree_contents(
552
[('tree/' + alpha, chr(0)),
554
('The %s and the %s\n' % (alpha_utf8, omega_utf8)))])
555
tree.add([alpha], ['file-id'])
556
tree.add([omega], ['file-id-2'])
557
diff_content = StringIO()
558
show_diff_trees(tree.basis_tree(), tree, diff_content)
559
diff = diff_content.getvalue()
560
self.assertContainsRe(diff, r"=== added file '%s'" % alpha_utf8)
561
self.assertContainsRe(
562
diff, "Binary files a/%s.*and b/%s.* differ\n" % (alpha_utf8, alpha_utf8))
563
self.assertContainsRe(diff, r"=== added file '%s'" % omega_utf8)
564
self.assertContainsRe(diff, r"--- a/%s" % (omega_utf8,))
565
self.assertContainsRe(diff, r"\+\+\+ b/%s" % (omega_utf8,))
567
def test_unicode_filename(self):
568
"""Test when the filename are unicode."""
569
self.requireFeature(tests.UnicodeFilenameFeature)
571
alpha, omega = u'\u03b1', u'\u03c9'
572
autf8, outf8 = alpha.encode('utf8'), omega.encode('utf8')
574
tree = self.make_branch_and_tree('tree')
575
self.build_tree_contents([('tree/ren_'+alpha, 'contents\n')])
576
tree.add(['ren_'+alpha], ['file-id-2'])
577
self.build_tree_contents([('tree/del_'+alpha, 'contents\n')])
578
tree.add(['del_'+alpha], ['file-id-3'])
579
self.build_tree_contents([('tree/mod_'+alpha, 'contents\n')])
580
tree.add(['mod_'+alpha], ['file-id-4'])
582
tree.commit('one', rev_id='rev-1')
584
tree.rename_one('ren_'+alpha, 'ren_'+omega)
585
tree.remove('del_'+alpha)
586
self.build_tree_contents([('tree/add_'+alpha, 'contents\n')])
587
tree.add(['add_'+alpha], ['file-id'])
588
self.build_tree_contents([('tree/mod_'+alpha, 'contents_mod\n')])
590
diff = self.get_diff(tree.basis_tree(), tree)
591
self.assertContainsRe(diff,
592
"=== renamed file 'ren_%s' => 'ren_%s'\n"%(autf8, outf8))
593
self.assertContainsRe(diff, "=== added file 'add_%s'"%autf8)
594
self.assertContainsRe(diff, "=== modified file 'mod_%s'"%autf8)
595
self.assertContainsRe(diff, "=== removed file 'del_%s'"%autf8)
598
class DiffWasIs(DiffPath):
600
def diff(self, file_id, old_path, new_path, old_kind, new_kind):
601
self.to_file.write('was: ')
602
self.to_file.write(self.old_tree.get_file(file_id).read())
603
self.to_file.write('is: ')
604
self.to_file.write(self.new_tree.get_file(file_id).read())
608
class TestDiffTree(TestCaseWithTransport):
611
TestCaseWithTransport.setUp(self)
612
self.old_tree = self.make_branch_and_tree('old-tree')
613
self.old_tree.lock_write()
614
self.addCleanup(self.old_tree.unlock)
615
self.new_tree = self.make_branch_and_tree('new-tree')
616
self.new_tree.lock_write()
617
self.addCleanup(self.new_tree.unlock)
618
self.differ = DiffTree(self.old_tree, self.new_tree, StringIO())
620
def test_diff_text(self):
621
self.build_tree_contents([('old-tree/olddir/',),
622
('old-tree/olddir/oldfile', 'old\n')])
623
self.old_tree.add('olddir')
624
self.old_tree.add('olddir/oldfile', 'file-id')
625
self.build_tree_contents([('new-tree/newdir/',),
626
('new-tree/newdir/newfile', 'new\n')])
627
self.new_tree.add('newdir')
628
self.new_tree.add('newdir/newfile', 'file-id')
629
differ = DiffText(self.old_tree, self.new_tree, StringIO())
630
differ.diff_text('file-id', None, 'old label', 'new label')
632
'--- old label\n+++ new label\n@@ -1,1 +0,0 @@\n-old\n\n',
633
differ.to_file.getvalue())
634
differ.to_file.seek(0)
635
differ.diff_text(None, 'file-id', 'old label', 'new label')
637
'--- old label\n+++ new label\n@@ -0,0 +1,1 @@\n+new\n\n',
638
differ.to_file.getvalue())
639
differ.to_file.seek(0)
640
differ.diff_text('file-id', 'file-id', 'old label', 'new label')
642
'--- old label\n+++ new label\n@@ -1,1 +1,1 @@\n-old\n+new\n\n',
643
differ.to_file.getvalue())
645
def test_diff_deletion(self):
646
self.build_tree_contents([('old-tree/file', 'contents'),
647
('new-tree/file', 'contents')])
648
self.old_tree.add('file', 'file-id')
649
self.new_tree.add('file', 'file-id')
650
os.unlink('new-tree/file')
651
self.differ.show_diff(None)
652
self.assertContainsRe(self.differ.to_file.getvalue(), '-contents')
654
def test_diff_creation(self):
655
self.build_tree_contents([('old-tree/file', 'contents'),
656
('new-tree/file', 'contents')])
657
self.old_tree.add('file', 'file-id')
658
self.new_tree.add('file', 'file-id')
659
os.unlink('old-tree/file')
660
self.differ.show_diff(None)
661
self.assertContainsRe(self.differ.to_file.getvalue(), '\+contents')
663
def test_diff_symlink(self):
664
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
665
differ.diff_symlink('old target', None)
666
self.assertEqual("=== target was 'old target'\n",
667
differ.to_file.getvalue())
669
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
670
differ.diff_symlink(None, 'new target')
671
self.assertEqual("=== target is 'new target'\n",
672
differ.to_file.getvalue())
674
differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
675
differ.diff_symlink('old target', 'new target')
676
self.assertEqual("=== target changed 'old target' => 'new target'\n",
677
differ.to_file.getvalue())
680
self.build_tree_contents([('old-tree/olddir/',),
681
('old-tree/olddir/oldfile', 'old\n')])
682
self.old_tree.add('olddir')
683
self.old_tree.add('olddir/oldfile', 'file-id')
684
self.build_tree_contents([('new-tree/newdir/',),
685
('new-tree/newdir/newfile', 'new\n')])
686
self.new_tree.add('newdir')
687
self.new_tree.add('newdir/newfile', 'file-id')
688
self.differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
689
self.assertContainsRe(
690
self.differ.to_file.getvalue(),
691
r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
692
' \@\@\n-old\n\+new\n\n')
694
def test_diff_kind_change(self):
695
self.requireFeature(tests.SymlinkFeature)
696
self.build_tree_contents([('old-tree/olddir/',),
697
('old-tree/olddir/oldfile', 'old\n')])
698
self.old_tree.add('olddir')
699
self.old_tree.add('olddir/oldfile', 'file-id')
700
self.build_tree(['new-tree/newdir/'])
701
os.symlink('new', 'new-tree/newdir/newfile')
702
self.new_tree.add('newdir')
703
self.new_tree.add('newdir/newfile', 'file-id')
704
self.differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
705
self.assertContainsRe(
706
self.differ.to_file.getvalue(),
707
r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+0,0'
709
self.assertContainsRe(self.differ.to_file.getvalue(),
710
"=== target is u'new'\n")
712
def test_diff_directory(self):
713
self.build_tree(['new-tree/new-dir/'])
714
self.new_tree.add('new-dir', 'new-dir-id')
715
self.differ.diff('new-dir-id', None, 'new-dir')
716
self.assertEqual(self.differ.to_file.getvalue(), '')
718
def create_old_new(self):
719
self.build_tree_contents([('old-tree/olddir/',),
720
('old-tree/olddir/oldfile', 'old\n')])
721
self.old_tree.add('olddir')
722
self.old_tree.add('olddir/oldfile', 'file-id')
723
self.build_tree_contents([('new-tree/newdir/',),
724
('new-tree/newdir/newfile', 'new\n')])
725
self.new_tree.add('newdir')
726
self.new_tree.add('newdir/newfile', 'file-id')
728
def test_register_diff(self):
729
self.create_old_new()
730
old_diff_factories = DiffTree.diff_factories
731
DiffTree.diff_factories=old_diff_factories[:]
732
DiffTree.diff_factories.insert(0, DiffWasIs.from_diff_tree)
734
differ = DiffTree(self.old_tree, self.new_tree, StringIO())
736
DiffTree.diff_factories = old_diff_factories
737
differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
738
self.assertNotContainsRe(
739
differ.to_file.getvalue(),
740
r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
741
' \@\@\n-old\n\+new\n\n')
742
self.assertContainsRe(differ.to_file.getvalue(),
743
'was: old\nis: new\n')
745
def test_extra_factories(self):
746
self.create_old_new()
747
differ = DiffTree(self.old_tree, self.new_tree, StringIO(),
748
extra_factories=[DiffWasIs.from_diff_tree])
749
differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
750
self.assertNotContainsRe(
751
differ.to_file.getvalue(),
752
r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
753
' \@\@\n-old\n\+new\n\n')
754
self.assertContainsRe(differ.to_file.getvalue(),
755
'was: old\nis: new\n')
757
def test_alphabetical_order(self):
758
self.build_tree(['new-tree/a-file'])
759
self.new_tree.add('a-file')
760
self.build_tree(['old-tree/b-file'])
761
self.old_tree.add('b-file')
762
self.differ.show_diff(None)
763
self.assertContainsRe(self.differ.to_file.getvalue(),
764
'.*a-file(.|\n)*b-file')
767
class TestPatienceDiffLib(TestCase):
770
super(TestPatienceDiffLib, self).setUp()
771
self._unique_lcs = bzrlib._patiencediff_py.unique_lcs_py
772
self._recurse_matches = bzrlib._patiencediff_py.recurse_matches_py
773
self._PatienceSequenceMatcher = \
774
bzrlib._patiencediff_py.PatienceSequenceMatcher_py
776
def test_diff_unicode_string(self):
777
a = ''.join([unichr(i) for i in range(4000, 4500, 3)])
778
b = ''.join([unichr(i) for i in range(4300, 4800, 2)])
779
sm = self._PatienceSequenceMatcher(None, a, b)
780
mb = sm.get_matching_blocks()
781
self.assertEquals(35, len(mb))
783
def test_unique_lcs(self):
784
unique_lcs = self._unique_lcs
785
self.assertEquals(unique_lcs('', ''), [])
786
self.assertEquals(unique_lcs('', 'a'), [])
787
self.assertEquals(unique_lcs('a', ''), [])
788
self.assertEquals(unique_lcs('a', 'a'), [(0,0)])
789
self.assertEquals(unique_lcs('a', 'b'), [])
790
self.assertEquals(unique_lcs('ab', 'ab'), [(0,0), (1,1)])
791
self.assertEquals(unique_lcs('abcde', 'cdeab'), [(2,0), (3,1), (4,2)])
792
self.assertEquals(unique_lcs('cdeab', 'abcde'), [(0,2), (1,3), (2,4)])
793
self.assertEquals(unique_lcs('abXde', 'abYde'), [(0,0), (1,1),
795
self.assertEquals(unique_lcs('acbac', 'abc'), [(2,1)])
797
def test_recurse_matches(self):
798
def test_one(a, b, matches):
800
self._recurse_matches(
801
a, b, 0, 0, len(a), len(b), test_matches, 10)
802
self.assertEquals(test_matches, matches)
804
test_one(['a', '', 'b', '', 'c'], ['a', 'a', 'b', 'c', 'c'],
805
[(0, 0), (2, 2), (4, 4)])
806
test_one(['a', 'c', 'b', 'a', 'c'], ['a', 'b', 'c'],
807
[(0, 0), (2, 1), (4, 2)])
808
# Even though 'bc' is not unique globally, and is surrounded by
809
# non-matching lines, we should still match, because they are locally
811
test_one('abcdbce', 'afbcgdbce', [(0,0), (1, 2), (2, 3), (3, 5),
812
(4, 6), (5, 7), (6, 8)])
814
# recurse_matches doesn't match non-unique
815
# lines surrounded by bogus text.
816
# The update has been done in patiencediff.SequenceMatcher instead
818
# This is what it could be
819
#test_one('aBccDe', 'abccde', [(0,0), (2,2), (3,3), (5,5)])
821
# This is what it currently gives:
822
test_one('aBccDe', 'abccde', [(0,0), (5,5)])
824
def assertDiffBlocks(self, a, b, expected_blocks):
825
"""Check that the sequence matcher returns the correct blocks.
827
:param a: A sequence to match
828
:param b: Another sequence to match
829
:param expected_blocks: The expected output, not including the final
830
matching block (len(a), len(b), 0)
832
matcher = self._PatienceSequenceMatcher(None, a, b)
833
blocks = matcher.get_matching_blocks()
835
self.assertEqual((len(a), len(b), 0), last)
836
self.assertEqual(expected_blocks, blocks)
838
def test_matching_blocks(self):
839
# Some basic matching tests
840
self.assertDiffBlocks('', '', [])
841
self.assertDiffBlocks([], [], [])
842
self.assertDiffBlocks('abc', '', [])
843
self.assertDiffBlocks('', 'abc', [])
844
self.assertDiffBlocks('abcd', 'abcd', [(0, 0, 4)])
845
self.assertDiffBlocks('abcd', 'abce', [(0, 0, 3)])
846
self.assertDiffBlocks('eabc', 'abce', [(1, 0, 3)])
847
self.assertDiffBlocks('eabce', 'abce', [(1, 0, 4)])
848
self.assertDiffBlocks('abcde', 'abXde', [(0, 0, 2), (3, 3, 2)])
849
self.assertDiffBlocks('abcde', 'abXYZde', [(0, 0, 2), (3, 5, 2)])
850
self.assertDiffBlocks('abde', 'abXYZde', [(0, 0, 2), (2, 5, 2)])
851
# This may check too much, but it checks to see that
852
# a copied block stays attached to the previous section,
854
# difflib would tend to grab the trailing longest match
855
# which would make the diff not look right
856
self.assertDiffBlocks('abcdefghijklmnop', 'abcdefxydefghijklmnop',
857
[(0, 0, 6), (6, 11, 10)])
859
# make sure it supports passing in lists
860
self.assertDiffBlocks(
863
'how are you today?\n'],
865
'how are you today?\n'],
866
[(0, 0, 1), (2, 1, 1)])
868
# non unique lines surrounded by non-matching lines
870
self.assertDiffBlocks('aBccDe', 'abccde', [(0,0,1), (5,5,1)])
872
# But they only need to be locally unique
873
self.assertDiffBlocks('aBcDec', 'abcdec', [(0,0,1), (2,2,1), (4,4,2)])
875
# non unique blocks won't be matched
876
self.assertDiffBlocks('aBcdEcdFg', 'abcdecdfg', [(0,0,1), (8,8,1)])
878
# but locally unique ones will
879
self.assertDiffBlocks('aBcdEeXcdFg', 'abcdecdfg', [(0,0,1), (2,2,2),
880
(5,4,1), (7,5,2), (10,8,1)])
882
self.assertDiffBlocks('abbabbXd', 'cabbabxd', [(7,7,1)])
883
self.assertDiffBlocks('abbabbbb', 'cabbabbc', [])
884
self.assertDiffBlocks('bbbbbbbb', 'cbbbbbbc', [])
886
def test_matching_blocks_tuples(self):
887
# Some basic matching tests
888
self.assertDiffBlocks([], [], [])
889
self.assertDiffBlocks([('a',), ('b',), ('c,')], [], [])
890
self.assertDiffBlocks([], [('a',), ('b',), ('c,')], [])
891
self.assertDiffBlocks([('a',), ('b',), ('c,')],
892
[('a',), ('b',), ('c,')],
894
self.assertDiffBlocks([('a',), ('b',), ('c,')],
895
[('a',), ('b',), ('d,')],
897
self.assertDiffBlocks([('d',), ('b',), ('c,')],
898
[('a',), ('b',), ('c,')],
900
self.assertDiffBlocks([('d',), ('a',), ('b',), ('c,')],
901
[('a',), ('b',), ('c,')],
903
self.assertDiffBlocks([('a', 'b'), ('c', 'd'), ('e', 'f')],
904
[('a', 'b'), ('c', 'X'), ('e', 'f')],
905
[(0, 0, 1), (2, 2, 1)])
906
self.assertDiffBlocks([('a', 'b'), ('c', 'd'), ('e', 'f')],
907
[('a', 'b'), ('c', 'dX'), ('e', 'f')],
908
[(0, 0, 1), (2, 2, 1)])
910
def test_opcodes(self):
911
def chk_ops(a, b, expected_codes):
912
s = self._PatienceSequenceMatcher(None, a, b)
913
self.assertEquals(expected_codes, s.get_opcodes())
917
chk_ops('abc', '', [('delete', 0,3, 0,0)])
918
chk_ops('', 'abc', [('insert', 0,0, 0,3)])
919
chk_ops('abcd', 'abcd', [('equal', 0,4, 0,4)])
920
chk_ops('abcd', 'abce', [('equal', 0,3, 0,3),
921
('replace', 3,4, 3,4)
923
chk_ops('eabc', 'abce', [('delete', 0,1, 0,0),
927
chk_ops('eabce', 'abce', [('delete', 0,1, 0,0),
930
chk_ops('abcde', 'abXde', [('equal', 0,2, 0,2),
931
('replace', 2,3, 2,3),
934
chk_ops('abcde', 'abXYZde', [('equal', 0,2, 0,2),
935
('replace', 2,3, 2,5),
938
chk_ops('abde', 'abXYZde', [('equal', 0,2, 0,2),
939
('insert', 2,2, 2,5),
942
chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
943
[('equal', 0,6, 0,6),
944
('insert', 6,6, 6,11),
945
('equal', 6,16, 11,21)
950
, 'how are you today?\n'],
952
, 'how are you today?\n'],
953
[('equal', 0,1, 0,1),
954
('delete', 1,2, 1,1),
957
chk_ops('aBccDe', 'abccde',
958
[('equal', 0,1, 0,1),
959
('replace', 1,5, 1,5),
962
chk_ops('aBcDec', 'abcdec',
963
[('equal', 0,1, 0,1),
964
('replace', 1,2, 1,2),
966
('replace', 3,4, 3,4),
969
chk_ops('aBcdEcdFg', 'abcdecdfg',
970
[('equal', 0,1, 0,1),
971
('replace', 1,8, 1,8),
974
chk_ops('aBcdEeXcdFg', 'abcdecdfg',
975
[('equal', 0,1, 0,1),
976
('replace', 1,2, 1,2),
978
('delete', 4,5, 4,4),
980
('delete', 6,7, 5,5),
982
('replace', 9,10, 7,8),
983
('equal', 10,11, 8,9)
986
def test_grouped_opcodes(self):
987
def chk_ops(a, b, expected_codes, n=3):
988
s = self._PatienceSequenceMatcher(None, a, b)
989
self.assertEquals(expected_codes, list(s.get_grouped_opcodes(n)))
993
chk_ops('abc', '', [[('delete', 0,3, 0,0)]])
994
chk_ops('', 'abc', [[('insert', 0,0, 0,3)]])
995
chk_ops('abcd', 'abcd', [])
996
chk_ops('abcd', 'abce', [[('equal', 0,3, 0,3),
997
('replace', 3,4, 3,4)
999
chk_ops('eabc', 'abce', [[('delete', 0,1, 0,0),
1000
('equal', 1,4, 0,3),
1001
('insert', 4,4, 3,4)
1003
chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
1004
[[('equal', 3,6, 3,6),
1005
('insert', 6,6, 6,11),
1006
('equal', 6,9, 11,14)
1008
chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
1009
[[('equal', 2,6, 2,6),
1010
('insert', 6,6, 6,11),
1011
('equal', 6,10, 11,15)
1013
chk_ops('Xabcdef', 'abcdef',
1014
[[('delete', 0,1, 0,0),
1017
chk_ops('abcdef', 'abcdefX',
1018
[[('equal', 3,6, 3,6),
1019
('insert', 6,6, 6,7)
1023
def test_multiple_ranges(self):
1024
# There was an earlier bug where we used a bad set of ranges,
1025
# this triggers that specific bug, to make sure it doesn't regress
1026
self.assertDiffBlocks('abcdefghijklmnop',
1027
'abcXghiYZQRSTUVWXYZijklmnop',
1028
[(0, 0, 3), (6, 4, 3), (9, 20, 7)])
1030
self.assertDiffBlocks('ABCd efghIjk L',
1031
'AxyzBCn mo pqrstuvwI1 2 L',
1032
[(0,0,1), (1, 4, 2), (9, 19, 1), (12, 23, 3)])
1034
# These are rot13 code snippets.
1035
self.assertDiffBlocks('''\
1036
trg nqqrq jura lbh nqq n svyr va gur qverpgbel.
1038
gnxrf_netf = ['svyr*']
1039
gnxrf_bcgvbaf = ['ab-erphefr']
1041
qrs eha(frys, svyr_yvfg, ab_erphefr=Snyfr):
1042
sebz omeyvo.nqq vzcbeg fzneg_nqq, nqq_ercbegre_cevag, nqq_ercbegre_ahyy
1044
ercbegre = nqq_ercbegre_ahyy
1046
ercbegre = nqq_ercbegre_cevag
1047
fzneg_nqq(svyr_yvfg, abg ab_erphefr, ercbegre)
1050
pynff pzq_zxqve(Pbzznaq):
1051
'''.splitlines(True), '''\
1052
trg nqqrq jura lbh nqq n svyr va gur qverpgbel.
1054
--qel-eha jvyy fubj juvpu svyrf jbhyq or nqqrq, ohg abg npghnyyl
1057
gnxrf_netf = ['svyr*']
1058
gnxrf_bcgvbaf = ['ab-erphefr', 'qel-eha']
1060
qrs eha(frys, svyr_yvfg, ab_erphefr=Snyfr, qel_eha=Snyfr):
1065
# Guvf vf cbvagyrff, ohg V'q engure abg envfr na reebe
1066
npgvba = omeyvo.nqq.nqq_npgvba_ahyy
1068
npgvba = omeyvo.nqq.nqq_npgvba_cevag
1070
npgvba = omeyvo.nqq.nqq_npgvba_nqq
1072
npgvba = omeyvo.nqq.nqq_npgvba_nqq_naq_cevag
1074
omeyvo.nqq.fzneg_nqq(svyr_yvfg, abg ab_erphefr, npgvba)
1077
pynff pzq_zxqve(Pbzznaq):
1078
'''.splitlines(True)
1079
, [(0,0,1), (1, 4, 2), (9, 19, 1), (12, 23, 3)])
1081
def test_patience_unified_diff(self):
1082
txt_a = ['hello there\n',
1084
'how are you today?\n']
1085
txt_b = ['hello there\n',
1086
'how are you today?\n']
1087
unified_diff = bzrlib.patiencediff.unified_diff
1088
psm = self._PatienceSequenceMatcher
1089
self.assertEquals(['--- \n',
1091
'@@ -1,3 +1,2 @@\n',
1094
' how are you today?\n'
1096
, list(unified_diff(txt_a, txt_b,
1097
sequencematcher=psm)))
1098
txt_a = map(lambda x: x+'\n', 'abcdefghijklmnop')
1099
txt_b = map(lambda x: x+'\n', 'abcdefxydefghijklmnop')
1100
# This is the result with LongestCommonSubstring matching
1101
self.assertEquals(['--- \n',
1103
'@@ -1,6 +1,11 @@\n',
1115
, list(unified_diff(txt_a, txt_b)))
1116
# And the patience diff
1117
self.assertEquals(['--- \n',
1119
'@@ -4,6 +4,11 @@\n',
1132
, list(unified_diff(txt_a, txt_b,
1133
sequencematcher=psm)))
1135
def test_patience_unified_diff_with_dates(self):
1136
txt_a = ['hello there\n',
1138
'how are you today?\n']
1139
txt_b = ['hello there\n',
1140
'how are you today?\n']
1141
unified_diff = bzrlib.patiencediff.unified_diff
1142
psm = self._PatienceSequenceMatcher
1143
self.assertEquals(['--- a\t2008-08-08\n',
1144
'+++ b\t2008-09-09\n',
1145
'@@ -1,3 +1,2 @@\n',
1148
' how are you today?\n'
1150
, list(unified_diff(txt_a, txt_b,
1151
fromfile='a', tofile='b',
1152
fromfiledate='2008-08-08',
1153
tofiledate='2008-09-09',
1154
sequencematcher=psm)))
1157
class TestPatienceDiffLib_c(TestPatienceDiffLib):
1159
_test_needs_features = [CompiledPatienceDiffFeature]
1162
super(TestPatienceDiffLib_c, self).setUp()
1163
import bzrlib._patiencediff_c
1164
self._unique_lcs = bzrlib._patiencediff_c.unique_lcs_c
1165
self._recurse_matches = bzrlib._patiencediff_c.recurse_matches_c
1166
self._PatienceSequenceMatcher = \
1167
bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1169
def test_unhashable(self):
1170
"""We should get a proper exception here."""
1171
# We need to be able to hash items in the sequence, lists are
1172
# unhashable, and thus cannot be diffed
1173
e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1175
e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1176
None, ['valid', []], [])
1177
e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1178
None, ['valid'], [[]])
1179
e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1180
None, ['valid'], ['valid', []])
1183
class TestPatienceDiffLibFiles(TestCaseInTempDir):
1186
super(TestPatienceDiffLibFiles, self).setUp()
1187
self._PatienceSequenceMatcher = \
1188
bzrlib._patiencediff_py.PatienceSequenceMatcher_py
1190
def test_patience_unified_diff_files(self):
1191
txt_a = ['hello there\n',
1193
'how are you today?\n']
1194
txt_b = ['hello there\n',
1195
'how are you today?\n']
1196
open('a1', 'wb').writelines(txt_a)
1197
open('b1', 'wb').writelines(txt_b)
1199
unified_diff_files = bzrlib.patiencediff.unified_diff_files
1200
psm = self._PatienceSequenceMatcher
1201
self.assertEquals(['--- a1\n',
1203
'@@ -1,3 +1,2 @@\n',
1206
' how are you today?\n',
1208
, list(unified_diff_files('a1', 'b1',
1209
sequencematcher=psm)))
1211
txt_a = map(lambda x: x+'\n', 'abcdefghijklmnop')
1212
txt_b = map(lambda x: x+'\n', 'abcdefxydefghijklmnop')
1213
open('a2', 'wb').writelines(txt_a)
1214
open('b2', 'wb').writelines(txt_b)
1216
# This is the result with LongestCommonSubstring matching
1217
self.assertEquals(['--- a2\n',
1219
'@@ -1,6 +1,11 @@\n',
1231
, list(unified_diff_files('a2', 'b2')))
1233
# And the patience diff
1234
self.assertEquals(['--- a2\n',
1236
'@@ -4,6 +4,11 @@\n',
1249
, list(unified_diff_files('a2', 'b2',
1250
sequencematcher=psm)))
1253
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
1255
_test_needs_features = [CompiledPatienceDiffFeature]
1258
super(TestPatienceDiffLibFiles_c, self).setUp()
1259
import bzrlib._patiencediff_c
1260
self._PatienceSequenceMatcher = \
1261
bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1264
class TestUsingCompiledIfAvailable(TestCase):
1266
def test_PatienceSequenceMatcher(self):
1267
if CompiledPatienceDiffFeature.available():
1268
from bzrlib._patiencediff_c import PatienceSequenceMatcher_c
1269
self.assertIs(PatienceSequenceMatcher_c,
1270
bzrlib.patiencediff.PatienceSequenceMatcher)
1272
from bzrlib._patiencediff_py import PatienceSequenceMatcher_py
1273
self.assertIs(PatienceSequenceMatcher_py,
1274
bzrlib.patiencediff.PatienceSequenceMatcher)
1276
def test_unique_lcs(self):
1277
if CompiledPatienceDiffFeature.available():
1278
from bzrlib._patiencediff_c import unique_lcs_c
1279
self.assertIs(unique_lcs_c,
1280
bzrlib.patiencediff.unique_lcs)
1282
from bzrlib._patiencediff_py import unique_lcs_py
1283
self.assertIs(unique_lcs_py,
1284
bzrlib.patiencediff.unique_lcs)
1286
def test_recurse_matches(self):
1287
if CompiledPatienceDiffFeature.available():
1288
from bzrlib._patiencediff_c import recurse_matches_c
1289
self.assertIs(recurse_matches_c,
1290
bzrlib.patiencediff.recurse_matches)
1292
from bzrlib._patiencediff_py import recurse_matches_py
1293
self.assertIs(recurse_matches_py,
1294
bzrlib.patiencediff.recurse_matches)
1297
class TestDiffFromTool(TestCaseWithTransport):
1299
def test_from_string(self):
1300
diff_obj = DiffFromTool.from_string('diff', None, None, None)
1301
self.addCleanup(diff_obj.finish)
1302
self.assertEqual(['diff', '@old_path', '@new_path'],
1303
diff_obj.command_template)
1305
def test_from_string_u5(self):
1306
diff_obj = DiffFromTool.from_string('diff -u\\ 5', None, None, None)
1307
self.addCleanup(diff_obj.finish)
1308
self.assertEqual(['diff', '-u 5', '@old_path', '@new_path'],
1309
diff_obj.command_template)
1310
self.assertEqual(['diff', '-u 5', 'old-path', 'new-path'],
1311
diff_obj._get_command('old-path', 'new-path'))
1313
def test_execute(self):
1315
diff_obj = DiffFromTool(['python', '-c',
1316
'print "@old_path @new_path"'],
1318
self.addCleanup(diff_obj.finish)
1319
diff_obj._execute('old', 'new')
1320
self.assertEqual(output.getvalue().rstrip(), 'old new')
1322
def test_excute_missing(self):
1323
diff_obj = DiffFromTool(['a-tool-which-is-unlikely-to-exist'],
1325
self.addCleanup(diff_obj.finish)
1326
e = self.assertRaises(ExecutableMissing, diff_obj._execute, 'old',
1328
self.assertEqual('a-tool-which-is-unlikely-to-exist could not be found'
1329
' on this machine', str(e))
1331
def test_prepare_files_creates_paths_readable_by_windows_tool(self):
1332
self.requireFeature(AttribFeature)
1334
tree = self.make_branch_and_tree('tree')
1335
self.build_tree_contents([('tree/file', 'content')])
1336
tree.add('file', 'file-id')
1337
tree.commit('old tree')
1339
self.addCleanup(tree.unlock)
1340
diff_obj = DiffFromTool(['python', '-c',
1341
'print "@old_path @new_path"'],
1343
diff_obj._prepare_files('file-id', 'file', 'file')
1344
self.assertReadableByAttrib(diff_obj._root, 'old\\file', r'old\\file')
1345
self.assertReadableByAttrib(diff_obj._root, 'new\\file', r'new\\file')
1347
def assertReadableByAttrib(self, cwd, relpath, regex):
1348
proc = subprocess.Popen(['attrib', relpath],
1349
stdout=subprocess.PIPE,
1352
result = proc.stdout.read()
1353
self.assertContainsRe(result, regex)
1355
def test_prepare_files(self):
1357
tree = self.make_branch_and_tree('tree')
1358
self.build_tree_contents([('tree/oldname', 'oldcontent')])
1359
self.build_tree_contents([('tree/oldname2', 'oldcontent2')])
1360
tree.add('oldname', 'file-id')
1361
tree.add('oldname2', 'file2-id')
1362
tree.commit('old tree', timestamp=0)
1363
tree.rename_one('oldname', 'newname')
1364
tree.rename_one('oldname2', 'newname2')
1365
self.build_tree_contents([('tree/newname', 'newcontent')])
1366
self.build_tree_contents([('tree/newname2', 'newcontent2')])
1367
old_tree = tree.basis_tree()
1368
old_tree.lock_read()
1369
self.addCleanup(old_tree.unlock)
1371
self.addCleanup(tree.unlock)
1372
diff_obj = DiffFromTool(['python', '-c',
1373
'print "@old_path @new_path"'],
1374
old_tree, tree, output)
1375
self.addCleanup(diff_obj.finish)
1376
self.assertContainsRe(diff_obj._root, 'bzr-diff-[^/]*')
1377
old_path, new_path = diff_obj._prepare_files('file-id', 'oldname',
1379
self.assertContainsRe(old_path, 'old/oldname$')
1380
self.assertEqual(0, os.stat(old_path).st_mtime)
1381
self.assertContainsRe(new_path, 'tree/newname$')
1382
self.assertFileEqual('oldcontent', old_path)
1383
self.assertFileEqual('newcontent', new_path)
1384
if osutils.host_os_dereferences_symlinks():
1385
self.assertTrue(os.path.samefile('tree/newname', new_path))
1386
# make sure we can create files with the same parent directories
1387
diff_obj._prepare_files('file2-id', 'oldname2', 'newname2')
1390
class TestGetTreesAndBranchesToDiff(TestCaseWithTransport):
1392
def test_basic(self):
1393
tree = self.make_branch_and_tree('tree')
1394
(old_tree, new_tree,
1395
old_branch, new_branch,
1396
specific_files, extra_trees) = \
1397
get_trees_and_branches_to_diff(['tree'], None, None, None)
1399
self.assertIsInstance(old_tree, RevisionTree)
1400
#print dir (old_tree)
1401
self.assertEqual(_mod_revision.NULL_REVISION, old_tree.get_revision_id())
1402
self.assertEqual(tree.basedir, new_tree.basedir)
1403
self.assertEqual(tree.branch.base, old_branch.base)
1404
self.assertEqual(tree.branch.base, new_branch.base)
1405
self.assertIs(None, specific_files)
1406
self.assertIs(None, extra_trees)
1408
def test_with_rev_specs(self):
1409
tree = self.make_branch_and_tree('tree')
1410
self.build_tree_contents([('tree/file', 'oldcontent')])
1411
tree.add('file', 'file-id')
1412
tree.commit('old tree', timestamp=0, rev_id="old-id")
1413
self.build_tree_contents([('tree/file', 'newcontent')])
1414
tree.commit('new tree', timestamp=0, rev_id="new-id")
1416
revisions = [RevisionSpec.from_string('1'),
1417
RevisionSpec.from_string('2')]
1418
(old_tree, new_tree,
1419
old_branch, new_branch,
1420
specific_files, extra_trees) = \
1421
get_trees_and_branches_to_diff(['tree'], revisions, None, None)
1423
self.assertIsInstance(old_tree, RevisionTree)
1424
self.assertEqual("old-id", old_tree.get_revision_id())
1425
self.assertIsInstance(new_tree, RevisionTree)
1426
self.assertEqual("new-id", new_tree.get_revision_id())
1427
self.assertEqual(tree.branch.base, old_branch.base)
1428
self.assertEqual(tree.branch.base, new_branch.base)
1429
self.assertIs(None, specific_files)
1430
self.assertEqual(tree.basedir, extra_trees[0].basedir)