/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_diff.py

(lifeless) When writing temporary files for external diff do not set the file utime if we don't know when the in-tree file was last modified. (Martin [gz])

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2010 Canonical Ltd
 
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.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
import os
 
18
import os.path
 
19
from cStringIO import StringIO
 
20
import subprocess
 
21
import sys
 
22
from tempfile import TemporaryFile
 
23
 
 
24
from bzrlib import tests
 
25
from bzrlib.diff import (
 
26
    DiffFromTool,
 
27
    DiffPath,
 
28
    DiffSymlink,
 
29
    DiffTree,
 
30
    DiffText,
 
31
    external_diff,
 
32
    internal_diff,
 
33
    show_diff_trees,
 
34
    get_trees_and_branches_to_diff,
 
35
    get_trees_and_branches_to_diff_locked,
 
36
    )
 
37
from bzrlib.errors import BinaryFile, NoDiff, ExecutableMissing
 
38
import bzrlib.osutils as osutils
 
39
import bzrlib.revision as _mod_revision
 
40
import bzrlib.transform as transform
 
41
import bzrlib.patiencediff
 
42
import bzrlib._patiencediff_py
 
43
from bzrlib.tests import (Feature, TestCase, TestCaseWithTransport,
 
44
                          TestCaseInTempDir, TestSkipped)
 
45
from bzrlib.revisiontree import RevisionTree
 
46
from bzrlib.revisionspec import RevisionSpec
 
47
from bzrlib.symbol_versioning import deprecated_in
 
48
 
 
49
from bzrlib.tests.test_win32utils import BackslashDirSeparatorFeature
 
50
 
 
51
 
 
52
class _AttribFeature(Feature):
 
53
 
 
54
    def _probe(self):
 
55
        if (sys.platform not in ('cygwin', 'win32')):
 
56
            return False
 
57
        try:
 
58
            proc = subprocess.Popen(['attrib', '.'], stdout=subprocess.PIPE)
 
59
        except OSError, e:
 
60
            return False
 
61
        return (0 == proc.wait())
 
62
 
 
63
    def feature_name(self):
 
64
        return 'attrib Windows command-line tool'
 
65
 
 
66
AttribFeature = _AttribFeature()
 
67
 
 
68
 
 
69
compiled_patiencediff_feature = tests.ModuleAvailableFeature(
 
70
                                    'bzrlib._patiencediff_c')
 
71
 
 
72
 
 
73
def udiff_lines(old, new, allow_binary=False):
 
74
    output = StringIO()
 
75
    internal_diff('old', old, 'new', new, output, allow_binary)
 
76
    output.seek(0, 0)
 
77
    return output.readlines()
 
78
 
 
79
 
 
80
def external_udiff_lines(old, new, use_stringio=False):
 
81
    if use_stringio:
 
82
        # StringIO has no fileno, so it tests a different codepath
 
83
        output = StringIO()
 
84
    else:
 
85
        output = TemporaryFile()
 
86
    try:
 
87
        external_diff('old', old, 'new', new, output, diff_opts=['-u'])
 
88
    except NoDiff:
 
89
        raise TestSkipped('external "diff" not present to test')
 
90
    output.seek(0, 0)
 
91
    lines = output.readlines()
 
92
    output.close()
 
93
    return lines
 
94
 
 
95
 
 
96
class TestDiff(TestCase):
 
97
 
 
98
    def test_add_nl(self):
 
99
        """diff generates a valid diff for patches that add a newline"""
 
100
        lines = udiff_lines(['boo'], ['boo\n'])
 
101
        self.check_patch(lines)
 
102
        self.assertEquals(lines[4], '\\ No newline at end of file\n')
 
103
            ## "expected no-nl, got %r" % lines[4]
 
104
 
 
105
    def test_add_nl_2(self):
 
106
        """diff generates a valid diff for patches that change last line and
 
107
        add a newline.
 
108
        """
 
109
        lines = udiff_lines(['boo'], ['goo\n'])
 
110
        self.check_patch(lines)
 
111
        self.assertEquals(lines[4], '\\ No newline at end of file\n')
 
112
            ## "expected no-nl, got %r" % lines[4]
 
113
 
 
114
    def test_remove_nl(self):
 
115
        """diff generates a valid diff for patches that change last line and
 
116
        add a newline.
 
117
        """
 
118
        lines = udiff_lines(['boo\n'], ['boo'])
 
119
        self.check_patch(lines)
 
120
        self.assertEquals(lines[5], '\\ No newline at end of file\n')
 
121
            ## "expected no-nl, got %r" % lines[5]
 
122
 
 
123
    def check_patch(self, lines):
 
124
        self.assert_(len(lines) > 1)
 
125
            ## "Not enough lines for a file header for patch:\n%s" % "".join(lines)
 
126
        self.assert_(lines[0].startswith ('---'))
 
127
            ## 'No orig line for patch:\n%s' % "".join(lines)
 
128
        self.assert_(lines[1].startswith ('+++'))
 
129
            ## 'No mod line for patch:\n%s' % "".join(lines)
 
130
        self.assert_(len(lines) > 2)
 
131
            ## "No hunks for patch:\n%s" % "".join(lines)
 
132
        self.assert_(lines[2].startswith('@@'))
 
133
            ## "No hunk header for patch:\n%s" % "".join(lines)
 
134
        self.assert_('@@' in lines[2][2:])
 
135
            ## "Unterminated hunk header for patch:\n%s" % "".join(lines)
 
136
 
 
137
    def test_binary_lines(self):
 
138
        self.assertRaises(BinaryFile, udiff_lines, [1023 * 'a' + '\x00'], [])
 
139
        self.assertRaises(BinaryFile, udiff_lines, [], [1023 * 'a' + '\x00'])
 
140
        udiff_lines([1023 * 'a' + '\x00'], [], allow_binary=True)
 
141
        udiff_lines([], [1023 * 'a' + '\x00'], allow_binary=True)
 
142
 
 
143
    def test_external_diff(self):
 
144
        lines = external_udiff_lines(['boo\n'], ['goo\n'])
 
145
        self.check_patch(lines)
 
146
        self.assertEqual('\n', lines[-1])
 
147
 
 
148
    def test_external_diff_no_fileno(self):
 
149
        # Make sure that we can handle not having a fileno, even
 
150
        # if the diff is large
 
151
        lines = external_udiff_lines(['boo\n']*10000,
 
152
                                     ['goo\n']*10000,
 
153
                                     use_stringio=True)
 
154
        self.check_patch(lines)
 
155
 
 
156
    def test_external_diff_binary_lang_c(self):
 
157
        old_env = {}
 
158
        for lang in ('LANG', 'LC_ALL', 'LANGUAGE'):
 
159
            old_env[lang] = osutils.set_or_unset_env(lang, 'C')
 
160
        try:
 
161
            lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
 
162
            # Older versions of diffutils say "Binary files", newer
 
163
            # versions just say "Files".
 
164
            self.assertContainsRe(lines[0],
 
165
                                  '(Binary f|F)iles old and new differ\n')
 
166
            self.assertEquals(lines[1:], ['\n'])
 
167
        finally:
 
168
            for lang, old_val in old_env.iteritems():
 
169
                osutils.set_or_unset_env(lang, old_val)
 
170
 
 
171
    def test_no_external_diff(self):
 
172
        """Check that NoDiff is raised when diff is not available"""
 
173
        # Use os.environ['PATH'] to make sure no 'diff' command is available
 
174
        orig_path = os.environ['PATH']
 
175
        try:
 
176
            os.environ['PATH'] = ''
 
177
            self.assertRaises(NoDiff, external_diff,
 
178
                              'old', ['boo\n'], 'new', ['goo\n'],
 
179
                              StringIO(), diff_opts=['-u'])
 
180
        finally:
 
181
            os.environ['PATH'] = orig_path
 
182
 
 
183
    def test_internal_diff_default(self):
 
184
        # Default internal diff encoding is utf8
 
185
        output = StringIO()
 
186
        internal_diff(u'old_\xb5', ['old_text\n'],
 
187
                    u'new_\xe5', ['new_text\n'], output)
 
188
        lines = output.getvalue().splitlines(True)
 
189
        self.check_patch(lines)
 
190
        self.assertEquals(['--- old_\xc2\xb5\n',
 
191
                           '+++ new_\xc3\xa5\n',
 
192
                           '@@ -1,1 +1,1 @@\n',
 
193
                           '-old_text\n',
 
194
                           '+new_text\n',
 
195
                           '\n',
 
196
                          ]
 
197
                          , lines)
 
198
 
 
199
    def test_internal_diff_utf8(self):
 
200
        output = StringIO()
 
201
        internal_diff(u'old_\xb5', ['old_text\n'],
 
202
                    u'new_\xe5', ['new_text\n'], output,
 
203
                    path_encoding='utf8')
 
204
        lines = output.getvalue().splitlines(True)
 
205
        self.check_patch(lines)
 
206
        self.assertEquals(['--- old_\xc2\xb5\n',
 
207
                           '+++ new_\xc3\xa5\n',
 
208
                           '@@ -1,1 +1,1 @@\n',
 
209
                           '-old_text\n',
 
210
                           '+new_text\n',
 
211
                           '\n',
 
212
                          ]
 
213
                          , lines)
 
214
 
 
215
    def test_internal_diff_iso_8859_1(self):
 
216
        output = StringIO()
 
217
        internal_diff(u'old_\xb5', ['old_text\n'],
 
218
                    u'new_\xe5', ['new_text\n'], output,
 
219
                    path_encoding='iso-8859-1')
 
