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
18
from cStringIO import StringIO
21
from tempfile import TemporaryFile
28
revision as _mod_revision,
23
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
32
from bzrlib.errors import BinaryFile, NoDiff
33
import bzrlib.osutils as osutils
34
import bzrlib.patiencediff
35
import bzrlib._patiencediff_py
36
from bzrlib.tests import (Feature, TestCase, TestCaseWithTransport,
37
TestCaseInTempDir, TestSkipped)
40
class _CompiledPatienceDiffFeature(Feature):
44
import bzrlib._patiencediff_c
49
def feature_name(self):
50
return 'bzrlib._patiencediff_c'
52
CompiledPatienceDiffFeature = _CompiledPatienceDiffFeature()
55
class _UnicodeFilename(Feature):
56
"""Does the filesystem support Unicode filenames?"""
61
except UnicodeEncodeError:
63
except (IOError, OSError):
64
# The filesystem allows the Unicode filename but the file doesn't
68
# The filesystem allows the Unicode filename and the file exists,
72
UnicodeFilename = _UnicodeFilename()
75
class TestUnicodeFilename(TestCase):
77
def test_probe_passes(self):
78
"""UnicodeFilename._probe passes."""
79
# We can't test much more than that because the behaviour depends
81
UnicodeFilename._probe()
45
84
def udiff_lines(old, new, allow_binary=False):
46
85
output = StringIO()
47
diff.internal_diff('old', old, 'new', new, output, allow_binary)
86
internal_diff('old', old, 'new', new, output, allow_binary)
49
88
return output.readlines()
151
165
self.check_patch(lines)
153
167
def test_external_diff_binary_lang_c(self):
154
169
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'])
170
old_env[lang] = osutils.set_or_unset_env(lang, 'C')
172
lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
173
# Older versions of diffutils say "Binary files", newer
174
# versions just say "Files".
175
self.assertContainsRe(lines[0],
176
'(Binary f|F)iles old and new differ\n')
177
self.assertEquals(lines[1:], ['\n'])
179
for lang, old_val in old_env.iteritems():
180
osutils.set_or_unset_env(lang, old_val)
162
182
def test_no_external_diff(self):
163
183
"""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'])
184
# Use os.environ['PATH'] to make sure no 'diff' command is available
185
orig_path = os.environ['PATH']
187
os.environ['PATH'] = ''
188
self.assertRaises(NoDiff, external_diff,
189
'old', ['boo\n'], 'new', ['goo\n'],
190
StringIO(), diff_opts=['-u'])
192
os.environ['PATH'] = orig_path
171
194
def test_internal_diff_default(self):
172
195
# Default internal diff encoding is utf8
173
196
output = StringIO()
174
diff.internal_diff(u'old_\xb5', ['old_text\n'],
175
u'new_\xe5', ['new_text\n'], output)
197
internal_diff(u'old_\xb5', ['old_text\n'],
198
u'new_\xe5', ['new_text\n'], output)
176
199
lines = output.getvalue().splitlines(True)
177
200
self.check_patch(lines)
178
self.assertEqual(['--- old_\xc2\xb5\n',
201
self.assertEquals(['--- old_\xc2\xb5\n',
179
202
'+++ new_\xc3\xa5\n',
180
203
'@@ -1,1 +1,1 @@\n',
219
242
def test_internal_diff_no_content(self):
220
243
output = StringIO()
221
diff.internal_diff(u'old', [], u'new', [], output)
244
internal_diff(u'old', [], u'new', [], output)
222
245
self.assertEqual('', output.getvalue())
224
247
def test_internal_diff_no_changes(self):
225
248
output = StringIO()
226
diff.internal_diff(u'old', ['text\n', 'contents\n'],
227
u'new', ['text\n', 'contents\n'],
249
internal_diff(u'old', ['text\n', 'contents\n'],
250
u'new', ['text\n', 'contents\n'],
229
252
self.assertEqual('', output.getvalue())
231
254
def test_internal_diff_returns_bytes(self):
233
256
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,
257
internal_diff(u'old_\xb5', ['old_text\n'],
258
u'new_\xe5', ['new_text\n'], output)
259
self.failUnless(isinstance(output.getvalue(), str),
237
260
'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):
263
class TestDiffFiles(TestCaseInTempDir):
305
265
def test_external_diff_binary(self):
306
266
"""The output when using external diff should use diff's i18n error"""
537
500
tree.rename_one('file', 'newname')
538
501
self.build_tree_contents([('tree/newname', 'new contents\n')])
539
d = get_diff_as_string(tree.basis_tree(), tree)
540
self.assertContainsRe(d, "=== renamed file 'file' => 'newname'\n")
541
self.assertContainsRe(d, '--- old/file\t')
542
self.assertContainsRe(d, '\\+\\+\\+ new/newname\t')
543
self.assertContainsRe(d, '-contents\n'
547
def test_internal_diff_exec_property(self):
548
tree = self.make_branch_and_tree('tree')
550
tt = transform.TreeTransform(tree)
551
tt.new_file('a', tt.root, 'contents\n', 'a-id', True)
552
tt.new_file('b', tt.root, 'contents\n', 'b-id', False)
553
tt.new_file('c', tt.root, 'contents\n', 'c-id', True)
554
tt.new_file('d', tt.root, 'contents\n', 'd-id', False)
555
tt.new_file('e', tt.root, 'contents\n', 'control-e-id', True)
556
tt.new_file('f', tt.root, 'contents\n', 'control-f-id', False)
558
tree.commit('one', rev_id='rev-1')
560
tt = transform.TreeTransform(tree)
561
tt.set_executability(False, tt.trans_id_file_id('a-id'))
562
tt.set_executability(True, tt.trans_id_file_id('b-id'))
563
tt.set_executability(False, tt.trans_id_file_id('c-id'))
564
tt.set_executability(True, tt.trans_id_file_id('d-id'))
566
tree.rename_one('c', 'new-c')
567
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'")
502
diff = self.get_diff(tree.basis_tree(), tree)
503
self.assertContainsRe(diff, "=== renamed file 'file' => 'newname'\n")
504
self.assertContainsRe(diff, '--- old/file\t')
505
self.assertContainsRe(diff, '\\+\\+\\+ new/newname\t')
506
self.assertContainsRe(diff, '-contents\n'
582
509
def test_binary_unicode_filenames(self):
583
510
"""Test that contents of files are *not* encoded in UTF-8 when there
584
511
is a binary file in the diff.
586
513
# See https://bugs.launchpad.net/bugs/110092.
587
self.requireFeature(features.UnicodeFilenameFeature)
514
self.requireFeature(UnicodeFilename)
589
516
# This bug isn't triggered with cStringIO.
590
517
from StringIO import StringIO
840
723
self.assertContainsRe(differ.to_file.getvalue(),
841
724
'was: old\nis: new\n')
843
def test_alphabetical_order(self):
844
self.build_tree(['new-tree/a-file'])
845
self.new_tree.add('a-file')
846
self.build_tree(['old-tree/b-file'])
847
self.old_tree.add('b-file')
848
self.differ.show_diff(None)
849
self.assertContainsRe(self.differ.to_file.getvalue(),
850
'.*a-file(.|\n)*b-file')
853
class TestPatienceDiffLib(tests.TestCase):
727
class TestPatienceDiffLib(TestCase):
856
730
super(TestPatienceDiffLib, self).setUp()
857
self._unique_lcs = _patiencediff_py.unique_lcs_py
858
self._recurse_matches = _patiencediff_py.recurse_matches_py
731
self._unique_lcs = bzrlib._patiencediff_py.unique_lcs_py
732
self._recurse_matches = bzrlib._patiencediff_py.recurse_matches_py
859
733
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))
734
bzrlib._patiencediff_py.PatienceSequenceMatcher_py
869
736
def test_unique_lcs(self):
870
737
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),
738
self.assertEquals(unique_lcs('', ''), [])
739
self.assertEquals(unique_lcs('', 'a'), [])
740
self.assertEquals(unique_lcs('a', ''), [])
741
self.assertEquals(unique_lcs('a', 'a'), [(0,0)])
742
self.assertEquals(unique_lcs('a', 'b'), [])
743
self.assertEquals(unique_lcs('ab', 'ab'), [(0,0), (1,1)])
744
self.assertEquals(unique_lcs('abcde', 'cdeab'), [(2,0), (3,1), (4,2)])
745
self.assertEquals(unique_lcs('cdeab', 'abcde'), [(0,2), (1,3), (2,4)])
746
self.assertEquals(unique_lcs('abXde', 'abYde'), [(0,0), (1,1),
881
self.assertEqual(unique_lcs('acbac', 'abc'), [(2,1)])
748
self.assertEquals(unique_lcs('acbac', 'abc'), [(2,1)])
883
750
def test_recurse_matches(self):
884
751
def test_one(a, b, matches):
885
752
test_matches = []
886
753
self._recurse_matches(
887
754
a, b, 0, 0, len(a), len(b), test_matches, 10)
888
self.assertEqual(test_matches, matches)
755
self.assertEquals(test_matches, matches)
890
757
test_one(['a', '', 'b', '', 'c'], ['a', 'a', 'b', 'c', 'c'],
891
758
[(0, 0), (2, 2), (4, 4)])
907
774
# This is what it currently gives:
908
775
test_one('aBccDe', 'abccde', [(0,0), (5,5)])
910
def assertDiffBlocks(self, a, b, expected_blocks):
911
"""Check that the sequence matcher returns the correct blocks.
913
:param a: A sequence to match
914
:param b: Another sequence to match
915
:param expected_blocks: The expected output, not including the final
916
matching block (len(a), len(b), 0)
918
matcher = self._PatienceSequenceMatcher(None, a, b)
919
blocks = matcher.get_matching_blocks()
921
self.assertEqual((len(a), len(b), 0), last)
922
self.assertEqual(expected_blocks, blocks)
924
777
def test_matching_blocks(self):
778
def chk_blocks(a, b, expected_blocks):
779
# difflib always adds a signature of the total
780
# length, with no matching entries at the end
781
s = self._PatienceSequenceMatcher(None, a, b)
782
blocks = s.get_matching_blocks()
783
self.assertEquals((len(a), len(b), 0), blocks[-1])
784
self.assertEquals(expected_blocks, blocks[:-1])
925
786
# Some basic matching tests
926
self.assertDiffBlocks('', '', [])
927
self.assertDiffBlocks([], [], [])
928
self.assertDiffBlocks('abc', '', [])
929
self.assertDiffBlocks('', 'abc', [])
930
self.assertDiffBlocks('abcd', 'abcd', [(0, 0, 4)])
931
self.assertDiffBlocks('abcd', 'abce', [(0, 0, 3)])
932
self.assertDiffBlocks('eabc', 'abce', [(1, 0, 3)])
933
self.assertDiffBlocks('eabce', 'abce', [(1, 0, 4)])
934
self.assertDiffBlocks('abcde', 'abXde', [(0, 0, 2), (3, 3, 2)])
935
self.assertDiffBlocks('abcde', 'abXYZde', [(0, 0, 2), (3, 5, 2)])
936
self.assertDiffBlocks('abde', 'abXYZde', [(0, 0, 2), (2, 5, 2)])
937
# This may check too much, but it checks to see that
787
chk_blocks('', '', [])
788
chk_blocks([], [], [])
789
chk_blocks('abc', '', [])
790
chk_blocks('', 'abc', [])
791
chk_blocks('abcd', 'abcd', [(0, 0, 4)])
792
chk_blocks('abcd', 'abce', [(0, 0, 3)])
793
chk_blocks('eabc', 'abce', [(1, 0, 3)])
794
chk_blocks('eabce', 'abce', [(1, 0, 4)])
795
chk_blocks('abcde', 'abXde', [(0, 0, 2), (3, 3, 2)])
796
chk_blocks('abcde', 'abXYZde', [(0, 0, 2), (3, 5, 2)])
797
chk_blocks('abde', 'abXYZde', [(0, 0, 2), (2, 5, 2)])
798
# This may check too much, but it checks to see that
938
799
# a copied block stays attached to the previous section,
939
800
# not the later one.
940
801
# difflib would tend to grab the trailing longest match
941
802
# which would make the diff not look right
942
self.assertDiffBlocks('abcdefghijklmnop', 'abcdefxydefghijklmnop',
943
[(0, 0, 6), (6, 11, 10)])
803
chk_blocks('abcdefghijklmnop', 'abcdefxydefghijklmnop',
804
[(0, 0, 6), (6, 11, 10)])
945
806
# make sure it supports passing in lists
946
self.assertDiffBlocks(
947
808
['hello there\n',
949
810
'how are you today?\n'],
954
815
# non unique lines surrounded by non-matching lines
956
self.assertDiffBlocks('aBccDe', 'abccde', [(0,0,1), (5,5,1)])
817
chk_blocks('aBccDe', 'abccde', [(0,0,1), (5,5,1)])
958
819
# But they only need to be locally unique
959
self.assertDiffBlocks('aBcDec', 'abcdec', [(0,0,1), (2,2,1), (4,4,2)])
820
chk_blocks('aBcDec', 'abcdec', [(0,0,1), (2,2,1), (4,4,2)])
961
822
# non unique blocks won't be matched
962
self.assertDiffBlocks('aBcdEcdFg', 'abcdecdfg', [(0,0,1), (8,8,1)])
823
chk_blocks('aBcdEcdFg', 'abcdecdfg', [(0,0,1), (8,8,1)])
964
825
# but locally unique ones will
965
self.assertDiffBlocks('aBcdEeXcdFg', 'abcdecdfg', [(0,0,1), (2,2,2),
826
chk_blocks('aBcdEeXcdFg', 'abcdecdfg', [(0,0,1), (2,2,2),
966
827
(5,4,1), (7,5,2), (10,8,1)])
968
self.assertDiffBlocks('abbabbXd', 'cabbabxd', [(7,7,1)])
969
self.assertDiffBlocks('abbabbbb', 'cabbabbc', [])
970
self.assertDiffBlocks('bbbbbbbb', 'cbbbbbbc', [])
972
def test_matching_blocks_tuples(self):
973
# Some basic matching tests
974
self.assertDiffBlocks([], [], [])
975
self.assertDiffBlocks([('a',), ('b',), ('c,')], [], [])
976
self.assertDiffBlocks([], [('a',), ('b',), ('c,')], [])
977
self.assertDiffBlocks([('a',), ('b',), ('c,')],
978
[('a',), ('b',), ('c,')],
980
self.assertDiffBlocks([('a',), ('b',), ('c,')],
981
[('a',), ('b',), ('d,')],
983
self.assertDiffBlocks([('d',), ('b',), ('c,')],
984
[('a',), ('b',), ('c,')],
986
self.assertDiffBlocks([('d',), ('a',), ('b',), ('c,')],
987
[('a',), ('b',), ('c,')],
989
self.assertDiffBlocks([('a', 'b'), ('c', 'd'), ('e', 'f')],
990
[('a', 'b'), ('c', 'X'), ('e', 'f')],
991
[(0, 0, 1), (2, 2, 1)])
992
self.assertDiffBlocks([('a', 'b'), ('c', 'd'), ('e', 'f')],
993
[('a', 'b'), ('c', 'dX'), ('e', 'f')],
994
[(0, 0, 1), (2, 2, 1)])
829
chk_blocks('abbabbXd', 'cabbabxd', [(7,7,1)])
830
chk_blocks('abbabbbb', 'cabbabbc', [])
831
chk_blocks('bbbbbbbb', 'cbbbbbbc', [])
996
833
def test_opcodes(self):
997
834
def chk_ops(a, b, expected_codes):
998
835
s = self._PatienceSequenceMatcher(None, a, b)
999
self.assertEqual(expected_codes, s.get_opcodes())
836
self.assertEquals(expected_codes, s.get_opcodes())
1001
838
chk_ops('', '', [])
1002
839
chk_ops([], [], [])
1109
946
def test_multiple_ranges(self):
1110
947
# There was an earlier bug where we used a bad set of ranges,
1111
948
# this triggers that specific bug, to make sure it doesn't regress
1112
self.assertDiffBlocks('abcdefghijklmnop',
1113
'abcXghiYZQRSTUVWXYZijklmnop',
1114
[(0, 0, 3), (6, 4, 3), (9, 20, 7)])
1116
self.assertDiffBlocks('ABCd efghIjk L',
1117
'AxyzBCn mo pqrstuvwI1 2 L',
1118
[(0,0,1), (1, 4, 2), (9, 19, 1), (12, 23, 3)])
949
def chk_blocks(a, b, expected_blocks):
950
# difflib always adds a signature of the total
951
# length, with no matching entries at the end
952
s = self._PatienceSequenceMatcher(None, a, b)
953
blocks = s.get_matching_blocks()
955
self.assertEquals(x, (len(a), len(b), 0))
956
self.assertEquals(expected_blocks, blocks)
958
chk_blocks('abcdefghijklmnop'
959
, 'abcXghiYZQRSTUVWXYZijklmnop'
960
, [(0, 0, 3), (6, 4, 3), (9, 20, 7)])
962
chk_blocks('ABCd efghIjk L'
963
, 'AxyzBCn mo pqrstuvwI1 2 L'
964
, [(0,0,1), (1, 4, 2), (9, 19, 1), (12, 23, 3)])
1120
966
# These are rot13 code snippets.
1121
self.assertDiffBlocks('''\
1122
968
trg nqqrq jura lbh nqq n svyr va gur qverpgbel.
1124
970
gnxrf_netf = ['svyr*']
1125
971
gnxrf_bcgvbaf = ['ab-erphefr']
1127
973
qrs eha(frys, svyr_yvfg, ab_erphefr=Snyfr):
1128
974
sebz omeyvo.nqq vzcbeg fzneg_nqq, nqq_ercbegre_cevag, nqq_ercbegre_ahyy
1218
1064
, list(unified_diff(txt_a, txt_b,
1219
1065
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
1068
class TestPatienceDiffLib_c(TestPatienceDiffLib):
1245
_test_needs_features = [features.compiled_patiencediff_feature]
1070
_test_needs_features = [CompiledPatienceDiffFeature]
1247
1072
def setUp(self):
1248
1073
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
1074
import bzrlib._patiencediff_c
1075
self._unique_lcs = bzrlib._patiencediff_c.unique_lcs_c
1076
self._recurse_matches = bzrlib._patiencediff_c.recurse_matches_c
1252
1077
self._PatienceSequenceMatcher = \
1253
_patiencediff_c.PatienceSequenceMatcher_c
1255
def test_unhashable(self):
1256
"""We should get a proper exception here."""
1257
# We need to be able to hash items in the sequence, lists are
1258
# unhashable, and thus cannot be diffed
1259
e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1261
e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1262
None, ['valid', []], [])
1263
e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1264
None, ['valid'], [[]])
1265
e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1266
None, ['valid'], ['valid', []])
1269
class TestPatienceDiffLibFiles(tests.TestCaseInTempDir):
1078
bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1081
class TestPatienceDiffLibFiles(TestCaseInTempDir):
1271
1083
def setUp(self):
1272
1084
super(TestPatienceDiffLibFiles, self).setUp()
1273
1085
self._PatienceSequenceMatcher = \
1274
_patiencediff_py.PatienceSequenceMatcher_py
1086
bzrlib._patiencediff_py.PatienceSequenceMatcher_py
1276
1088
def test_patience_unified_diff_files(self):
1277
1089
txt_a = ['hello there\n',
1317
1129
, list(unified_diff_files('a2', 'b2')))
1319
1131
# 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)))
1132
self.assertEquals(['--- a2 \n',
1134
'@@ -4,6 +4,11 @@\n',
1147
, list(unified_diff_files('a2', 'b2',
1148
sequencematcher=psm)))
1338
1151
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
1340
_test_needs_features = [features.compiled_patiencediff_feature]
1153
_test_needs_features = [CompiledPatienceDiffFeature]
1342
1155
def setUp(self):
1343
1156
super(TestPatienceDiffLibFiles_c, self).setUp()
1344
from bzrlib import _patiencediff_c
1157
import bzrlib._patiencediff_c
1345
1158
self._PatienceSequenceMatcher = \
1346
_patiencediff_c.PatienceSequenceMatcher_c
1349
class TestUsingCompiledIfAvailable(tests.TestCase):
1159
bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1162
class TestUsingCompiledIfAvailable(TestCase):
1351
1164
def test_PatienceSequenceMatcher(self):
1352
if features.compiled_patiencediff_feature.available():
1165
if CompiledPatienceDiffFeature.available():
1353
1166
from bzrlib._patiencediff_c import PatienceSequenceMatcher_c
1354
1167
self.assertIs(PatienceSequenceMatcher_c,
1355
patiencediff.PatienceSequenceMatcher)
1168
bzrlib.patiencediff.PatienceSequenceMatcher)
1357
1170
from bzrlib._patiencediff_py import PatienceSequenceMatcher_py
1358
1171
self.assertIs(PatienceSequenceMatcher_py,
1359
patiencediff.PatienceSequenceMatcher)
1172
bzrlib.patiencediff.PatienceSequenceMatcher)
1361
1174
def test_unique_lcs(self):
1362
if features.compiled_patiencediff_feature.available():
1175
if CompiledPatienceDiffFeature.available():
1363
1176
from bzrlib._patiencediff_c import unique_lcs_c
1364
1177
self.assertIs(unique_lcs_c,
1365
patiencediff.unique_lcs)
1178
bzrlib.patiencediff.unique_lcs)
1367
1180
from bzrlib._patiencediff_py import unique_lcs_py
1368
1181
self.assertIs(unique_lcs_py,
1369
patiencediff.unique_lcs)
1182
bzrlib.patiencediff.unique_lcs)
1371
1184
def test_recurse_matches(self):
1372
if features.compiled_patiencediff_feature.available():
1185
if CompiledPatienceDiffFeature.available():
1373
1186
from bzrlib._patiencediff_c import recurse_matches_c
1374
1187
self.assertIs(recurse_matches_c,
1375
patiencediff.recurse_matches)
1188
bzrlib.patiencediff.recurse_matches)
1377
1190
from bzrlib._patiencediff_py import recurse_matches_py
1378
1191
self.assertIs(recurse_matches_py,
1379
patiencediff.recurse_matches)
1382
class TestDiffFromTool(tests.TestCaseWithTransport):
1384
def test_from_string(self):
1385
diff_obj = diff.DiffFromTool.from_string('diff', None, None, None)
1386
self.addCleanup(diff_obj.finish)
1387
self.assertEqual(['diff', '@old_path', '@new_path'],
1388
diff_obj.command_template)
1390
def test_from_string_u5(self):
1391
diff_obj = diff.DiffFromTool.from_string('diff "-u 5"',
1393
self.addCleanup(diff_obj.finish)
1394
self.assertEqual(['diff', '-u 5', '@old_path', '@new_path'],
1395
diff_obj.command_template)
1396
self.assertEqual(['diff', '-u 5', 'old-path', 'new-path'],
1397
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
def test_execute(self):
1411
diff_obj = diff.DiffFromTool(['python', '-c',
1412
'print "@old_path @new_path"'],
1414
self.addCleanup(diff_obj.finish)
1415
diff_obj._execute('old', 'new')
1416
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'],
1421
self.addCleanup(diff_obj.finish)
1422
e = self.assertRaises(errors.ExecutableMissing, diff_obj._execute,
1424
self.assertEqual('a-tool-which-is-unlikely-to-exist could not be found'
1425
' on this machine', str(e))
1427
def test_prepare_files_creates_paths_readable_by_windows_tool(self):
1428
self.requireFeature(features.AttribFeature)
1430
tree = self.make_branch_and_tree('tree')
1431
self.build_tree_contents([('tree/file', 'content')])
1432
tree.add('file', 'file-id')
1433
tree.commit('old tree')
1435
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)
1442
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$')
1450
def assertReadableByAttrib(self, cwd, relpath, regex):
1451
proc = subprocess.Popen(['attrib', relpath],
1452
stdout=subprocess.PIPE,
1454
(result, err) = proc.communicate()
1455
self.assertContainsRe(result.replace('\r\n', '\n'), regex)
1457
def test_prepare_files(self):
1459
tree = self.make_branch_and_tree('tree')
1460
self.build_tree_contents([('tree/oldname', 'oldcontent')])
1461
self.build_tree_contents([('tree/oldname2', 'oldcontent2')])
1462
tree.add('oldname', 'file-id')
1463
tree.add('oldname2', 'file2-id')
1464
# Earliest allowable date on FAT32 filesystems is 1980-01-01
1465
tree.commit('old tree', timestamp=315532800)
1466
tree.rename_one('oldname', 'newname')
1467
tree.rename_one('oldname2', 'newname2')
1468
self.build_tree_contents([('tree/newname', 'newcontent')])
1469
self.build_tree_contents([('tree/newname2', 'newcontent2')])
1470
old_tree = tree.basis_tree()
1471
old_tree.lock_read()
1472
self.addCleanup(old_tree.unlock)
1474
self.addCleanup(tree.unlock)
1475
diff_obj = diff.DiffFromTool(['python', '-c',
1476
'print "@old_path @new_path"'],
1477
old_tree, tree, output)
1478
self.addCleanup(diff_obj.finish)
1479
self.assertContainsRe(diff_obj._root, 'bzr-diff-[^/]*')
1480
old_path, new_path = diff_obj._prepare_files('file-id', 'oldname',
1482
self.assertContainsRe(old_path, 'old/oldname$')
1483
self.assertEqual(315532800, os.stat(old_path).st_mtime)
1484
self.assertContainsRe(new_path, 'tree/newname$')
1485
self.assertFileEqual('oldcontent', old_path)
1486
self.assertFileEqual('newcontent', new_path)
1487
if osutils.host_os_dereferences_symlinks():
1488
self.assertTrue(os.path.samefile('tree/newname', new_path))
1489
# make sure we can create files with the same parent directories
1490
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)
1192
bzrlib.patiencediff.recurse_matches)