~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_diff.py

  • Committer: Colin Watson
  • Date: 2015-07-02 11:30:47 UTC
  • mto: This revision was merged to the branch mainline in revision 6605.
  • Revision ID: cjwatson@canonical.com-20150702113047-359s4zsi07wvfwso
Use assertLength.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Copyright (C) 2005-2014 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
import os
18
 
import os.path
19
18
from cStringIO import StringIO
20
 
import errno
21
19
import subprocess
22
 
import sys
23
 
from tempfile import TemporaryFile
 
20
import tempfile
24
21
 
25
 
from bzrlib import tests
26
 
from bzrlib.diff import (
27
 
    DiffFromTool,
28
 
    DiffPath,
29
 
    DiffSymlink,
30
 
    DiffTree,
31
 
    DiffText,
32
 
    external_diff,
33
 
    internal_diff,
34
 
    show_diff_trees,
35
 
    get_trees_and_branches_to_diff,
 
22
from bzrlib import (
 
23
    diff,
 
24
    errors,
 
25
    osutils,
 
26
    patiencediff,
 
27
    _patiencediff_py,
 
28
    revision as _mod_revision,
 
29
    revisionspec,
 
30
    revisiontree,
 
31
    tests,
 
32
    transform,
36
33
    )
37
 
from bzrlib.errors import BinaryFile, NoDiff, ExecutableMissing
38
 
import bzrlib.osutils as osutils
39
 
import bzrlib.revision as _mod_revision
40
 
import bzrlib.transform as transform
41
 
import bzrlib.patiencediff
42
 
import bzrlib._patiencediff_py
43
 
from bzrlib.tests import (Feature, TestCase, TestCaseWithTransport,
44
 
                          TestCaseInTempDir, TestSkipped)
45
 
from bzrlib.revisiontree import RevisionTree
46
 
from bzrlib.revisionspec import RevisionSpec
47
 
 
48
 
 
49
 
class _AttribFeature(Feature):
50
 
 
51
 
    def _probe(self):
52
 
        if (sys.platform not in ('cygwin', 'win32')):
53
 
            return False
54
 
        try:
55
 
            proc = subprocess.Popen(['attrib', '.'], stdout=subprocess.PIPE)
56
 
        except OSError, e:
57
 
            return False
58
 
        return (0 == proc.wait())
59
 
 
60
 
    def feature_name(self):
61
 
        return 'attrib Windows command-line tool'
62
 
 
63
 
AttribFeature = _AttribFeature()
64
 
 
65
 
 
66
 
compiled_patiencediff_feature = tests.ModuleAvailableFeature(
67
 
                                    'bzrlib._patiencediff_c')
 
34
from bzrlib.tests import (
 
35
    features,
 
36
    EncodingAdapter,
 
37
)
 
38
from bzrlib.tests.blackbox.test_diff import subst_dates
 
39
from bzrlib.tests.scenarios import load_tests_apply_scenarios
 
40
 
 
41
 
 
42
load_tests = load_tests_apply_scenarios
68
43
 
69
44
 
70
45
def udiff_lines(old, new, allow_binary=False):
71
46
    output = StringIO()
72
 
    internal_diff('old', old, 'new', new, output, allow_binary)
 
47
    diff.internal_diff('old', old, 'new', new, output, allow_binary)
73
48
    output.seek(0, 0)
74
49
    return output.readlines()
75
50
 
79
54
        # StringIO has no fileno, so it tests a different codepath
80
55
        output = StringIO()
81
56
    else:
82
 
        output = TemporaryFile()
 
57
        output = tempfile.TemporaryFile()
83
58
    try:
84
 
        external_diff('old', old, 'new', new, output, diff_opts=['-u'])
85
 
    except NoDiff:
86
 
        raise TestSkipped('external "diff" not present to test')
 
59
        diff.external_diff('old', old, 'new', new, output, diff_opts=['-u'])
 
60
    except errors.NoDiff:
 
61
        raise tests.TestSkipped('external "diff" not present to test')
87
62
    output.seek(0, 0)
88
63
    lines = output.readlines()
89
64
    output.close()
90
65
    return lines
91
66
 
92
67
 
93
 
class TestDiff(TestCase):
 
68
class TestDiffOptions(tests.TestCase):
 
69
 
 
70
    def test_unified_added(self):
 
71
        """Check for default style '-u' only if no other style specified
 
72
        in 'diff-options'.
 
73
        """
 
74
        # Verify that style defaults to unified, id est '-u' appended
 
75
        # to option list, in the absence of an alternative style.
 
76
        self.assertEqual(['-a', '-u'], diff.default_style_unified(['-a']))
 
77
 
 
78
 
 
79
class TestDiffOptionsScenarios(tests.TestCase):
 
80
 
 
81
    scenarios = [(s, dict(style=s)) for s in diff.style_option_list]
 
82
    style = None # Set by load_tests_apply_scenarios from scenarios
 
83
 
 
84
    def test_unified_not_added(self):
 
85
        # Verify that for all valid style options, '-u' is not
 
86
        # appended to option list.
 
87
        ret_opts = diff.default_style_unified(diff_opts=["%s" % (self.style,)])
 
88
        self.assertEqual(["%s" % (self.style,)], ret_opts)
 
89
 
 
90
 
 
91
class TestDiff(tests.TestCase):
94
92
 
95
93
    def test_add_nl(self):
96
94
        """diff generates a valid diff for patches that add a newline"""
132
130
            ## "Unterminated hunk header for patch:\n%s" % "".join(lines)
133
131
 
134
132
    def test_binary_lines(self):
135
 
        self.assertRaises(BinaryFile, udiff_lines, [1023 * 'a' + '\x00'], [])
136
 
        self.assertRaises(BinaryFile, udiff_lines, [], [1023 * 'a' + '\x00'])
137
 
        udiff_lines([1023 * 'a' + '\x00'], [], allow_binary=True)
138
 
        udiff_lines([], [1023 * 'a' + '\x00'], allow_binary=True)
 
133
        empty = []
 
134
        uni_lines = [1023 * 'a' + '\x00']
 
135
        self.assertRaises(errors.BinaryFile, udiff_lines, uni_lines , empty)
 
136
        self.assertRaises(errors.BinaryFile, udiff_lines, empty, uni_lines)
 
137
        udiff_lines(uni_lines , empty, allow_binary=True)
 
138
        udiff_lines(empty, uni_lines, allow_binary=True)
139
139
 
140
140
    def test_external_diff(self):
141
141
        lines = external_udiff_lines(['boo\n'], ['goo\n'])
151
151
        self.check_patch(lines)
152
152
 
153
153
    def test_external_diff_binary_lang_c(self):
154
 
        old_env = {}
155
154
        for lang in ('LANG', 'LC_ALL', 'LANGUAGE'):
156
 
            old_env[lang] = osutils.set_or_unset_env(lang, 'C')
157
 
        try:
158
 
            lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
159
 
            # Older versions of diffutils say "Binary files", newer
160
 
            # versions just say "Files".
161
 
            self.assertContainsRe(lines[0],
162
 
                                  '(Binary f|F)iles old and new differ\n')
163
 
            self.assertEquals(lines[1:], ['\n'])
164
 
        finally:
165
 
            for lang, old_val in old_env.iteritems():
166
 
                osutils.set_or_unset_env(lang, old_val)
 
155
            self.overrideEnv(lang, 'C')
 
156
        lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
 
157
        # Older versions of diffutils say "Binary files", newer
 
158
        # versions just say "Files".
 
159
        self.assertContainsRe(lines[0], '(Binary f|F)iles old and new differ\n')
 
160
        self.assertEquals(lines[1:], ['\n'])
167
161
 
168
162
    def test_no_external_diff(self):
169
163
        """Check that NoDiff is raised when diff is not available"""
170
 
        # Use os.environ['PATH'] to make sure no 'diff' command is available
171
 
        orig_path = os.environ['PATH']
172
 
        try:
173
 
            os.environ['PATH'] = ''
174
 
            self.assertRaises(NoDiff, external_diff,
175
 
                              'old', ['boo\n'], 'new', ['goo\n'],
176
 
                              StringIO(), diff_opts=['-u'])
177
 
        finally:
178
 
            os.environ['PATH'] = orig_path
 
164
        # Make sure no 'diff' command is available
 
165
        # XXX: Weird, using None instead of '' breaks the test -- vila 20101216
 
166
        self.overrideEnv('PATH', '')
 
167
        self.assertRaises(errors.NoDiff, diff.external_diff,
 
168
                          'old', ['boo\n'], 'new', ['goo\n'],
 
169
                          StringIO(), diff_opts=['-u'])
179
170
 
180
171
    def test_internal_diff_default(self):
181
172
        # Default internal diff encoding is utf8
182
173
        output = StringIO()
183
 
        internal_diff(u'old_\xb5', ['old_text\n'],
184
 
                    u'new_\xe5', ['new_text\n'], output)
 
174
        diff.internal_diff(u'old_\xb5', ['old_text\n'],
 
175
                           u'new_\xe5', ['new_text\n'], output)
185
176
        lines = output.getvalue().splitlines(True)
186
177
        self.check_patch(lines)
187
178
        self.assertEquals(['--- old_\xc2\xb5\n',
195
186
 
196
187
    def test_internal_diff_utf8(self):
197
188
        output = StringIO()
198
 
        internal_diff(u'old_\xb5', ['old_text\n'],
199
 
                    u'new_\xe5', ['new_text\n'], output,
200
 
                    path_encoding='utf8')
 
189
        diff.internal_diff(u'old_\xb5', ['old_text\n'],
 
190
                           u'new_\xe5', ['new_text\n'], output,
 
191
                           path_encoding='utf8')
201
192
        lines = output.getvalue().splitlines(True)
202
193
        self.check_patch(lines)
203
194
        self.assertEquals(['--- old_\xc2\xb5\n',
211
202
 
212
203
    def test_internal_diff_iso_8859_1(self):
213
204
        output = StringIO()
214
 
        internal_diff(u'old_\xb5', ['old_text\n'],
215
 
                    u'new_\xe5', ['new_text\n'], output,
216
 
                    path_encoding='iso-8859-1')
 
205
        diff.internal_diff(u'old_\xb5', ['old_text\n'],
 
206
                           u'new_\xe5', ['new_text\n'], output,
 
207
                           path_encoding='iso-8859-1')
217
208
        lines = output.getvalue().splitlines(True)
218
209
        self.check_patch(lines)
219
210
        self.assertEquals(['--- old_\xb5\n',
227
218
 
228
219
    def test_internal_diff_no_content(self):
229
220
        output = StringIO()
230
 
        internal_diff(u'old', [], u'new', [], output)
 
221
        diff.internal_diff(u'old', [], u'new', [], output)
231
222
        self.assertEqual('', output.getvalue())
232
223
 
233
224
    def test_internal_diff_no_changes(self):
234
225
        output = StringIO()
235
 
        internal_diff(u'old', ['text\n', 'contents\n'],
236
 
                      u'new', ['text\n', 'contents\n'],
237
 
                      output)
 
226
        diff.internal_diff(u'old', ['text\n', 'contents\n'],
 
227
                           u'new', ['text\n', 'contents\n'],
 
228
                           output)
238
229
        self.assertEqual('', output.getvalue())
239
230
 
240
231
    def test_internal_diff_returns_bytes(self):
241
232
        import StringIO
242
233
        output = StringIO.StringIO()
243
 
        internal_diff(u'old_\xb5', ['old_text\n'],
244
 
                    u'new_\xe5', ['new_text\n'], output)
245
 
        self.failUnless(isinstance(output.getvalue(), str),
 
234
        diff.internal_diff(u'old_\xb5', ['old_text\n'],
 
235
                            u'new_\xe5', ['new_text\n'], output)
 
236
        self.assertIsInstance(output.getvalue(), str,
246
237
            'internal_diff should return bytestrings')
247
238
 
248
 
 
249
 
class TestDiffFiles(TestCaseInTempDir):
 
239
    def test_internal_diff_default_context(self):
 
240
        output = StringIO()
 
241
        diff.internal_diff('old', ['same_text\n','same_text\n','same_text\n',
 
242
                           'same_text\n','same_text\n','old_text\n'],
 
243
                           'new', ['same_text\n','same_text\n','same_text\n',
 
244
                           'same_text\n','same_text\n','new_text\n'], output)
 
245
        lines = output.getvalue().splitlines(True)
 
246
        self.check_patch(lines)
 
247
        self.assertEquals(['--- old\n',
 
248
                           '+++ new\n',
 
249
                           '@@ -3,4 +3,4 @@\n',
 
250
                           ' same_text\n',
 
251
                           ' same_text\n',
 
252
                           ' same_text\n',
 
253
                           '-old_text\n',
 
254
                           '+new_text\n',
 
255
                           '\n',
 
256
                          ]
 
257
                          , lines)
 
258
 
 
259
    def test_internal_diff_no_context(self):
 
260
        output = StringIO()
 
261
        diff.internal_diff('old', ['same_text\n','same_text\n','same_text\n',
 
262
                           'same_text\n','same_text\n','old_text\n'],
 
263
                           'new', ['same_text\n','same_text\n','same_text\n',
 
264
                           'same_text\n','same_text\n','new_text\n'], output,
 
265
                           context_lines=0)
 
266
        lines = output.getvalue().splitlines(True)
 
267
        self.check_patch(lines)
 
268
        self.assertEquals(['--- old\n',
 
269
                           '+++ new\n',
 
270
                           '@@ -6,1 +6,1 @@\n',
 
271
                           '-old_text\n',
 
272
                           '+new_text\n',
 
273
                           '\n',
 
274
                          ]
 
275
                          , lines)
 
276
 
 
277
    def test_internal_diff_more_context(self):
 
278
        output = StringIO()
 
279
        diff.internal_diff('old', ['same_text\n','same_text\n','same_text\n',
 
280
                           'same_text\n','same_text\n','old_text\n'],
 
281
                           'new', ['same_text\n','same_text\n','same_text\n',
 
282
                           'same_text\n','same_text\n','new_text\n'], output,
 
283
                           context_lines=4)
 
284
        lines = output.getvalue().splitlines(True)
 
285
        self.check_patch(lines)
 
286
        self.assertEquals(['--- old\n',
 
287
                           '+++ new\n',
 
288
                           '@@ -2,5 +2,5 @@\n',
 
289
                           ' same_text\n',
 
290
                           ' same_text\n',
 
291
                           ' same_text\n',
 
292
                           ' same_text\n',
 
293
                           '-old_text\n',
 
294
                           '+new_text\n',
 
295
                           '\n',
 
296
                          ]
 
297
                          , lines)
 
298
 
 
299
 
 
300
 
 
301
 
 
302
 
 
303
class TestDiffFiles(tests.TestCaseInTempDir):
250
304
 
251
305
    def test_external_diff_binary(self):
252
306
        """The output when using external diff should use diff's i18n error"""
254
308
        lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
255
309
 
256
310
        cmd = ['diff', '-u', '--binary', 'old', 'new']
257
 
        open('old', 'wb').write('\x00foobar\n')
258
 
        open('new', 'wb').write('foo\x00bar\n')
 
311
        with open('old', 'wb') as f: f.write('\x00foobar\n')
 
312
        with open('new', 'wb') as f: f.write('foo\x00bar\n')
259
313
        pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
260
314
                                     stdin=subprocess.PIPE)
261
315
        out, err = pipe.communicate()
265
319
        self.assertEqual(out.splitlines(True) + ['\n'], lines)
266
320
 
267
321
 
268
 
class TestShowDiffTreesHelper(TestCaseWithTransport):
269
 
    """Has a helper for running show_diff_trees"""
270
 
 
271
 
    def get_diff(self, tree1, tree2, specific_files=None, working_tree=None):
272
 
        output = StringIO()
273
 
        if working_tree is not None:
274
 
            extra_trees = (working_tree,)
275
 
        else:
276
 
            extra_trees = ()
277
 
        show_diff_trees(tree1, tree2, output, specific_files=specific_files,
278
 
                        extra_trees=extra_trees, old_label='old/',
279
 
                        new_label='new/')
280
 
        return output.getvalue()
281
 
 
282
 
 
283
 
class TestDiffDates(TestShowDiffTreesHelper):
 
322
def get_diff_as_string(tree1, tree2, specific_files=None, working_tree=None):
 
323
    output = StringIO()
 
324
    if working_tree is not None:
 
325
        extra_trees = (working_tree,)
 
326
    else:
 
327
        extra_trees = ()
 
328
    diff.show_diff_trees(tree1, tree2, output,
 
329
        specific_files=specific_files,
 
330
        extra_trees=extra_trees, old_label='old/',
 
331
        new_label='new/')
 
332
    return output.getvalue()
 
333
 
 
334
 
 
335
class TestDiffDates(tests.TestCaseWithTransport):
284
336
 
285
337
    def setUp(self):
286
338
        super(TestDiffDates, self).setUp()
321
373
        os.utime('file1', (1144195200, 1144195200)) # 2006-04-05 00:00:00 UTC
322
374
 
323
375
    def test_diff_rev_tree_working_tree(self):
324
 
        output = self.get_diff(self.wt.basis_tree(), self.wt)
 
376
        output = get_diff_as_string(self.wt.basis_tree(), self.wt)
325
377
        # note that the date for old/file1 is from rev 2 rather than from
326
378
        # the basis revision (rev 4)
327
379
        self.assertEqualDiff(output, '''\
337
389
    def test_diff_rev_tree_rev_tree(self):
338
390
        tree1 = self.b.repository.revision_tree('rev-2')
339
391
        tree2 = self.b.repository.revision_tree('rev-3')
340
 
        output = self.get_diff(tree1, tree2)
 
392
        output = get_diff_as_string(tree1, tree2)
341
393
        self.assertEqualDiff(output, '''\
342
394
=== modified file 'file2'
343
395
--- old/file2\t2006-04-01 00:00:00 +0000
351
403
    def test_diff_add_files(self):
352
404
        tree1 = self.b.repository.revision_tree(_mod_revision.NULL_REVISION)
353
405
        tree2 = self.b.repository.revision_tree('rev-1')
354
 
        output = self.get_diff(tree1, tree2)
 
406
        output = get_diff_as_string(tree1, tree2)
355
407
        # the files have the epoch time stamp for the tree in which
356
408
        # they don't exist.
357
409
        self.assertEqualDiff(output, '''\
372
424
    def test_diff_remove_files(self):
373
425
        tree1 = self.b.repository.revision_tree('rev-3')
374
426
        tree2 = self.b.repository.revision_tree('rev-4')
375
 
        output = self.get_diff(tree1, tree2)
 
427
        output = get_diff_as_string(tree1, tree2)
376
428
        # the file has the epoch time stamp for the tree in which
377
429
        # it doesn't exist.
378
430
        self.assertEqualDiff(output, '''\
389
441
        self.wt.rename_one('file1', 'file1b')
390
442
        old_tree = self.b.repository.revision_tree('rev-1')
391
443
        new_tree = self.b.repository.revision_tree('rev-4')
392
 
        out = self.get_diff(old_tree, new_tree, specific_files=['file1b'],
 
444
        out = get_diff_as_string(old_tree, new_tree, specific_files=['file1b'],
393
445
                            working_tree=self.wt)
394
446
        self.assertContainsRe(out, 'file1\t')
395
447
 
401
453
        self.wt.rename_one('file1', 'dir1/file1')
402
454
        old_tree = self.b.repository.revision_tree('rev-1')
403
455
        new_tree = self.b.repository.revision_tree('rev-4')
404
 
        out = self.get_diff(old_tree, new_tree, specific_files=['dir1'],
 
456
        out = get_diff_as_string(old_tree, new_tree, specific_files=['dir1'],
405
457
                            working_tree=self.wt)
406
458
        self.assertContainsRe(out, 'file1\t')
407
 
        out = self.get_diff(old_tree, new_tree, specific_files=['dir2'],
 
459
        out = get_diff_as_string(old_tree, new_tree, specific_files=['dir2'],
408
460
                            working_tree=self.wt)
409
461
        self.assertNotContainsRe(out, 'file1\t')
410
462
 
411
463
 
412
 
 
413
 
class TestShowDiffTrees(TestShowDiffTreesHelper):
 
464
class TestShowDiffTrees(tests.TestCaseWithTransport):
414
465
    """Direct tests for show_diff_trees"""
415
466
 
416
467
    def test_modified_file(self):
421
472
        tree.commit('one', rev_id='rev-1')
422
473
 
423
474
        self.build_tree_contents([('tree/file', 'new contents\n')])
424
 
        diff = self.get_diff(tree.basis_tree(), tree)
425
 
        self.assertContainsRe(diff, "=== modified file 'file'\n")
426
 
        self.assertContainsRe(diff, '--- old/file\t')
427
 
        self.assertContainsRe(diff, '\\+\\+\\+ new/file\t')
428
 
        self.assertContainsRe(diff, '-contents\n'
429
 
                                    '\\+new contents\n')
 
475
        d = get_diff_as_string(tree.basis_tree(), tree)
 
476
        self.assertContainsRe(d, "=== modified file 'file'\n")
 
477
        self.assertContainsRe(d, '--- old/file\t')
 
478
        self.assertContainsRe(d, '\\+\\+\\+ new/file\t')
 
479
        self.assertContainsRe(d, '-contents\n'
 
480
                                 '\\+new contents\n')
430
481
 
431
482
    def test_modified_file_in_renamed_dir(self):
432
483
        """Test when a file is modified in a renamed directory."""
438
489
 
439
490
        tree.rename_one('dir', 'other')
440
491
        self.build_tree_contents([('tree/other/file', 'new contents\n')])
441
 
        diff = self.get_diff(tree.basis_tree(), tree)
442
 
        self.assertContainsRe(diff, "=== renamed directory 'dir' => 'other'\n")
443
 
        self.assertContainsRe(diff, "=== modified file 'other/file'\n")
 
492
        d = get_diff_as_string(tree.basis_tree(), tree)
 
493
        self.assertContainsRe(d, "=== renamed directory 'dir' => 'other'\n")
 
494
        self.assertContainsRe(d, "=== modified file 'other/file'\n")
444
495
        # XXX: This is technically incorrect, because it used to be at another
445
496
        # location. What to do?
446
 
        self.assertContainsRe(diff, '--- old/dir/file\t')
447
 
        self.assertContainsRe(diff, '\\+\\+\\+ new/other/file\t')
448
 
        self.assertContainsRe(diff, '-contents\n'
449
 
                                    '\\+new contents\n')
 
497
        self.assertContainsRe(d, '--- old/dir/file\t')
 
498
        self.assertContainsRe(d, '\\+\\+\\+ new/other/file\t')
 
499
        self.assertContainsRe(d, '-contents\n'
 
500
                                 '\\+new contents\n')
450
501
 
451
502
    def test_renamed_directory(self):
452
503
        """Test when only a directory is only renamed."""
457
508
        tree.commit('one', rev_id='rev-1')
458
509
 
459
510
        tree.rename_one('dir', 'newdir')
460
 
        diff = self.get_diff(tree.basis_tree(), tree)
 
511
        d = get_diff_as_string(tree.basis_tree(), tree)
461
512
        # Renaming a directory should be a single "you renamed this dir" even
462
513
        # when there are files inside.
463
 
        self.assertEqual("=== renamed directory 'dir' => 'newdir'\n", diff)
 
514
        self.assertEqual(d, "=== renamed directory 'dir' => 'newdir'\n")
464
515
 
465
516
    def test_renamed_file(self):
466
517
        """Test when a file is only renamed."""
470
521
        tree.commit('one', rev_id='rev-1')
471
522
 
472
523
        tree.rename_one('file', 'newname')
473
 
        diff = self.get_diff(tree.basis_tree(), tree)
474
 
        self.assertContainsRe(diff, "=== renamed file 'file' => 'newname'\n")
 
524
        d = get_diff_as_string(tree.basis_tree(), tree)
 
525
        self.assertContainsRe(d, "=== renamed file 'file' => 'newname'\n")
475
526
        # We shouldn't have a --- or +++ line, because there is no content
476
527
        # change
477
 
        self.assertNotContainsRe(diff, '---')
 
528
        self.assertNotContainsRe(d, '---')
478
529
 
479
530
    def test_renamed_and_modified_file(self):
480
531
        """Test when a file is only renamed."""
485
536
 
486
537
        tree.rename_one('file', 'newname')
487
538
        self.build_tree_contents([('tree/newname', 'new contents\n')])
488
 
        diff = self.get_diff(tree.basis_tree(), tree)
489
 
        self.assertContainsRe(diff, "=== renamed file 'file' => 'newname'\n")
490
 
        self.assertContainsRe(diff, '--- old/file\t')
491
 
        self.assertContainsRe(diff, '\\+\\+\\+ new/newname\t')
492
 
        self.assertContainsRe(diff, '-contents\n'
493
 
                                    '\\+new contents\n')
 
539
        d = get_diff_as_string(tree.basis_tree(), tree)
 
540
        self.assertContainsRe(d, "=== renamed file 'file' => 'newname'\n")
 
541
        self.assertContainsRe(d, '--- old/file\t')
 
542
        self.assertContainsRe(d, '\\+\\+\\+ new/newname\t')
 
543
        self.assertContainsRe(d, '-contents\n'
 
544
                                 '\\+new contents\n')
494
545
 
495
546
 
496
547
    def test_internal_diff_exec_property(self):
515
566
        tree.rename_one('c', 'new-c')
516
567
        tree.rename_one('d', 'new-d')
517
568
 
518
 
        diff = self.get_diff(tree.basis_tree(), tree)
519
 
 
520
 
        self.assertContainsRe(diff, r"file 'a'.*\(properties changed:.*\+x to -x.*\)")
521
 
        self.assertContainsRe(diff, r"file 'b'.*\(properties changed:.*-x to \+x.*\)")
522
 
        self.assertContainsRe(diff, r"file 'c'.*\(properties changed:.*\+x to -x.*\)")
523
 
        self.assertContainsRe(diff, r"file 'd'.*\(properties changed:.*-x to \+x.*\)")
524
 
        self.assertNotContainsRe(diff, r"file 'e'")
525
 
        self.assertNotContainsRe(diff, r"file 'f'")
526
 
 
 
569
        d = get_diff_as_string(tree.basis_tree(), tree)
 
570
 
 
571
        self.assertContainsRe(d, r"file 'a'.*\(properties changed:"
 
572
                                  ".*\+x to -x.*\)")
 
573
        self.assertContainsRe(d, r"file 'b'.*\(properties changed:"
 
574
                                  ".*-x to \+x.*\)")
 
575
        self.assertContainsRe(d, r"file 'c'.*\(properties changed:"
 
576
                                  ".*\+x to -x.*\)")
 
577
        self.assertContainsRe(d, r"file 'd'.*\(properties changed:"
 
578
                                  ".*-x to \+x.*\)")
 
579
        self.assertNotContainsRe(d, r"file 'e'")
 
580
        self.assertNotContainsRe(d, r"file 'f'")
527
581
 
528
582
    def test_binary_unicode_filenames(self):
529
583
        """Test that contents of files are *not* encoded in UTF-8 when there
530
584
        is a binary file in the diff.
531
585
        """
532
586
        # See https://bugs.launchpad.net/bugs/110092.
533
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
587
        self.requireFeature(features.UnicodeFilenameFeature)
534
588
 
535
589
        # This bug isn't triggered with cStringIO.
536
590
        from StringIO import StringIO
544
598
        tree.add([alpha], ['file-id'])
545
599
        tree.add([omega], ['file-id-2'])
546
600
        diff_content = StringIO()
547
 
        show_diff_trees(tree.basis_tree(), tree, diff_content)
548
 
        diff = diff_content.getvalue()
549
 
        self.assertContainsRe(diff, r"=== added file '%s'" % alpha_utf8)
550
 
        self.assertContainsRe(
551
 
            diff, "Binary files a/%s.*and b/%s.* differ\n" % (alpha_utf8, alpha_utf8))
552
 
        self.assertContainsRe(diff, r"=== added file '%s'" % omega_utf8)
553
 
        self.assertContainsRe(diff, r"--- a/%s" % (omega_utf8,))
554
 
        self.assertContainsRe(diff, r"\+\+\+ b/%s" % (omega_utf8,))
 
601
        diff.show_diff_trees(tree.basis_tree(), tree, diff_content)
 
602
        d = diff_content.getvalue()
 
603
        self.assertContainsRe(d, r"=== added file '%s'" % alpha_utf8)
 
604
        self.assertContainsRe(d, "Binary files a/%s.*and b/%s.* differ\n"
 
605
                              % (alpha_utf8, alpha_utf8))
 
606
        self.assertContainsRe(d, r"=== added file '%s'" % omega_utf8)
 
607
        self.assertContainsRe(d, r"--- a/%s" % (omega_utf8,))
 
608
        self.assertContainsRe(d, r"\+\+\+ b/%s" % (omega_utf8,))
555
609
 
556
610
    def test_unicode_filename(self):
557
611
        """Test when the filename are unicode."""
558
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
612
        self.requireFeature(features.UnicodeFilenameFeature)
559
613
 
560
614
        alpha, omega = u'\u03b1', u'\u03c9'
561
615
        autf8, outf8 = alpha.encode('utf8'), omega.encode('utf8')
576
630
        tree.add(['add_'+alpha], ['file-id'])
577
631
        self.build_tree_contents([('tree/mod_'+alpha, 'contents_mod\n')])
578
632
 
579
 
        diff = self.get_diff(tree.basis_tree(), tree)
580
 
        self.assertContainsRe(diff,
 
633
        d = get_diff_as_string(tree.basis_tree(), tree)
 
634
        self.assertContainsRe(d,
581
635
                "=== renamed file 'ren_%s' => 'ren_%s'\n"%(autf8, outf8))
582
 
        self.assertContainsRe(diff, "=== added file 'add_%s'"%autf8)
583
 
        self.assertContainsRe(diff, "=== modified file 'mod_%s'"%autf8)
584
 
        self.assertContainsRe(diff, "=== removed file 'del_%s'"%autf8)
585
 
 
586
 
 
587
 
class DiffWasIs(DiffPath):
 
636
        self.assertContainsRe(d, "=== added file 'add_%s'"%autf8)
 
637
        self.assertContainsRe(d, "=== modified file 'mod_%s'"%autf8)
 
638
        self.assertContainsRe(d, "=== removed file 'del_%s'"%autf8)
 
639
 
 
640
    def test_unicode_filename_path_encoding(self):
 
641
        """Test for bug #382699: unicode filenames on Windows should be shown
 
642
        in user encoding.
 
643
        """
 
644
        self.requireFeature(features.UnicodeFilenameFeature)
 
645
        # The word 'test' in Russian
 
646
        _russian_test = u'\u0422\u0435\u0441\u0442'
 
647
        directory = _russian_test + u'/'
 
648
        test_txt = _russian_test + u'.txt'
 
649
        u1234 = u'\u1234.txt'
 
650
 
 
651
        tree = self.make_branch_and_tree('.')
 
652
        self.build_tree_contents([
 
653
            (test_txt, 'foo\n'),
 
654
            (u1234, 'foo\n'),
 
655
            (directory, None),
 
656
            ])
 
657
        tree.add([test_txt, u1234, directory])
 
658
 
 
659
        sio = StringIO()
 
660
        diff.show_diff_trees(tree.basis_tree(), tree, sio,
 
661
            path_encoding='cp1251')
 
662
 
 
663
        output = subst_dates(sio.getvalue())
 
664
        shouldbe = ('''\
 
665
=== added directory '%(directory)s'
 
666
=== added file '%(test_txt)s'
 
667
--- a/%(test_txt)s\tYYYY-MM-DD HH:MM:SS +ZZZZ
 
668
+++ b/%(test_txt)s\tYYYY-MM-DD HH:MM:SS +ZZZZ
 
669
@@ -0,0 +1,1 @@
 
670
+foo
 
671
 
 
672
=== added file '?.txt'
 
673
--- a/?.txt\tYYYY-MM-DD HH:MM:SS +ZZZZ
 
674
+++ b/?.txt\tYYYY-MM-DD HH:MM:SS +ZZZZ
 
675
@@ -0,0 +1,1 @@
 
676
+foo
 
677
 
 
678
''' % {'directory': _russian_test.encode('cp1251'),
 
679
       'test_txt': test_txt.encode('cp1251'),
 
680
      })
 
681
        self.assertEqualDiff(output, shouldbe)
 
682
 
 
683
 
 
684
class DiffWasIs(diff.DiffPath):
588
685
 
589
686
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
590
687
        self.to_file.write('was: ')
594
691
        pass
595
692
 
596
693
 
597
 
class TestDiffTree(TestCaseWithTransport):
 
694
class TestDiffTree(tests.TestCaseWithTransport):
598
695
 
599
696
    def setUp(self):
600
 
        TestCaseWithTransport.setUp(self)
 
697
        super(TestDiffTree, self).setUp()
601
698
        self.old_tree = self.make_branch_and_tree('old-tree')
602
699
        self.old_tree.lock_write()
603
700
        self.addCleanup(self.old_tree.unlock)
604
701
        self.new_tree = self.make_branch_and_tree('new-tree')
605
702
        self.new_tree.lock_write()
606
703
        self.addCleanup(self.new_tree.unlock)
607
 
        self.differ = DiffTree(self.old_tree, self.new_tree, StringIO())
 
704
        self.differ = diff.DiffTree(self.old_tree, self.new_tree, StringIO())
608
705
 
609
706
    def test_diff_text(self):
610
707
        self.build_tree_contents([('old-tree/olddir/',),
615
712
                                  ('new-tree/newdir/newfile', 'new\n')])
616
713
        self.new_tree.add('newdir')
617
714
        self.new_tree.add('newdir/newfile', 'file-id')
618
 
        differ = DiffText(self.old_tree, self.new_tree, StringIO())
 
715
        differ = diff.DiffText(self.old_tree, self.new_tree, StringIO())
619
716
        differ.diff_text('file-id', None, 'old label', 'new label')
620
717
        self.assertEqual(
621
718
            '--- old label\n+++ new label\n@@ -1,1 +0,0 @@\n-old\n\n',
650
747
        self.assertContainsRe(self.differ.to_file.getvalue(), '\+contents')
651
748
 
652
749
    def test_diff_symlink(self):
653
 
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
 
750
        differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
654
751
        differ.diff_symlink('old target', None)
655
752
        self.assertEqual("=== target was 'old target'\n",
656
753
                         differ.to_file.getvalue())
657
754
 
658
 
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
 
755
        differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
659
756
        differ.diff_symlink(None, 'new target')
660
757
        self.assertEqual("=== target is 'new target'\n",
661
758
                         differ.to_file.getvalue())
662
759
 
663
 
        differ = DiffSymlink(self.old_tree, self.new_tree, StringIO())
 
760
        differ = diff.DiffSymlink(self.old_tree, self.new_tree, StringIO())
664
761
        differ.diff_symlink('old target', 'new target')
665
762
        self.assertEqual("=== target changed 'old target' => 'new target'\n",
666
763
                         differ.to_file.getvalue())
681
778
             ' \@\@\n-old\n\+new\n\n')
682
779
 
683
780
    def test_diff_kind_change(self):
684
 
        self.requireFeature(tests.SymlinkFeature)
 
781
        self.requireFeature(features.SymlinkFeature)
685
782
        self.build_tree_contents([('old-tree/olddir/',),
686
783
                                  ('old-tree/olddir/oldfile', 'old\n')])
687
784
        self.old_tree.add('olddir')
716
813
 
717
814
    def test_register_diff(self):
718
815
        self.create_old_new()
719
 
        old_diff_factories = DiffTree.diff_factories
720
 
        DiffTree.diff_factories=old_diff_factories[:]
721
 
        DiffTree.diff_factories.insert(0, DiffWasIs.from_diff_tree)
 
816
        old_diff_factories = diff.DiffTree.diff_factories
 
817
        diff.DiffTree.diff_factories=old_diff_factories[:]
 
818
        diff.DiffTree.diff_factories.insert(0, DiffWasIs.from_diff_tree)
722
819
        try:
723
 
            differ = DiffTree(self.old_tree, self.new_tree, StringIO())
 
820
            differ = diff.DiffTree(self.old_tree, self.new_tree, StringIO())
724
821
        finally:
725
 
            DiffTree.diff_factories = old_diff_factories
 
822
            diff.DiffTree.diff_factories = old_diff_factories
726
823
        differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
727
824
        self.assertNotContainsRe(
728
825
            differ.to_file.getvalue(),
733
830
 
734
831
    def test_extra_factories(self):
735
832
        self.create_old_new()
736
 
        differ = DiffTree(self.old_tree, self.new_tree, StringIO(),
737
 
                            extra_factories=[DiffWasIs.from_diff_tree])
 
833
        differ = diff.DiffTree(self.old_tree, self.new_tree, StringIO(),
 
834
                               extra_factories=[DiffWasIs.from_diff_tree])
738
835
        differ.diff('file-id', 'olddir/oldfile', 'newdir/newfile')
739
836
        self.assertNotContainsRe(
740
837
            differ.to_file.getvalue(),
753
850
            '.*a-file(.|\n)*b-file')
754
851
 
755
852
 
756
 
class TestPatienceDiffLib(TestCase):
 
853
class TestPatienceDiffLib(tests.TestCase):
757
854
 
758
855
    def setUp(self):
759
856
        super(TestPatienceDiffLib, self).setUp()
760
 
        self._unique_lcs = bzrlib._patiencediff_py.unique_lcs_py
761
 
        self._recurse_matches = bzrlib._patiencediff_py.recurse_matches_py
 
857
        self._unique_lcs = _patiencediff_py.unique_lcs_py
 
858
        self._recurse_matches = _patiencediff_py.recurse_matches_py
762
859
        self._PatienceSequenceMatcher = \
763
 
            bzrlib._patiencediff_py.PatienceSequenceMatcher_py
 
860
            _patiencediff_py.PatienceSequenceMatcher_py
764
861
 
765
862
    def test_diff_unicode_string(self):
766
863
        a = ''.join([unichr(i) for i in range(4000, 4500, 3)])
1073
1170
                 'how are you today?\n']
1074
1171
        txt_b = ['hello there\n',
1075
1172
                 'how are you today?\n']
1076
 
        unified_diff = bzrlib.patiencediff.unified_diff
 
1173
        unified_diff = patiencediff.unified_diff
1077
1174
        psm = self._PatienceSequenceMatcher
1078
1175
        self.assertEquals(['--- \n',
1079
1176
                           '+++ \n',
1127
1224
                 'how are you today?\n']
1128
1225
        txt_b = ['hello there\n',
1129
1226
                 'how are you today?\n']
1130
 
        unified_diff = bzrlib.patiencediff.unified_diff
 
1227
        unified_diff = patiencediff.unified_diff
1131
1228
        psm = self._PatienceSequenceMatcher
1132
1229
        self.assertEquals(['--- a\t2008-08-08\n',
1133
1230
                           '+++ b\t2008-09-09\n',
1145
1242
 
1146
1243
class TestPatienceDiffLib_c(TestPatienceDiffLib):
1147
1244
 
1148
 
    _test_needs_features = [compiled_patiencediff_feature]
 
1245
    _test_needs_features = [features.compiled_patiencediff_feature]
1149
1246
 
1150
1247
    def setUp(self):
1151
1248
        super(TestPatienceDiffLib_c, self).setUp()
1152
 
        import bzrlib._patiencediff_c
1153
 
        self._unique_lcs = bzrlib._patiencediff_c.unique_lcs_c
1154
 
        self._recurse_matches = bzrlib._patiencediff_c.recurse_matches_c
 
1249
        from bzrlib import _patiencediff_c
 
1250
        self._unique_lcs = _patiencediff_c.unique_lcs_c
 
1251
        self._recurse_matches = _patiencediff_c.recurse_matches_c
1155
1252
        self._PatienceSequenceMatcher = \
1156
 
            bzrlib._patiencediff_c.PatienceSequenceMatcher_c
 
1253
            _patiencediff_c.PatienceSequenceMatcher_c
1157
1254
 
1158
1255
    def test_unhashable(self):
1159
1256
        """We should get a proper exception here."""
1169
1266
                                         None, ['valid'], ['valid', []])
1170
1267
 
1171
1268
 
1172
 
class TestPatienceDiffLibFiles(TestCaseInTempDir):
 
1269
class TestPatienceDiffLibFiles(tests.TestCaseInTempDir):
1173
1270
 
1174
1271
    def setUp(self):
1175
1272
        super(TestPatienceDiffLibFiles, self).setUp()
1176
1273
        self._PatienceSequenceMatcher = \
1177
 
            bzrlib._patiencediff_py.PatienceSequenceMatcher_py
 
1274
            _patiencediff_py.PatienceSequenceMatcher_py
1178
1275
 
1179
1276
    def test_patience_unified_diff_files(self):
1180
1277
        txt_a = ['hello there\n',
1182
1279
                 'how are you today?\n']
1183
1280
        txt_b = ['hello there\n',
1184
1281
                 'how are you today?\n']
1185
 
        open('a1', 'wb').writelines(txt_a)
1186
 
        open('b1', 'wb').writelines(txt_b)
 
1282
        with open('a1', 'wb') as f: f.writelines(txt_a)
 
1283
        with open('b1', 'wb') as f: f.writelines(txt_b)
1187
1284
 
1188
 
        unified_diff_files = bzrlib.patiencediff.unified_diff_files
 
1285
        unified_diff_files = patiencediff.unified_diff_files
1189
1286
        psm = self._PatienceSequenceMatcher
1190
1287
        self.assertEquals(['--- a1\n',
1191
1288
                           '+++ b1\n',
1199
1296
 
1200
1297
        txt_a = map(lambda x: x+'\n', 'abcdefghijklmnop')
1201
1298
        txt_b = map(lambda x: x+'\n', 'abcdefxydefghijklmnop')
1202
 
        open('a2', 'wb').writelines(txt_a)
1203
 
        open('b2', 'wb').writelines(txt_b)
 
1299
        with open('a2', 'wb') as f: f.writelines(txt_a)
 
1300
        with open('b2', 'wb') as f: f.writelines(txt_b)
1204
1301
 
1205
1302
        # This is the result with LongestCommonSubstring matching
1206
1303
        self.assertEquals(['--- a2\n',
1241
1338
 
1242
1339
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
1243
1340
 
1244
 
    _test_needs_features = [compiled_patiencediff_feature]
 
1341
    _test_needs_features = [features.compiled_patiencediff_feature]
1245
1342
 
1246
1343
    def setUp(self):
1247
1344
        super(TestPatienceDiffLibFiles_c, self).setUp()
1248
 
        import bzrlib._patiencediff_c
 
1345
        from bzrlib import _patiencediff_c
1249
1346
        self._PatienceSequenceMatcher = \
1250
 
            bzrlib._patiencediff_c.PatienceSequenceMatcher_c
1251
 
 
1252
 
 
1253
 
class TestUsingCompiledIfAvailable(TestCase):
 
1347
            _patiencediff_c.PatienceSequenceMatcher_c
 
1348
 
 
1349
 
 
1350
class TestUsingCompiledIfAvailable(tests.TestCase):
1254
1351
 
1255
1352
    def test_PatienceSequenceMatcher(self):
1256
 
        if compiled_patiencediff_feature.available():
 
1353
        if features.compiled_patiencediff_feature.available():
1257
1354
            from bzrlib._patiencediff_c import PatienceSequenceMatcher_c
1258
1355
            self.assertIs(PatienceSequenceMatcher_c,
1259
 
                          bzrlib.patiencediff.PatienceSequenceMatcher)
 
1356
                          patiencediff.PatienceSequenceMatcher)
1260
1357
        else:
1261
1358
            from bzrlib._patiencediff_py import PatienceSequenceMatcher_py
1262
1359
            self.assertIs(PatienceSequenceMatcher_py,
1263
 
                          bzrlib.patiencediff.PatienceSequenceMatcher)
 
1360
                          patiencediff.PatienceSequenceMatcher)
1264
1361
 
1265
1362
    def test_unique_lcs(self):
1266
 
        if compiled_patiencediff_feature.available():
 
1363
        if features.compiled_patiencediff_feature.available():
1267
1364
            from bzrlib._patiencediff_c import unique_lcs_c
1268
1365
            self.assertIs(unique_lcs_c,
1269
 
                          bzrlib.patiencediff.unique_lcs)
 
1366
                          patiencediff.unique_lcs)
1270
1367
        else:
1271
1368
            from bzrlib._patiencediff_py import unique_lcs_py
1272
1369
            self.assertIs(unique_lcs_py,
1273
 
                          bzrlib.patiencediff.unique_lcs)
 
1370
                          patiencediff.unique_lcs)
1274
1371
 
1275
1372
    def test_recurse_matches(self):
1276
 
        if compiled_patiencediff_feature.available():
 
1373
        if features.compiled_patiencediff_feature.available():
1277
1374
            from bzrlib._patiencediff_c import recurse_matches_c
1278
1375
            self.assertIs(recurse_matches_c,
1279
 
                          bzrlib.patiencediff.recurse_matches)
 
1376
                          patiencediff.recurse_matches)
1280
1377
        else:
1281
1378
            from bzrlib._patiencediff_py import recurse_matches_py
1282
1379
            self.assertIs(recurse_matches_py,
1283
 
                          bzrlib.patiencediff.recurse_matches)
1284
 
 
1285
 
 
1286
 
class TestDiffFromTool(TestCaseWithTransport):
 
1380
                          patiencediff.recurse_matches)
 
1381
 
 
1382
 
 
1383
class TestDiffFromTool(tests.TestCaseWithTransport):
1287
1384
 
1288
1385
    def test_from_string(self):
1289
 
        diff_obj = DiffFromTool.from_string('diff', None, None, None)
 
1386
        diff_obj = diff.DiffFromTool.from_string('diff', None, None, None)
1290
1387
        self.addCleanup(diff_obj.finish)
1291
1388
        self.assertEqual(['diff', '@old_path', '@new_path'],
1292
1389
            diff_obj.command_template)
1293
1390
 
1294
1391
    def test_from_string_u5(self):
1295
 
        diff_obj = DiffFromTool.from_string('diff -u\\ 5', None, None, None)
 
1392
        diff_obj = diff.DiffFromTool.from_string('diff "-u 5"',
 
1393
                                                 None, None, None)
1296
1394
        self.addCleanup(diff_obj.finish)
1297
1395
        self.assertEqual(['diff', '-u 5', '@old_path', '@new_path'],
1298
1396
                         diff_obj.command_template)
1299
1397
        self.assertEqual(['diff', '-u 5', 'old-path', 'new-path'],
1300
1398
                         diff_obj._get_command('old-path', 'new-path'))
1301
1399
 
 
1400
    def test_from_string_path_with_backslashes(self):
 
1401
        self.requireFeature(features.backslashdir_feature)
 
1402
        tool = 'C:\\Tools\\Diff.exe'
 
1403
        diff_obj = diff.DiffFromTool.from_string(tool, None, None, None)
 
1404
        self.addCleanup(diff_obj.finish)
 
1405
        self.assertEqual(['C:\\Tools\\Diff.exe', '@old_path', '@new_path'],
 
1406
                         diff_obj.command_template)
 
1407
        self.assertEqual(['C:\\Tools\\Diff.exe', 'old-path', 'new-path'],
 
1408
                         diff_obj._get_command('old-path', 'new-path'))
 
1409
 
1302
1410
    def test_execute(self):
1303
1411
        output = StringIO()
1304
 
        diff_obj = DiffFromTool(['python', '-c',
1305
 
                                 'print "@old_path @new_path"'],
1306
 
                                None, None, output)
 
1412
        diff_obj = diff.DiffFromTool(['python', '-c',
 
1413
                                      'print "@old_path @new_path"'],
 
1414
                                     None, None, output)
1307
1415
        self.addCleanup(diff_obj.finish)
1308
1416
        diff_obj._execute('old', 'new')
1309
1417
        self.assertEqual(output.getvalue().rstrip(), 'old new')
1310
1418
 
1311
 
    def test_excute_missing(self):
1312
 
        diff_obj = DiffFromTool(['a-tool-which-is-unlikely-to-exist'],
1313
 
                                None, None, None)
 
1419
    def test_execute_missing(self):
 
1420
        diff_obj = diff.DiffFromTool(['a-tool-which-is-unlikely-to-exist'],
 
1421
                                     None, None, None)
1314
1422
        self.addCleanup(diff_obj.finish)
1315
 
        e = self.assertRaises(ExecutableMissing, diff_obj._execute, 'old',
1316
 
                              'new')
 
1423
        e = self.assertRaises(errors.ExecutableMissing, diff_obj._execute,
 
1424
                              'old', 'new')
1317
1425
        self.assertEqual('a-tool-which-is-unlikely-to-exist could not be found'
1318
1426
                         ' on this machine', str(e))
1319
1427
 
1320
1428
    def test_prepare_files_creates_paths_readable_by_windows_tool(self):
1321
 
        self.requireFeature(AttribFeature)
 
1429
        self.requireFeature(features.AttribFeature)
1322
1430
        output = StringIO()
1323
1431
        tree = self.make_branch_and_tree('tree')
1324
1432
        self.build_tree_contents([('tree/file', 'content')])
1329
1437
        basis_tree = tree.basis_tree()
1330
1438
        basis_tree.lock_read()
1331
1439
        self.addCleanup(basis_tree.unlock)
1332
 
        diff_obj = DiffFromTool(['python', '-c',
1333
 
                                 'print "@old_path @new_path"'],
1334
 
                                basis_tree, tree, output)
 
1440
        diff_obj = diff.DiffFromTool(['python', '-c',
 
1441
                                      'print "@old_path @new_path"'],
 
1442
                                     basis_tree, tree, output)
1335
1443
        diff_obj._prepare_files('file-id', 'file', 'file')
1336
1444
        # The old content should be readonly
1337
1445
        self.assertReadableByAttrib(diff_obj._root, 'old\\file',
1354
1462
        self.build_tree_contents([('tree/oldname2', 'oldcontent2')])
1355
1463
        tree.add('oldname', 'file-id')
1356
1464
        tree.add('oldname2', 'file2-id')
1357
 
        tree.commit('old tree', timestamp=0)
 
1465
        # Earliest allowable date on FAT32 filesystems is 1980-01-01
 
1466
        tree.commit('old tree', timestamp=315532800)
1358
1467
        tree.rename_one('oldname', 'newname')
1359
1468
        tree.rename_one('oldname2', 'newname2')
1360
1469
        self.build_tree_contents([('tree/newname', 'newcontent')])
1364
1473
        self.addCleanup(old_tree.unlock)
1365
1474
        tree.lock_read()
1366
1475
        self.addCleanup(tree.unlock)
1367
 
        diff_obj = DiffFromTool(['python', '-c',
1368
 
                                 'print "@old_path @new_path"'],
1369
 
                                old_tree, tree, output)
 
1476
        diff_obj = diff.DiffFromTool(['python', '-c',
 
1477
                                      'print "@old_path @new_path"'],
 
1478
                                     old_tree, tree, output)
1370
1479
        self.addCleanup(diff_obj.finish)
1371
1480
        self.assertContainsRe(diff_obj._root, 'bzr-diff-[^/]*')
1372
1481
        old_path, new_path = diff_obj._prepare_files('file-id', 'oldname',
1373
1482
                                                     'newname')
1374
1483
        self.assertContainsRe(old_path, 'old/oldname$')
1375
 
        self.assertEqual(0, os.stat(old_path).st_mtime)
 
1484
        self.assertEqual(315532800, os.stat(old_path).st_mtime)
1376
1485
        self.assertContainsRe(new_path, 'tree/newname$')
1377
1486
        self.assertFileEqual('oldcontent', old_path)
1378
1487
        self.assertFileEqual('newcontent', new_path)
1382
1491
        diff_obj._prepare_files('file2-id', 'oldname2', 'newname2')
1383
1492
 
1384
1493
 
1385
 
class TestGetTreesAndBranchesToDiff(TestCaseWithTransport):
 
1494
class TestDiffFromToolEncodedFilename(tests.TestCaseWithTransport):
 
1495
 
 
1496
    def test_encodable_filename(self):
 
1497
        # Just checks file path for external diff tool.
 
1498
        # We cannot change CPython's internal encoding used by os.exec*.
 
1499
        diffobj = diff.DiffFromTool(['dummy', '@old_path', '@new_path'],
 
1500
                                    None, None, None)
 
1501
        for _, scenario in EncodingAdapter.encoding_scenarios:
 
1502
            encoding = scenario['encoding']
 
1503
            dirname  = scenario['info']['directory']
 
1504
            filename = scenario['info']['filename']
 
1505
 
 
1506
            self.overrideAttr(diffobj, '_fenc', lambda: encoding)
 
1507
            relpath = dirname + u'/' + filename
 
1508
            fullpath = diffobj._safe_filename('safe', relpath)
 
1509
            self.assertEqual(
 
1510
                    fullpath,
 
1511
                    fullpath.encode(encoding).decode(encoding)
 
1512
                    )
 
1513
            self.assert_(fullpath.startswith(diffobj._root + '/safe'))
 
1514
 
 
1515
    def test_unencodable_filename(self):
 
1516
        diffobj = diff.DiffFromTool(['dummy', '@old_path', '@new_path'],
 
1517
                                    None, None, None)
 
1518
        for _, scenario in EncodingAdapter.encoding_scenarios:
 
1519
            encoding = scenario['encoding']
 
1520
            dirname  = scenario['info']['directory']
 
1521
            filename = scenario['info']['filename']
 
1522
 
 
1523
            if encoding == 'iso-8859-1':
 
1524
                encoding = 'iso-8859-2'
 
1525
            else:
 
1526
                encoding = 'iso-8859-1'
 
1527
 
 
1528
            self.overrideAttr(diffobj, '_fenc', lambda: encoding)
 
1529
            relpath = dirname + u'/' + filename
 
1530
            fullpath = diffobj._safe_filename('safe', relpath)
 
1531
            self.assertEqual(
 
1532
                    fullpath,
 
1533
                    fullpath.encode(encoding).decode(encoding)
 
1534
                    )
 
1535
            self.assert_(fullpath.startswith(diffobj._root + '/safe'))
 
1536
 
 
1537
 
 
1538
class TestGetTreesAndBranchesToDiffLocked(tests.TestCaseWithTransport):
 
1539
 
 
1540
    def call_gtabtd(self, path_list, revision_specs, old_url, new_url):
 
1541
        """Call get_trees_and_branches_to_diff_locked."""
 
1542
        return diff.get_trees_and_branches_to_diff_locked(
 
1543
            path_list, revision_specs, old_url, new_url, self.addCleanup)
1386
1544
 
1387
1545
    def test_basic(self):
1388
1546
        tree = self.make_branch_and_tree('tree')
1389
1547
        (old_tree, new_tree,
1390
1548
         old_branch, new_branch,
1391
 
         specific_files, extra_trees) = \
1392
 
            get_trees_and_branches_to_diff(['tree'], None, None, None)
 
1549
         specific_files, extra_trees) = self.call_gtabtd(
 
1550
             ['tree'], None, None, None)
1393
1551
 
1394
 
        self.assertIsInstance(old_tree, RevisionTree)
1395
 
        #print dir (old_tree)
1396
 
        self.assertEqual(_mod_revision.NULL_REVISION, old_tree.get_revision_id())
 
1552
        self.assertIsInstance(old_tree, revisiontree.RevisionTree)
 
1553
        self.assertEqual(_mod_revision.NULL_REVISION,
 
1554
                         old_tree.get_revision_id())
1397
1555
        self.assertEqual(tree.basedir, new_tree.basedir)
1398
1556
        self.assertEqual(tree.branch.base, old_branch.base)
1399
1557
        self.assertEqual(tree.branch.base, new_branch.base)
1408
1566
        self.build_tree_contents([('tree/file', 'newcontent')])
1409
1567
        tree.commit('new tree', timestamp=0, rev_id="new-id")
1410
1568
 
1411
 
        revisions = [RevisionSpec.from_string('1'),
1412
 
                     RevisionSpec.from_string('2')]
 
1569
        revisions = [revisionspec.RevisionSpec.from_string('1'),
 
1570
                     revisionspec.RevisionSpec.from_string('2')]
1413
1571
        (old_tree, new_tree,
1414
1572
         old_branch, new_branch,
1415
 
         specific_files, extra_trees) = \
1416
 
            get_trees_and_branches_to_diff(['tree'], revisions, None, None)
 
1573
         specific_files, extra_trees) = self.call_gtabtd(
 
1574
            ['tree'], revisions, None, None)
1417
1575
 
1418
 
        self.assertIsInstance(old_tree, RevisionTree)
 
1576
        self.assertIsInstance(old_tree, revisiontree.RevisionTree)
1419
1577
        self.assertEqual("old-id", old_tree.get_revision_id())
1420
 
        self.assertIsInstance(new_tree, RevisionTree)
 
1578
        self.assertIsInstance(new_tree, revisiontree.RevisionTree)
1421
1579
        self.assertEqual("new-id", new_tree.get_revision_id())
1422
1580
        self.assertEqual(tree.branch.base, old_branch.base)
1423
1581
        self.assertEqual(tree.branch.base, new_branch.base)