220
        lines = output.getvalue().splitlines(True)
 
221
        self.check_patch(lines)
 
222
        self.assertEquals(['--- old_\xb5\n',
 
223
                           '+++ new_\xe5\n',
 
224
                           '@@ -1,1 +1,1 @@\n',
 
225
                           '-old_text\n',
 
226
                           '+new_text\n',
 
227
                           '\n',
 
228
                          ]
 
229
                          , lines)
 
230
 
 
231
    def test_internal_diff_no_content(self):
 
232
        output = StringIO()
 
233
        internal_diff(u'old', [], u'new', [], output)
 
234
        self.assertEqual('', output.getvalue())
 
235
 
 
236
    def test_internal_diff_no_changes(self):
 
237
        output = StringIO()
 
238
        internal_diff(u'old', ['text\n', 'contents\n'],
 
239
                      u'new', ['text\n', 'contents\n'],
 
240
                      output)
 
241
        self.assertEqual('', output.getvalue())
 
242
 
 
243
    def test_internal_diff_returns_bytes(self):
 
244
        import StringIO
 
245
        output = StringIO.StringIO()
 
246
        internal_diff(u'old_\xb5', ['old_text\n'],
 
247
                    u'new_\xe5', ['new_text\n'], output)
 
248
        self.failUnless(isinstance(output.getvalue(), str),
 
249
            'internal_diff should return bytestrings')
 
250
 
 
251
 
 
252
class TestDiffFiles(TestCaseInTempDir):
 
253
 
 
254
    def test_external_diff_binary(self):
 
255
        """The output when using external diff should use diff's i18n error"""
 
256
        # Make sure external_diff doesn't fail in the current LANG
 
257
        lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
 
258
 
 
259
        cmd = ['diff', '-u', '--binary', 'old', 'new']
 
260
        open('old', 'wb').write('\x00foobar\n')
 
261
        open('new', 'wb').write('foo\x00bar\n')
 
262
        pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
 
263
                                     stdin=subprocess.PIPE)
 
264
        out, err = pipe.communicate()
 
265
        # Diff returns '2' on Binary files.
 
266
        self.assertEqual(2, pipe.returncode)
 
267
        # We should output whatever diff tells us, plus a trailing newline
 
268
        self.assertEqual(out.splitlines(True) + ['\n'], lines)
 
269
 
 
270
 
 
271
class TestShowDiffTreesHelper(TestCaseWithTransport):
 
272
    """Has a helper for running show_diff_trees"""
 
273
 
 
274
    def get_diff(self, tree1, tree2, specific_files=None, working_tree=None):
 
275
        output = StringIO()
 
276
        if working_tree is not None:
 
277
            extra_trees = (working_tree,)
 
278
        else:
 
279
            extra_trees = ()
 
280
        show_diff_trees(tree1, tree2, output, specific_files=specific_files,
 
281
                        extra_trees=extra_trees, old_label='old/',
 
282
                        new_label='new/')
 
283
        return output.getvalue()
 
284
 
 
285
 
 
286
class TestDiffDates(TestShowDiffTreesHelper):
 
287
 
 
288
    def setUp(self):
 
289
        super(TestDiffDates, self).setUp()
 
290
        self.wt = self.make_branch_and_tree('.')
 
291
        self.b = self.wt.branch
 
292
        self.build_tree_contents([
 
293
            ('file1', 'file1 contents at rev 1\n'),
 
294
            ('file2', 'file2 contents at rev 1\n')
 
295
            ])
 
296
        self.wt.add(['file1', 'file2'])
 
297
        self.wt.commit(
 
298
            message='Revision 1',
 
299
            timestamp=1143849600, # 2006-04-01 00:00:00 UTC
 
300
            timezone=0,
 
301
            rev_id='rev-1')
 
302
        self.build_tree_contents([('file1', 'file1 contents at rev 2\n')])
 
303
        self.wt.commit(
 
304
            message='Revision 2',
 
305
            timestamp=1143936000, # 2006-04-02 00:00:00 UTC
 
306
            timezone=28800,
 
307
            rev_id='rev-2')
 
308
        self.build_tree_contents([('file2', 'file2 contents at rev 3\n')])
 
309
        self.wt.commit(
 
310
            message='Revision 3',
 
311
            timestamp=1144022400, # 2006-04-03 00:00:00 UTC
 
312
            timezone=-3600,
 
313
            rev_id='rev-3')
 
314
        self.wt.remove(['file2'])
 
315
        self.wt.commit(
 
316
            message='Revision 4',
 
317
            timestamp=1144108800, # 2006-04-04 00:00:00 UTC
 
318
            timezone=0,
 
319
            rev_id='rev-4')
 
320
        self.build_tree_contents([
 
321
            ('file1', 'file1 contents in working tree\n')
 
322
            ])
 
323
        # set the date stamps for files in the working tree to known values
 
324
        os.utime('file1', (1144195200, 1144195200)) # 2006-04-05 00:00:00 UTC
 
325
 
 
326
    def test_diff_rev_tree_working_tree(self):
 
327
        output = self.get_diff(self.wt.basis_tree(), self.wt)
 
328
        # note that the date for old/file1 is from rev 2 rather than from
 
329
        # the basis revision (rev 4)
 
330
        self.assertEqualDiff(output, '''\
 
331
=== modified file 'file1'
 
332
--- old/file1\t2006-04-02 00:00:00 +0000
 
333
+++ new/file1\t2006-04-05 00:00:00 +0000
 
334
@@ -1,1 +1,1 @@
 
335
-file1 contents at rev 2
 
336
+file1 contents in working tree
 
337
 
 
338
''')
 
339
 
 
340
    def test_diff_rev_tree_rev_tree(self):
 
341
        tree1 = self.b.repository.revision_tree('rev-2')
 
342
        tree2 = self.b.repository.revision_tree('rev-3')
 
343
        output = self.get_diff(tree1, tree2)
 
344
        self.assertEqualDiff(output, '''\
 
345
=== modified file 'file2'
 
346
--- old/file2\t2006-04-01 00:00:00 +0000
 
347
+++ new/file2\t2006-04-03 00:00:00 +0000
 
348
@@ -1,1 +1,1 @@
 
349
-file2 contents at rev 1
 
350
+file2 contents at rev 3
 
351
 
 
352
''')
 
353
 
 
354
    def test_diff_add_files(self):
 
355
        tree1 = self.b.repository.revision_tree(_mod_revision.NULL_REVISION)
 
356
        tree2 = self.b.repository.revision_tree('rev-1')
 
357
        output = self.get_diff(tree1, tree2)
 
358
        # the files have the epoch time stamp for the tree in which
 
359
        # they don't exist.
 
360
        self.assertEqualDiff(output, '''\
 
361
=== added file 'file1'
 
362
--- old/file1\t1970-01-01 00:00:00 +0000
 
363
+++ new/file1\t2006-04-01 00:00:00 +0000
 
364
@@ -0,0 +1,1 @@
 
365
+file1 contents at rev 1
 
366
 
 
367
=== added file 'file2'
 
368
--- old/file2\t1970-01-01 00:00:00 +0000
 
369
+++ new/file2\t2006-04-01 00:00:00 +0000
 
370
@@ -0,0 +1,1 @@
 
371
+file2 contents at rev 1
 
372
 
 
373
''')
 
374
 
 
375
    def test_diff_remove_files(self):
 
376
        tree1 = self.b.repository.revision_tree('rev-3')
 
377
        tree2 = self.b.repository.revision_tree('rev-4')
 
378
        output = self.get_diff(tree1, tree2)
 
379
        # the file has the epoch time stamp for the tree in which
 
380
        # it doesn't exist.
 
381
        self.assertEqualDiff(output, '''\
 
382
=== removed file 'file2'
 
383
--- old/file2\t2006-04-03 00:00:00 +0000
 
384
+++ new/file2\t1970-01-01 00:00:00 +0000
 
385
@@ -1,1 +0,0 @@
 
386
-file2 contents at rev 3
 
387
 
 
388
''')
 
389
 
 
390
    def test_show_diff_specified(self):
 
391
        """A working tree filename can be used to identify a file"""
 
392
        self.wt.rename_one('file1', 'file1b')
 
393
        old_tree = self.b.repository.revision_tree('rev-1')
 
394
        new_tree = self.b.repository.revision_tree('rev-4')
 
395
        out = self.get_diff(old_tree, new_tree, specific_files=['file1b'],
 
396
                            working_tree=self.wt)
 
397
        self.assertContainsRe(out, 'file1\t')
 
398
 
 
399
    def test_recursive_diff(self):
 
400
        """Children of directories are matched"""
 
401
        os.mkdir('dir1')
 
402
        os.mkdir('dir2')
 
403
        self.wt.add(['dir1', 'dir2'])
 
404
        self.wt.rename_one('file1', 'dir1/file1')
 
405
        old_tree = self.b.repository.revision_tree('rev-1')
 
406
        new_tree = self.b.repository.revision_tree('rev-4')
 
407
        out = self.get_diff(old_tree, new_tree, specific_files=['dir1'],
 
408
                            working_tree=self.wt)
 
409
        self.assertContainsRe(out, 'file1\t')
 
410
        out = self.get_diff(old_tree, new_tree, specific_files=['dir2'],
 
411
                            working_tree=self.wt)
 
412
        self.assertNotContainsRe(out, 'file1\t')
 
413
 
 
414
 
 
415
 
 
416
class TestShowDiffTrees(TestShowDiffTreesHelper):
 
417
    """Direct tests for show_diff_trees"""
 
418
 
 
419
    def test_modified_file(self):
 
