/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4763.2.4 by John Arbash Meinel
merge bzr.2.1 in preparation for NEWS entry.
1
# Copyright (C) 2005-2010 Canonical Ltd
1711.2.16 by John Arbash Meinel
test_diff needs a copyright statement
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
12
#
1711.2.16 by John Arbash Meinel
test_diff needs a copyright statement
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1711.2.16 by John Arbash Meinel
test_diff needs a copyright statement
16
1740.2.5 by Aaron Bentley
Merge from bzr.dev
17
import os
3123.6.5 by Aaron Bentley
Symlink to real files if possible
18
import os.path
1558.15.2 by Aaron Bentley
Implemented binary file handling for diff
19
from cStringIO import StringIO
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
20
import subprocess
3287.18.6 by Matt McClure
Snapshot of unfinished work.
21
import sys
1920.1.3 by John Arbash Meinel
Remove spurious import
22
from tempfile import TemporaryFile
1558.15.2 by Aaron Bentley
Implemented binary file handling for diff
23
3146.4.3 by Aaron Bentley
Add missing Symlink requirement
24
from bzrlib import tests
3009.2.9 by Aaron Bentley
Add tests for Differ
25
from bzrlib.diff import (
3123.6.2 by Aaron Bentley
Implement diff --using natively
26
    DiffFromTool,
3009.2.22 by Aaron Bentley
Update names & docstring
27
    DiffPath,
28
    DiffSymlink,
29
    DiffTree,
30
    DiffText,
3123.6.2 by Aaron Bentley
Implement diff --using natively
31
    external_diff,
32
    internal_diff,
33
    show_diff_trees,
4705.1.2 by Gary van der Merwe
Start on tests for get_trees_and_branches_to_diff.
34
    get_trees_and_branches_to_diff,
5147.3.7 by Andrew Bennetts
Expect DeprecationWarnings for get_trees_and_branches_to_diff in test_diff, and add corresponding test coverage for get_trees_and_branches_to_diff_locked.
35
    get_trees_and_branches_to_diff_locked,
3009.2.9 by Aaron Bentley
Add tests for Differ
36
    )
3145.1.1 by Aaron Bentley
Handle missing tools gracefully in diff --using
37
from bzrlib.errors import BinaryFile, NoDiff, ExecutableMissing
2321.2.5 by Alexander Belchenko
external diff: no need for special code path for win32 (suggested by John Meinel)
38
import bzrlib.osutils as osutils
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
39
import bzrlib.revision as _mod_revision
3268.1.1 by C Miller
Describe the property changes in diffs. Currently, this is the executable-bit
40
import bzrlib.transform as transform
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
41
import bzrlib.patiencediff
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
42
import bzrlib._patiencediff_py
2592.2.4 by Jonathan Lange
Skip the unicode filename test if the platform doesn't support unicode
43
from bzrlib.tests import (Feature, TestCase, TestCaseWithTransport,
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
44
                          TestCaseInTempDir, TestSkipped)
4705.1.2 by Gary van der Merwe
Start on tests for get_trees_and_branches_to_diff.
45
from bzrlib.revisiontree import RevisionTree
46
from bzrlib.revisionspec import RevisionSpec
5147.3.7 by Andrew Bennetts
Expect DeprecationWarnings for get_trees_and_branches_to_diff in test_diff, and add corresponding test coverage for get_trees_and_branches_to_diff_locked.
47
from bzrlib.symbol_versioning import deprecated_in
1558.15.2 by Aaron Bentley
Implemented binary file handling for diff
48
4913.5.9 by Gordon Tyler
Use test_win32utils' BackslashDirSeparatorFeature instead of checking sys.platform for win32.
49
from bzrlib.tests.test_win32utils import BackslashDirSeparatorFeature
50
1558.15.2 by Aaron Bentley
Implemented binary file handling for diff
51
3287.18.20 by Matt McClure
Introduces a Feature subclass to encapsulate the availability of 'attrib'.
52
class _AttribFeature(Feature):
53
54
    def _probe(self):
55
        if (sys.platform not in ('cygwin', 'win32')):
3287.18.21 by Matt McClure
Fixes capitalization of False.
56
            return False
3287.18.20 by Matt McClure
Introduces a Feature subclass to encapsulate the availability of 'attrib'.
57
        try:
58
            proc = subprocess.Popen(['attrib', '.'], stdout=subprocess.PIPE)
59
        except OSError, e:
3287.18.21 by Matt McClure
Fixes capitalization of False.
60
            return False
3287.18.20 by Matt McClure
Introduces a Feature subclass to encapsulate the availability of 'attrib'.
61
        return (0 == proc.wait())
3287.18.24 by Matt McClure
Cleans up for submission. Removes comments.
62
3287.18.20 by Matt McClure
Introduces a Feature subclass to encapsulate the availability of 'attrib'.
63
    def feature_name(self):
64
        return 'attrib Windows command-line tool'
65
66
AttribFeature = _AttribFeature()
67
68
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
69
compiled_patiencediff_feature = tests.ModuleAvailableFeature(
70
                                    'bzrlib._patiencediff_c')
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
71
72
1558.15.11 by Aaron Bentley
Apply merge review suggestions
73
def udiff_lines(old, new, allow_binary=False):
974.1.6 by Aaron Bentley
Added unit tests
74
    output = StringIO()
1558.15.11 by Aaron Bentley
Apply merge review suggestions
75
    internal_diff('old', old, 'new', new, output, allow_binary)
974.1.6 by Aaron Bentley
Added unit tests
76
    output.seek(0, 0)
77
    return output.readlines()
78
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
79
1711.2.57 by John Arbash Meinel
Allow external diff to write to a file without a fileno.
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()
1692.8.7 by James Henstridge
changes suggested by John Meinel
86
    try:
87
        external_diff('old', old, 'new', new, output, diff_opts=['-u'])
