/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
1
# Copyright (C) 2005, 2006 Canonical Ltd
1711.2.16 by John Arbash Meinel
test_diff needs a copyright statement
2
#
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.
7
#
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.
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
12
#
1711.2.16 by John Arbash Meinel
test_diff needs a copyright statement
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
1740.2.5 by Aaron Bentley
Merge from bzr.dev
17
import os
1558.15.2 by Aaron Bentley
Implemented binary file handling for diff
18
from cStringIO import StringIO
1692.8.7 by James Henstridge
changes suggested by John Meinel
19
import errno
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
20
import subprocess
1920.1.3 by John Arbash Meinel
Remove spurious import
21
from tempfile import TemporaryFile
1558.15.2 by Aaron Bentley
Implemented binary file handling for diff
22
3009.2.9 by Aaron Bentley
Add tests for Differ
23
from bzrlib.diff import (
24
    internal_diff,
25
    external_diff,
3009.2.22 by Aaron Bentley
Update names & docstring
26
    DiffPath,
3009.2.9 by Aaron Bentley
Add tests for Differ
27
    show_diff_trees,
3009.2.22 by Aaron Bentley
Update names & docstring
28
    DiffSymlink,
29
    DiffTree,
30
    DiffText,
3009.2.9 by Aaron Bentley
Add tests for Differ
31
    )
1711.2.56 by John Arbash Meinel
Raise NoDiff if 'diff' not present.
32
from bzrlib.errors import BinaryFile, NoDiff
2321.2.5 by Alexander Belchenko
external diff: no need for special code path for win32 (suggested by John Meinel)
33
import bzrlib.osutils as osutils
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
34
import bzrlib.patiencediff
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
35
import bzrlib._patiencediff_py
2592.2.4 by Jonathan Lange
Skip the unicode filename test if the platform doesn't support unicode
36
from bzrlib.tests import (Feature, TestCase, TestCaseWithTransport,
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
37
                          TestCaseInTempDir, TestSkipped)
1558.15.2 by Aaron Bentley
Implemented binary file handling for diff
38
39
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
40
class _CompiledPatienceDiffFeature(Feature):
41
42
    def _probe(self):
43
        try:
44
            import bzrlib._patiencediff_c
45
        except ImportError:
46
            return False
47
        return True
48
49
    def feature_name(self):
50
        return 'bzrlib._patiencediff_c'
51
52
CompiledPatienceDiffFeature = _CompiledPatienceDiffFeature()
53
54
2592.2.4 by Jonathan Lange
Skip the unicode filename test if the platform doesn't support unicode
55
class _UnicodeFilename(Feature):
56
    """Does the filesystem support Unicode filenames?"""
57
58
    def _probe(self):
59
        try:
2653.1.1 by John Arbash Meinel
(Jonathan Lange) Fix bug #110092, when displaying a diff that includes a binary file, make sure the binary filenames are encoded
60
            os.stat(u'\u03b1')
2592.2.4 by Jonathan Lange
Skip the unicode filename test if the platform doesn't support unicode
61
        except UnicodeEncodeError:
62
            return False
2592.2.5 by Jonathan Lange
Make UnicodeFilename feature less insane. Add a simple test for it too.
63
        except (IOError, OSError):
64
            # The filesystem allows the Unicode filename but the file doesn't
2653.1.1 by John Arbash Meinel
(Jonathan Lange) Fix bug #110092, when displaying a diff that includes a binary file, make sure the binary filenames are encoded
65
            # exist.
2592.2.5 by Jonathan Lange
Make UnicodeFilename feature less insane. Add a simple test for it too.
66
            return True
67
        else:
68
            # The filesystem allows the Unicode filename and the file exists,
69
            # for some reason.
70
            return True
2592.2.4 by Jonathan Lange
Skip the unicode filename test if the platform doesn't support unicode
71
72
UnicodeFilename = _UnicodeFilename()
73
74
2592.2.5 by Jonathan Lange
Make UnicodeFilename feature less insane. Add a simple test for it too.
75
class TestUnicodeFilename(TestCase):
76
77
    def test_probe_passes(self):
78
        """UnicodeFilename._probe passes."""
79
        # We can't test much more than that because the behaviour depends
80
        # on the platform.
81
        UnicodeFilename._probe()
82
        
83
1558.15.11 by Aaron Bentley
Apply merge review suggestions
84
def udiff_lines(old, new, allow_binary=False):
974.1.6 by Aaron Bentley
Added unit tests
85
    output = StringIO()
1558.15.11 by Aaron Bentley
Apply merge review suggestions
86
    internal_diff('old', old, 'new', new, output, allow_binary)
974.1.6 by Aaron Bentley
Added unit tests
87
    output.seek(0, 0)
88
    return output.readlines()
89
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
90
1711.2.57 by John Arbash Meinel
Allow external diff to write to a file without a fileno.
91
def external_udiff_lines(old, new, use_stringio=False):
92
    if use_stringio:
93
        # StringIO has no fileno, so it tests a different codepath
94
        output = StringIO()
95
    else:
96
        output = TemporaryFile()
1692.8.7 by James Henstridge
changes suggested by John Meinel
97
    try:
98
        external_diff('old', old, 'new', new, output, diff_opts=['-u'])
1711.2.58 by John Arbash Meinel
Use osutils.pumpfile so we don't have to buffer everything in ram
99
    except NoDiff:
1711.2.56 by John Arbash Meinel
Raise NoDiff if 'diff' not present.
100
        raise TestSkipped('external "diff" not present to test')
1692.8.2 by James Henstridge
add a test for sending external diff output to a file
101
    output.seek(0, 0)
102
    lines = output.readlines()
103
    output.close()
104
    return lines
105
106
1102 by Martin Pool
- merge test refactoring from robertc
107
class TestDiff(TestCase):
1185.81.25 by Aaron Bentley
Clean up test_diff
108
1102 by Martin Pool
- merge test refactoring from robertc
109
    def test_add_nl(self):
110
        """diff generates a valid diff for patches that add a newline"""
974.1.6 by Aaron Bentley
Added unit tests
111
        lines = udiff_lines(['boo'], ['boo\n'])
1185.16.145 by Martin Pool
Remove all assert statements from test cases.
112
        self.check_patch(lines)
113
        self.assertEquals(lines[4], '\\ No newline at end of file\n')
114
            ## "expected no-nl, got %r" % lines[4]
974.1.6 by Aaron Bentley
Added unit tests
115
1102 by Martin Pool
- merge test refactoring from robertc
116
    def test_add_nl_2(self):
117
        """diff generates a valid diff for patches that change last line and
118
        add a newline.
119
        """
974.1.6 by Aaron Bentley
Added unit tests
120
        lines = udiff_lines(['boo'], ['goo\n'])
1185.16.145 by Martin Pool
Remove all assert statements from test cases.
121
        self.check_patch(lines)
122
        self.assertEquals(lines[4], '\\ No newline at end of file\n')
123
            ## "expected no-nl, got %r" % lines[4]
974.1.6 by Aaron Bentley
Added unit tests
124
1102 by Martin Pool
- merge test refactoring from robertc
125
    def test_remove_nl(self):
126
        """diff generates a valid diff for patches that change last line and
127
        add a newline.
128
        """
974.1.6 by Aaron Bentley
Added unit tests
129
        lines = udiff_lines(['boo\n'], ['boo'])
1185.16.145 by Martin Pool
Remove all assert statements from test cases.
130
        self.check_patch(lines)
131
        self.assertEquals(lines[5], '\\ No newline at end of file\n')
132
            ## "expected no-nl, got %r" % lines[5]
133
134
    def check_patch(self, lines):
135
        self.assert_(len(lines) > 1)
136
            ## "Not enough lines for a file header for patch:\n%s" % "".join(lines)
137
        self.assert_(lines[0].startswith ('---'))
138
            ## 'No orig line for patch:\n%s' % "".join(lines)
139
        self.assert_(lines[1].startswith ('+++'))
140
            ## 'No mod line for patch:\n%s' % "".join(lines)
141
        self.assert_(len(lines) > 2)
142
            ## "No hunks for patch:\n%s" % "".join(lines)
143
        self.assert_(lines[2].startswith('@@'))
144
            ## "No hunk header for patch:\n%s" % "".join(lines)
145
        self.assert_('@@' in lines[2][2:])
146
            ## "Unterminated hunk header for patch:\n%s" % "".join(lines)
147
1558.15.2 by Aaron Bentley
Implemented binary file handling for diff
148
    def test_binary_lines(self):
149
        self.assertRaises(BinaryFile, udiff_lines, [1023 * 'a' + '\x00'], [])