420
        """Test when a file is modified."""
 
421
        tree = self.make_branch_and_tree('tree')
 
422
        self.build_tree_contents([('tree/file', 'contents\n')])
 
423
        tree.add(['file'], ['file-id'])
 
424
        tree.commit('one', rev_id='rev-1')
 
425
 
 
426
        self.build_tree_contents([('tree/file', 'new contents\n')])
 
427
        diff = self.get_diff(tree.basis_tree(), tree)
 
428
        self.assertContainsRe(diff, "=== modified file 'file'\n")
 
429
        self.assertContainsRe(diff, '--- old/file\t')
 
430
        self.assertContainsRe(diff, '\\+\\+\\+ new/file\t')
 
431
        self.assertContainsRe(diff, '-contents\n'
 
432
                                    '\\+new contents\n')
 
433
 
 
434
    def test_modified_file_in_renamed_dir(self):
 
435
        """Test when a file is modified in a renamed directory."""
 
436
        tree = self.make_branch_and_tree('tree')
 
437
        self.build_tree(['tree/dir/'])
 
438
        self.build_tree_contents([('tree/dir/file', 'contents\n')])
 
439
        tree.add(['dir', 'dir/file'], ['dir-id', 'file-id'])
 
440
        tree.commit('one', rev_id='rev-1')
 
441
 
 
442
        tree.rename_one('dir', 'other')
 
443
        self.build_tree_contents([('tree/other/file', 'new contents\n')])
 
444
        diff = self.get_diff(tree.basis_tree(), tree)
 
445
        self.assertContainsRe(diff, "=== renamed directory 'dir' => 'other'\n")
 
446
        self.assertContainsRe(diff, "=== modified file 'other/file'\n")
 
447
        # XXX: This is technically incorrect, because it used to be at another
 
448
        # location. What to do?
 
449
        self.assertContainsRe(diff, '--- old/dir/file\t')
 
450
        self.assertContainsRe(diff, '\\+\\+\\+ new/other/file\t')
 
451
        self.assertContainsRe(diff, '-contents\n'
 
452
                                    '\\+new contents\n')
 
453
 
 
454
    def test_renamed_directory(self):
 
455
        """Test when only a directory is only renamed."""
 
456
        tree = self.make_branch_and_tree('tree')
 
457
        self.build_tree(['tree/dir/'])
 
458
        self.build_tree_contents([('tree/dir/file', 'contents\n')])
 
459
        tree.add(['dir', 'dir/file'], ['dir-id', 'file-id'])
 
460
        tree.commit('one', rev_id='rev-1')
 
461
 
 
462
        tree.rename_one('dir', 'newdir')
 
463
        diff = self.get_diff(tree.basis_tree(), tree)
 
464
        # Renaming a directory should be a single "you renamed this dir" even
 
465
        # when there are files inside.
 
466
        self.assertEqual("=== renamed directory 'dir' => 'newdir'\n", diff)
 
467
 
 
468
    def test_renamed_file(self):
 
469
        """Test when a file is only renamed."""
 
470
        tree = self.make_branch_and_tree('tree')
 
471
        self.build_tree_contents([('tree/file', 'contents\n')])
 
472
        tree.add(['file'], ['file-id'])
 
473
        tree.commit('one', rev_id='rev-1')
 
474
 
 
475
        tree.rename_one('file', 'newname')
 
476
        diff = self.get_diff(tree.basis_tree(), tree)
 
477
        self.assertContainsRe(diff, "=== renamed file 'file' => 'newname'\n")
 
478
        # We shouldn't have a --- or +++ line, because there is no content
 
479
        # change
 
480
        self.assertNotContainsRe(diff, '---')
 
481
 
 
482
    def test_renamed_and_modified_file(self):
 
483
        """Test when a file is only renamed."""
 
484
        tree = self.make_branch_and_tree('tree')
 
485
        self.build_tree_contents([('tree/file', 'contents\n')])
 
486
        tree.add(['file'], ['file-id'])
 
487
        tree.commit('one', rev_id='rev-1')
 
488
 
 
489
        tree.rename_one('file', 'newname')
 
490
        self.build_tree_contents([('tree/newname', 'new contents\n')])
 
491
        diff = self.get_diff(tree.basis_tree(), tree)
 
492
        self.assertContainsRe(diff, "=== renamed file 'file' => 'newname'\n")
 
493
        self.assertContainsRe(diff, '--- old/file\t')
 
494
        self.assertContainsRe(diff, '\\+\\+\\+ new/newname\t')
 
495
        self.assertContainsRe(diff, '-contents\n'
 
496
                                    '\\+new contents\n')
 
497
 
 
498
 
 
499
    def test_internal_diff_exec_property(self):
 
500
        tree = self.make_branch_and_tree('tree')
 
501
 
 
502
        tt = transform.TreeTransform(tree)
 
503
        tt.new_file('a', tt.root, 'contents\n', 'a-id', True)
 
504
        tt.new_file('b', tt.root, 'contents\n', 'b-id', False)
 
505
        tt.new_file('c', tt.root, 'contents\n', 'c-id', True)
 
506
        tt.new_file('d', tt.root, 'contents\n', 'd-id', False)
 
507
        tt.new_file('e', tt.root, 'contents\n', 'control-e-id', True)
 
508
        tt.new_file('f', tt.root, 'contents\n', 'control-f-id', False)
 
509
        tt.apply()
 
510
        tree.commit('one', rev_id='rev-1')
 
511
 
 
512
        tt = transform.TreeTransform(tree)
 
513
        tt.set_executability(False, tt.trans_id_file_id('a-id'))
 
514
        tt.set_executability(True, tt.trans_id_file_id('b-id'))
 
515
        tt.set_executability(False, tt.trans_id_file_id('c-id'))
 
516
        tt.set_executability(True, tt.trans_id_file_id('d-id'))
 
517
        tt.apply()
 
518
        tree.rename_one('c', 'new-c')
 
519
        tree.rename_one('d', 'new-d')
 
520
 
 
521
        diff = self.get_diff(tree.basis_tree(), tree)
 
522
 
 
523
        self.assertContainsRe(diff, r"file 'a'.*\(properties changed:.*\+x to -x.*\)")
 
524
        self.assertContainsRe(diff, r"file 'b'.*\(properties changed:.*-x to \+x.*\)")
 
525
        self.assertContainsRe(diff, r"file 'c'.*\(properties changed:.*\+x to -x.*\)")
 
526
        self.assertContainsRe(diff, r"file 'd'.*\(properties changed:.*-x to \+x.*\)")
 
527
        self.assertNotContainsRe(diff, r"file 'e'")
 
528
        self.assertNotContainsRe(diff, r"file 'f'")
 
529
 
 
530
 
 
531
    def test_binary_unicode_filenames(self):
 
532
        """Test that contents of files are *not* encoded in UTF-8 when there
 
533
        is a binary file in the diff.
 
534
        """
 
535
        # See https://bugs.launchpad.net/bugs/110092.
 
536
        self.requireFeature(tests.UnicodeFilenameFeature)
 
537
 
 
538
        # This bug isn't triggered with cStringIO.
 
539
        from StringIO import StringIO
 
540
        tree = self.make_branch_and_tree('tree')
 
541
        alpha, omega = u'\u03b1', u'\u03c9'
 
542
        alpha_utf8, omega_utf8 = alpha.encode('utf8'), omega.encode('utf8')
 
543
        self.build_tree_contents(
 
544
            [('tree/' + alpha, chr(0)),
 
545
             ('tree/' + omega,
 
546
              ('The %s and the %s\n' % (alpha_utf8, omega_utf8)))])
 
547
        tree.add([alpha], ['file-id'])
 
548
        tree.add([omega], ['file-id-2'])
 
549
        diff_content = StringIO()
 
550
        show_diff_trees(tree.basis_tree(), tree, diff_content)
 
551
        diff = diff_content.getvalue()
 
552
        self.assertContainsRe(diff, r"=== added file '%s'" % alpha_utf8)
 
553
        self.assertContainsRe(
 
554
            diff, "Binary files a/%s.*and b/%s.* differ\n" % (alpha_utf8, alpha_utf8))
 
555
        self.assertContainsRe(diff, r"=== added file '%s'" % omega_utf8)
 
556
        self.assertContainsRe(diff, r"--- a/%s" % (omega_utf8,))
 
557
        self.assertContainsRe(diff, r"\+\+\+ b/%s" % (omega_utf8,))
 
558
 
 
559
    def test_unicode_filename(self):
 
560
        """Test when the filename are unicode."""
 
561
        self.requireFeature(tests.UnicodeFilenameFeature)
 
562
 
 
563
        alpha, omega = u'\u03b1', u'\u03c9'
 
564
        autf8, outf8 = alpha.encode('utf8'), omega.encode('utf8')
 
565
 
 
566
        tree = self.make_branch_and_tree('tree')
 
567
        self.build_tree_contents([('tree/ren_'+alpha, 'contents\n')])
 
568
        tree.add(['ren_'+alpha], ['file-id-2'])
 
569
        self.build_tree_contents([('tree/del_'+alpha, 'contents\n')])
 
570
        tree.add(['del_'+alpha], ['file-id-3'])
 
571
        self.build_tree_contents([('tree/mod_'+alpha, 'contents\n')])
 
572
        tree.add(['mod_'+alpha], ['file-id-4'])
 
573
 
 
574
        tree.commit('one', rev_id='rev-1')
 
575
 
 
576
        tree.rename_one('ren_'+alpha, 'ren_'+omega)
 
577
        tree.remove('del_'+alpha)
 