1711.2.58 by John Arbash Meinel
Use osutils.pumpfile so we don't have to buffer everything in ram
88
    except NoDiff:
1711.2.56 by John Arbash Meinel
Raise NoDiff if 'diff' not present.
89
        raise TestSkipped('external "diff" not present to test')
1692.8.2 by James Henstridge
add a test for sending external diff output to a file
90
    output.seek(0, 0)
91
    lines = output.readlines()
92
    output.close()
93
    return lines
94
95
1102 by Martin Pool
- merge test refactoring from robertc
96
class TestDiff(TestCase):
1185.81.25 by Aaron Bentley
Clean up test_diff
97
1102 by Martin Pool
- merge test refactoring from robertc
98
    def test_add_nl(self):
99
        """diff generates a valid diff for patches that add a newline"""
974.1.6 by Aaron Bentley
Added unit tests
100
        lines = udiff_lines(['boo'], ['boo\n'])
1185.16.145 by Martin Pool
Remove all assert statements from test cases.
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]
974.1.6 by Aaron Bentley
Added unit tests
104
1102 by Martin Pool
- merge test refactoring from robertc
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
        """
974.1.6 by Aaron Bentley
Added unit tests
109
        lines = udiff_lines(['boo'], ['goo\n'])
1185.16.145 by Martin Pool
Remove all assert statements from test cases.
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]
974.1.6 by Aaron Bentley
Added unit tests
113
1102 by Martin Pool
- merge test refactoring from robertc
114
    def test_remove_nl(self):
115
        """diff generates a valid diff for patches that change last line and
116
        add a newline.
117
        """
974.1.6 by Aaron Bentley
Added unit tests
118
        lines = udiff_lines(['boo\n'], ['boo'])
1185.16.145 by Martin Pool
Remove all assert statements from test cases.
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
1558.15.2 by Aaron Bentley
Implemented binary file handling for diff
137
    def test_binary_lines(self):
138
        self.assertRaises(BinaryFile, udiff_lines, [1023 * 'a' + '\x00'], [])
139
        self.assertRaises(BinaryFile, udiff_lines, [], [1023 * 'a' + '\x00'])
1558.15.11 by Aaron Bentley
Apply merge review suggestions
140
        udiff_lines([1023 * 'a' + '\x00'], [], allow_binary=True)
141
        udiff_lines([], [1023 * 'a' + '\x00'], allow_binary=True)
1692.8.2 by James Henstridge
add a test for sending external diff output to a file
142
143
    def test_external_diff(self):
144
        lines = external_udiff_lines(['boo\n'], ['goo\n'])
145
        self.check_patch(lines)
1899.1.6 by John Arbash Meinel
internal_diff always adds a trailing \n, make sure external_diff does too
146
        self.assertEqual('\n', lines[-1])
1711.2.57 by John Arbash Meinel
Allow external diff to write to a file without a fileno.
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)
1899.1.1 by John Arbash Meinel
Fix the bug in the NoDiff exception class, and add a test
155
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
156
    def test_external_diff_binary_lang_c(self):
2321.2.5 by Alexander Belchenko
external diff: no need for special code path for win32 (suggested by John Meinel)
157
        old_env = {}
158
        for lang in ('LANG', 'LC_ALL', 'LANGUAGE'):
159
            old_env[lang] = osutils.set_or_unset_env(lang, 'C')
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
160
        try:
161
            lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
1959.1.1 by Marien Zwart
merge.
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'])
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
167
        finally:
2321.2.5 by Alexander Belchenko
external diff: no need for special code path for win32 (suggested by John Meinel)
168
            for lang, old_val in old_env.iteritems():
169
                osutils.set_or_unset_env(lang, old_val)
1899.1.4 by John Arbash Meinel
Just swallow a return code of 2
170
1899.1.1 by John Arbash Meinel
Fix the bug in the NoDiff exception class, and add a test
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
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
182
1711.2.30 by John Arbash Meinel
Fix bug in internal_diff handling of unicode paths
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)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
190
        self.assertEquals(['--- old_\xc2\xb5\n',
191
                           '+++ new_\xc3\xa5\n',
1711.2.30 by John Arbash Meinel
Fix bug in internal_diff handling of unicode paths
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)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
206
        self.assertEquals(['--- old_\xc2\xb5\n',
207
                           '+++ new_\xc3\xa5\n',
1711.2.30 by John Arbash Meinel
Fix bug in internal_diff handling of unicode paths
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)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
222
        self.assertEquals(['--- old_\xb5\n',
223
                           '+++ new_\xe5\n',
1711.2.30 by John Arbash Meinel
Fix bug in internal_diff handling of unicode paths
224
                           '@@ -1,1 +1,1 @@\n',
225
                           '-old_text\n',
226
                           '+new_text\n',
227
                           '\n',
228
                          ]
229
                          , lines)
230
3085.1.1 by John Arbash Meinel
Fix internal_diff to not fail when the texts are identical.
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
1711.2.30 by John Arbash Meinel
Fix bug in internal_diff handling of unicode paths
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
1185.81.25 by Aaron Bentley
Clean up test_diff
251
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
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
2240.1.1 by Alexander Belchenko
test_external_diff_binary: run external diff with --binary flag
259
        cmd = ['diff', '-u', '--binary', 'old', 'new']
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
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
2405.1.1 by John Arbash Meinel
Add a bunch of direct tests for 'show_diff_trees'
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):
1740.2.5 by Aaron Bentley
Merge from bzr.dev
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
''')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
353
1740.2.5 by Aaron Bentley
Merge from bzr.dev
354
    def test_diff_add_files(self):
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
355
        tree1 = self.b.repository.revision_tree(_mod_revision.NULL_REVISION)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
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
1551.7.17 by Aaron Bentley
Switch to PathsNotVersioned, accept extra_trees
390
    def test_show_diff_specified(self):
1551.7.22 by Aaron Bentley
Changes from review
391
        """A working tree filename can be used to identify a file"""
1551.7.17 by Aaron Bentley
Switch to PathsNotVersioned, accept extra_trees
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')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
395
        out = self.get_diff(old_tree, new_tree, specific_files=['file1b'],
1551.7.22 by Aaron Bentley
Changes from review
396
                            working_tree=self.wt)
397
        self.assertContainsRe(out, 'file1\t')
1551.7.17 by Aaron Bentley
Switch to PathsNotVersioned, accept extra_trees
398
1551.7.22 by Aaron Bentley
Changes from review
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')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
407
        out = self.get_diff(old_tree, new_tree, specific_files=['dir1'],
1551.7.22 by Aaron Bentley
Changes from review
408
                            working_tree=self.wt)
409
        self.assertContainsRe(out, 'file1\t')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
410
        out = self.get_diff(old_tree, new_tree, specific_files=['dir2'],
1551.7.22 by Aaron Bentley
Changes from review
411
                            working_tree=self.wt)
412
        self.assertNotContainsRe(out, 'file1\t')
1740.2.5 by Aaron Bentley
Merge from bzr.dev
413
1899.1.1 by John Arbash Meinel
Fix the bug in the NoDiff exception class, and add a test
414
2405.1.1 by John Arbash Meinel
Add a bunch of direct tests for 'show_diff_trees'
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
2405.1.2 by John Arbash Meinel
Fix bug #103870 by passing None instead of a (sometimes wrong) path
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?
2405.1.3 by John Arbash Meinel
Do a better fix, which recognizes that we should pass the correct old path.
449
        self.assertContainsRe(diff, '--- old/dir/file\t')
2405.1.2 by John Arbash Meinel
Fix bug #103870 by passing None instead of a (sometimes wrong) path
450
        self.assertContainsRe(diff, '\\+\\+\\+ new/other/file\t')
451
        self.assertContainsRe(diff, '-contents\n'
452
                                    '\\+new contents\n')
453
2405.1.1 by John Arbash Meinel
Add a bunch of direct tests for 'show_diff_trees'
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
3268.1.1 by C Miller
Describe the property changes in diffs. Currently, this is the executable-bit
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
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
531
    def test_binary_unicode_filenames(self):
2592.2.2 by Jonathan Lange
Apply jam's comments to test_binary_unicode_filenames. Change the
532
        """Test that contents of files are *not* encoded in UTF-8 when there