150
        self.assertRaises(BinaryFile, udiff_lines, [], [1023 * 'a' + '\x00'])
1558.15.11 by Aaron Bentley
Apply merge review suggestions
151
        udiff_lines([1023 * 'a' + '\x00'], [], allow_binary=True)
152
        udiff_lines([], [1023 * 'a' + '\x00'], allow_binary=True)
1692.8.2 by James Henstridge
add a test for sending external diff output to a file
153
154
    def test_external_diff(self):
155
        lines = external_udiff_lines(['boo\n'], ['goo\n'])
156
        self.check_patch(lines)
1899.1.6 by John Arbash Meinel
internal_diff always adds a trailing \n, make sure external_diff does too
157
        self.assertEqual('\n', lines[-1])
1711.2.57 by John Arbash Meinel
Allow external diff to write to a file without a fileno.
158
159
    def test_external_diff_no_fileno(self):
160
        # Make sure that we can handle not having a fileno, even
161
        # if the diff is large
162
        lines = external_udiff_lines(['boo\n']*10000,
163
                                     ['goo\n']*10000,
164
                                     use_stringio=True)
165
        self.check_patch(lines)
1899.1.1 by John Arbash Meinel
Fix the bug in the NoDiff exception class, and add a test
166
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
167
    def test_external_diff_binary_lang_c(self):
2321.2.5 by Alexander Belchenko
external diff: no need for special code path for win32 (suggested by John Meinel)
168
        old_env = {}
169
        for lang in ('LANG', 'LC_ALL', 'LANGUAGE'):
170
            old_env[lang] = osutils.set_or_unset_env(lang, 'C')
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
171
        try:
172
            lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
1959.1.1 by Marien Zwart
merge.
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'])
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
178
        finally:
2321.2.5 by Alexander Belchenko
external diff: no need for special code path for win32 (suggested by John Meinel)
179
            for lang, old_val in old_env.iteritems():
180
                osutils.set_or_unset_env(lang, old_val)
1899.1.4 by John Arbash Meinel
Just swallow a return code of 2
181
1899.1.1 by John Arbash Meinel
Fix the bug in the NoDiff exception class, and add a test
182
    def test_no_external_diff(self):
183
        """Check that NoDiff is raised when diff is not available"""
184
        # Use os.environ['PATH'] to make sure no 'diff' command is available
185
        orig_path = os.environ['PATH']
186
        try:
187
            os.environ['PATH'] = ''
188
            self.assertRaises(NoDiff, external_diff,
189
                              'old', ['boo\n'], 'new', ['goo\n'],
190
                              StringIO(), diff_opts=['-u'])
191
        finally:
192
            os.environ['PATH'] = orig_path
1692.8.2 by James Henstridge
add a test for sending external diff output to a file
193
        
1711.2.30 by John Arbash Meinel
Fix bug in internal_diff handling of unicode paths
194
    def test_internal_diff_default(self):
195
        # Default internal diff encoding is utf8
196
        output = StringIO()
197
        internal_diff(u'old_\xb5', ['old_text\n'],
198
                    u'new_\xe5', ['new_text\n'], output)
199
        lines = output.getvalue().splitlines(True)
200
        self.check_patch(lines)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
201
        self.assertEquals(['--- old_\xc2\xb5\n',
202
                           '+++ new_\xc3\xa5\n',
1711.2.30 by John Arbash Meinel
Fix bug in internal_diff handling of unicode paths
203
                           '@@ -1,1 +1,1 @@\n',
204
                           '-old_text\n',
205
                           '+new_text\n',
206
                           '\n',
207
                          ]
208
                          , lines)
209
210
    def test_internal_diff_utf8(self):
211
        output = StringIO()
212
        internal_diff(u'old_\xb5', ['old_text\n'],
213
                    u'new_\xe5', ['new_text\n'], output,
214
                    path_encoding='utf8')
215
        lines = output.getvalue().splitlines(True)
216
        self.check_patch(lines)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
217
        self.assertEquals(['--- old_\xc2\xb5\n',
218
                           '+++ new_\xc3\xa5\n',
1711.2.30 by John Arbash Meinel
Fix bug in internal_diff handling of unicode paths
219
                           '@@ -1,1 +1,1 @@\n',
220
                           '-old_text\n',
221
                           '+new_text\n',
222
                           '\n',
223
                          ]
224
                          , lines)
225
226
    def test_internal_diff_iso_8859_1(self):
227
        output = StringIO()
228
        internal_diff(u'old_\xb5', ['old_text\n'],
229
                    u'new_\xe5', ['new_text\n'], output,
230
                    path_encoding='iso-8859-1')
231
        lines = output.getvalue().splitlines(True)
232
        self.check_patch(lines)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
233
        self.assertEquals(['--- old_\xb5\n',
234
                           '+++ new_\xe5\n',
1711.2.30 by John Arbash Meinel
Fix bug in internal_diff handling of unicode paths
235
                           '@@ -1,1 +1,1 @@\n',
236
                           '-old_text\n',
237
                           '+new_text\n',
238
                           '\n',
239
                          ]
240
                          , lines)
241
3085.1.1 by John Arbash Meinel
Fix internal_diff to not fail when the texts are identical.
242
    def test_internal_diff_no_content(self):
243
        output = StringIO()
244
        internal_diff(u'old', [], u'new', [], output)
245
        self.assertEqual('', output.getvalue())
246
247
    def test_internal_diff_no_changes(self):
248
        output = StringIO()
249
        internal_diff(u'old', ['text\n', 'contents\n'],
250
                      u'new', ['text\n', 'contents\n'],
251
                      output)
252
        self.assertEqual('', output.getvalue())
253
1711.2.30 by John Arbash Meinel
Fix bug in internal_diff handling of unicode paths
254
    def test_internal_diff_returns_bytes(self):
255
        import StringIO
256
        output = StringIO.StringIO()
257
        internal_diff(u'old_\xb5', ['old_text\n'],
258
                    u'new_\xe5', ['new_text\n'], output)
259
        self.failUnless(isinstance(output.getvalue(), str),
260
            'internal_diff should return bytestrings')
261
1185.81.25 by Aaron Bentley
Clean up test_diff
262
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
263
class TestDiffFiles(TestCaseInTempDir):
264
265
    def test_external_diff_binary(self):
266
        """The output when using external diff should use diff's i18n error"""
267
        # Make sure external_diff doesn't fail in the current LANG
268
        lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
269
2240.1.1 by Alexander Belchenko
test_external_diff_binary: run external diff with --binary flag
270
        cmd = ['diff', '-u', '--binary', 'old', 'new']
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
271
        open('old', 'wb').write('\x00foobar\n')
272
        open('new', 'wb').write('foo\x00bar\n')
273
        pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
274
                                     stdin=subprocess.PIPE)
275
        out, err = pipe.communicate()
276
        # Diff returns '2' on Binary files.
277
        self.assertEqual(2, pipe.returncode)
278
        # We should output whatever diff tells us, plus a trailing newline
279
        self.assertEqual(out.splitlines(True) + ['\n'], lines)
280
281
2405.1.1 by John Arbash Meinel
Add a bunch of direct tests for 'show_diff_trees'
282
class TestShowDiffTreesHelper(TestCaseWithTransport):
283
    """Has a helper for running show_diff_trees"""
284
285
    def get_diff(self, tree1, tree2, specific_files=None, working_tree=None):
286
        output = StringIO()
287
        if working_tree is not None:
288
            extra_trees = (working_tree,)
289
        else:
290
            extra_trees = ()
291
        show_diff_trees(tree1, tree2, output, specific_files=specific_files,
292
                        extra_trees=extra_trees, old_label='old/',
293
                        new_label='new/')
294
        return output.getvalue()
295
296
297
class TestDiffDates(TestShowDiffTreesHelper):
1740.2.5 by Aaron Bentley
Merge from bzr.dev
298
299
    def setUp(self):
300
        super(TestDiffDates, self).setUp()
301
        self.wt = self.make_branch_and_tree('.')
302
        self.b = self.wt.branch
303
        self.build_tree_contents([
304
            ('file1', 'file1 contents at rev 1\n'),
305
            ('file2', 'file2 contents at rev 1\n')
306
            ])
307
        self.wt.add(['file1', 'file2'])
308
        self.wt.commit(
309
            message='Revision 1',
310
            timestamp=1143849600, # 2006-04-01 00:00:00 UTC
311
            timezone=0,
312
            rev_id='rev-1')
313
        self.build_tree_contents([('file1', 'file1 contents at rev 2\n')])
314
        self.wt.commit(
315
            message='Revision 2',
316
            timestamp=1143936000, # 2006-04-02 00:00:00 UTC
317
            timezone=28800,
318
            rev_id='rev-2')