578
        self.build_tree_contents([('tree/add_'+alpha, 'contents\n')])
 
579
        tree.add(['add_'+alpha], ['file-id'])
 
580
        self.build_tree_contents([('tree/mod_'+alpha, 'contents_mod\n')])
 
581
 
 
582
        diff = self.get_diff(tree.basis_tree(), tree)
 
583
        self.assertContainsRe(diff,
 
584
                "=== renamed file 'ren_%s' => 'ren_%s'\n"%(autf8, outf8))
 
585
        self.assertContainsRe(diff, "=== added file 'add_%s'"%autf8)
 
586
        self.assertContainsRe(diff, "=== modified file 'mod_%s'"%autf8)
 
587
        self.assertContainsRe(diff, "=== removed file 'del_%s'"%autf8)
 
588
 
 
589
 
 
590
class DiffWasIs(DiffPath):
 
591
 
 
592
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
 
593
        self.to_file.write('was: ')
 
594
        self.to_file.write(self.old_tree.get_file(file_id).read())
 
595
        self.to_file.write('is: ')
 
596
        self.to_file.write(self.new_tree.get_file(file_id).read())
 
597
        pass
 
598
 
 
599
 
 
600
class TestDiffTree(TestCaseWithTransport):
 
601
 
 
602
    def setUp(self):
 
603
        TestCaseWithTransport.setUp(self)
 
604
        self.old_tree = self.make_branch_and_tree('old-tree')
 
605
        self.old_tree.lock_write()
 
606
        self.addCleanup(self.old_tree.unlock)
 
607
        self.new_tree = self.make_branch_and_tree('new-tree')
 
608
        self.new_tree.lock_write()
 
609
        self.addCleanup(self.new_tree.unlock)
 
610
        self.differ = DiffTree(self.old_tree, self.new_tree, StringIO())
 
611
 
 
612
    def test_diff_text(self):
 
613
        self.build_tree_contents([('old-tree/olddir/',),
 
614
                                  ('old-tree/olddir/oldfile', 'old\n')])
 
615
        self.old_tree.add('olddir')
 
616
        self.old_tree.add('olddir/oldfile', 'file-id')
 
617
        self.build_tree_contents([('new-tree/newdir/',),
 
618
                                  ('new-tree/newdir/newfile', 'new\n')])
 
619
        self.new_tree.add('newdir')
 
620
        self.new_tree.add('newdir/newfile', 'file-id')
 
621
        differ = DiffText(self.old_tree, self.new_tree, StringIO())
 
622
        differ.diff_text('file-id', None, 'old label', 'new label')
 
623
        self.assertEqual(
 
624
            '--- old label\n+++ new label\n@@ -1,1 +0,0 @@\n-old\n\n',
 
625
            differ.to_file.getvalue())
 
626
        differ.to_file.seek(0)
 
627
        differ.diff_text(None, 'file-id', 'old label', 'new label')
 
628
        self.assertEqual(
 
629
            '--- old label\n+++ new label\n@@ -0,0 +1,1 @@\n+new\n\n',
 
630
            differ.to_file.getvalue())
 
631
        differ.to_file.seek(0)
 
632
        differ.diff_text('file-id', 'file-id', 'old label', 'new label')
 
633
        self.assertEqual(
 
634
            '--- old label\n+++ new label\n@@ -1,1 +1,1 @@\n-old\n+new\n\n',
 
635
            differ.to_file.getvalue())
 
636
 
 
637
    def test_diff_deletion(self):
 
638
        self.build_tree_contents([('old-tree/file', 'contents'),
 
639
                                  ('new-tree/file', 'contents')])
 
640
        self.old_tree.add('file', 'file-id')
 
641
        self.new_tree.add('file', 'file-id')
 
642
        os.unlink('new-tree/file')
 
643
        self.differ.show_diff(None)
 
644
        self.assertContainsRe(self.differ.to_file.getvalue(), '-contents')
 
645
 
 
646
    def test_diff_creation(self):
 
647
        self.build_tree_contents([('old-tree/file', 'contents'),
 
648
                                  ('new-tree/file', 'contents')])
 
649
        self.old_tree.add('file', 'file-id')
 
650
        self.new_tree.add('file', 'file-id')
 
651
        os.unlink('old-tree/file')
 
652
        self.differ.show_diff(None)
 
653
        self.assertContainsRe(self.differ.to_file.getvalue(), '\+contents')
 
654
 
 
655
    def test_diff_symlink(self):
 
656
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
 
657
        differ.diff_symlink('old target', None)
 
658
        self.assertEqual("=== target was 'old target'\n",
 
659
                         differ.to_file.getvalue())
 
660
 
 
661
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
 
662
        differ.diff_symlink(None, 'new target')
 
663
        self.assertEqual("=== target is 'new target'\n",
 
664
                         differ.to_file.getvalue())
 
665
 
 
666
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
 
667
        differ.diff_symlink('old target', 'new target')
 
668
        self.assertEqual("=== target changed 'old target' => 'new target'\n",
 
669
                         differ.to_file.getvalue())
 
670
 
 
671
    def test_diff(self):
 
672
        self.build_tree_contents([('old-tree/olddir/',),
 
673
                                  ('old-tree/olddir/oldfile', 'old\n')])
 
674
        self.old_tree.add('olddir')
 
675
        self.old_tree.add('olddir/oldfile', 'file-id')
 
676
        self.build_tree_contents([('new-tree/newdir/',),
 
677
                                  ('new-tree/newdir/newfile', 'new\n')])
 
678
        self.new_tree.add('newdir')
 
679
        self.new_tree.add('newdir/newfile', 'file-id')
 
680
        self.differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
 
681
        self.assertContainsRe(
 
682
            self.differ.to_file.getvalue(),
 
683
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
 
684
             ' \@\@\n-old\n\+new\n\n')
 
685
 
 
686
    def test_diff_kind_change(self):
 
687
        self.requireFeature(tests.SymlinkFeature)
 
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(['new-tree/newdir/'])
 
693
        os.symlink('new', 'new-tree/newdir/newfile')
 
694
        self.new_tree.add('newdir')
 
695
        self.new_tree.add('newdir/newfile', 'file-id')
 
696
        self.differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
 
697
        self.assertContainsRe(
 
698
            self.differ.to_file.getvalue(),
 
699
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+0,0'
 
700
             ' \@\@\n-old\n\n')
 
701
        self.assertContainsRe(self.differ.to_file.getvalue(),
 
702
                              "=== target is u'new'\n")
 
703
 
 
704
    def test_diff_directory(self):
 
705
        self.build_tree(['new-tree/new-dir/'])
 
706
        self.new_tree.add('new-dir', 'new-dir-id')
 
707
        self.differ.diff('new-dir-id', None, 'new-dir')
 
708
        self.assertEqual(self.differ.to_file.getvalue(), '')
 
709
 
 
710
    def create_old_new(self):
 
711
        self.build_tree_contents([('old-tree/olddir/',),
 
712
                                  ('old-tree/olddir/oldfile', 'old\n')])
 
713
        self.old_tree.add('olddir')
 
714
        self.old_tree.add('olddir/oldfile', 'file-id')
 
715
        self.build_tree_contents([('new-tree/newdir/',),
 
716
                                  ('new-tree/newdir/newfile', 'new\n')])
 
717
        self.new_tree.add('newdir')
 
718
        self.new_tree.add('newdir/newfile', 'file-id')
 
719
 
 
720
    def test_register_diff(self):
 
721
        self.create_old_new()
 
722
        old_diff_factories = DiffTree.diff_factories
 
723
        DiffTree.diff_factories=old_diff_factories[:]
 
724
        DiffTree.diff_factories.insert(0, DiffWasIs.from_diff_tree)
 
725
        try:
 
726
            differ = DiffTree(self.old_tree, self.new_tree, StringIO())
 
727
        finally:
 
728
            DiffTree.diff_factories = old_diff_factories
 
729
        differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
 
730
        self.assertNotContainsRe(
 
731
            differ.to_file.getvalue(),
 
732
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
 
733
             ' \@\@\n-old\n\+new\n\n')
 
734
        self.assertContainsRe(differ.to_file.getvalue(),
 
735
                              'was: old\nis: new\n')
 
736
 
 
737
    def test_extra_factories(self):
 
738
        self.create_old_new()
 
739
        differ = DiffTree(self.old_tree, self.new_tree, StringIO(),
 
740
                            extra_factories=[DiffWasIs.from_diff_tree])
 
741
        differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
 
742
        self.assertNotContainsRe(
 
743
            differ.to_file.getvalue(),
 
744
            r'--- olddir/oldfile.*\n\+\+\+ newdir/newfile.*\n\@\@ -1,1 \+1,1'
 
745
             ' \@\@\n-old\n\+new\n\n')
 
746
        self.assertContainsRe(differ.to_file.getvalue(),
 
747
                              'was: old\nis: new\n')
 
748
 
 
749
    def test_alphabetical_order(self):
 
750
        self.build_tree(['new-tree/a-file'])
 
751
        self.new_tree.add('a-file')
 
752
        self.build_tree(['old-tree/b-file'])
 
753
        self.old_tree.add('b-file')
 
754
        self.differ.show_diff(None)
 
755
        self.assertContainsRe(self.differ.to_file.getvalue(),
 
756
            '.*a-file(.|\n)*b-file')
 
757
 
 
758
 
 
759
class TestPatienceDiffLib(TestCase):
 
760
 
 
761
    def setUp(self):
 
762
        super(TestPatienceDiffLib, self).setUp()
 