533
        is a binary file in the diff.
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
534
        """
535
        # See https://bugs.launchpad.net/bugs/110092.
3477.1.2 by John Arbash Meinel
Rename UnicodeFilename => UnicodeFilenameFeature
536
        self.requireFeature(tests.UnicodeFilenameFeature)
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
537
538
        # This bug isn't triggered with cStringIO.
539
        from StringIO import StringIO
540
        tree = self.make_branch_and_tree('tree')
2592.2.2 by Jonathan Lange
Apply jam's comments to test_binary_unicode_filenames. Change the
541
        alpha, omega = u'\u03b1', u'\u03c9'
542
        alpha_utf8, omega_utf8 = alpha.encode('utf8'), omega.encode('utf8')
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
543
        self.build_tree_contents(
2592.2.2 by Jonathan Lange
Apply jam's comments to test_binary_unicode_filenames. Change the
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'])
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
549
        diff_content = StringIO()
550
        show_diff_trees(tree.basis_tree(), tree, diff_content)
551
        diff = diff_content.getvalue()
2592.2.2 by Jonathan Lange
Apply jam's comments to test_binary_unicode_filenames. Change the
552
        self.assertContainsRe(diff, r"=== added file '%s'" % alpha_utf8)
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
553
        self.assertContainsRe(
2592.2.2 by Jonathan Lange
Apply jam's comments to test_binary_unicode_filenames. Change the
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,))
2592.2.1 by Jonathan Lange
Reproduce and fix bug 110092.
558
2725.2.1 by ghigo
When a unicode filename is renamed, in the diff is showed a wrong result
559
    def test_unicode_filename(self):
560
        """Test when the filename are unicode."""
3477.1.2 by John Arbash Meinel
Rename UnicodeFilename => UnicodeFilenameFeature
561
        self.requireFeature(tests.UnicodeFilenameFeature)
2725.2.1 by ghigo
When a unicode filename is renamed, in the diff is showed a wrong result
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)
2405.1.1 by John Arbash Meinel
Add a bunch of direct tests for 'show_diff_trees'
588
3009.2.9 by Aaron Bentley
Add tests for Differ
589
3009.2.22 by Aaron Bentley
Update names & docstring
590
class DiffWasIs(DiffPath):
3009.2.15 by Aaron Bentley
Test differ registration
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
3009.2.22 by Aaron Bentley
Update names & docstring
600
class TestDiffTree(TestCaseWithTransport):
3009.2.9 by Aaron Bentley
Add tests for Differ
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)
3009.2.22 by Aaron Bentley
Update names & docstring
610
        self.differ = DiffTree(self.old_tree, self.new_tree, StringIO())
3009.2.9 by Aaron Bentley
Add tests for Differ
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')
3009.2.22 by Aaron Bentley
Update names & docstring
621
        differ = DiffText(self.old_tree, self.new_tree, StringIO())
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
622
        differ.diff_text('file-id', None, 'old label', 'new label')
3009.2.9 by Aaron Bentley
Add tests for Differ
623
        self.assertEqual(
624
            '--- old label\n+++ new label\n@@ -1,1 +0,0 @@\n-old\n\n',
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
625
            differ.to_file.getvalue())
626
        differ.to_file.seek(0)
627
        differ.diff_text(None, 'file-id', 'old label', 'new label')
3009.2.9 by Aaron Bentley
Add tests for Differ
628
        self.assertEqual(
629
            '--- old label\n+++ new label\n@@ -0,0 +1,1 @@\n+new\n\n',
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
630
            differ.to_file.getvalue())
631
        differ.to_file.seek(0)
632
        differ.diff_text('file-id', 'file-id', 'old label', 'new label')
3009.2.9 by Aaron Bentley
Add tests for Differ
633
        self.assertEqual(
634
            '--- old label\n+++ new label\n@@ -1,1 +1,1 @@\n-old\n+new\n\n',
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
635
            differ.to_file.getvalue())
3009.2.9 by Aaron Bentley
Add tests for Differ
636
3087.1.1 by Aaron Bentley
Diff handles missing files correctly, with no tracebacks
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
3009.2.9 by Aaron Bentley
Add tests for Differ
655
    def test_diff_symlink(self):
3009.2.22 by Aaron Bentley
Update names & docstring
656
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
657
        differ.diff_symlink('old target', None)
3009.2.9 by Aaron Bentley
Add tests for Differ
658
        self.assertEqual("=== target was 'old target'\n",
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
659
                         differ.to_file.getvalue())
3009.2.9 by Aaron Bentley
Add tests for Differ
660
3009.2.22 by Aaron Bentley
Update names & docstring
661
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
662
        differ.diff_symlink(None, 'new target')
3009.2.9 by Aaron Bentley
Add tests for Differ
663
        self.assertEqual("=== target is 'new target'\n",
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
664
                         differ.to_file.getvalue())
665
3009.2.22 by Aaron Bentley
Update names & docstring
666
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
667
        differ.diff_symlink('old target', 'new target')
3009.2.9 by Aaron Bentley
Add tests for Differ
668
        self.assertEqual("=== target changed 'old target' => 'new target'\n",
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
669
                         differ.to_file.getvalue())
3009.2.9 by Aaron Bentley
Add tests for Differ
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')
3009.2.12 by Aaron Bentley
Associate labels with text diffing only
680
        self.differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
3009.2.9 by Aaron Bentley
Add tests for Differ
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):
3146.4.3 by Aaron Bentley
Add missing Symlink requirement
687
        self.requireFeature(tests.SymlinkFeature)
3009.2.9 by Aaron Bentley
Add tests for Differ
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')
3009.2.12 by Aaron Bentley
Associate labels with text diffing only
696
        self.differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
3009.2.9 by Aaron Bentley
Add tests for Differ
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(),
4216.3.1 by Robert Collins
Fix Tree.get_symlink_target to decode from the disk encoding to get a unicode encoded string.
702
                              "=== target is u'new'\n")
3009.2.9 by Aaron Bentley
Add tests for Differ
703
3009.2.19 by Aaron Bentley
Implement directory diffing
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
3009.2.16 by Aaron Bentley
Test support for extra differs
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
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
720
    def test_register_diff(self):
3009.2.16 by Aaron Bentley
Test support for extra differs
721
        self.create_old_new()
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
722
        old_diff_factories = DiffTree.diff_factories
723
        DiffTree.diff_factories=old_diff_factories[:]
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
724
        DiffTree.diff_factories.insert(0, DiffWasIs.from_diff_tree)
3009.2.16 by Aaron Bentley
Test support for extra differs
725
        try:
3009.2.22 by Aaron Bentley
Update names & docstring
726
            differ = DiffTree(self.old_tree, self.new_tree, StringIO())
3009.2.16 by Aaron Bentley
Test support for extra differs
727
        finally:
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
728
            DiffTree.diff_factories = old_diff_factories
3009.2.16 by Aaron Bentley
Test support for extra differs
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
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
737
    def test_extra_factories(self):
3009.2.16 by Aaron Bentley
Test support for extra differs
738
        self.create_old_new()
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
739
        differ = DiffTree(self.old_tree, self.new_tree, StringIO(),
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
740
                            extra_factories=[DiffWasIs.from_diff_tree])
3009.2.16 by Aaron Bentley
Test support for extra differs
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
3123.4.1 by Aaron Bentley
Diff sorts files in alphabetical order
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
3009.2.9 by Aaron Bentley
Add tests for Differ
758
1711.2.15 by John Arbash Meinel
Found a couple CDV left
759
class TestPatienceDiffLib(TestCase):
1185.81.1 by John Arbash Meinel
Adding nofrillsprecisemerge's diff algorithm, wrapped in difflib.
760
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
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
3628.1.3 by Lukáš Lalinský
Add a test
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
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
775
    def test_unique_lcs(self):
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
776
        unique_lcs = self._unique_lcs
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
777
        self.assertEquals(unique_lcs('', ''), [])
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
778
        self.assertEquals(unique_lcs('', 'a'), [])
779
        self.assertEquals(unique_lcs('a', ''), [])
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
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)])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
785
        self.assertEquals(unique_lcs('abXde', 'abYde'), [(0,0), (1,1),
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
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 = []
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
792
            self._recurse_matches(
793
                a, b, 0, 0, len(a), len(b), test_matches, 10)
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
794
            self.assertEquals(test_matches, matches)
795
1711.2.17 by John Arbash Meinel
Small cleanups to patience_diff code.
796
        test_one(['a', '', 'b', '', 'c'], ['a', 'a', 'b', 'c', 'c'],
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
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)])
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
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)])
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
805
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
806
        # recurse_matches doesn't match non-unique
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
807
        # lines surrounded by bogus text.
1185.81.24 by Aaron Bentley
Reoganize patience-related code
808
        # The update has been done in patiencediff.SequenceMatcher instead
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
809
810
        # This is what it could be
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
811
        #test_one('aBccDe', 'abccde', [(0,0), (2,2), (3,3), (5,5)])
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
812
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
813
        # This is what it currently gives:
814
        test_one('aBccDe', 'abccde', [(0,0), (5,5)])
815
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
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
1185.81.1 by John Arbash Meinel
Adding nofrillsprecisemerge's diff algorithm, wrapped in difflib.
830
    def test_matching_blocks(self):
1185.81.2 by John Arbash Meinel
A couple small tests.
831
        # Some basic matching tests
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
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
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
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
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
848
        self.assertDiffBlocks('abcdefghijklmnop', 'abcdefxydefghijklmnop',
849
                              [(0, 0, 6), (6, 11, 10)])
1185.81.1 by John Arbash Meinel
Adding nofrillsprecisemerge's diff algorithm, wrapped in difflib.
850
1185.81.2 by John Arbash Meinel
A couple small tests.
851
        # make sure it supports passing in lists
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
852
        self.assertDiffBlocks(
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
853
                   ['hello there\n',
854
                    'world\n',
855
                    'how are you today?\n'],
856
                   ['hello there\n',
857
                    'how are you today?\n'],
1185.81.2 by John Arbash Meinel
A couple small tests.
858
                [(0, 0, 1), (2, 1, 1)])
1185.81.1 by John Arbash Meinel
Adding nofrillsprecisemerge's diff algorithm, wrapped in difflib.
859
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
860
        # non unique lines surrounded by non-matching lines
861
        # won't be found
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
862
        self.assertDiffBlocks('aBccDe', 'abccde', [(0,0,1), (5,5,1)])
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
863
864
        # But they only need to be locally unique
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
865
        self.assertDiffBlocks('aBcDec', 'abcdec', [(0,0,1), (2,2,1), (4,4,2)])
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
866
867
        # non unique blocks won't be matched
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
868
        self.assertDiffBlocks('aBcdEcdFg', 'abcdecdfg', [(0,0,1), (8,8,1)])
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
869
870
        # but locally unique ones will
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
871
        self.assertDiffBlocks('aBcdEeXcdFg', 'abcdecdfg', [(0,0,1), (2,2,2),
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
872
                                              (5,4,1), (7,5,2), (10,8,1)])
873
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
874
        self.assertDiffBlocks('abbabbXd', 'cabbabxd', [(7,7,1)])
875
        self.assertDiffBlocks('abbabbbb', 'cabbabbc', [])
876
        self.assertDiffBlocks('bbbbbbbb', 'cbbbbbbc', [])
1185.81.11 by John Arbash Meinel
Found some edge cases that weren't being matched.
877
3074.2.1 by John Arbash Meinel
Change the C PatienceDiff implementation to support arbitrary objects.
878
    def test_matching_blocks_tuples(self):
879
        # Some basic matching tests
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
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)])
3074.2.1 by John Arbash Meinel
Change the C PatienceDiff implementation to support arbitrary objects.
901
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
902
    def test_opcodes(self):
1711.2.10 by John Arbash Meinel
Clarify the patience tests a little bit.
903
        def chk_ops(a, b, expected_codes):
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
904
            s = self._PatienceSequenceMatcher(None, a, b)
1711.2.10 by John Arbash Meinel
Clarify the patience tests a little bit.
905
            self.assertEquals(expected_codes, s.get_opcodes())
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
906
907
        chk_ops('', '', [])
908
        chk_ops([], [], [])
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
909
        chk_ops('abc', '', [('delete', 0,3, 0,0)])
910
        chk_ops('', 'abc', [('insert', 0,0, 0,3)])
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
911
        chk_ops('abcd', 'abcd', [('equal',    0,4, 0,4)])
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
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)
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
921
                                 ])
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
922
        chk_ops('abcde', 'abXde', [('equal',   0,2, 0,2),
923
                                   ('replace', 2,3, 2,3),
924
                                   ('equal',   3,5, 3,5)
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
925
                                  ])
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
926
        chk_ops('abcde', 'abXYZde', [('equal',   0,2, 0,2),
927
                                     ('replace', 2,3, 2,5),
928
                                     ('equal',   3,5, 5,7)
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
929
                                    ])
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
930
        chk_ops('abde', 'abXYZde', [('equal',  0,2, 0,2),
931
                                    ('insert', 2,2, 2,5),
932
                                    ('equal',  2,4, 5,7)
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
933
                                   ])
934
        chk_ops('abcdefghijklmnop', 'abcdefxydefghijklmnop',
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
935
                [('equal',  0,6,  0,6),
936
                 ('insert', 6,6,  6,11),
937
                 ('equal',  6,16, 11,21)
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
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'],
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
945
                [('equal',  0,1, 0,1),
946
                 ('delete', 1,2, 1,1),
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
947
                 ('equal',  2,3, 1,2),
1185.81.9 by John Arbash Meinel
Added (failing) tests for cdv.recurse_matches with common sections,
948
                ])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
949
        chk_ops('aBccDe', 'abccde',
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
950
                [('equal',   0,1, 0,1),
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
951
                 ('replace', 1,5, 1,5),
952
                 ('equal',   5,6, 5,6),
953
                ])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
954
        chk_ops('aBcDec', 'abcdec',
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
955
                [('equal',   0,1, 0,1),
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
956
                 ('replace', 1,2, 1,2),
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
957
                 ('equal',   2,3, 2,3),
958
                 ('replace', 3,4, 3,4),
959
                 ('equal',   4,6, 4,6),
1185.81.3 by John Arbash Meinel
Adding tests for checking opcodes.
960
                ])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
961
        chk_ops('aBcdEcdFg', 'abcdecdfg',
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
962
                [('equal',   0,1, 0,1),
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
963
                 ('replace', 1,8, 1,8),
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
964
                 ('equal',   8,9, 8,9)
1185.81.10 by John Arbash Meinel
Added some more test cases.
965
                ])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
966
        chk_ops('aBcdEeXcdFg', 'abcdecdfg',
1711.2.21 by John Arbash Meinel
Cleanup patiencediff, remove the use of difflib.SequenceMatcher.
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
                ])
1185.81.10 by John Arbash Meinel
Added some more test cases.
977
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
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
1185.81.16 by John Arbash Meinel
Added tests, and an assert check to make sure ranges are always increasing.
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
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
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)])
1185.81.16 by John Arbash Meinel
Added tests, and an assert check to make sure ranges are always increasing.
1025
1711.2.8 by John Arbash Meinel
rot13 the code snippet to help with clarity.
1026
        # These are rot13 code snippets.
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
1027
        self.assertDiffBlocks('''\
1711.2.8 by John Arbash Meinel
rot13 the code snippet to help with clarity.
1028
    trg nqqrq jura lbh nqq n svyr va gur qverpgbel.
1029
    """