319
        self.build_tree_contents([('file2', 'file2 contents at rev 3\n')])
320
        self.wt.commit(
321
            message='Revision 3',
322
            timestamp=1144022400, # 2006-04-03 00:00:00 UTC
323
            timezone=-3600,
324
            rev_id='rev-3')
325
        self.wt.remove(['file2'])
326
        self.wt.commit(
327
            message='Revision 4',
328
            timestamp=1144108800, # 2006-04-04 00:00:00 UTC
329
            timezone=0,
330
            rev_id='rev-4')
331
        self.build_tree_contents([
332
            ('file1', 'file1 contents in working tree\n')
333
            ])
334
        # set the date stamps for files in the working tree to known values
335
        os.utime('file1', (1144195200, 1144195200)) # 2006-04-05 00:00:00 UTC
336
337
    def test_diff_rev_tree_working_tree(self):
338
        output = self.get_diff(self.wt.basis_tree(), self.wt)
339
        # note that the date for old/file1 is from rev 2 rather than from
340
        # the basis revision (rev 4)
341
        self.assertEqualDiff(output, '''\
342
=== modified file 'file1'
343
--- old/file1\t2006-04-02 00:00:00 +0000
344
+++ new/file1\t2006-04-05 00:00:00 +0000
345
@@ -1,1 +1,1 @@
346
-file1 contents at rev 2
347
+file1 contents in working tree
348
349
''')
350
351
    def test_diff_rev_tree_rev_tree(self):
352
        tree1 = self.b.repository.revision_tree('rev-2')
353
        tree2 = self.b.repository.revision_tree('rev-3')
354
        output = self.get_diff(tree1, tree2)
355
        self.assertEqualDiff(output, '''\
356
=== modified file 'file2'
357
--- old/file2\t2006-04-01 00:00:00 +0000
358
+++ new/file2\t2006-04-03 00:00:00 +0000
359
@@ -1,1 +1,1 @@
360
-file2 contents at rev 1
361
+file2 contents at rev 3
362
363
''')
364
        
365
    def test_diff_add_files(self):
366
        tree1 = self.b.repository.revision_tree(None)
367
        tree2 = self.b.repository.revision_tree('rev-1')
368
        output = self.get_diff(tree1, tree2)
369
        # the files have the epoch time stamp for the tree in which
370
        # they don't exist.
371
        self.assertEqualDiff(output, '''\
372
=== added file 'file1'
373
--- old/file1\t1970-01-01 00:00:00 +0000
374
+++ new/file1\t2006-04-01 00:00:00 +0000
375
@@ -0,0 +1,1 @@
376
+file1 contents at rev 1
377
378
=== added file 'file2'
379
--- old/file2\t1970-01-01 00:00:00 +0000
380
+++ new/file2\t2006-04-01 00:00:00 +0000
381
@@ -0,0 +1,1 @@
382
+file2 contents at rev 1
383
384
''')
385
386
    def test_diff_remove_files(self):
387
        tree1 = self.b.repository.revision_tree('rev-3')
388
        tree2 = self.b.repository.revision_tree('rev-4')
389
        output = self.get_diff(tree1, tree2)
390
        # the file has the epoch time stamp for the tree in which
391
        # it doesn't exist.
392
        self.assertEqualDiff(output, '''\
393
=== removed file 'file2'
394
--- old/file2\t2006-04-03 00:00:00 +0000
395
+++ new/file2\t1970-01-01 00:00:00 +0000
396
@@ -1,1 +0,0 @@
397
-file2 contents at rev 3
398
399
''')
400
1551.7.17 by Aaron Bentley
Switch to PathsNotVersioned, accept extra_trees
401
    def test_show_diff_specified(self):
1551.7.22 by Aaron Bentley
Changes from review
402
        """A working tree filename can be used to identify a file"""
1551.7.17 by Aaron Bentley
Switch to PathsNotVersioned, accept extra_trees
403
        self.wt.rename_one('file1', 'file1b')
404
        old_tree = self.b.repository.revision_tree('rev-1')
405
        new_tree = self.b.repository.revision_tree('rev-4')
1551.7.22 by Aaron Bentley
Changes from review
406
        out = self.get_diff(old_tree, new_tree, specific_files=['file1b'], 
407
                            working_tree=self.wt)
408
        self.assertContainsRe(out, 'file1\t')
1551.7.17 by Aaron Bentley
Switch to PathsNotVersioned, accept extra_trees
409
1551.7.22 by Aaron Bentley
Changes from review
410
    def test_recursive_diff(self):
411
        """Children of directories are matched"""
412
        os.mkdir('dir1')
413
        os.mkdir('dir2')
414
        self.wt.add(['dir1', 'dir2'])
415
        self.wt.rename_one('file1', 'dir1/file1')
416
        old_tree = self.b.repository.revision_tree('rev-1')
417
        new_tree = self.b.repository.revision_tree('rev-4')
418
        out = self.get_diff(old_tree, new_tree, specific_files=['dir1'], 
419
                            working_tree=self.wt)
420
        self.assertContainsRe(out, 'file1\t')
421
        out = self.get_diff(old_tree, new_tree, specific_files=['dir2'], 
422
                            working_tree=self.wt)
423
        self.assertNotContainsRe(out, 'file1\t')
1740.2.5 by Aaron Bentley
Merge from bzr.dev
424
1899.1.1 by John Arbash Meinel
Fix the bug in the NoDiff exception class, and add a test
425
2405.1.1 by John Arbash Meinel
Add a bunch of direct tests for 'show_diff_trees'
426
427
class TestShowDiffTrees(TestShowDiffTreesHelper):
428
    """Direct tests for show_diff_trees"""
429
430
    def test_modified_file(self):
431
        """Test when a file is modified."""
432
        tree = self.make_branch_and_tree('tree')
433
        self.build_tree_contents([('tree/file', 'contents\n')])
434
        tree.add(['file'], ['file-id'])
435
        tree.commit('one', rev_id='rev-1')
436
437
        self.build_tree_contents([('tree/file', 'new contents\n')])
438
        diff = self.get_diff(tree.basis_tree(), tree)
439
        self.assertContainsRe(diff, "=== modified file 'file'\n")
440
        self.assertContainsRe(diff, '--- old/file\t')
441
        self.assertContainsRe(diff, '\\+\\+\\+ new/file\t')
442
        self.assertContainsRe(diff, '-contents\n'
443
                                    '\\+new contents\n')
444
2405.1.2 by John Arbash Meinel
Fix bug #103870 by passing None instead of a (sometimes wrong) path
445
    def test_modified_file_in_renamed_dir(self):
446
        """Test when a file is modified in a renamed directory."""
447
        tree = self.make_branch_and_tree('tree')
448
        self.build_tree(['tree/dir/'])
449
        self.build_tree_contents([('tree/dir/file', 'contents\n')])
450
        tree.add(['dir', 'dir/file'], ['dir-id', 'file-id'])
451
        tree.commit('one', rev_id='rev-1')
452
453
        tree.rename_one('dir', 'other')
454
        self.build_tree_contents([('tree/other/file', 'new contents\n')])
455
        diff = self.get_diff(tree.basis_tree(), tree)
456
        self.assertContainsRe(diff, "=== renamed directory 'dir' => 'other'\n")
457
        self.assertContainsRe(diff, "=== modified file 'other/file'\n")
458
        # XXX: This is technically incorrect, because it used to be at another
459
        # location. What to do?
2405.1.3 by John Arbash Meinel
Do a better fix, which recognizes that we should pass the correct old path.
460
        self.assertContainsRe(diff, '--- old/dir/file\t')
2405.1.2 by John Arbash Meinel
Fix bug #103870 by passing None instead of a (sometimes wrong) path
461
        self.assertContainsRe(diff, '\\+\\+\\+ new/other/file\t')
462
        self.assertContainsRe(diff, '-contents\n'
463
                                    '\\+new contents\n')
464
2405.1.1 by John Arbash Meinel
Add a bunch of direct tests for 'show_diff_trees'
465
    def test_renamed_directory(self):
466
        """Test when only a directory is only renamed."""
467
        tree = self.make_branch_and_tree('tree')
468
        self.build_tree(['tree/dir/'])
469
        self.build_tree_contents([('tree/dir/file', 'contents\n')])
470
        tree.add(['dir', 'dir/file'], ['dir-id', 'file-id'])
471
        tree.commit('one', rev_id='rev-1')
472
473
        tree.rename_one('dir', 'newdir')
474
        diff = self.get_diff(tree.basis_tree(), tree)
