~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: wang
  • Date: 2006-10-29 13:41:32 UTC
  • mto: (2104.4.1 wang_65714)
  • mto: This revision was merged to the branch mainline in revision 2109.
  • Revision ID: wang@ubuntu-20061029134132-3d7f4216f20c4aef
Replace python's difflib by patiencediff because the worst case 
performance is cubic for difflib and people commiting large data 
files are often hurt by this. The worst case performance of patience is 
quadratic. Fix bug 65714.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 by Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
 
# it under the terms of the GNU General Public License version 2 as published by
5
 
# the Free Software Foundation.
 
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.
6
7
#
7
8
# This program is distributed in the hope that it will be useful,
8
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
16
 
16
17
"""Tests for the test framework."""
17
18
 
 
19
import cStringIO
18
20
import os
19
21
from StringIO import StringIO
20
22
import sys
22
24
import unittest
23
25
import warnings
24
26
 
25
 
from bzrlib import osutils
26
27
import bzrlib
 
28
from bzrlib import (
 
29
    bzrdir,
 
30
    memorytree,
 
31
    osutils,
 
32
    repository,
 
33
    )
27
34
from bzrlib.progress import _BaseProgressBar
28
35
from bzrlib.tests import (
29
36
                          ChrootedTestCase,
30
37
                          TestCase,
31
38
                          TestCaseInTempDir,
 
39
                          TestCaseWithMemoryTransport,
32
40
                          TestCaseWithTransport,
33
41
                          TestSkipped,
34
42
                          TestSuite,
35
43
                          TextTestRunner,
36
44
                          )
 
45
from bzrlib.tests.test_sftp_transport import TestCaseWithSFTPServer
37
46
from bzrlib.tests.TestUtil import _load_module_by_name
38
47
import bzrlib.errors as errors
 
48
from bzrlib import symbol_versioning
 
49
from bzrlib.symbol_versioning import zero_ten, zero_eleven
39
50
from bzrlib.trace import note
 
51
from bzrlib.transport.memory import MemoryServer, MemoryTransport
 
52
from bzrlib.version import _get_bzr_source_tree
40
53
 
41
54
 
42
55
class SelftestTests(TestCase):
57
70
        """Test logs are captured when a test fails."""
58
71
        self.log('a test message')
59
72
        self._log_file.flush()
60
 
        self.assertContainsRe(self._get_log(), 'a test message\n')
 
73
        self.assertContainsRe(self._get_log(keep_log_file=True),
 
74
                              'a test message\n')
61
75
 
62
76
 
63
77
class TestTreeShape(TestCaseInTempDir):
417
431
        self.assertEqual(tests[1].transport_server, server1)
418
432
        self.assertEqual(tests[1].transport_readonly_server, server2)
419
433
 
 
434
 
 
435
class TestTestCaseInTempDir(TestCaseInTempDir):
 
436
 
 
437
    def test_home_is_not_working(self):
 
438
        self.assertNotEqual(self.test_dir, self.test_home_dir)
 
439
        cwd = osutils.getcwd()
 
440
        self.assertEqual(self.test_dir, cwd)
 
441
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
 
442
 
 
443
 
 
444
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
 
445
 
 
446
    def test_home_is_non_existant_dir_under_root(self):
 
447
        """The test_home_dir for TestCaseWithMemoryTransport is missing.
 
448
 
 
449
        This is because TestCaseWithMemoryTransport is for tests that do not
 
450
        need any disk resources: they should be hooked into bzrlib in such a 
 
451
        way that no global settings are being changed by the test (only a 
 
452
        few tests should need to do that), and having a missing dir as home is
 
453
        an effective way to ensure that this is the case.
 
454
        """
 
455
        self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
 
456
            self.test_home_dir)
 
457
        self.assertEqual(self.test_home_dir, os.environ['HOME'])
 
458
        
 
459
    def test_cwd_is_TEST_ROOT(self):
 
460
        self.assertEqual(self.test_dir, self.TEST_ROOT)
 
461
        cwd = osutils.getcwd()
 
462
        self.assertEqual(self.test_dir, cwd)
 
463
 
 
464
    def test_make_branch_and_memory_tree(self):
 