763
        self._unique_lcs = bzrlib._patiencediff_py.unique_lcs_py
 
764
        self._recurse_matches = bzrlib._patiencediff_py.recurse_matches_py
 
765
        self._PatienceSequenceMatcher = \
 
766
            bzrlib._patiencediff_py.PatienceSequenceMatcher_py
 
767
 
 
768
    def test_diff_unicode_string(self):
 
769
        a = ''.join([unichr(i) for i in range(4000, 4500, 3)])
 
770
        b = ''.join([unichr(i) for i in range(4300, 4800, 2)])
 
771
        sm = self._PatienceSequenceMatcher(None, a, b)
 
772
        mb = sm.get_matching_blocks()
 
773
        self.assertEquals(35, len(mb))
 
774
 
 
775
    def test_unique_lcs(self):
 
776
        unique_lcs = self._unique_lcs
 
777
        self.assertEquals(unique_lcs('', ''), [])
 
778
        self.assertEquals(unique_lcs('', 'a'), [])
 
779
        self.assertEquals(unique_lcs('a', ''), [])
 
780
        self.assertEquals(unique_lcs('a', 'a'), [(0,0)])
 
781
        self.assertEquals(unique_lcs('a', 'b'), [])
 
782
        self.assertEquals(unique_lcs('ab', 'ab'), [(0,0), (1,1)])
 
783
        self.assertEquals(unique_lcs('abcde', 'cdeab'), [(2,0), (3,1), (4,2)])
 
784
        self.assertEquals(unique_lcs('cdeab', 'abcde'), [(0,2), (1,3), (2,4)])
 
785
        self.assertEquals(unique_lcs('abXde', 'abYde'), [(0,0), (1,1),
 
786
                                                         (3,3), (4,4)])
 
787
        self.assertEquals(unique_lcs('acbac', 'abc'), [(2,1)])
 
788
 
 
789
    def test_recurse_matches(self):
 
790
        def test_one(a, b, matches):
 
791
            test_matches = []
 
792
            self._recurse_matches(
 
793
                a, b, 0, 0, len(a), len(b), test_matches, 10)
 
794
            self.assertEquals(test_matches, matches)
 
795
 
 
796
        test_one(['a', '', 'b', '', 'c'], ['a', 'a', 'b', 'c', 'c'],
 
797
                 [(0, 0), (2, 2), (4, 4)])
 
798
        test_one(['a', 'c', 'b', 'a', 'c'], ['a', 'b', 'c'],
 
799
                 [(0, 0), (2, 1), (4, 2)])
 
800
        # Even though 'bc' is not unique globally, and is surrounded by
 
801
        # non-matching lines, we should still match, because they are locally
 
802
        # unique
 
803
        test_one('abcdbce', 'afbcgdbce', [(0,0), (1, 2), (2, 3), (3, 5),
 
804
                                          (4, 6), (5, 7), (6, 8)])
 
805
 
 
806
        # recurse_matches doesn't match non-unique
 
807
        # lines surrounded by bogus text.
 
808
        # The update has been done in patiencediff.SequenceMatcher instead
 
809
 
 
810
        # This is what it could be
 
811
        #test_one('aBccDe', 'abccde', [(0,0), (2,2), (3,3), (5,5)])
 
812
 
 
813
        # This is what it currently gives:
 
814
        test_one('aBccDe', 'abccde', [(0,0), (5,5)])
 
815
 
 
816
    def assertDiffBlocks(self, a, b, expected_blocks):
 
817
        """Check that the sequence matcher returns the correct blocks.
 
818
 
 
819
        :param a: A sequence to match
 
820
        :param b: Another sequence to match
 
821
        :param expected_blocks: The expected output, not including the final
 
822
            matching block (len(a), len(b), 0)
 
823
        """
 
824
        matcher = self._PatienceSequenceMatcher(None, a, b)
 
825
        blocks = matcher.get_matching_blocks()
 
826
        last = blocks.pop()
 
827
        self.assertEqual((len(a), len(b), 0), last)
 
828
        self.assertEqual(expected_blocks, blocks)
 
829
 
 
830
    def test_matching_blocks(self):
 
831
        # Some basic matching tests
 
832
        self.assertDiffBlocks('', '', [])
 
833
        self.assertDiffBlocks([], [], [])
 
834
        self.assertDiffBlocks('abc', '', [])
 
835
        self.assertDiffBlocks('', 'abc', [])
 
836
        self.assertDiffBlocks('abcd', 'abcd', [(0, 0, 4)])
 
837
        self.assertDiffBlocks('abcd', 'abce', [(0, 0, 3)])
 
838
        self.assertDiffBlocks('eabc', 'abce', [(1, 0, 3)])
 
839
        self.assertDiffBlocks('eabce', 'abce', [(1, 0, 4)])
 
840
        self.assertDiffBlocks('abcde', 'abXde', [(0, 0, 2), (3, 3, 2)])
 
841
        self.assertDiffBlocks('abcde', 'abXYZde', [(0, 0, 2), (3, 5, 2)])
 
842
        self.assertDiffBlocks('abde', 'abXYZde', [(0, 0, 2), (2, 5, 2)])
 
843
        # This may check too much, but it checks to see that
 
844
        # a copied block stays attached to the previous section,
 
845
        # not the later one.
 
846
        # difflib would tend to grab the trailing longest match
 
847
        # which would make the diff not look right
 
848
        self.assertDiffBlocks('abcdefghijklmnop', 'abcdefxydefghijklmnop',
 
849
                              [(0, 0, 6), (6, 11, 10)])
 
850
 
 
851
        # make sure it supports passing in lists
 
852
        self.assertDiffBlocks(
 
853
                   ['hello there\n',
 
854
                    'world\n',
 
855
                    'how are you today?\n'],
 
856
                   ['hello there\n',
 
857
                    'how are you today?\n'],
 
858
                [(0, 0, 1), (2, 1, 1)])
 
859
 
 
860
        # non unique lines surrounded by non-matching lines
 
861
        # won't be found
 
862
        self.assertDiffBlocks('aBccDe', 'abccde', [(0,0,1), (5,5,1)])
 
863
 
 
864
        # But they only need to be locally unique
 
865
        self.assertDiffBlocks('aBcDec', 'abcdec', [(0,0,1), (2,2,1), (4,4,2)])
 
866
 
 
867
        # non unique blocks won't be matched
 
868
        self.assertDiffBlocks('aBcdEcdFg', 'abcdecdfg', [(0,0,1), (8,8,1)])
 
869
 
 
870
        # but locally unique ones will
 
871
        self.assertDiffBlocks('aBcdEeXcdFg', 'abcdecdfg', [(0,0,1), (2,2,2),
 
872
                                              (5,4,1), (7,5,2), (10,8,1)])
 
873
 
 
874
        self.assertDiffBlocks('abbabbXd', 'cabbabxd', [(7,7,1)])
 
875
        self.assertDiffBlocks('abbabbbb', 'cabbabbc', [])
 
876
        self.assertDiffBlocks('bbbbbbbb', 'cbbbbbbc', [])
 
877
 
 
878
    def test_matching_blocks_tuples(self):
 
879
        # Some basic matching tests
 
880
        self.assertDiffBlocks([], [], [])
 
881
        self.assertDiffBlocks([('a',), ('b',), ('c,')], [], [])
 
882
        self.assertDiffBlocks([], [('a',), ('b',), ('c,')], [])
 
883
        self.assertDiffBlocks([('a',), ('b',), ('c,')],
 
884
                              [('a',), ('b',), ('c,')],
 
885
                              [(0, 0, 3)])
 
886
        self.assertDiffBlocks([('a',), ('b',), ('c,')],
 
887
                              [('a',), ('b',), ('d,')],
 
888
                              [(0, 0, 2)])
 
889
        self.assertDiffBlocks([('d',), ('b',), ('c,')],
 
890
                              [('a',), ('b',), ('c,')],
 
891
                              [(1, 1, 2)])
 
892
        self.assertDiffBlocks([('d',), ('a',), ('b',), ('c,')],
 
893
                              [('a',), ('b',), ('c,')],
 
894
                              [(1, 0, 3)])
 
895
        self.assertDiffBlocks([('a', 'b'), ('c', 'd'), ('e', 'f')],
 
896
                              [('a', 'b'), ('c', 'X'), ('e', 'f')],
 
897
                              [(0, 0, 1), (2, 2, 1)])
 
898
        self.assertDiffBlocks([('a', 'b'), ('c', 'd'), ('e', 'f')],
 
899
                              [('a', 'b'), ('c', 'dX'), ('e', 'f')],
 
900
                              [(0, 0, 1), (2, 2, 1)])
 
901
 
 
902
    def test_opcodes(self):
 
903
        def chk_ops(a, b, expected_codes):
 
904
            s = self._PatienceSequenceMatcher(None, a, b)
 
905
            self.assertEquals(expected_codes, s.get_opcodes())
 
906
 
 
907
        chk_ops('', '', [])
 
908
        chk_ops([], [], [])
 
909
        chk_ops('abc', '', [('delete', 0,3, 0,0)])
 
910
        chk_ops('', 'abc', [('insert', 0,0, 0,3)])
 
911
        chk_ops('abcd', 'abcd', [('equal',    0,4, 0,4)])
 
912
        chk_ops('abcd', 'abce', [('equal',   0,3, 0,3),
 
913
                                 ('replace', 3,4, 3,4)
 
914
                                ])
 
915
        chk_ops('eabc', 'abce', [('delete', 0,1, 0,0),
 
916
                                 ('equal',  1,4, 0,3),
 
917
                                 ('insert', 4,4, 3,4)
 
918
                                ])
 