475
        # Renaming a directory should be a single "you renamed this dir" even
476
        # when there are files inside.
477
        self.assertEqual("=== renamed directory 'dir' => 'newdir'\n", diff)
478
479
    def test_renamed_file(self):
480
        """Test when a file is only renamed."""
481
        tree = self.make_branch_and_tree('tree')
482
        self.build_tree_contents([('tree/file', 'contents\n')])
483
        tree.add(['file'], ['file-id'])
484
        tree.commit('one', rev_id='rev-1')
485
486
        tree.rename_one('file', 'newname')
487
        diff = self.get_diff(tree.basis_tree(), tree)
488
        self.assertContainsRe(diff, "=== renamed file 'file' => 'newname'\n")
489
        # We shouldn't have a --- or +++ line, because there is no content
490
        # change
491
        self.assertNotContainsRe(diff, '---')
492
493
    def test_renamed_and_modified_file(self):
494
        """Test when a file is only renamed."""
495
        tree = self.make_branch_and_tree('tree')
496
        self.build_tree_contents([('tree/file', 'contents\n')])
497
        tree.add(['file'], ['file-id'])
498
        tree.commit('one', rev_id='rev-1')
499
500
        tree.rename_one('file', 'newname')
501
        self.build_tree_contents([('tree/newname', 'new contents\n')])
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'
507
                                    '\\+new contents\n')
508
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
509
    def test_binary_unicode_filenames(self):
2592.2.2 by Jonathan Lange
Apply jam's comments to test_binary_unicode_filenames. Change the
510
        """Test that contents of files are *not* encoded in UTF-8 when there
511
        is a binary file in the diff.
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
512
        """
513
        # See https://bugs.launchpad.net/bugs/110092.
2592.2.4 by Jonathan Lange
Skip the unicode filename test if the platform doesn't support unicode
514
        self.requireFeature(UnicodeFilename)
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
515
516
        # This bug isn't triggered with cStringIO.
517
        from StringIO import StringIO
518
        tree = self.make_branch_and_tree('tree')
2592.2.2 by Jonathan Lange
Apply jam's comments to test_binary_unicode_filenames. Change the
519
        alpha, omega = u'\u03b1', u'\u03c9'
520
        alpha_utf8, omega_utf8 = alpha.encode('utf8'), omega.encode('utf8')
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
521
        self.build_tree_contents(
2592.2.2 by Jonathan Lange
Apply jam's comments to test_binary_unicode_filenames. Change the
522
            [('tree/' + alpha, chr(0)),
523
             ('tree/' + omega,
524
              ('The %s and the %s\n' % (alpha_utf8, omega_utf8)))])
525
        tree.add([alpha], ['file-id'])
526
        tree.add([omega], ['file-id-2'])
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
527
        diff_content = StringIO()
528
        show_diff_trees(tree.basis_tree(), tree, diff_content)
529
        diff = diff_content.getvalue()
2592.2.2 by Jonathan Lange
Apply jam's comments to test_binary_unicode_filenames. Change the
530
        self.assertContainsRe(diff, r"=== added file '%s'" % alpha_utf8)
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
531
        self.assertContainsRe(
2592.2.2 by Jonathan Lange
Apply jam's comments to test_binary_unicode_filenames. Change the
532
            diff, "Binary files a/%s.*and b/%s.* differ\n" % (alpha_utf8, alpha_utf8))
533
        self.assertContainsRe(diff, r"=== added file '%s'" % omega_utf8)
534
        self.assertContainsRe(diff, r"--- a/%s" % (omega_utf8,))
535
        self.assertContainsRe(diff, r"\+\+\+ b/%s" % (omega_utf8,))
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
536
2725.2.1 by ghigo
When a unicode filename is renamed, in the diff is showed a wrong result
537
    def test_unicode_filename(self):
538
        """Test when the filename are unicode."""
539
        self.requireFeature(UnicodeFilename)
540
541
        alpha, omega = u'\u03b1', u'\u03c9'
542
        autf8, outf8 = alpha.encode('utf8'), omega.encode('utf8')
543
544
        tree = self.make_branch_and_tree('tree')
545
        self.build_tree_contents([('tree/ren_'+alpha, 'contents\n')])
546
        tree.add(['ren_'+alpha], ['file-id-2'])
547
        self.build_tree_contents([('tree/del_'+alpha, 'contents\n')])
548
        tree.add(['del_'+alpha], ['file-id-3'])
549
        self.build_tree_contents([('tree/mod_'+alpha, 'contents\n')])
550
        tree.add(['mod_'+alpha], ['file-id-4'])
551
552
        tree.commit('one', rev_id='rev-1')
553
554
        tree.rename_one('ren_'+alpha, 'ren_'+omega)
555
        tree.remove('del_'+alpha)
556
        self.build_tree_contents([('tree/add_'+alpha, 'contents\n')])
557
        tree.add(['add_'+alpha], ['file-id'])
558
        self.build_tree_contents([('tree/mod_'+alpha, 'contents_mod\n')])
559
560
        diff = self.get_diff(tree.basis_tree(), tree)
561
        self.assertContainsRe(diff,
562
                "=== renamed file 'ren_%s' => 'ren_%s'\n"%(autf8, outf8))
563
        self.assertContainsRe(diff, "=== added file 'add_%s'"%autf8)
564
        self.assertContainsRe(diff, "=== modified file 'mod_%s'"%autf8)
565
        self.assertContainsRe(diff, "=== removed file 'del_%s'"%autf8)
2405.1.1 by John Arbash Meinel
Add a bunch of direct tests for 'show_diff_trees'
566
3009.2.9 by Aaron Bentley
Add tests for Differ
567
3009.2.22 by Aaron Bentley
Update names & docstring
568
class DiffWasIs(DiffPath):
3009.2.15 by Aaron Bentley
Test differ registration
569
570
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
571
        self.to_file.write('was: ')
572
        self.to_file.write(self.old_tree.get_file(file_id).read())
573
        self.to_file.write('is: ')
574
        self.to_file.write(self.new_tree.get_file(file_id).read())
575
        pass
576
577
3009.2.22 by Aaron Bentley
Update names & docstring
578
class TestDiffTree(TestCaseWithTransport):
3009.2.9 by Aaron Bentley
Add tests for Differ
579
580
    def setUp(self):
581
        TestCaseWithTransport.setUp(self)
582
        self.old_tree = self.make_branch_and_tree('old-tree')
583
        self.old_tree.lock_write()
584
        self.addCleanup(self.old_tree.unlock)
585
        self.new_tree = self.make_branch_and_tree('new-tree')
586
        self.new_tree.lock_write()
587
        self.addCleanup(self.new_tree.unlock)
3009.2.22 by Aaron Bentley
Update names & docstring
588
        self.differ = DiffTree(self.old_tree, self.new_tree, StringIO())
3009.2.9 by Aaron Bentley
Add tests for Differ
589
590
    def test_diff_text(self):
591
        self.build_tree_contents([('old-tree/olddir/',),
592
                                  ('old-tree/olddir/oldfile', 'old\n')])
593
        self.old_tree.add('olddir')
594
        self.old_tree.add('olddir/oldfile', 'file-id')
595
        self.build_tree_contents([('new-tree/newdir/',),
596
                                  ('new-tree/newdir/newfile', 'new\n')])
597
        self.new_tree.add('newdir')
598
        self.new_tree.add('newdir/newfile', 'file-id')
3009.2.22 by Aaron Bentley
Update names & docstring
599
        differ = DiffText(self.old_tree, self.new_tree, StringIO())
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
600
        differ.diff_text('file-id', None, 'old label', 'new label')
3009.2.9 by Aaron Bentley
Add tests for Differ
601
        self.assertEqual(
602
            '--- old label\n+++ new label\n@@ -1,1 +0,0 @@\n-old\n\n',
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
603
            differ.to_file.getvalue())
604
        differ.to_file.seek(0)
605
        differ.diff_text(None, 'file-id', 'old label', 'new label')
3009.2.9 by Aaron Bentley
Add tests for Differ
606
        self.assertEqual(
607
            '--- old label\n+++ new label\n@@ -0,0 +1,1 @@\n+new\n\n',
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
608
            differ.to_file.getvalue())
609
        differ.to_file.seek(0)
610
        differ.diff_text('file-id', 'file-id', 'old label', 'new label')
3009.2.9 by Aaron Bentley
Add tests for Differ
611
        self.assertEqual(
612
            '--- old label\n+++ new label\n@@ -1,1 +1,1 @@\n-old\n+new\n\n',
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
613
            differ.to_file.getvalue())
