~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_diff.py

  • Committer: Jelmer Vernooij
  • Date: 2012-01-24 13:14:06 UTC
  • mto: (6445.4.5 nested-trees-spec)
  • mto: This revision was merged to the branch mainline in revision 6518.
  • Revision ID: jelmer@samba.org-20120124131406-wedftkorbpv37bm0
Import nested tree doc from devnotes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
33
33
    transform,
34
34
    )
35
35
from bzrlib.symbol_versioning import deprecated_in
36
 
from bzrlib.tests import features
 
36
from bzrlib.tests import features, EncodingAdapter
37
37
from bzrlib.tests.blackbox.test_diff import subst_dates
38
 
 
39
 
 
40
 
class _AttribFeature(tests.Feature):
41
 
 
42
 
    def _probe(self):
43
 
        if (sys.platform not in ('cygwin', 'win32')):
44
 
            return False
45
 
        try:
46
 
            proc = subprocess.Popen(['attrib', '.'], stdout=subprocess.PIPE)
47
 
        except OSError, e:
48
 
            return False
49
 
        return (0 == proc.wait())
50
 
 
51
 
    def feature_name(self):
52
 
        return 'attrib Windows command-line tool'
53
 
 
54
 
AttribFeature = _AttribFeature()
55
 
 
56
 
 
57
 
compiled_patiencediff_feature = tests.ModuleAvailableFeature(
58
 
                                    'bzrlib._patiencediff_c')
 
38
from bzrlib.tests import (
 
39
    features,
 
40
    )
59
41
 
60
42
 
61
43
def udiff_lines(old, new, allow_binary=False):
144
126
        self.check_patch(lines)
145
127
 
146
128
    def test_external_diff_binary_lang_c(self):
147
 
        old_env = {}
148
129
        for lang in ('LANG', 'LC_ALL', 'LANGUAGE'):
149
 
            old_env[lang] = osutils.set_or_unset_env(lang, 'C')
150
 
        try:
151
 
            lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
152
 
            # Older versions of diffutils say "Binary files", newer
153
 
            # versions just say "Files".
154
 
            self.assertContainsRe(lines[0],
155
 
                                  '(Binary f|F)iles old and new differ\n')
156
 
            self.assertEquals(lines[1:], ['\n'])
157
 
        finally:
158
 
            for lang, old_val in old_env.iteritems():
159
 
                osutils.set_or_unset_env(lang, old_val)
 
130
            self.overrideEnv(lang, 'C')
 
131
        lines = external_udiff_lines(['\x00foobar\n'], ['foo\x00bar\n'])
 
132
        # Older versions of diffutils say "Binary files", newer
 
133
        # versions just say "Files".
 
134
        self.assertContainsRe(lines[0], '(Binary f|F)iles old and new differ\n')
 
135
        self.assertEquals(lines[1:], ['\n'])
160
136
 
161
137
    def test_no_external_diff(self):
162
138
        """Check that NoDiff is raised when diff is not available"""
163
 
        # Use os.environ['PATH'] to make sure no 'diff' command is available
164
 
        orig_path = os.environ['PATH']
165
 
        try:
166
 
            os.environ['PATH'] = ''
167
 
            self.assertRaises(errors.NoDiff, diff.external_diff,
168
 
                              'old', ['boo\n'], 'new', ['goo\n'],
169
 
                              StringIO(), diff_opts=['-u'])
170
 
        finally:
171
 
            os.environ['PATH'] = orig_path
 
139
        # Make sure no 'diff' command is available
 
140
        # XXX: Weird, using None instead of '' breaks the test -- vila 20101216
 
141
        self.overrideEnv('PATH', '')
 
142
        self.assertRaises(errors.NoDiff, diff.external_diff,
 
143
                          'old', ['boo\n'], 'new', ['goo\n'],
 
144
                          StringIO(), diff_opts=['-u'])
172
145
 
173
146
    def test_internal_diff_default(self):
174
147
        # Default internal diff encoding is utf8
235
208
        output = StringIO.StringIO()
236
209
        diff.internal_diff(u'old_\xb5', ['old_text\n'],
237
210
                            u'new_\xe5', ['new_text\n'], output)