1030
    gnxrf_netf = ['svyr*']
1031
    gnxrf_bcgvbaf = ['ab-erphefr']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1032
1711.2.8 by John Arbash Meinel
rot13 the code snippet to help with clarity.
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
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1046
    --qel-eha jvyy fubj juvpu svyrf jbhyq or nqqrq, ohg abg npghnyyl
1711.2.8 by John Arbash Meinel
rot13 the code snippet to help with clarity.
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):
1185.81.16 by John Arbash Meinel
Added tests, and an assert check to make sure ranges are always increasing.
1070
'''.splitlines(True)
1071
, [(0,0,1), (1, 4, 2), (9, 19, 1), (12, 23, 3)])
1072
1711.2.9 by John Arbash Meinel
Rename cdv => patience
1073
    def test_patience_unified_diff(self):
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
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']
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1079
        unified_diff = bzrlib.patiencediff.unified_diff
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1080
        psm = self._PatienceSequenceMatcher
3922.1.3 by John Arbash Meinel
fix some odd spacing.
1081
        self.assertEquals(['--- \n',
3922.1.2 by John Arbash Meinel
Update the test cases for the new patience diff code.
1082
                           '+++ \n',
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
1083
                           '@@ -1,3 +1,2 @@\n',
1084
                           ' hello there\n',
1085
                           '-world\n',
1086
                           ' how are you today?\n'
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1087
                          ]
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1088
                          , list(unified_diff(txt_a, txt_b,
1089
                                 sequencematcher=psm)))
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
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
3922.1.2 by John Arbash Meinel
Update the test cases for the new patience diff code.
1093
        self.assertEquals(['--- \n',
1094
                           '+++ \n',
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
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']
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1107
                          , list(unified_diff(txt_a, txt_b)))
1711.2.9 by John Arbash Meinel
Rename cdv => patience
1108
        # And the patience diff
3922.1.2 by John Arbash Meinel
Update the test cases for the new patience diff code.
1109
        self.assertEquals(['--- \n',
1110
                           '+++ \n',
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
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',
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1123
                          ]
1185.81.25 by Aaron Bentley
Clean up test_diff
1124
                          , list(unified_diff(txt_a, txt_b,
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1125
                                 sequencematcher=psm)))
1185.81.25 by Aaron Bentley
Clean up test_diff
1126
3922.1.2 by John Arbash Meinel
Update the test cases for the new patience diff code.
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
3922.1.4 by John Arbash Meinel
It turns out that internal_diff worked around the trailing whitespace problem
1135
        self.assertEquals(['--- a\t2008-08-08\n',
1136
                           '+++ b\t2008-09-09\n',
3922.1.2 by John Arbash Meinel
Update the test cases for the new patience diff code.
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
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1148
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1149
class TestPatienceDiffLib_c(TestPatienceDiffLib):
1150
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
1151
    _test_needs_features = [compiled_patiencediff_feature]
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
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
3074.2.3 by John Arbash Meinel
Enable some error checking, and small amount of code cleanup.
1161
    def test_unhashable(self):
1162
        """We should get a proper exception here."""
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
1163
        # We need to be able to hash items in the sequence, lists are
1164
        # unhashable, and thus cannot be diffed
3074.2.3 by John Arbash Meinel
Enable some error checking, and small amount of code cleanup.
1165
        e = self.assertRaises(TypeError, self._PatienceSequenceMatcher,
1166
                                         None, [[]], [])
3074.2.10 by John Arbash Meinel
Cleanup the test cases (Andrew)
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', []])
3074.2.3 by John Arbash Meinel
Enable some error checking, and small amount of code cleanup.
1173
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1174
1711.2.15 by John Arbash Meinel
Found a couple CDV left
1175
class TestPatienceDiffLibFiles(TestCaseInTempDir):
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1176
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1177
    def setUp(self):
1178
        super(TestPatienceDiffLibFiles, self).setUp()
1179
        self._PatienceSequenceMatcher = \
1180
            bzrlib._patiencediff_py.PatienceSequenceMatcher_py
1181
1711.2.9 by John Arbash Meinel
Rename cdv => patience
1182
    def test_patience_unified_diff_files(self):
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
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']
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1188
        open('a1', 'wb').writelines(txt_a)
1189
        open('b1', 'wb').writelines(txt_b)
1190
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1191
        unified_diff_files = bzrlib.patiencediff.unified_diff_files
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1192
        psm = self._PatienceSequenceMatcher
3922.1.2 by John Arbash Meinel
Update the test cases for the new patience diff code.
1193
        self.assertEquals(['--- a1\n',
1194
                           '+++ b1\n',
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
1195
                           '@@ -1,3 +1,2 @@\n',
1196
                           ' hello there\n',
1197
                           '-world\n',
1198
                           ' how are you today?\n',
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1199
                          ]
1185.81.25 by Aaron Bentley
Clean up test_diff
1200
                          , list(unified_diff_files('a1', 'b1',
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1201
                                 sequencematcher=psm)))
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
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
3922.1.2 by John Arbash Meinel
Update the test cases for the new patience diff code.
1209
        self.assertEquals(['--- a2\n',
1210
                           '+++ b2\n',
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
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']
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1223
                          , list(unified_diff_files('a2', 'b2')))
1224
1711.2.9 by John Arbash Meinel
Rename cdv => patience
1225
        # And the patience diff
3922.1.2 by John Arbash Meinel
Update the test cases for the new patience diff code.
1226
        self.assertEquals(['--- a2\n',
1227
                           '+++ b2\n',
1185.81.29 by Aaron Bentley
Fix style issues and duplicated tests
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',
1185.81.14 by John Arbash Meinel
Added a main function for running cdvdifflib manually, included tests for unified_diff interfaces
1240
                          ]
1185.81.25 by Aaron Bentley
Clean up test_diff
1241
                          , list(unified_diff_files('a2', 'b2',
1711.2.20 by John Arbash Meinel
Late bind to patiencediff objects to make it easier to plug-in
1242
                                 sequencematcher=psm)))
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
1243
1244
1245
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
1246
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
1247
    _test_needs_features = [compiled_patiencediff_feature]
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
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):
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
1259
        if compiled_patiencediff_feature.available():
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
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):
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
1269
        if compiled_patiencediff_feature.available():
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
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):
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
1279
        if compiled_patiencediff_feature.available():
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
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)
3123.6.2 by Aaron Bentley
Implement diff --using natively
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)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
1294
        self.assertEqual(['diff', '@old_path', '@new_path'],
3123.6.2 by Aaron Bentley
Implement diff --using natively
1295
            diff_obj.command_template)
3199.1.6 by Vincent Ladeuil
Fiz last leaking tmp dir.
1296
1297
    def test_from_string_u5(self):
4913.5.13 by Gordon Tyler
Fixed a few more tests.
1298
        diff_obj = DiffFromTool.from_string('diff "-u 5"', None, None, None)
3199.1.6 by Vincent Ladeuil
Fiz last leaking tmp dir.
1299
        self.addCleanup(diff_obj.finish)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
1300
        self.assertEqual(['diff', '-u 5', '@old_path', '@new_path'],
3123.6.2 by Aaron Bentley
Implement diff --using natively
1301
                         diff_obj.command_template)
1302
        self.assertEqual(['diff', '-u 5', 'old-path', 'new-path'],
1303
                         diff_obj._get_command('old-path', 'new-path'))
4913.5.8 by Gordon Tyler
Added test_from_string_path_with_backslashes, which tests the actual scenario in bug 392428.
1304
        
1305
    def test_from_string_path_with_backslashes(self):
4913.5.9 by Gordon Tyler
Use test_win32utils' BackslashDirSeparatorFeature instead of checking sys.platform for win32.
1306
        self.requireFeature(BackslashDirSeparatorFeature)
4913.5.8 by Gordon Tyler
Added test_from_string_path_with_backslashes, which tests the actual scenario in bug 392428.
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'))
3123.6.2 by Aaron Bentley
Implement diff --using natively
1314
1315
    def test_execute(self):
1316
        output = StringIO()
1317
        diff_obj = DiffFromTool(['python', '-c',
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
1318
                                 'print "@old_path @new_path"'],
3123.6.2 by Aaron Bentley
Implement diff --using natively
1319
                                None, None, output)
1320
        self.addCleanup(diff_obj.finish)
1321
        diff_obj._execute('old', 'new')
3146.4.2 by Aaron Bentley
Avoid assuming unix newline on output
1322
        self.assertEqual(output.getvalue().rstrip(), 'old new')
3123.6.2 by Aaron Bentley
Implement diff --using natively
1323
3145.1.1 by Aaron Bentley
Handle missing tools gracefully in diff --using
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
3287.18.22 by Matt McClure
Reverts to prior decomposition of exercise and verification, as suggested
1333
    def test_prepare_files_creates_paths_readable_by_windows_tool(self):
3287.18.20 by Matt McClure
Introduces a Feature subclass to encapsulate the availability of 'attrib'.
1334
        self.requireFeature(AttribFeature)
3287.18.10 by Matt McClure
Uses TestSkipped for test_execute_windows_tool on non-Windows platforms.
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')
3287.18.11 by Matt McClure
Removed unnecessary timestamp parameter.
1339
        tree.commit('old tree')
3287.18.10 by Matt McClure
Uses TestSkipped for test_execute_windows_tool on non-Windows platforms.
1340
        tree.lock_read()
1341
        self.addCleanup(tree.unlock)
4873.3.1 by John Arbash Meinel
Now that we return files directly from the working tree
1342
        basis_tree = tree.basis_tree()
1343
        basis_tree.lock_read()
1344
        self.addCleanup(basis_tree.unlock)
3287.18.10 by Matt McClure
Uses TestSkipped for test_execute_windows_tool on non-Windows platforms.
1345
        diff_obj = DiffFromTool(['python', '-c',
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
1346
                                 'print "@old_path @new_path"'],
4873.3.1 by John Arbash Meinel
Now that we return files directly from the working tree
1347
                                basis_tree, tree, output)
3287.18.22 by Matt McClure
Reverts to prior decomposition of exercise and verification, as suggested
1348
        diff_obj._prepare_files('file-id', 'file', 'file')
4873.3.1 by John Arbash Meinel
Now that we return files directly from the working tree
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$')
3287.18.22 by Matt McClure
Reverts to prior decomposition of exercise and verification, as suggested
1355
1356
    def assertReadableByAttrib(self, cwd, relpath, regex):
1357
        proc = subprocess.Popen(['attrib', relpath],
1358
                                stdout=subprocess.PIPE,
1359
                                cwd=cwd)
4873.3.1 by John Arbash Meinel
Now that we return files directly from the working tree
1360
        (result, err) = proc.communicate()
1361
        self.assertContainsRe(result.replace('\r\n', '\n'), regex)
3287.18.9 by Matt McClure
Adds a test asserting that a Windows tool that understands forward slashes
1362
3123.6.2 by Aaron Bentley
Implement diff --using natively
1363
    def test_prepare_files(self):
1364
        output = StringIO()
1365
        tree = self.make_branch_and_tree('tree')
3123.6.5 by Aaron Bentley
Symlink to real files if possible
1366
        self.build_tree_contents([('tree/oldname', 'oldcontent')])
3287.18.23 by Matt McClure
Adds comments that document my understanding of
1367
        self.build_tree_contents([('tree/oldname2', 'oldcontent2')])
3123.6.5 by Aaron Bentley
Symlink to real files if possible
1368
        tree.add('oldname', 'file-id')
3287.18.23 by Matt McClure
Adds comments that document my understanding of
1369
        tree.add('oldname2', 'file2-id')
5151.3.1 by Martin
Fix os.utime test failures, three on FAT filesystems and one with readonly files
1370
        # Earliest allowable date on FAT32 filesystems is 1980-01-01
1371
        tree.commit('old tree', timestamp=315532800)
3123.6.5 by Aaron Bentley
Symlink to real files if possible
1372
        tree.rename_one('oldname', 'newname')
3287.18.23 by Matt McClure
Adds comments that document my understanding of
1373
        tree.rename_one('oldname2', 'newname2')
3123.6.5 by Aaron Bentley
Symlink to real files if possible
1374
        self.build_tree_contents([('tree/newname', 'newcontent')])
3287.19.1 by Matt McClure
Fixes https://bugs.launchpad.net/bzr/+bug/212289. I submitted this patch.
1375
        self.build_tree_contents([('tree/newname2', 'newcontent2')])
3123.6.2 by Aaron Bentley
Implement diff --using natively
1376
        old_tree = tree.basis_tree()
1377
        old_tree.lock_read()
1378
        self.addCleanup(old_tree.unlock)
3123.6.4 by Aaron Bentley
Set mtime (and atime) on files for --using
1379
        tree.lock_read()
1380
        self.addCleanup(tree.unlock)
3123.6.2 by Aaron Bentley
Implement diff --using natively
1381
        diff_obj = DiffFromTool(['python', '-c',
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
1382
                                 'print "@old_path @new_path"'],
3123.6.2 by Aaron Bentley
Implement diff --using natively
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$')
5151.3.1 by Martin
Fix os.utime test failures, three on FAT filesystems and one with readonly files
1389
        self.assertEqual(315532800, os.stat(old_path).st_mtime)
4845.2.1 by Gary van der Merwe
When launching an external diff app, don't write temporary files for a working tree.
1390
        self.assertContainsRe(new_path, 'tree/newname$')
3123.6.2 by Aaron Bentley
Implement diff --using natively
1391
        self.assertFileEqual('oldcontent', old_path)
1392
        self.assertFileEqual('newcontent', new_path)
3287.18.14 by Matt McClure
Extracted a host_os_dereferences_symlinks method.
1393
        if osutils.host_os_dereferences_symlinks():
3123.6.5 by Aaron Bentley
Symlink to real files if possible
1394
            self.assertTrue(os.path.samefile('tree/newname', new_path))
3123.6.2 by Aaron Bentley
Implement diff --using natively
1395
        # make sure we can create files with the same parent directories
3287.18.25 by Matt McClure
Uses the correct file_id as the argument to _prepare_files.
1396
        diff_obj._prepare_files('file2-id', 'oldname2', 'newname2')
4705.1.2 by Gary van der Merwe
Start on tests for get_trees_and_branches_to_diff.
1397
1398
5147.3.7 by Andrew Bennetts
Expect DeprecationWarnings for get_trees_and_branches_to_diff in test_diff, and add corresponding test coverage for get_trees_and_branches_to_diff_locked.
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)
4732.1.2 by Vincent Ladeuil
(trivial) Fix some PEP8 issues
1407
4705.1.2 by Gary van der Merwe
Start on tests for get_trees_and_branches_to_diff.
1408
    def test_basic(self):
1409
        tree = self.make_branch_and_tree('tree')
1410
        (old_tree, new_tree,
1411
         old_branch, new_branch,
5147.3.7 by Andrew Bennetts
Expect DeprecationWarnings for get_trees_and_branches_to_diff in test_diff, and add corresponding test coverage for get_trees_and_branches_to_diff_locked.
1412
         specific_files, extra_trees) = self.call_gtabtd(
1413
             ['tree'], None, None, None)
4732.1.2 by Vincent Ladeuil
(trivial) Fix some PEP8 issues
1414
4705.1.2 by Gary van der Merwe
Start on tests for get_trees_and_branches_to_diff.
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")
4732.1.2 by Vincent Ladeuil
(trivial) Fix some PEP8 issues
1430
4705.1.2 by Gary van der Merwe
Start on tests for get_trees_and_branches_to_diff.
1431
        revisions = [RevisionSpec.from_string('1'),
1432
                     RevisionSpec.from_string('2')]
1433
        (old_tree, new_tree,
1434
         old_branch, new_branch,
5147.3.7 by Andrew Bennetts
Expect DeprecationWarnings for get_trees_and_branches_to_diff in test_diff, and add corresponding test coverage for get_trees_and_branches_to_diff_locked.
1435
         specific_files, extra_trees) = self.call_gtabtd(
1436
            ['tree'], revisions, None, None)
4732.1.2 by Vincent Ladeuil
(trivial) Fix some PEP8 issues
1437
4705.1.2 by Gary van der Merwe
Start on tests for get_trees_and_branches_to_diff.
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)
4705.1.4 by Gary van der Merwe
Add newline to end of test_diff.py
1445
        self.assertEqual(tree.basedir, extra_trees[0].basedir)
5147.3.7 by Andrew Bennetts
Expect DeprecationWarnings for get_trees_and_branches_to_diff in test_diff, and add corresponding test coverage for get_trees_and_branches_to_diff_locked.
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