3009.2.9 by Aaron Bentley
Add tests for Differ
614
3087.1.1 by Aaron Bentley
Diff handles missing files correctly, with no tracebacks
615
    def test_diff_deletion(self):
616
        self.build_tree_contents([('old-tree/file', 'contents'),
617
                                  ('new-tree/file', 'contents')])
618
        self.old_tree.add('file', 'file-id')
619
        self.new_tree.add('file', 'file-id')
620
        os.unlink('new-tree/file')
621
        self.differ.show_diff(None)
622
        self.assertContainsRe(self.differ.to_file.getvalue(), '-contents')
623
624
    def test_diff_creation(self):
625
        self.build_tree_contents([('old-tree/file', 'contents'),
626
                                  ('new-tree/file', 'contents')])
627
        self.old_tree.add('file', 'file-id')
628
        self.new_tree.add('file', 'file-id')
629
        os.unlink('old-tree/file')
630
        self.differ.show_diff(None)
631
        self.assertContainsRe(self.differ.to_file.getvalue(), '\+contents')
632
3009.2.9 by Aaron Bentley
Add tests for Differ
633
    def test_diff_symlink(self):
3009.2.22 by Aaron Bentley
Update names & docstring
634
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
635
        differ.diff_symlink('old target', None)
3009.2.9 by Aaron Bentley
Add tests for Differ
636
        self.assertEqual("=== target was 'old target'\n",
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
637
                         differ.to_file.getvalue())
3009.2.9 by Aaron Bentley
Add tests for Differ
638
3009.2.22 by Aaron Bentley
Update names & docstring
639
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
640
        differ.diff_symlink(None, 'new target')
3009.2.9 by Aaron Bentley
Add tests for Differ
641
        self.assertEqual("=== target is 'new target'\n",
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
642
                         differ.to_file.getvalue())
643
3009.2.22 by Aaron Bentley
Update names & docstring
644
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
645
        differ.diff_symlink('old target', 'new target')
3009.2.9 by Aaron Bentley
Add tests for Differ
646
        self.assertEqual("=== target changed 'old target' => 'new target'\n",
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
647
                         differ.to_file.getvalue())
3009.2.9 by Aaron Bentley
Add tests for Differ
648
649
    def test_diff(self):
650
        self.build_tree_contents([('old-tree/olddir/',),
651
                                  ('old-tree/olddir/oldfile', 'old\n')])
652
        self.old_tree.add('olddir')
653
        self.old_tree.add('olddir/oldfile', 'file-id')
654
        self.build_tree_contents([('new-tree/newdir/',),
655
                                  ('new-tree/newdir/newfile', 'new\n')])
656
        self.new_tree.add('newdir')
657
        self.new_tree.add('newdir/newfile', 'file-id')
3009.2.12 by Aaron Bentley
Associate labels with text diffing only
658
        self.differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
3009.2.9 by Aaron Bentley
Add tests for Differ
659
        self.assertContainsRe(
660
            self.differ.to_file.getvalue(),
661
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
662
             ' \@\@\n-old\n\+new\n\n')
663
664
    def test_diff_kind_change(self):
665
        self.build_tree_contents([('old-tree/olddir/',),
666
                                  ('old-tree/olddir/oldfile', 'old\n')])
667
        self.old_tree.add('olddir')
668
        self.old_tree.add('olddir/oldfile', 'file-id')
669
        self.build_tree(['new-tree/newdir/'])
670
        os.symlink('new', 'new-tree/newdir/newfile')
671
        self.new_tree.add('newdir')
672
        self.new_tree.add('newdir/newfile', 'file-id')
3009.2.12 by Aaron Bentley
Associate labels with text diffing only
673
        self.differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
3009.2.9 by Aaron Bentley
Add tests for Differ
674
        self.assertContainsRe(
675
            self.differ.to_file.getvalue(),
676
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+0,0'
677
             ' \@\@\n-old\n\n')
678
        self.assertContainsRe(self.differ.to_file.getvalue(),
679
                              "=== target is 'new'\n")
680
3009.2.19 by Aaron Bentley
Implement directory diffing
681
    def test_diff_directory(self):
682
        self.build_tree(['new-tree/new-dir/'])
683
        self.new_tree.add('new-dir', 'new-dir-id')
684
        self.differ.diff('new-dir-id', None, 'new-dir')
685
        self.assertEqual(self.differ.to_file.getvalue(), '')
686
3009.2.16 by Aaron Bentley
Test support for extra differs
687
    def create_old_new(self):
688
        self.build_tree_contents([('old-tree/olddir/',),
689
                                  ('old-tree/olddir/oldfile', 'old\n')])
690
        self.old_tree.add('olddir')
691
        self.old_tree.add('olddir/oldfile', 'file-id')
692
        self.build_tree_contents([('new-tree/newdir/',),
693
                                  ('new-tree/newdir/newfile', 'new\n')])
694
        self.new_tree.add('newdir')
695
        self.new_tree.add('newdir/newfile', 'file-id')
696
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
697
    def test_register_diff(self):
3009.2.16 by Aaron Bentley
Test support for extra differs
698
        self.create_old_new()
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
699
        old_diff_factories = DiffTree.diff_factories
700
        DiffTree.diff_factories=old_diff_factories[:]
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
701
        DiffTree.diff_factories.insert(0, DiffWasIs.from_diff_tree)
3009.2.16 by Aaron Bentley
Test support for extra differs
702
        try:
3009.2.22 by Aaron Bentley
Update names & docstring
703
            differ = DiffTree(self.old_tree, self.new_tree, StringIO())
3009.2.16 by Aaron Bentley
Test support for extra differs
704
        finally:
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
705
            DiffTree.diff_factories = old_diff_factories
3009.2.16 by Aaron Bentley
Test support for extra differs
706
        differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
707
        self.assertNotContainsRe(
708
            differ.to_file.getvalue(),
709
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
710
             ' \@\@\n-old\n\+new\n\n')
711
        self.assertContainsRe(differ.to_file.getvalue(),
712
                              'was: old\nis: new\n')
713
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
714
    def test_extra_factories(self):
3009.2.16 by Aaron Bentley
Test support for extra differs
715
        self.create_old_new()
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
716
        differ = DiffTree(self.old_tree, self.new_tree, StringIO(),
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
717
                            extra_factories=[DiffWasIs.from_diff_tree])
3009.2.16 by Aaron Bentley
Test support for extra differs
718
        differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
719
        self.assertNotContainsRe(
720
            differ.to_file.getvalue(),
721
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
722
             ' \@\@\n-old\n\+new\n\n')
723
        self.assertContainsRe(differ.to_file.getvalue(),
724
                              'was: old\nis: new\n')
725
3123.4.1 by Aaron Bentley
Diff sorts files in alphabetical order
726
    def test_alphabetical_order(self):
727
        self.build_tree(['new-tree/a-file'])
728
        self.new_tree.add('a-file')
729
        self.build_tree(['old-tree/b-file'])
730
        self.old_tree.add('b-file')
731
        self.differ.show_diff(None)
732
        self.assertContainsRe(self.differ.to_file.getvalue(),
733
            '.*a-file(.|\n)*b-file')
734
3009.2.9 by Aaron Bentley
Add tests for Differ
735
1711.2.15 by John Arbash Meinel
Found a couple CDV left
736
class TestPatienceDiffLib(TestCase):
1185.81.1 by John Arbash Meinel
Adding nofrillsprecisemerge's diff algorithm, wrapped in difflib.
737
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
738
    def setUp(self):
739
        super(TestPatienceDiffLib, self).setUp()
740
        self._unique_lcs = bzrlib._patiencediff_py.unique_lcs_py
741
        self._recurse_matches = bzrlib._patiencediff_py.recurse_matches_py
742
        self._PatienceSequenceMatcher = \
743
            bzrlib._patiencediff_py.PatienceSequenceMatcher_py
744
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
745
    def test_unique_lcs(self):
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
746
        unique_lcs = self._unique_lcs
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
747
        self.assertEquals(unique_lcs('', ''), [])
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
748
        self.assertEquals(unique_lcs('', 'a'), [])
749
        self.assertEquals(unique_lcs('a', ''), [])
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
750
        self.assertEquals(unique_lcs('a', 'a'), [(0,0)])
751
        self.assertEquals(unique_lcs('a', 'b'), [])
752
        self.assertEquals(unique_lcs('ab', 'ab'), [(0,0), (1,1)])
753
        self.assertEquals(unique_lcs('abcde', 'cdeab'), [(2,0), (3,1), (4,2)])
754
        self.assertEquals(unique_lcs('cdeab', 'abcde'), [(0,2), (1,3), (2,4)])