465
        """In TestCaseWithMemoryTransport we should not make the branch on disk.
 
466
 
 
467
        This is hard to comprehensively robustly test, so we settle for making
 
468
        a branch and checking no directory was created at its relpath.
 
469
        """
 
470
        tree = self.make_branch_and_memory_tree('dir')
 
471
        self.failIfExists('dir')
 
472
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
473
 
 
474
    def test_make_branch_and_memory_tree_with_format(self):
 
475
        """make_branch_and_memory_tree should accept a format option."""
 
476
        format = bzrdir.BzrDirMetaFormat1()
 
477
        format.repository_format = repository.RepositoryFormat7()
 
478
        tree = self.make_branch_and_memory_tree('dir', format=format)
 
479
        self.failIfExists('dir')
 
480
        self.assertIsInstance(tree, memorytree.MemoryTree)
 
481
        self.assertEqual(format.repository_format.__class__,
 
482
            tree.branch.repository._format.__class__)
 
483
 
 
484
 
420
485
class TestTestCaseWithTransport(TestCaseWithTransport):
421
486
    """Tests for the convenience functions TestCaseWithTransport introduces."""
422
487
 
438
503
 
439
504
    def test_get_readonly_url_http(self):
440
505
        from bzrlib.transport import get_transport
441
 
        from bzrlib.transport.local import LocalRelpathServer
 
506
        from bzrlib.transport.local import LocalURLServer
442
507
        from bzrlib.transport.http import HttpServer, HttpTransportBase
443
 
        self.transport_server = LocalRelpathServer
 
508
        self.transport_server = LocalURLServer
444
509
        self.transport_readonly_server = HttpServer
445
510
        # calling get_readonly_transport() gives us a HTTP server instance.
446
511
        url = self.get_readonly_url()
461
526
        self.assertRaises(AssertionError, self.assertIsDirectory, 'not_here', t)
462
527
 
463
528
 
 
529
class TestTestCaseTransports(TestCaseWithTransport):
 
530
 
 
531
    def setUp(self):
 
532
        super(TestTestCaseTransports, self).setUp()
 
533
        self.transport_server = MemoryServer
 
534
 
 
535
    def test_make_bzrdir_preserves_transport(self):
 
536
        t = self.get_transport()
 
537
        result_bzrdir = self.make_bzrdir('subdir')
 
538
        self.assertIsInstance(result_bzrdir.transport, 
 
539
                              MemoryTransport)
 
540
        # should not be on disk, should only be in memory
 
541
        self.failIfExists('subdir')
 
542
 
 
543
 
464
544
class TestChrootedTest(ChrootedTestCase):
465
545
 
466
546
    def test_root_is_root(self):
576
656
        # cheat. Yes, wash thy mouth out with soap.
577
657
        self._benchtime = None
578
658
 
 
659
    def test_assigned_benchmark_file_stores_date(self):
 
660
        output = StringIO()
 
661
        result = bzrlib.tests._MyResult(self._log_file,
 
662
                                        descriptions=0,
 
663
                                        verbosity=1,
 
664
                                        bench_history=output
 
665
                                        )
 
666
        output_string = output.getvalue()
 
667
        # if you are wondering about the regexp please read the comment in
 
668
        # test_bench_history (bzrlib.tests.test_selftest.TestRunner)
 
669
        # XXX: what comment?  -- Andrew Bennetts
 
670
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
671
 
 
672
    def test_benchhistory_records_test_times(self):
 
673
        result_stream = StringIO()
 
674
        result = bzrlib.tests._MyResult(
 
675
            self._log_file,
 
676
            descriptions=0,
 
677
            verbosity=1,
 
678
            bench_history=result_stream
 
679
            )
 
680
 
 
681
        # we want profile a call and check that its test duration is recorded
 
682
        # make a new test instance that when run will generate a benchmark
 
683
        example_test_case = TestTestResult("_time_hello_world_encoding")
 
684
        # execute the test, which should succeed and record times
 
685
        example_test_case.run(result)
 
686
        lines = result_stream.getvalue().splitlines()
 
687
        self.assertEqual(2, len(lines))
 
688
        self.assertContainsRe(lines[1],
 
689
            " *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
 
690
            "._time_hello_world_encoding")
 
691
 
579
692
    def _time_hello_world_encoding(self):