919
        chk_ops('eabce', 'abce', [('delete', 0,1, 0,0),
 
920
                                  ('equal',  1,5, 0,4)
 
921
                                 ])
 
922
        chk_ops('abcde', 'abXde', [('equal',   0,2, 0,2),
 
923
                                   ('replace', 2,3, 2,3),
 
924
                                   ('equal',   3,5, 3,5)
 
925
                                  ])
 
926
        chk_ops('abcde', 'abXYZde', [('equal',   0,2, 0,2),
 
927
                                     ('replace', 2,3, 2,5),
 
928
                                     ('equal',   3,5, 5,7)
 
929
                                    ])
 
930
        chk_ops('abde', 'abXYZde', [('equal',  0,2, 0,2),
 
931
                                    ('insert', 2,2, 2,5),
 
932
                                    ('equal',  2,4, 5,7)
 
933
                                   ])
 
934
        chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
 
935
                [('equal',  0,6,  0,6),
 
936
                 ('insert', 6,6,  6,11),
 
937
                 ('equal',  6,16, 11,21)
 
938
                ])
 
939
        chk_ops(
 
940
                [ 'hello there\n'
 
941
                , 'world\n'
 
942
                , 'how are you today?\n'],
 
943
                [ 'hello there\n'
 
944
                , 'how are you today?\n'],
 
945
                [('equal',  0,1, 0,1),
 
946
                 ('delete', 1,2, 1,1),
 
947
                 ('equal',  2,3, 1,2),
 
948
                ])
 
949
        chk_ops('aBccDe', 'abccde',
 
950
                [('equal',   0,1, 0,1),
 
951
                 ('replace', 1,5, 1,5),
 
952
                 ('equal',   5,6, 5,6),
 
953
                ])
 
954
        chk_ops('aBcDec', 'abcdec',
 
955
                [('equal',   0,1, 0,1),
 
956
                 ('replace', 1,2, 1,2),
 
957
                 ('equal',   2,3, 2,3),
 
958
                 ('replace', 3,4, 3,4),
 
959
                 ('equal',   4,6, 4,6),
 
960
                ])
 
961
        chk_ops('aBcdEcdFg', 'abcdecdfg',
 
962
                [('equal',   0,1, 0,1),
 
963
                 ('replace', 1,8, 1,8),
 
964
                 ('equal',   8,9, 8,9)
 
965
                ])
 
966
        chk_ops('aBcdEeXcdFg', 'abcdecdfg',
 
967
                [('equal',   0,1, 0,1),
 
968
                 ('replace', 1,2, 1,2),
 
969
                 ('equal',   2,4, 2,4),
 
970
                 ('delete', 4,5, 4,4),
 
971
                 ('equal',   5,6, 4,5),
 
972
                 ('delete', 6,7, 5,5),
 
973
                 ('equal',   7,9, 5,7),
 
974
                 ('replace', 9,10, 7,8),
 
975
                 ('equal',   10,11, 8,9)
 
976
                ])
 
977
 
 
978
    def test_grouped_opcodes(self):
 
979
        def chk_ops(a, b, expected_codes, n=3):
 
980
            s = self._PatienceSequenceMatcher(None, a, b)
 
981
            self.assertEquals(expected_codes, list(s.get_grouped_opcodes(n)))
 
982
 
 
983
        chk_ops('', '', [])
 
984
        chk_ops([], [], [])
 
985
        chk_ops('abc', '', [[('delete', 0,3, 0,0)]])
 
986
        chk_ops('', 'abc', [[('insert', 0,0, 0,3)]])
 
987
        chk_ops('abcd', 'abcd', [])
 
988
        chk_ops('abcd', 'abce', [[('equal',   0,3, 0,3),
 
989
                                  ('replace', 3,4, 3,4)
 
990
                                 ]])
 
991
        chk_ops('eabc', 'abce', [[('delete', 0,1, 0,0),
 
992
                                 ('equal',  1,4, 0,3),
 
993
                                 ('insert', 4,4, 3,4)
 
994
                                ]])
 
995
        chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
 
996
                [[('equal',  3,6, 3,6),
 
997
                  ('insert', 6,6, 6,11),
 
998
                  ('equal',  6,9, 11,14)
 
999
                  ]])
 
1000
        chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
 
1001
                [[('equal',  2,6, 2,6),
 
1002
                  ('insert', 6,6, 6,11),
 
1003
                  ('equal',  6,10, 11,15)
 
1004
                  ]], 4)
 
1005
        chk_ops('Xabcdef', 'abcdef',
 
1006
                [[('delete', 0,1, 0,0),
 
1007
                  ('equal',  1,4, 0,3)
 
1008
                  ]])
 
1009
        chk_ops('abcdef', 'abcdefX',
 
1010
                [[('equal',  3,6, 3,6),
 
1011
                  ('insert', 6,6, 6,7)
 
1012
                  ]])
 
1013
 
 
1014
 
 
1015
    def test_multiple_ranges(self):
 
1016
        # There was an earlier bug where we used a bad set of ranges,
 
1017
        # this triggers that specific bug, to make sure it doesn't regress
 
1018
        self.assertDiffBlocks('abcdefghijklmnop',
 
1019
                              'abcXghiYZQRSTUVWXYZijklmnop',
 
1020
                              [(0, 0, 3), (6, 4, 3), (9, 20, 7)])
 
1021
 
 
1022
        self.assertDiffBlocks('ABCd efghIjk  L',
 
1023
                              'AxyzBCn mo pqrstuvwI1 2  L',
 
1024
                              [(0,0,1), (1, 4, 2), (9, 19, 1), (12, 23, 3)])
 
1025
 
 
1026
        # These are rot13 code snippets.
 
1027
        self.assertDiffBlocks('''\
 
1028
    trg nqqrq jura lbh nqq n svyr va gur qverpgbel.
 
1029
    """
 
1030
    gnxrf_netf = ['svyr*']
 
1031
    gnxrf_bcgvbaf = ['ab-erphefr']
 
1032
 
 
1033
    qrs eha(frys, svyr_yvfg, ab_erphefr=Snyfr):
 
1034
        sebz omeyvo.nqq vzcbeg fzneg_nqq, nqq_ercbegre_cevag, nqq_ercbegre_ahyy
 
1035
        vs vf_dhvrg():
 
1036
            ercbegre = nqq_ercbegre_ahyy
 
1037
        ryfr:
 
1038
            ercbegre = nqq_ercbegre_cevag
 
1039
        fzneg_nqq(svyr_yvfg, abg ab_erphefr, ercbegre)
 
1040
 
 
1041
 
 
1042
pynff pzq_zxqve(Pbzznaq):
 
1043
'''.splitlines(True), '''\
 
1044
    trg nqqrq jura lbh nqq n svyr va gur qverpgbel.
 
1045
 
 
1046
    --qel-eha jvyy fubj juvpu svyrf jbhyq or nqqrq, ohg abg npghnyyl
 
1047
    nqq gurz.
 
1048
    """
 
1049
    gnxrf_netf = ['svyr*']
 
1050
    gnxrf_bcgvbaf = ['ab-erphefr', 'qel-eha']
 
1051
 
 
1052
    qrs eha(frys, svyr_yvfg, ab_erphefr=Snyfr, qel_eha=Snyfr):
 
1053
        vzcbeg omeyvo.nqq
 
1054
 
 
1055
        vs qel_eha:
 
1056
            vs vf_dhvrg():
 
1057
                # Guvf vf cbvagyrff, ohg V'q engure abg envfr na reebe
 
1058
                npgvba = omeyvo.nqq.nqq_npgvba_ahyy
 
1059
            ryfr:
 
1060
  npgvba = omeyvo.nqq.nqq_npgvba_cevag
 
1061
        ryvs vf_dhvrg():
 
1062
            npgvba = omeyvo.nqq.nqq_npgvba_nqq
 
1063
        ryfr:
 
1064
       npgvba = omeyvo.nqq.nqq_npgvba_nqq_naq_cevag
 
1065
 
 
1066
        omeyvo.nqq.fzneg_nqq(svyr_yvfg, abg ab_erphefr, npgvba)
 
1067
 
 
1068
 
 
1069
pynff pzq_zxqve(Pbzznaq):
 
1070
'''.splitlines(True)
 
1071
, [(0,0,1), (1, 4, 2), (9, 19, 1), (12, 23, 3)])
 
1072
 
 
1073
    def test_patience_unified_diff(self):
 
1074
        txt_a = ['hello there\n',
 
1075
                 'world\n',
 
1076
                 'how are you today?\n']
 
1077
        txt_b = ['hello there\n',
 
1078
                 'how are you today?\n']
 
1079
        unified_diff = bzrlib.patiencediff.unified_diff
 
1080
        psm = self._PatienceSequenceMatcher
 
1081
        self.assertEquals(['--- \n',
 
1082
                           '+++ \n',
 
1083
                           '@@ -1,3 +1,2 @@\n',
 
1084
                           ' hello there\n',
 
1085
                           '-world\n',
 
1086
                           ' how are you today?\n'
 
1087
                          ]
 
1088
                          , list(unified_diff(txt_a, txt_b,
 
1089
                                 sequencematcher=psm)))
 
1090
        txt_a = map(lambda x: x+'\n', 'abcdefghijklmnop')
 
1091
        txt_b = map(lambda x: x+'\n', 'abcdefxydefghijklmnop')
 
1092
        # This is the result with LongestCommonSubstring matching
 