755
        self.assertEquals(unique_lcs('abXde', 'abYde'), [(0,0), (1,1), 
756
                                                         (3,3), (4,4)])
757
        self.assertEquals(unique_lcs('acbac', 'abc'), [(2,1)])
758
759
    def test_recurse_matches(self):
760
        def test_one(a, b, matches):
761
            test_matches = []
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
762
            self._recurse_matches(
763
                a, b, 0, 0, len(a), len(b), test_matches, 10)
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
764
            self.assertEquals(test_matches, matches)
765
1711.2.17 by John Arbash Meinel
Small cleanups to patience_diff code.
766
        test_one(['a', '', 'b', '', 'c'], ['a', 'a', 'b', 'c', 'c'],
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
767
                 [(0, 0), (2, 2), (4, 4)])
768
        test_one(['a', 'c', 'b', 'a', 'c'], ['a', 'b', 'c'],
769
                 [(0, 0), (2, 1), (4, 2)])
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
770
        # Even though 'bc' is not unique globally, and is surrounded by
771
        # non-matching lines, we should still match, because they are locally
772
        # unique
773
        test_one('abcdbce', 'afbcgdbce', [(0,0), (1, 2), (2, 3), (3, 5),
774
                                          (4, 6), (5, 7), (6, 8)])
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
775
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
776
        # recurse_matches doesn't match non-unique 
777
        # lines surrounded by bogus text.
1185.81.24 by Aaron Bentley
Reoganize patience-related code
778
        # The update has been done in patiencediff.SequenceMatcher instead
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
779
780
        # This is what it could be
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
781
        #test_one('aBccDe', 'abccde', [(0,0), (2,2), (3,3), (5,5)])
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
782
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
783
        # This is what it currently gives:
784
        test_one('aBccDe', 'abccde', [(0,0), (5,5)])
785
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
786
    def assertDiffBlocks(self, a, b, expected_blocks):
787
        """Check that the sequence matcher returns the correct blocks.
788
789
        :param a: A sequence to match
790
        :param b: Another sequence to match
791
        :param expected_blocks: The expected output, not including the final
792
            matching block (len(a), len(b), 0)
793
        """
794
        matcher = self._PatienceSequenceMatcher(None, a, b)
795
        blocks = matcher.get_matching_blocks()
796
        last = blocks.pop()
797
        self.assertEqual((len(a), len(b), 0), last)
798
        self.assertEqual(expected_blocks, blocks)
799
1185.81.1 by John Arbash Meinel
Adding nofrillsprecisemerge's diff algorithm, wrapped in difflib.
800
    def test_matching_blocks(self):
1185.81.2 by John Arbash Meinel
A couple small tests.
801
        # Some basic matching tests
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
802
        self.assertDiffBlocks('', '', [])
803
        self.assertDiffBlocks([], [], [])
804
        self.assertDiffBlocks('abc', '', [])
805
        self.assertDiffBlocks('', 'abc', [])
806
        self.assertDiffBlocks('abcd', 'abcd', [(0, 0, 4)])
807
        self.assertDiffBlocks('abcd', 'abce', [(0, 0, 3)])
808
        self.assertDiffBlocks('eabc', 'abce', [(1, 0, 3)])
809
        self.assertDiffBlocks('eabce', 'abce', [(1, 0, 4)])
810
        self.assertDiffBlocks('abcde', 'abXde', [(0, 0, 2), (3, 3, 2)])
811
        self.assertDiffBlocks('abcde', 'abXYZde', [(0, 0, 2), (3, 5, 2)])
812
        self.assertDiffBlocks('abde', 'abXYZde', [(0, 0, 2), (2, 5, 2)])
813
        # This may check too much, but it checks to see that
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
814
        # a copied block stays attached to the previous section,
815
        # not the later one.
816
        # difflib would tend to grab the trailing longest match
817
        # which would make the diff not look right
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
818
        self.assertDiffBlocks('abcdefghijklmnop', 'abcdefxydefghijklmnop',
819
                              [(0, 0, 6), (6, 11, 10)])
1185.81.1 by John Arbash Meinel
Adding nofrillsprecisemerge's diff algorithm, wrapped in difflib.
820
1185.81.2 by John Arbash Meinel
A couple small tests.
821
        # make sure it supports passing in lists
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
822
        self.assertDiffBlocks(
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
823
                   ['hello there\n',
824
                    'world\n',
825
                    'how are you today?\n'],
826
                   ['hello there\n',
827
                    'how are you today?\n'],
1185.81.2 by John Arbash Meinel
A couple small tests.
828
                [(0, 0, 1), (2, 1, 1)])
1185.81.1 by John Arbash Meinel
Adding nofrillsprecisemerge's diff algorithm, wrapped in difflib.
829
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
830
        # non unique lines surrounded by non-matching lines
831
        # won't be found
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
832
        self.assertDiffBlocks('aBccDe', 'abccde', [(0,0,1), (5,5,1)])
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
833
834
        # But they only need to be locally unique
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
835
        self.assertDiffBlocks('aBcDec', 'abcdec', [(0,0,1), (2,2,1), (4,4,2)])
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
836
837
        # non unique blocks won't be matched
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
838
        self.assertDiffBlocks('aBcdEcdFg', 'abcdecdfg', [(0,0,1), (8,8,1)])
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
839
840
        # but locally unique ones will
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
841
        self.assertDiffBlocks('aBcdEeXcdFg', 'abcdecdfg', [(0,0,1), (2,2,2),
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
842
                                              (5,4,1), (7,5,2), (10,8,1)])
843
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
844
        self.assertDiffBlocks('abbabbXd', 'cabbabxd', [(7,7,1)])
845
        self.assertDiffBlocks('abbabbbb', 'cabbabbc', [])
846
        self.assertDiffBlocks('bbbbbbbb', 'cbbbbbbc', [])
1185.81.11 by John Arbash Meinel
Found some edge cases that weren't being matched.
847
3074.2.1 by John Arbash Meinel
Change the C PatienceDiff implementation to support arbitrary objects.
848
    def test_matching_blocks_tuples(self):
849
        # Some basic matching tests
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
850
        self.assertDiffBlocks([], [], [])
851
        self.assertDiffBlocks([('a',), ('b',), ('c,')], [], [])
852
        self.assertDiffBlocks([], [('a',), ('b',), ('c,')], [])
853
        self.assertDiffBlocks([('a',), ('b',), ('c,')],
854
                              [('a',), ('b',), ('c,')],
855
                              [(0, 0, 3)])
856
        self.assertDiffBlocks([('a',), ('b',), ('c,')],
857
                              [('a',), ('b',), ('d,')],
858
                              [(0, 0, 2)])
859
        self.assertDiffBlocks([('d',), ('b',), ('c,')],
860
                              [('a',), ('b',), ('c,')],
861
                              [(1, 1, 2)])
862
        self.assertDiffBlocks([('d',), ('a',), ('b',), ('c,')],
863
                              [('a',), ('b',), ('c,')],
864
                              [(1, 0, 3)])
865
        self.assertDiffBlocks([('a', 'b'), ('c', 'd'), ('e', 'f')],
866
                              [('a', 'b'), ('c', 'X'), ('e', 'f')],
867
                              [(0, 0, 1), (2, 2, 1)])
868
        self.assertDiffBlocks([('a', 'b'), ('c', 'd'), ('e', 'f')],
869
                              [('a', 'b'), ('c', 'dX'), ('e', 'f')],
870
                              [(0, 0, 1), (2, 2, 1)])
3074.2.1 by John Arbash Meinel
Change the C PatienceDiff implementation to support arbitrary objects.
871
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
872
    def test_opcodes(self):
1711.2.10 by John Arbash Meinel
Clarify the patience tests a little bit.
873
        def chk_ops(a, b, expected_codes):
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
874
            s = self._PatienceSequenceMatcher(None, a, b)
1711.2.10 by John Arbash Meinel
Clarify the patience tests a little bit.
875
            self.assertEquals(expected_codes, s.get_opcodes())
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
876
877
        chk_ops('', '', [])
878
        chk_ops([], [], [])
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
879
        chk_ops('abc', '', [('delete', 0,3, 0,0)])
880
        chk_ops('', 'abc', [('insert', 0,0, 0,3)])
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
881
        chk_ops('abcd', 'abcd', [('equal',    0,4, 0,4)])
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
882
        chk_ops('abcd', 'abce', [('equal',   0,3, 0,3),
883
                                 ('replace', 3,4, 3,4)
884
                                ])
885
        chk_ops('eabc', 'abce', [('delete', 0,1, 0,0),
886
                                 ('equal',  1,4, 0,3),
887
                                 ('insert', 4,4, 3,4)
888
                                ])