238
 
        self.failUnless(isinstance(output.getvalue(), str),
 
211
        self.assertIsInstance(output.getvalue(), str,
239
212
            'internal_diff should return bytestrings')
240
213
 
241
214
 
258
231
        self.assertEqual(out.splitlines(True) + ['\n'], lines)
259
232
 
260
233
 
261
 
class TestShowDiffTreesHelper(tests.TestCaseWithTransport):
262
 
    """Has a helper for running show_diff_trees"""
263
 
 
264
 
    def get_diff(self, tree1, tree2, specific_files=None, working_tree=None):
265
 
        output = StringIO()
266
 
        if working_tree is not None:
267
 
            extra_trees = (working_tree,)
268
 
        else:
269
 
            extra_trees = ()
270
 
        diff.show_diff_trees(tree1, tree2, output,
271
 
                             specific_files=specific_files,
272
 
                             extra_trees=extra_trees, old_label='old/',
273
 
                             new_label='new/')
274
 
        return output.getvalue()
275
 
 
276
 
 
277
 
class TestDiffDates(TestShowDiffTreesHelper):
 
234
def get_diff_as_string(tree1, tree2, specific_files=None, working_tree=None):
 
235
    output = StringIO()
 
236
    if working_tree is not None:
 
237
        extra_trees = (working_tree,)
 
238
    else:
 
239
        extra_trees = ()
 
240
    diff.show_diff_trees(tree1, tree2, output,
 
241
        specific_files=specific_files,
 
242
        extra_trees=extra_trees, old_label='old/',
 
243
        new_label='new/')
 
244
    return output.getvalue()
 
245
 
 
246
 
 
247
class TestDiffDates(tests.TestCaseWithTransport):
278
248
 
279
249
    def setUp(self):
280
250
        super(TestDiffDates, self).setUp()
315
285
        os.utime('file1', (1144195200, 1144195200)) # 2006-04-05 00:00:00 UTC
316
286
 
317
287
    def test_diff_rev_tree_working_tree(self):
318
 
        output = self.get_diff(self.wt.basis_tree(), self.wt)
 
288
        output = get_diff_as_string(self.wt.basis_tree(), self.wt)
319
289
        # note that the date for old/file1 is from rev 2 rather than from
320
290
        # the basis revision (rev 4)
321
291
        self.assertEqualDiff(output, '''\
331
301
    def test_diff_rev_tree_rev_tree(self):
332
302
        tree1 = self.b.repository.revision_tree('rev-2')
333
303
        tree2 = self.b.repository.revision_tree('rev-3')
334
 
        output = self.get_diff(tree1, tree2)
 
304
        output = get_diff_as_string(tree1, tree2)
335
305
        self.assertEqualDiff(output, '''\
336
306
=== modified file 'file2'
337
307
--- old/file2\t2006-04-01 00:00:00 +0000
345
315
    def test_diff_add_files(self):
346
316
        tree1 = self.b.repository.revision_tree(_mod_revision.NULL_REVISION)
347
317
        tree2 = self.b.repository.revision_tree('rev-1')
348
 
        output = self.get_diff(tree1, tree2)
 
318
        output = get_diff_as_string(tree1, tree2)
349
319
        # the files have the epoch time stamp for the tree in which
350
320
        # they don't exist.
351
321
        self.assertEqualDiff(output, '''\
366
336
    def test_diff_remove_files(self):
367
337
        tree1 = self.b.repository.revision_tree('rev-3')
368
338
        tree2 = self.b.repository.revision_tree('rev-4')
369
 
        output = self.get_diff(tree1, tree2)
 
339
        output = get_diff_as_string(tree1, tree2)
370
340
        # the file has the epoch time stamp for the tree in which
371
341
        # it doesn't exist.
372
342
        self.assertEqualDiff(output, '''\
383
353
        self.wt.rename_one('file1', 'file1b')
384
354
        old_tree = self.b.repository.revision_tree('rev-1')
385
355
        new_tree = self.b.repository.revision_tree('rev-4')
386
 
        out = self.get_diff(old_tree, new_tree, specific_files=['file1b'],
 
356
        out = get_diff_as_string(old_tree, new_tree, specific_files=['file1b'],
387
357
                            working_tree=self.wt)
388
358
        self.assertContainsRe(out, 'file1\t')
389
359
 
395
365
        self.wt.rename_one('file1', 'dir1/file1')
396
366
        old_tree = self.b.repository.revision_tree('rev-1')
397
367
        new_tree = self.b.repository.revision_tree('rev-4')
398
 
        out = self.get_diff(old_tree, new_tree, specific_files=['dir1'],
 
368
        out = get_diff_as_string(old_tree, new_tree, specific_files=['dir1'],
399
369
                            working_tree=self.wt)
400
370
        self.assertContainsRe(out, 'file1\t')
401
 
        out = self.get_diff(old_tree, new_tree, specific_files=['dir2'],
 
371
        out = get_diff_as_string(old_tree, new_tree, specific_files=['dir2'],
402
372
                            working_tree=self.wt)
403
373
        self.assertNotContainsRe(out, 'file1\t')
404
374
 
405
375
 
406
 
 
407
 
class TestShowDiffTrees(TestShowDiffTreesHelper):
 
376
class TestShowDiffTrees(tests.TestCaseWithTransport):
408
377
    """Direct tests for show_diff_trees"""
409
378
 
410
379
    def test_modified_file(self):
415
384
        tree.commit('one', rev_id='rev-1')
416
385
 
417
386
        self.build_tree_contents([('tree/file', 'new contents\n')])
418
 
        d = self.get_diff(tree.basis_tree(), tree)
 
387
        d = get_diff_as_string(tree.basis_tree(), tree)
419
388
        self.assertContainsRe(d, "=== modified file 'file'\n")
420
389
        self.assertContainsRe(d, '--- old/file\t')
421
390
        self.assertContainsRe(d, '\\+\\+\\+ new/file\t')
432
401
 
433
402
        tree.rename_one('dir', 'other')
434
403
        self.build_tree_contents([('tree/other/file', 'new contents\n')])
435
 
        d = self.get_diff(tree.basis_tree(), tree)
 
404
        d = get_diff_as_string(tree.basis_tree(), tree)
436
405
        self.assertContainsRe(d, "=== renamed directory 'dir' => 'other'\n")
437
406
        self.assertContainsRe(d, "=== modified file 'other/file'\n")
438
407
        # XXX: This is technically incorrect, because it used to be at another
451
420
        tree.commit('one', rev_id='rev-1')
452
421
 
453
422
        tree.rename_one('dir', 'newdir')
454
 
        d = self.get_diff(tree.basis_tree(), tree)
 
423
        d = get_diff_as_string(tree.basis_tree(), tree)
455
424
        # Renaming a directory should be a single "you renamed this dir" even
456
425
        # when there are files inside.
457
426
        self.assertEqual(d, "=== renamed directory 'dir' => 'newdir'\n")
464
433
        tree.commit('one', rev_id='rev-1')
465
434
 
466
435
        tree.rename_one('file', 'newname')
467
 
        d = self.get_diff(tree.basis_tree(), tree)
 
436
        d = get_diff_as_string(tree.basis_tree(), tree)
468
437
        self.assertContainsRe(d, "=== renamed file 'file' => 'newname'\n")
469
438
        # We shouldn't have a --- or +++ line, because there is no content
470
439
        # change
479
448
 
480
449
        tree.rename_one('file', 'newname')
481
450
        self.build_tree_contents([('tree/newname', 'new contents\n')])
482
 
        d = self.get_diff(tree.basis_tree(), tree)
 
451
        d = get_diff_as_string(tree.basis_tree(), tree)
483
452
        self.assertContainsRe(d, "=== renamed file 'file' => 'newname'\n")
484
453
        self.assertContainsRe(d, '--- old/file\t')
485
454
        self.assertContainsRe(d, '\\+\\+\\+ new/newname\t')
509
478
        tree.rename_one('c', 'new-c')
510
479
        tree.rename_one('d', 'new-d')
511
480
 
512
 
        d = self.get_diff(tree.basis_tree(), tree)
 
481
        d = get_diff_as_string(tree.basis_tree(), tree)
513
482
 
514
483
        self.assertContainsRe(d, r"file 'a'.*\(properties changed:"
515
484
                                  ".*\+x to -x.*\)")
527
496
        is a binary file in the diff.
528
497
        """
529
498
        # See https://bugs.launchpad.net/bugs/110092.
530
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
499
        self.requireFeature(features.UnicodeFilenameFeature)
531
500
 
532
501
        # This bug isn't triggered with cStringIO.
533
502
        from StringIO import StringIO
552
521
 
553
522
    def test_unicode_filename(self):
554
523
        """Test when the filename are unicode."""
555
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
524
        self.requireFeature(features.UnicodeFilenameFeature)
556
525
 
557
526
        alpha, omega = u'\u03b1', u'\u03c9'
558
527
        autf8, outf8 = alpha.encode('utf8'), omega.encode('utf8')
573
542
        tree.add(['add_'+alpha], ['file-id'])
574
543
        self.build_tree_contents([('tree/mod_'+alpha, 'contents_mod\n')])
575
544
 
576
 
        d = self.get_diff(tree.basis_tree(), tree)
 
545
        d = get_diff_as_string(tree.basis_tree(), tree)
577
546
        self.assertContainsRe(d,
578
547
                "=== renamed file 'ren_%s' => 'ren_%s'\n"%(autf8, outf8))
579
548
        self.assertContainsRe(d, "=== added file 'add_%s'"%autf8)
584
553
        """Test for bug #382699: unicode filenames on Windows should be shown
585
554
        in user encoding.
586
555
        """
587
 
        self.requireFeature(tests.UnicodeFilenameFeature)
 
556
        self.requireFeature(features.UnicodeFilenameFeature)
588
557
        # The word 'test' in Russian
589
558
        _russian_test = u'\u0422\u0435\u0441\u0442'
590
559
        directory = _russian_test + u'/'
721
690
             ' \@\@\n-old\n\+new\n\n')
722
691
 
723
692
    def test_diff_kind_change(self):
724
 
        self.requireFeature(tests.SymlinkFeature)
 
693
        self.requireFeature(features.SymlinkFeature)
725
694
        self.build_tree_contents([('old-tree/olddir/',),
726
695
                                  ('old-tree/olddir/oldfile', 'old\n')])
727
696
        self.old_tree.add('olddir')
1185
1154
 
1186
1155
class TestPatienceDiffLib_c(TestPatienceDiffLib):
1187
1156
 
1188
 
    _test_needs_features = [compiled_patiencediff_feature]
 
1157
    _test_needs_features = [features.compiled_patiencediff_feature]
1189
1158
 
1190
1159
    def setUp(self):
1191
1160
        super(TestPatienceDiffLib_c, self).setUp()
1281
1250
 
1282
1251
class TestPatienceDiffLibFiles_c(TestPatienceDiffLibFiles):
1283
1252
 
1284
 
    _test_needs_features = [compiled_patiencediff_feature]
 
1253
    _test_needs_features = [features.compiled_patiencediff_feature]
1285
1254
 
1286
1255
    def setUp(self):
1287
1256
        super(TestPatienceDiffLibFiles_c, self).setUp()
1293
1262
class TestUsingCompiledIfAvailable(tests.TestCase):
1294
1263
 
1295
1264
    def test_PatienceSequenceMatcher(self):
1296
 
        if compiled_patiencediff_feature.available():
 
1265
        if features.compiled_patiencediff_feature.available():
1297
1266
            from bzrlib._patiencediff_c import PatienceSequenceMatcher_c
1298
1267
            self.assertIs(PatienceSequenceMatcher_c,
1299
1268
                          patiencediff.PatienceSequenceMatcher)
1303
1272
                          patiencediff.PatienceSequenceMatcher)
1304
1273
 
1305
1274
    def test_unique_lcs(self):
1306
 
        if compiled_patiencediff_feature.available():
 
1275
        if features.compiled_patiencediff_feature.available():
1307
1276
            from bzrlib._patiencediff_c import unique_lcs_c
1308
1277
            self.assertIs(unique_lcs_c,
1309
1278
                          patiencediff.unique_lcs)
1313
1282
                          patiencediff.unique_lcs)
1314
1283
 
1315
1284
    def test_recurse_matches(self):
1316
 
        if compiled_patiencediff_feature.available():
 
1285
        if features.compiled_patiencediff_feature.available():
1317
1286
            from bzrlib._patiencediff_c import recurse_matches_c
1318
1287
            self.assertIs(recurse_matches_c,
1319
1288
                          patiencediff.recurse_matches)
1369
1338
                         ' on this machine', str(e))
1370
1339
 
1371
1340
    def test_prepare_files_creates_paths_readable_by_windows_tool(self):
1372
 
        self.requireFeature(AttribFeature)
 
1341
        self.requireFeature(features.AttribFeature)
1373
1342
        output = StringIO()
1374
1343
        tree = self.make_branch_and_tree('tree')
1375
1344
        self.build_tree_contents([('tree/file', 'content')])
1434
1403
        diff_obj._prepare_files('file2-id', 'oldname2', 'newname2')
1435
1404
 
1436
1405
 
 
1406
class TestDiffFromToolEncodedFilename(tests.TestCaseWithTransport):
 
1407
 
 
1408
    def test_encodable_filename(self):
 
1409
        # Just checks file path for external diff tool.
 
1410
        # We cannot change CPython's internal encoding used by os.exec*.
 
1411
        import sys
 
1412
        diffobj = diff.DiffFromTool(['dummy', '@old_path', '@new_path'],
 
1413
                                    None, None, None)
 
1414
        for _, scenario in EncodingAdapter.encoding_scenarios:
 
1415
            encoding = scenario['encoding']
 
1416
            dirname  = scenario['info']['directory']
 
1417
            filename = scenario['info']['filename']
 
1418
 
 
1419
            self.overrideAttr(diffobj, '_fenc', lambda: encoding)
 
1420
            relpath = dirname + u'/' + filename
 
1421
            fullpath = diffobj._safe_filename('safe', relpath)
 
1422
            self.assertEqual(
 
1423
                    fullpath,
 
1424
                    fullpath.encode(encoding).decode(encoding)
 
1425
                    )
 
1426
            self.assert_(fullpath.startswith(diffobj._root + '/safe'))
 
1427
 
 
1428
    def test_unencodable_filename(self):
 
1429
        import sys
 
1430
        diffobj = diff.DiffFromTool(['dummy', '@old_path', '@new_path'],
 
1431
                                    None, None, None)
 
1432
        for _, scenario in EncodingAdapter.encoding_scenarios:
 
1433
            encoding = scenario['encoding']
 
1434
            dirname  = scenario['info']['directory']
 
1435
            filename = scenario['info']['filename']
 
1436
 
 
1437
            if encoding == 'iso-8859-1':
 
1438
                encoding = 'iso-8859-2'
 
1439
            else:
 
1440
                encoding = 'iso-8859-1'
 
1441
 
 
1442
            self.overrideAttr(diffobj, '_fenc', lambda: encoding)
 
1443
            relpath = dirname + u'/' + filename
 
1444
            fullpath = diffobj._safe_filename('safe', relpath)
 
1445
            self.assertEqual(
 
1446
                    fullpath,
 
1447
                    fullpath.encode(encoding).decode(encoding)
 
1448
                    )
 
1449
            self.assert_(fullpath.startswith(diffobj._root + '/safe'))
 
1450
 
 
1451
 
1437
1452
class TestGetTreesAndBranchesToDiffLocked(tests.TestCaseWithTransport):
1438
1453
 
1439
1454
    def call_gtabtd(self, path_list, revision_specs, old_url, new_url):
1440
 
        """Call get_trees_and_branches_to_diff_locked.  Overridden by
1441
 
        TestGetTreesAndBranchesToDiff.
1442
 
        """
 
1455
        """Call get_trees_and_branches_to_diff_locked."""
1443
1456
        return diff.get_trees_and_branches_to_diff_locked(
1444
1457
            path_list, revision_specs, old_url, new_url, self.addCleanup)
1445
1458
 
1482
1495
        self.assertEqual(tree.branch.base, new_branch.base)
1483
1496
        self.assertIs(None, specific_files)
1484
1497
        self.assertEqual(tree.basedir, extra_trees[0].basedir)
1485
 
 
1486
 
 
1487
 
class TestGetTreesAndBranchesToDiff(TestGetTreesAndBranchesToDiffLocked):
1488
 
    """Apply the tests for get_trees_and_branches_to_diff_locked to the
1489
 
    deprecated get_trees_and_branches_to_diff function.
1490
 
    """
1491
 
 
1492
 
    def call_gtabtd(self, path_list, revision_specs, old_url, new_url):
1493
 
        return self.applyDeprecated(
1494
 
            deprecated_in((2, 2, 0)), diff.get_trees_and_branches_to_diff,
1495
 
            path_list, revision_specs, old_url, new_url)
1496