580
693
        """Profile two sleep calls
581
694
        
671
784
        result = self.run_test_runner(runner, test)
672
785
        self.assertTrue(result.wasSuccessful())
673
786
 
 
787
    def test_bench_history(self):
 
788
        # tests that the running the benchmark produces a history file
 
789
        # containing a timestamp and the revision id of the bzrlib source which
 
790
        # was tested.
 
791
        workingtree = _get_bzr_source_tree()
 
792
        test = TestRunner('dummy_test')
 
793
        output = StringIO()
 
794
        runner = TextTestRunner(stream=self._log_file, bench_history=output)
 
795
        result = self.run_test_runner(runner, test)
 
796
        output_string = output.getvalue()
 
797
        self.assertContainsRe(output_string, "--date [0-9.]+")
 
798
        if workingtree is not None:
 
799
            revision_id = workingtree.get_parent_ids()[0]
 
800
            self.assertEndsWith(output_string.rstrip(), revision_id)
 
801
 
 
802
    def test_success_log_deleted(self):
 
803
        """Successful tests have their log deleted"""
 
804
 
 
805
        class LogTester(TestCase):
 
806
 
 
807
            def test_success(self):
 
808
                self.log('this will be removed\n')
 
809
 
 
810
        sio = cStringIO.StringIO()
 
811
        runner = TextTestRunner(stream=sio)
 
812
        test = LogTester('test_success')
 
813
        result = self.run_test_runner(runner, test)
 
814
 
 
815
        log = test._get_log()
 
816
        self.assertEqual("DELETED log file to reduce memory footprint", log)
 
817
        self.assertEqual('', test._log_contents)
 
818
        self.assertIs(None, test._log_file_name)
 
819
 
 
820
    def test_fail_log_kept(self):
 
821
        """Failed tests have their log kept"""
 
822
 
 
823
        class LogTester(TestCase):
 
824
 
 
825
            def test_fail(self):
 
826
                self.log('this will be kept\n')
 
827
                self.fail('this test fails')
 
828
 
 
829
        sio = cStringIO.StringIO()
 
830
        runner = TextTestRunner(stream=sio)
 
831
        test = LogTester('test_fail')
 
832
        result = self.run_test_runner(runner, test)
 
833
 
 
834
        text = sio.getvalue()
 
835
        self.assertContainsRe(text, 'this will be kept')
 
836
        self.assertContainsRe(text, 'this test fails')
 
837
 
 
838
        log = test._get_log()
 
839
        self.assertContainsRe(log, 'this will be kept')
 
840
        self.assertEqual(log, test._log_contents)
 
841
 
 
842
    def test_error_log_kept(self):
 
843
        """Tests with errors have their log kept"""
 
844
 
 
845
        class LogTester(TestCase):
 
846
 
 
847
            def test_error(self):
 
848
                self.log('this will be kept\n')
 
849
                raise ValueError('random exception raised')
 
850
 
 
851
        sio = cStringIO.StringIO()
 
852
        runner = TextTestRunner(stream=sio)
 
853
        test = LogTester('test_error')
 
854
        result = self.run_test_runner(runner, test)
 
855
 
 
856
        text = sio.getvalue()
 
857
        self.assertContainsRe(text, 'this will be kept')
 
858
        self.assertContainsRe(text, 'random exception raised')
 
859
 
 
860
        log = test._get_log()
 
861
        self.assertContainsRe(log, 'this will be kept')
 
862
        self.assertEqual(log, test._log_contents)
 
863
 
674
864
 
675
865
class TestTestCase(TestCase):
676
866
    """Tests that test the core bzrlib TestCase."""
748
938
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
749
939
 
750
940
 
 
941
@symbol_versioning.deprecated_function(zero_eleven)
 
942
def sample_deprecated_function():
 
943
    """A deprecated function to test applyDeprecated with."""
 
944
    return 2
 
945
 
 
946
 
 
947
def sample_undeprecated_function(a_param):
 
948
    """A undeprecated function to test applyDeprecated with."""
 
949
 
 
950
 
 
951
class ApplyDeprecatedHelper(object):
 
952
    """A helper class for ApplyDeprecated tests."""
 
953
 
 
954
    @symbol_versioning.deprecated_method(zero_eleven)
 
955
    def sample_deprecated_method(self, param_one):
 
956
        """A deprecated method for testing with."""
 
957
        return param_one
 
958
 
 
959
    def sample_normal_method(self):
 
960
        """A undeprecated method."""
 
961
 
 
962
    @symbol_versioning.deprecated_method(zero_ten)
 
963
    def sample_nested_deprecation(self):
 
964
        return sample_deprecated_function()
 
965
 
 
966
 
751
967
class TestExtraAssertions(TestCase):
752
968
    """Tests for new test assertions in bzrlib test suite"""
753
969
 
761
977
        self.assertEndsWith('foo', 'oo')
762
978
        self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
763
979
 
 
980
    def test_applyDeprecated_not_deprecated(self):
 
981
        sample_object = ApplyDeprecatedHelper()
 
982
        # calling an undeprecated callable raises an assertion
 
983
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
984
            sample_object.sample_normal_method)
 
985
        self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
 
986
            sample_undeprecated_function, "a param value")
 
987
        # calling a deprecated callable (function or method) with the wrong
 
988
        # expected deprecation fails.
 
989
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
990
            sample_object.sample_deprecated_method, "a param value")
 
991
        self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
 
992
            sample_deprecated_function)
 
993
        # calling a deprecated callable (function or method) with the right
 
994
        # expected deprecation returns the functions result.
 
995
        self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
 
996
            sample_object.sample_deprecated_method, "a param value"))
 
997
        self.assertEqual(2, self.applyDeprecated(zero_eleven,
 
998
            sample_deprecated_function))
 
999
        # calling a nested deprecation with the wrong deprecation version
 
1000
        # fails even if a deeper nested function was deprecated with the 
 
1001
        # supplied version.
 
1002
        self.assertRaises(AssertionError, self.applyDeprecated,
 
1003
            zero_eleven, sample_object.sample_nested_deprecation)
 
1004
        # calling a nested deprecation with the right deprecation value
 
1005
        # returns the calls result.
 
1006
        self.assertEqual(2, self.applyDeprecated(zero_ten,
 
1007
            sample_object.sample_nested_deprecation))
 
1008
 
 
1009
    def test_callDeprecated(self):
 
1010
        def testfunc(be_deprecated, result=None):
 
1011
            if be_deprecated is True:
 
1012
                symbol_versioning.warn('i am deprecated', DeprecationWarning, 
 
1013
                                       stacklevel=1)
 
1014
            return result
 
1015
        result = self.callDeprecated(['i am deprecated'], testfunc, True)
 
1016
        self.assertIs(None, result)
 
1017
        result = self.callDeprecated([], testfunc, False, 'result')
 
1018
        self.assertEqual('result', result)
 
1019
        self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
 
1020
        self.callDeprecated([], testfunc, be_deprecated=False)
 
1021
 
764
1022
 
765
1023
class TestConvenienceMakers(TestCaseWithTransport):
766
1024
    """Test for the make_* convenience functions."""
774
1032
        self.assertIsInstance(bzrlib.bzrdir.BzrDir.open('b')._format,
775
1033
                              bzrlib.bzrdir.BzrDirFormat6)
776
1034
 
 
1035
    def test_make_branch_and_memory_tree(self):
 
1036
        # we should be able to get a new branch and a mutable tree from
 
1037
        # TestCaseWithTransport
 
1038
        tree = self.make_branch_and_memory_tree('a')
 
1039
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
 
1040
 
 
1041
 
 
1042
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
 
1043
 
 
1044
    def test_make_tree_for_sftp_branch(self):
 
1045
        """Transports backed by local directories create local trees."""
 
1046
 
 
1047
        tree = self.make_branch_and_tree('t1')
 
1048
        base = tree.bzrdir.root_transport.base
 
1049
        self.failIf(base.startswith('sftp'),
 
1050
                'base %r is on sftp but should be local' % base)
 
1051
        self.assertEquals(tree.bzrdir.root_transport,
 
1052
                tree.branch.bzrdir.root_transport)
 
1053
        self.assertEquals(tree.bzrdir.root_transport,
 
1054
                tree.branch.repository.bzrdir.root_transport)
 
1055
 
777
1056
 
778
1057
class TestSelftest(TestCase):
779
1058
    """Tests of bzrlib.tests.selftest."""