889
        chk_ops('eabce', 'abce', [('delete', 0,1, 0,0),
890
                                  ('equal',  1,5, 0,4)
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
891
                                 ])
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
892
        chk_ops('abcde', 'abXde', [('equal',   0,2, 0,2),
893
                                   ('replace', 2,3, 2,3),
894
                                   ('equal',   3,5, 3,5)
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
895
                                  ])
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
896
        chk_ops('abcde', 'abXYZde', [('equal',   0,2, 0,2),
897
                                     ('replace', 2,3, 2,5),
898
                                     ('equal',   3,5, 5,7)
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
899
                                    ])
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
900
        chk_ops('abde', 'abXYZde', [('equal',  0,2, 0,2),
901
                                    ('insert', 2,2, 2,5),
902
                                    ('equal',  2,4, 5,7)
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
903
                                   ])
904
        chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
905
                [('equal',  0,6,  0,6),
906
                 ('insert', 6,6,  6,11),
907
                 ('equal',  6,16, 11,21)
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
908
                ])
909
        chk_ops(
910
                [ 'hello there\n'
911
                , 'world\n'
912
                , 'how are you today?\n'],
913
                [ 'hello there\n'
914
                , 'how are you today?\n'],
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
915
                [('equal',  0,1, 0,1),
916
                 ('delete', 1,2, 1,1),
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
917
                 ('equal',  2,3, 1,2),
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
918
                ])
919
        chk_ops('aBccDe', 'abccde', 
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
920
                [('equal',   0,1, 0,1),
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
921
                 ('replace', 1,5, 1,5),
922
                 ('equal',   5,6, 5,6),
923
                ])
924
        chk_ops('aBcDec', 'abcdec', 
925
                [('equal',   0,1, 0,1),
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
926
                 ('replace', 1,2, 1,2),
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
927
                 ('equal',   2,3, 2,3),
928
                 ('replace', 3,4, 3,4),
929
                 ('equal',   4,6, 4,6),
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
930
                ])
1185.81.10 by John Arbash Meinel
Added some more test cases.
931
        chk_ops('aBcdEcdFg', 'abcdecdfg', 
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
932
                [('equal',   0,1, 0,1),
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
933
                 ('replace', 1,8, 1,8),
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
934
                 ('equal',   8,9, 8,9)
1185.81.10 by John Arbash Meinel
Added some more test cases.
935
                ])
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
936
        chk_ops('aBcdEeXcdFg', 'abcdecdfg', 
937
                [('equal',   0,1, 0,1),
938
                 ('replace', 1,2, 1,2),
939
                 ('equal',   2,4, 2,4),
940
                 ('delete', 4,5, 4,4),
941
                 ('equal',   5,6, 4,5),
942
                 ('delete', 6,7, 5,5),
943
                 ('equal',   7,9, 5,7),
944
                 ('replace', 9,10, 7,8),
945
                 ('equal',   10,11, 8,9)
946
                ])
1185.81.10 by John Arbash Meinel
Added some more test cases.
947
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
948
    def test_grouped_opcodes(self):
949
        def chk_ops(a, b, expected_codes, n=3):
950
            s = self._PatienceSequenceMatcher(None, a, b)
951
            self.assertEquals(expected_codes, list(s.get_grouped_opcodes(n)))
952
953
        chk_ops('', '', [])
954
        chk_ops([], [], [])
955
        chk_ops('abc', '', [[('delete', 0,3, 0,0)]])
956
        chk_ops('', 'abc', [[('insert', 0,0, 0,3)]])
957
        chk_ops('abcd', 'abcd', [])
958
        chk_ops('abcd', 'abce', [[('equal',   0,3, 0,3),
959
                                  ('replace', 3,4, 3,4)
960
                                 ]])
961
        chk_ops('eabc', 'abce', [[('delete', 0,1, 0,0),
962
                                 ('equal',  1,4, 0,3),
963
                                 ('insert', 4,4, 3,4)
964
                                ]])
965
        chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
966
                [[('equal',  3,6, 3,6),
967
                  ('insert', 6,6, 6,11),
968
                  ('equal',  6,9, 11,14)
969
                  ]])
970
        chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
971
                [[('equal',  2,6, 2,6),
972
                  ('insert', 6,6, 6,11),
973
                  ('equal',  6,10, 11,15)
974
                  ]], 4)
975
        chk_ops('Xabcdef', 'abcdef',
976
                [[('delete', 0,1, 0,0),
977
                  ('equal',  1,4, 0,3)
978
                  ]])
979
        chk_ops('abcdef', 'abcdefX',
980
                [[('equal',  3,6, 3,6),
981
                  ('insert', 6,6, 6,7)
982
                  ]])
983
984
1185.81.16 by John Arbash Meinel
Added tests, and an assert check to make sure ranges are always increasing.
985
    def test_multiple_ranges(self):
986
        # There was an earlier bug where we used a bad set of ranges,
987
        # this triggers that specific bug, to make sure it doesn't regress
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
988
        self.assertDiffBlocks('abcdefghijklmnop',
989
                              'abcXghiYZQRSTUVWXYZijklmnop',
990
                              [(0, 0, 3), (6, 4, 3), (9, 20, 7)])
991
992
        self.assertDiffBlocks('ABCd efghIjk  L',
993
                              'AxyzBCn mo pqrstuvwI1 2  L',
994
                              [(0,0,1), (1, 4, 2), (9, 19, 1), (12, 23, 3)])
1185.81.16 by John Arbash Meinel
Added tests, and an assert check to make sure ranges are always increasing.
995
1711.2.8 by John Arbash Meinel
rot13 the code snippet to help with clarity.
996
        # These are rot13 code snippets.
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
997
        self.assertDiffBlocks('''\
1711.2.8 by John Arbash Meinel
rot13 the code snippet to help with clarity.
998
    trg nqqrq jura lbh nqq n svyr va gur qverpgbel.
999
    """
1000
    gnxrf_netf = ['svyr*']
1001
    gnxrf_bcgvbaf = ['ab-erphefr']
1002
  
1003
    qrs eha(frys, svyr_yvfg, ab_erphefr=Snyfr):
1004
        sebz omeyvo.nqq vzcbeg fzneg_nqq, nqq_ercbegre_cevag, nqq_ercbegre_ahyy
1005
        vs vf_dhvrg():
1006
            ercbegre = nqq_ercbegre_ahyy
1007
        ryfr:
1008
            ercbegre = nqq_ercbegre_cevag
1009
        fzneg_nqq(svyr_yvfg, abg ab_erphefr, ercbegre)
1010
1011
1012
pynff pzq_zxqve(Pbzznaq):
1013
'''.splitlines(True), '''\
1014
    trg nqqrq jura lbh nqq n svyr va gur qverpgbel.
1015
1016
    --qel-eha jvyy fubj juvpu svyrf jbhyq or nqqrq, ohg abg npghnyyl 
1017
    nqq gurz.
1018
    """
1019
    gnxrf_netf = ['svyr*']
1020
    gnxrf_bcgvbaf = ['ab-erphefr', 'qel-eha']
1021
1022
    qrs eha(frys, svyr_yvfg, ab_erphefr=Snyfr, qel_eha=Snyfr):
1023
        vzcbeg omeyvo.nqq
1024
1025
        vs qel_eha:
1026
            vs vf_dhvrg():
1027
                # Guvf vf cbvagyrff, ohg V'q engure abg envfr na reebe
1028
                npgvba = omeyvo.nqq.nqq_npgvba_ahyy
1029
            ryfr:
1030
  npgvba = omeyvo.nqq.nqq_npgvba_cevag
1031
        ryvs vf_dhvrg():
1032
            npgvba = omeyvo.nqq.nqq_npgvba_nqq
1033
        ryfr:
1034
       npgvba = omeyvo.nqq.nqq_npgvba_nqq_naq_cevag
1035
1036
        omeyvo.nqq.fzneg_nqq(svyr_yvfg, abg ab_erphefr, npgvba)
1037
1038
1039
pynff pzq_zxqve(Pbzznaq):
1185.81.16 by John Arbash Meinel
Added tests, and an assert check to make sure ranges are always increasing.
1040
'''.splitlines(True)
1041
, [(0,0,1), (1, 4, 2), (9, 19, 1), (12, 23, 3)])
1042
1711.2.9 by John Arbash Meinel
Rename cdv => patience
1043
    def test_patience_unified_diff(self):
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
1044
        txt_a = ['hello there\n',
1045
                 'world\n',
1046
                 'how are you today?\n']