1093
        self.assertEquals(['--- \n',
 
1094
                           '+++ \n',
 
1095
                           '@@ -1,6 +1,11 @@\n',
 
1096
                           ' a\n',
 
1097
                           ' b\n',
 
1098
                           ' c\n',
 
1099
                           '+d\n',
 
1100
                           '+e\n',
 
1101
                           '+f\n',
 
1102
                           '+x\n',
 
1103
                           '+y\n',
 
1104
                           ' d\n',
 
1105
                           ' e\n',
 
1106
                           ' f\n']
 
1107
                          , list(unified_diff(txt_a, txt_b)))
 
1108
        # And the patience diff
 
1109
        self.assertEquals(['--- \n',
 
1110
                           '+++ \n',
 
1111
                           '@@ -4,6 +4,11 @@\n',
 
1112
                           ' d\n',
 
1113
                           ' e\n',
 
1114
                           ' f\n',
 
1115
                           '+x\n',
 
1116
                           '+y\n',
 
1117
                           '+d\n',
 
1118
                           '+e\n',
 
1119
                           '+f\n',
 
1120
                           ' g\n',
 
1121
                           ' h\n',
 
1122
                           ' i\n',
 
1123
                          ]
 
1124
                          , list(unified_diff(txt_a, txt_b,
 
1125
                                 sequencematcher=psm)))
 
1126
 
 
1127
    def test_patience_unified_diff_with_dates(self):
 
1128
        txt_a = ['hello there\n',
 
1129
                 'world\n',
 
1130
                 'how are you today?\n']
 
1131
        txt_b = ['hello there\n',
 
1132
                 'how are you today?\n']
 
1133
        unified_diff = bzrlib.patiencediff.unified_diff
 
1134
        psm = self._PatienceSequenceMatcher
 
1135
        self.assertEquals(['--- a\t2008-08-08\n',
 
1136
                           '+++ b\t2008-09-09\n',
 
1137
                           '@@ -1,3 +1,2 @@\n',
 
1138
                           ' hello there\n',
 
1139
                           '-world\n',
 
1140
                           ' how are you today?\n'
 
1141
                          ]
 
1142
                          , list(unified_diff(txt_a, txt_b,
 
1143
                                 fromfile='a', tofile='b',
 
1144
                                 fromfiledate='2008-08-08',
 
1145
                                 tofiledate='2008-09-09',
 
1146
                                 sequencematcher=psm)))
 
1147
 
 
1148
 
 
1149
class TestPatienceDiffLib_c(TestPatienceDiffLib):
 
1150
 
 
1151
    _test_needs_features = [compiled_patiencediff_feature]
 
1152
 
 
1153
    def setUp(self):
 
1154
        super(TestPatienceDiffLib_c, self).setUp()
 
1155
        import bzrlib._patiencediff_c
 
1156
        self._unique_lcs = bzrlib._patiencediff_c.unique_lcs_c
 
1157
        self._recurse_matches = bzrlib._patiencediff_c.recurse_matches_c
 
1158
        self._PatienceSequenceMatcher = \
 
1159
            bzrlib._patiencediff_c.PatienceSequenceMatcher_c
 
1160
 
 
1161
    def test_unhashable(self):
 
1162
        """We should get a proper exception here."""
 
1163
        # We need to be able to hash items in the sequence, lists are
 
1164
        # unhashable, and thus cannot be diffed
 
1165
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
 
1166
                                         None, [[]], [])
 
1167
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
 
1168
                                         None, ['valid', []], [])
 
1169
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
 
1170
                                         None, ['valid'], [[]])
 
1171
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
 
1172
                                         None, ['valid'], ['valid', []])
 
1173
 
 
1174
 
 
1175
class TestPatienceDiffLibFiles(TestCaseInTempDir):
 
1176
 
 
1177
    def setUp(self):
 
1178
        super(TestPatienceDiffLibFiles, self).setUp()
 
1179
        self._PatienceSequenceMatcher = \
 
1180
            bzrlib._patiencediff_py.PatienceSequenceMatcher_py
 
1181
 
 
1182
    def test_patience_unified_diff_files(self):
 
1183
        txt_a = ['hello there\n',
 
1184
                 'world\n',
 
1185
                 'how are you today?\n']
 
1186
        txt_b = ['hello there\n',
 
1187
                 'how are you today?\n']
 
1188
        open('a1', 'wb').writelines(txt_a)
 
1189
        open('b1', 'wb').writelines(txt_b)
 
1190
 
 
1191
        unified_diff_files = bzrlib.patiencediff.unified_diff_files
 
1192
        psm = self._PatienceSequenceMatcher
 
1193
        self.assertEquals(['--- a1\n',
 
1194
                           '+++ b1\n',
 
1195
                           '@@ -1,3 +1,2 @@\n',
 
1196
                           ' hello there\n',
 
1197
                           '-world\n',
 
1198
                           ' how are you today?\n',
 
1199
                          ]
 
1200
                          , list(unified_diff_files('a1', 'b1',
 
1201
                                 sequencematcher=psm)))
 
1202
 
 
1203
        txt_a = map(lambda x: x+'\n', 'abcdefghijklmnop')
 
1204
        txt_b = map(lambda x: x+'\n', 'abcdefxydefghijklmnop')
 
1205
        open('a2', 'wb').writelines(txt_a)
 
1206
        open('b2', 'wb').writelines(txt_b)
 
1207
 
 
1208
        # This is the result with LongestCommonSubstring matching
 
1209
        self.assertEquals(['--- a2\n',
 
1210
                           '+++ b2\n',
 
1211
                           '@@ -1,6 +1,11 @@\n',
 
1212
                           ' a\n',
 
1213
                           ' b\n',
 
1214
                           ' c\n',
 
1215
                           '+d\n',
 
1216
                           '+e\n',
 
1217
                           '+f\n',
 
1218
                           '+x\n',
 
1219
                           '+y\n',
 
1220
                           ' d\n',
 
1221
                           ' e\n',
 
1222
                           ' f\n']
 
1223
                          , list(unified_diff_files('a2', 'b2')))
 
1224
 
 
1225
        # And the patience diff
 
1226
        self.assertEquals(['--- a2\n',
 
1227
                           '+++ b2\n',
 
1228
                           '@@ -4,6 +4,11 @@\n',
 
1229
                           ' d\n',
 
1230
                           ' e\n',
 
1231
                           ' f\n',
 
1232
                           '+x\n',
 
1233
                           '+y\n',
 
1234
                           '+d\n',
 
1235
                           '+e\n',
 
1236
                           '+f\n',
 
1237
                           ' g\n',
 
1238
                           ' h\n',
 
1239
                           ' i\n',
 
1240
                          ]
 
1241
                          , list(unified_diff_files('a2', 'b2',
 
1242
                                 sequencematcher=psm)))
 
1243
 
 
1244
 
 
1245
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
 
1246
 
 
1247
    _test_needs_features = [compiled_patiencediff_feature]
 
1248
 
 
1249
    def setUp(self):
 
1250
        super(TestPatienceDiffLibFiles_c, self).setUp()
 
1251
        import bzrlib._patiencediff_c
 
1252
        self._PatienceSequenceMatcher = \
 
1253
            bzrlib._patiencediff_c.PatienceSequenceMatcher_c
 
1254
 
 
1255
 
 
1256
class TestUsingCompiledIfAvailable(TestCase):
 
1257
 
 
1258
    def test_PatienceSequenceMatcher(self):
 
1259
        if compiled_patiencediff_feature.available():
 
1260
            from bzrlib._patiencediff_c import PatienceSequenceMatcher_c
 
1261
            self.assertIs(PatienceSequenceMatcher_c,
 
1262
                          bzrlib.patiencediff.PatienceSequenceMatcher)
 
1263
        else:
 
1264
            from bzrlib._patiencediff_py import PatienceSequenceMatcher_py
 
1265
            self.assertIs(PatienceSequenceMatcher_py,
 
1266
                          bzrlib.patiencediff.PatienceSequenceMatcher)
 
1267
 
 
1268
    def test_unique_lcs(self):
 
1269
        if compiled_patiencediff_feature.available():
 
1270
            from bzrlib._patiencediff_c import unique_lcs_c
 
1271
            self.assertIs(unique_lcs_c,
 
1272
                          bzrlib.patiencediff.unique_lcs)
 
1273
        else:
 
1274
            from bzrlib._patiencediff_py import unique_lcs_py
 
1275
            self.assertIs(unique_lcs_py,
 
1276
                          bzrlib.patiencediff.unique_lcs)
 
1277
 
 
1278
    def test_recurse_matches(self):
 
1279
        if compiled_patiencediff_feature.available():
 
1280
            from bzrlib._patiencediff_c import recurse_matches_c
 
1281
            self.assertIs(recurse_matches_c,
 
1282
                          bzrlib.patiencediff.recurse_matches)
 
1283
        else:
 
1284
            from bzrlib._patiencediff_py import recurse_matches_py
 
1285
            self.assertIs(recurse_matches_py,
 
1286
                          bzrlib.patiencediff.recurse_matches)
 
1287
 
 
1288
 
 
1289
class TestDiffFromTool(TestCaseWithTransport):
 
1290
 
 
1291
    def test_from_string(self):
 
1292
        diff_obj = DiffFromTool.from_string('diff', None, None, None)
 
1293
        self.addCleanup(diff_obj.finish)
 
1294
        self.assertEqual(['diff', '@old_path', '@new_path'],
 
1295
            diff_obj.command_template)
 
1296
 
 
1297
    def test_from_string_u5(self):
 
