~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_diff.py

  • Committer: Vincent Ladeuil
  • Date: 2009-12-14 15:51:36 UTC
  • mto: (4894.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4895.
  • Revision ID: v.ladeuil+lp@free.fr-20091214155136-rf4nkqvxda9oiw4u
Cleanup tests and tweak the text displayed.

* bzrlib/tests/blackbox/test_update.py:
Fix imports and replace the assertContainsRe with assertEqualDiff
to make the test clearer, more robust and easier to debug.

* bzrlib/tests/commands/test_update.py: 
Fix imports.

* bzrlib/tests/blackbox/test_filtered_view_ops.py: 
Fix imports and strange accesses to base class methods.
(TestViewTreeOperations.test_view_on_update): Avoid os.chdir()
call, simplify string matching assertions.

* bzrlib/builtins.py:
(cmd_update.run): Fix spurious space, get rid of the final '/' for
the base path, don't add a final period (it's a legal char in a
path and would be annoying for people that like to copy/paste).

Show diffs side-by-side

added added

removed removed

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