1047
        txt_b = ['hello there\n',
1048
                 'how are you today?\n']
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1049
        unified_diff = bzrlib.patiencediff.unified_diff
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1050
        psm = self._PatienceSequenceMatcher
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
1051
        self.assertEquals([ '---  \n',
1052
                           '+++  \n',
1053
                           '@@ -1,3 +1,2 @@\n',
1054
                           ' hello there\n',
1055
                           '-world\n',
1056
                           ' how are you today?\n'
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1057
                          ]
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1058
                          , list(unified_diff(txt_a, txt_b,
1059
                                 sequencematcher=psm)))
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1060
        txt_a = map(lambda x: x+'\n', 'abcdefghijklmnop')
1061
        txt_b = map(lambda x: x+'\n', 'abcdefxydefghijklmnop')
1062
        # This is the result with LongestCommonSubstring matching
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
1063
        self.assertEquals(['---  \n',
1064
                           '+++  \n',
1065
                           '@@ -1,6 +1,11 @@\n',
1066
                           ' a\n',
1067
                           ' b\n',
1068
                           ' c\n',
1069
                           '+d\n',
1070
                           '+e\n',
1071
                           '+f\n',
1072
                           '+x\n',
1073
                           '+y\n',
1074
                           ' d\n',
1075
                           ' e\n',
1076
                           ' f\n']
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1077
                          , list(unified_diff(txt_a, txt_b)))
1711.2.9 by John Arbash Meinel
Rename cdv => patience
1078
        # And the patience diff
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
1079
        self.assertEquals(['---  \n',
1080
                           '+++  \n',
1081
                           '@@ -4,6 +4,11 @@\n',
1082
                           ' d\n',
1083
                           ' e\n',
1084
                           ' f\n',
1085
                           '+x\n',
1086
                           '+y\n',
1087
                           '+d\n',
1088
                           '+e\n',
1089
                           '+f\n',
1090
                           ' g\n',
1091
                           ' h\n',
1092
                           ' i\n',
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1093
                          ]
1185.81.25 by Aaron Bentley
Clean up test_diff
1094
                          , list(unified_diff(txt_a, txt_b,
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1095
                                 sequencematcher=psm)))
1185.81.25 by Aaron Bentley
Clean up test_diff
1096
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1097
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1098
class TestPatienceDiffLib_c(TestPatienceDiffLib):
1099
1100
    _test_needs_features = [CompiledPatienceDiffFeature]
1101
1102
    def setUp(self):
1103
        super(TestPatienceDiffLib_c, self).setUp()
1104
        import bzrlib._patiencediff_c
1105
        self._unique_lcs = bzrlib._patiencediff_c.unique_lcs_c
1106
        self._recurse_matches = bzrlib._patiencediff_c.recurse_matches_c
1107
        self._PatienceSequenceMatcher = \
1108
            bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1109
3074.2.3 by John Arbash Meinel
Enable some error checking, and small amount of code cleanup.
1110
    def test_unhashable(self):
1111
        """We should get a proper exception here."""
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
1112
        # We need to be able to hash items in the sequence, lists are
1113
        # unhashable, and thus cannot be diffed
3074.2.3 by John Arbash Meinel
Enable some error checking, and small amount of code cleanup.
1114
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1115
                                         None, [[]], [])
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
1116
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1117
                                         None, ['valid', []], [])
1118
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1119
                                         None, ['valid'], [[]])
1120
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1121
                                         None, ['valid'], ['valid', []])
3074.2.3 by John Arbash Meinel
Enable some error checking, and small amount of code cleanup.
1122
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1123
1711.2.15 by John Arbash Meinel
Found a couple CDV left
1124
class TestPatienceDiffLibFiles(TestCaseInTempDir):
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1125
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1126
    def setUp(self):
1127
        super(TestPatienceDiffLibFiles, self).setUp()
1128
        self._PatienceSequenceMatcher = \
1129
            bzrlib._patiencediff_py.PatienceSequenceMatcher_py
1130
1711.2.9 by John Arbash Meinel
Rename cdv => patience
1131
    def test_patience_unified_diff_files(self):
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
1132
        txt_a = ['hello there\n',
1133
                 'world\n',
1134
                 'how are you today?\n']
1135
        txt_b = ['hello there\n',
1136
                 'how are you today?\n']
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1137
        open('a1', 'wb').writelines(txt_a)
1138
        open('b1', 'wb').writelines(txt_b)
1139
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1140
        unified_diff_files = bzrlib.patiencediff.unified_diff_files
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1141
        psm = self._PatienceSequenceMatcher
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
1142
        self.assertEquals(['--- a1 \n',
1143
                           '+++ b1 \n',
1144
                           '@@ -1,3 +1,2 @@\n',
1145
                           ' hello there\n',
1146
                           '-world\n',
1147
                           ' how are you today?\n',
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1148
                          ]
1185.81.25 by Aaron Bentley
Clean up test_diff
1149
                          , list(unified_diff_files('a1', 'b1',
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1150
                                 sequencematcher=psm)))
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1151
1152
        txt_a = map(lambda x: x+'\n', 'abcdefghijklmnop')
1153
        txt_b = map(lambda x: x+'\n', 'abcdefxydefghijklmnop')
1154
        open('a2', 'wb').writelines(txt_a)
1155
        open('b2', 'wb').writelines(txt_b)
1156
1157
        # This is the result with LongestCommonSubstring matching
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
1158
        self.assertEquals(['--- a2 \n',
1159
                           '+++ b2 \n',
1160
                           '@@ -1,6 +1,11 @@\n',
1161
                           ' a\n',
1162
                           ' b\n',
1163
                           ' c\n',
1164
                           '+d\n',
1165
                           '+e\n',
1166
                           '+f\n',
1167
                           '+x\n',
1168
                           '+y\n',
1169
                           ' d\n',
1170
                           ' e\n',
1171
                           ' f\n']
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1172
                          , list(unified_diff_files('a2', 'b2')))
1173
1711.2.9 by John Arbash Meinel
Rename cdv => patience
1174
        # And the patience diff
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
1175
        self.assertEquals(['--- a2 \n',
1176
                           '+++ b2 \n',
1177
                           '@@ -4,6 +4,11 @@\n',
1178
                           ' d\n',
1179
                           ' e\n',
1180
                           ' f\n',
1181
                           '+x\n',
1182
                           '+y\n',
1183
                           '+d\n',
1184
                           '+e\n',
1185
                           '+f\n',
1186
                           ' g\n',
1187
                           ' h\n',
1188
                           ' i\n',
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1189
                          ]
1185.81.25 by Aaron Bentley
Clean up test_diff
1190
                          , list(unified_diff_files('a2', 'b2',
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1191
                                 sequencematcher=psm)))
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1192
1193
1194
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
1195
1196
    _test_needs_features = [CompiledPatienceDiffFeature]
1197
1198
    def setUp(self):
1199
        super(TestPatienceDiffLibFiles_c, self).setUp()
1200
        import bzrlib._patiencediff_c
1201
        self._PatienceSequenceMatcher = \
1202
            bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1203
1204
1205
class TestUsingCompiledIfAvailable(TestCase):
1206
1207
    def test_PatienceSequenceMatcher(self):
1208
        if CompiledPatienceDiffFeature.available():
1209
            from bzrlib._patiencediff_c import PatienceSequenceMatcher_c
1210
            self.assertIs(PatienceSequenceMatcher_c,
1211
                          bzrlib.patiencediff.PatienceSequenceMatcher)
1212
        else:
1213
            from bzrlib._patiencediff_py import PatienceSequenceMatcher_py
1214
            self.assertIs(PatienceSequenceMatcher_py,
1215
                          bzrlib.patiencediff.PatienceSequenceMatcher)
1216
1217
    def test_unique_lcs(self):
1218
        if CompiledPatienceDiffFeature.available():
1219
            from bzrlib._patiencediff_c import unique_lcs_c
1220
            self.assertIs(unique_lcs_c,
1221
                          bzrlib.patiencediff.unique_lcs)
1222
        else:
1223
            from bzrlib._patiencediff_py import unique_lcs_py
1224
            self.assertIs(unique_lcs_py,
1225
                          bzrlib.patiencediff.unique_lcs)
1226
1227
    def test_recurse_matches(self):
1228
        if CompiledPatienceDiffFeature.available():
1229
            from bzrlib._patiencediff_c import recurse_matches_c
1230
            self.assertIs(recurse_matches_c,
1231
                          bzrlib.patiencediff.recurse_matches)
1232
        else:
1233
            from bzrlib._patiencediff_py import recurse_matches_py
1234
            self.assertIs(recurse_matches_py,
1235
                          bzrlib.patiencediff.recurse_matches)