1298
        diff_obj = DiffFromTool.from_string('diff "-u 5"', None, None, None)
 
1299
        self.addCleanup(diff_obj.finish)
 
1300
        self.assertEqual(['diff', '-u 5', '@old_path', '@new_path'],
 
1301
                         diff_obj.command_template)
 
1302
        self.assertEqual(['diff', '-u 5', 'old-path', 'new-path'],
 
1303
                         diff_obj._get_command('old-path', 'new-path'))
 
1304
        
 
1305
    def test_from_string_path_with_backslashes(self):
 
1306
        self.requireFeature(BackslashDirSeparatorFeature)
 
1307
        tool = 'C:\\Tools\\Diff.exe'
 
1308
        diff_obj = DiffFromTool.from_string(tool, None, None, None)
 
1309
        self.addCleanup(diff_obj.finish)
 
1310
        self.assertEqual(['C:\\Tools\\Diff.exe', '@old_path', '@new_path'],
 
1311
                         diff_obj.command_template)
 
1312
        self.assertEqual(['C:\\Tools\\Diff.exe', 'old-path', 'new-path'],
 
1313
                         diff_obj._get_command('old-path', 'new-path'))
 
1314
 
 
1315
    def test_execute(self):
 
1316
        output = StringIO()
 
1317
        diff_obj = DiffFromTool(['python', '-c',
 
1318
                                 'print "@old_path @new_path"'],
 
1319
                                None, None, output)
 
1320
        self.addCleanup(diff_obj.finish)
 
1321
        diff_obj._execute('old', 'new')
 
1322
        self.assertEqual(output.getvalue().rstrip(), 'old new')
 
1323
 
 
1324
    def test_excute_missing(self):
 
1325
        diff_obj = DiffFromTool(['a-tool-which-is-unlikely-to-exist'],
 
1326
                                None, None, None)
 
1327
        self.addCleanup(diff_obj.finish)
 
1328
        e = self.assertRaises(ExecutableMissing, diff_obj._execute, 'old',
 
1329
                              'new')
 
1330
        self.assertEqual('a-tool-which-is-unlikely-to-exist could not be found'
 
1331
                         ' on this machine', str(e))
 
1332
 
 
1333
    def test_prepare_files_creates_paths_readable_by_windows_tool(self):
 
1334
        self.requireFeature(AttribFeature)
 
1335
        output = StringIO()
 
1336
        tree = self.make_branch_and_tree('tree')
 
1337
        self.build_tree_contents([('tree/file', 'content')])
 
1338
        tree.add('file', 'file-id')
 
1339
        tree.commit('old tree')
 
1340
        tree.lock_read()
 
1341
        self.addCleanup(tree.unlock)
 
1342
        basis_tree = tree.basis_tree()
 
1343
        basis_tree.lock_read()
 
1344
        self.addCleanup(basis_tree.unlock)
 
1345
        diff_obj = DiffFromTool(['python', '-c',
 
1346
                                 'print "@old_path @new_path"'],
 
1347
                                basis_tree, tree, output)
 
1348
        diff_obj._prepare_files('file-id', 'file', 'file')
 
1349
        # The old content should be readonly
 
1350
        self.assertReadableByAttrib(diff_obj._root, 'old\\file',
 
1351
                                    r'R.*old\\file$')
 
1352
        # The new content should use the tree object, not a 'new' file anymore
 
1353
        self.assertEndsWith(tree.basedir, 'work/tree')
 
1354
        self.assertReadableByAttrib(tree.basedir, 'file', r'work\\tree\\file$')
 
1355
 
 
1356
    def assertReadableByAttrib(self, cwd, relpath, regex):
 
1357
        proc = subprocess.Popen(['attrib', relpath],
 
1358
                                stdout=subprocess.PIPE,
 
1359
                                cwd=cwd)
 
1360
        (result, err) = proc.communicate()
 
1361
        self.assertContainsRe(result.replace('\r\n', '\n'), regex)
 
1362
 
 
1363
    def test_prepare_files(self):
 
1364
        output = StringIO()
 
1365
        tree = self.make_branch_and_tree('tree')
 
1366
        self.build_tree_contents([('tree/oldname', 'oldcontent')])
 
1367
        self.build_tree_contents([('tree/oldname2', 'oldcontent2')])
 
1368
        tree.add('oldname', 'file-id')
 
1369
        tree.add('oldname2', 'file2-id')
 
1370
        # Earliest allowable date on FAT32 filesystems is 1980-01-01
 
1371
        tree.commit('old tree', timestamp=315532800)
 
1372
        tree.rename_one('oldname', 'newname')
 
1373
        tree.rename_one('oldname2', 'newname2')
 
1374
        self.build_tree_contents([('tree/newname', 'newcontent')])
 
1375
        self.build_tree_contents([('tree/newname2', 'newcontent2')])
 
1376
        old_tree = tree.basis_tree()
 
1377
        old_tree.lock_read()
 
1378
        self.addCleanup(old_tree.unlock)
 
1379
        tree.lock_read()
 
1380
        self.addCleanup(tree.unlock)
 
1381
        diff_obj = DiffFromTool(['python', '-c',
 
1382
                                 'print "@old_path @new_path"'],
 
1383
                                old_tree, tree, output)
 
1384
        self.addCleanup(diff_obj.finish)
 
1385
        self.assertContainsRe(diff_obj._root, 'bzr-diff-[^/]*')
 
1386
        old_path, new_path = diff_obj._prepare_files('file-id', 'oldname',
 
1387
                                                     'newname')
 
1388
        self.assertContainsRe(old_path, 'old/oldname$')
 
1389
        self.assertEqual(315532800, os.stat(old_path).st_mtime)
 
1390
        self.assertContainsRe(new_path, 'tree/newname$')
 
1391
        self.assertFileEqual('oldcontent', old_path)
 
1392
        self.assertFileEqual('newcontent', new_path)
 
1393
        if osutils.host_os_dereferences_symlinks():
 
1394
            self.assertTrue(os.path.samefile('tree/newname', new_path))
 
1395
        # make sure we can create files with the same parent directories
 
1396
        diff_obj._prepare_files('file2-id', 'oldname2', 'newname2')
 
1397
 
 
1398
 
 
1399
class TestGetTreesAndBranchesToDiffLocked(TestCaseWithTransport):
 
1400
 
 
1401
    def call_gtabtd(self, path_list, revision_specs, old_url, new_url):
 
1402
        """Call get_trees_and_branches_to_diff_locked.  Overridden by
 
1403
        TestGetTreesAndBranchesToDiff.
 
1404
        """
 
1405
        return get_trees_and_branches_to_diff_locked(
 
1406
            path_list, revision_specs, old_url, new_url, self.addCleanup)
 
1407
 
 
1408
    def test_basic(self):
 
1409
        tree = self.make_branch_and_tree('tree')
 
1410
        (old_tree, new_tree,
 
1411
         old_branch, new_branch,
 
1412
         specific_files, extra_trees) = self.call_gtabtd(
 
1413
             ['tree'], None, None, None)
 
1414
 
 
1415
        self.assertIsInstance(old_tree, RevisionTree)
 
1416
        self.assertEqual(_mod_revision.NULL_REVISION, old_tree.get_revision_id())
 
1417
        self.assertEqual(tree.basedir, new_tree.basedir)
 
1418
        self.assertEqual(tree.branch.base, old_branch.base)
 
1419
        self.assertEqual(tree.branch.base, new_branch.base)
 
1420
        self.assertIs(None, specific_files)
 
1421
        self.assertIs(None, extra_trees)
 
1422
 
 
1423
    def test_with_rev_specs(self):
 
1424
        tree = self.make_branch_and_tree('tree')
 
1425
        self.build_tree_contents([('tree/file', 'oldcontent')])
 
1426
        tree.add('file', 'file-id')
 
1427
        tree.commit('old tree', timestamp=0, rev_id="old-id")
 
1428
        self.build_tree_contents([('tree/file', 'newcontent')])
 
1429
        tree.commit('new tree', timestamp=0, rev_id="new-id")
 
1430
 
 
1431
        revisions = [RevisionSpec.from_string('1'),
 
1432
                     RevisionSpec.from_string('2')]
 
1433
        (old_tree, new_tree,
 
1434
         old_branch, new_branch,
 
1435
         specific_files, extra_trees) = self.call_gtabtd(
 
1436
            ['tree'], revisions, None, None)
 
1437
 
 
1438
        self.assertIsInstance(old_tree, RevisionTree)
 
1439
        self.assertEqual("old-id", old_tree.get_revision_id())
 
1440
        self.assertIsInstance(new_tree, RevisionTree)
 
1441
        self.assertEqual("new-id", new_tree.get_revision_id())
 
1442
        self.assertEqual(tree.branch.base, old_branch.base)
 
1443
        self.assertEqual(tree.branch.base, new_branch.base)
 
1444
        self.assertIs(None, specific_files)
 
1445
        self.assertEqual(tree.basedir, extra_trees[0].basedir)
 
1446
 
 
1447
 
 
1448
class TestGetTreesAndBranchesToDiff(TestGetTreesAndBranchesToDiffLocked):
 
1449
    """Apply the tests for get_trees_and_branches_to_diff_locked to the
 
1450
    deprecated get_trees_and_branches_to_diff function.
 
1451
    """
 
1452
 
 
1453
    def call_gtabtd(self, path_list, revision_specs, old_url, new_url):
 
1454
        return self.applyDeprecated(
 
1455
            deprecated_in((2, 2, 0)), get_trees_and_branches_to_diff,
 
1456
            path_list, revision_specs, old_url, new_url)
 
1457