/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_selftest.py

  • Committer: Martin Pool
  • Date: 2009-08-28 05:00:33 UTC
  • mfrom: (4659 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4660.
  • Revision ID: mbp@sourcefrog.net-20090828050033-blwvnig3gdzbr1iw
merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
687
687
        self.assertEqual(url, t.clone('..').base)
688
688
 
689
689
 
 
690
class TestProfileResult(tests.TestCase):
 
691
 
 
692
    def test_profiles_tests(self):
 
693
        self.requireFeature(test_lsprof.LSProfFeature)
 
694
        terminal = unittest.TestResult()
 
695
        result = tests.ProfileResult(terminal)
 
696
        class Sample(tests.TestCase):
 
697
            def a(self):
 
698
                self.sample_function()
 
699
            def sample_function(self):
 
700
                pass
 
701
        test = Sample("a")
 
702
        test.attrs_to_keep = test.attrs_to_keep + ('_benchcalls',)
 
703
        test.run(result)
 
704
        self.assertLength(1, test._benchcalls)
 
705
        # We must be able to unpack it as the test reporting code wants
 
706
        (_, _, _), stats = test._benchcalls[0]
 
707
        self.assertTrue(callable(stats.pprint))
 
708
 
 
709
 
690
710
class TestTestResult(tests.TestCase):
691
711
 
692
712
    def check_timing(self, test_case, expected_re):
800
820
    def test_known_failure(self):
801
821
        """A KnownFailure being raised should trigger several result actions."""
802
822
        class InstrumentedTestResult(tests.ExtendedTestResult):
803
 
            def done(self): pass
 
823
            def stopTestRun(self): pass
804
824
            def startTests(self): pass
805
825
            def report_test_start(self, test): pass
806
826
            def report_known_failure(self, test, err):
854
874
    def test_add_not_supported(self):
855
875
        """Test the behaviour of invoking addNotSupported."""
856
876
        class InstrumentedTestResult(tests.ExtendedTestResult):
857
 
            def done(self): pass
 
877
            def stopTestRun(self): pass
858
878
            def startTests(self): pass
859
879
            def report_test_start(self, test): pass
860
880
            def report_unsupported(self, test, feature):
898
918
    def test_unavailable_exception(self):
899
919
        """An UnavailableFeature being raised should invoke addNotSupported."""
900
920
        class InstrumentedTestResult(tests.ExtendedTestResult):
901
 
            def done(self): pass
 
921
            def stopTestRun(self): pass
902
922
            def startTests(self): pass
903
923
            def report_test_start(self, test): pass
904
924
            def addNotSupported(self, test, feature):
981
1001
        because of our use of global state.
982
1002
        """
983
1003
        old_root = tests.TestCaseInTempDir.TEST_ROOT
 
1004
        old_leak = tests.TestCase._first_thread_leaker_id
984
1005
        try:
985
1006
            tests.TestCaseInTempDir.TEST_ROOT = None
 
1007
            tests.TestCase._first_thread_leaker_id = None
986
1008
            return testrunner.run(test)
987
1009
        finally:
988
1010
            tests.TestCaseInTempDir.TEST_ROOT = old_root
 
1011
            tests.TestCase._first_thread_leaker_id = old_leak
989
1012
 
990
1013
    def test_known_failure_failed_run(self):
991
1014
        # run a test that generates a known failure which should be printed in
1031
1054
            '\n'
1032
1055
            'OK \\(known_failures=1\\)\n')
1033
1056
 
 
1057
    def test_result_decorator(self):
 
1058
        # decorate results
 
1059
        calls = []
 
1060
        class LoggingDecorator(tests.ForwardingResult):
 
1061
            def startTest(self, test):
 
1062
                tests.ForwardingResult.startTest(self, test)
 
1063
                calls.append('start')
 
1064
        test = unittest.FunctionTestCase(lambda:None)
 
1065
        stream = StringIO()
 
1066
        runner = tests.TextTestRunner(stream=stream,
 
1067
            result_decorators=[LoggingDecorator])
 
1068
        result = self.run_test_runner(runner, test)
 
1069
        self.assertLength(1, calls)
 
1070
 
1034
1071
    def test_skipped_test(self):
1035
1072
        # run a test that is skipped, and check the suite as a whole still
1036
1073
        # succeeds.
1103
1140
        self.assertContainsRe(out.getvalue(),
1104
1141
                r'(?m)^    this test never runs')
1105
1142
 
1106
 
    def test_not_applicable_demo(self):
1107
 
        # just so you can see it in the test output
1108
 
        raise tests.TestNotApplicable('this test is just a demonstation')
1109
 
 
1110
1143
    def test_unsupported_features_listed(self):
1111
1144
        """When unsupported features are encountered they are detailed."""
1112
1145
        class Feature1(tests.Feature):
1261
1294
        self.assertContainsRe(log, 'this will be kept')
1262
1295
        self.assertEqual(log, test._log_contents)
1263
1296
 
 
1297
    def test_startTestRun(self):
 
1298
        """run should call result.startTestRun()"""
 
1299
        calls = []
 
1300
        class LoggingDecorator(tests.ForwardingResult):
 
1301
            def startTestRun(self):
 
1302
                tests.ForwardingResult.startTestRun(self)
 
1303
                calls.append('startTestRun')
 
1304
        test = unittest.FunctionTestCase(lambda:None)
 
1305
        stream = StringIO()
 
1306
        runner = tests.TextTestRunner(stream=stream,
 
1307
            result_decorators=[LoggingDecorator])
 
1308
        result = self.run_test_runner(runner, test)
 
1309
        self.assertLength(1, calls)
 
1310
 
 
1311
    def test_stopTestRun(self):
 
1312
        """run should call result.stopTestRun()"""
 
1313
        calls = []
 
1314
        class LoggingDecorator(tests.ForwardingResult):
 
1315
            def stopTestRun(self):
 
1316
                tests.ForwardingResult.stopTestRun(self)
 
1317
                calls.append('stopTestRun')
 
1318
        test = unittest.FunctionTestCase(lambda:None)
 
1319
        stream = StringIO()
 
1320
        runner = tests.TextTestRunner(stream=stream,
 
1321
            result_decorators=[LoggingDecorator])
 
1322
        result = self.run_test_runner(runner, test)
 
1323
        self.assertLength(1, calls)
 
1324
 
1264
1325
 
1265
1326
class SampleTestCase(tests.TestCase):
1266
1327
 
1480
1541
        self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1481
1542
        self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1482
1543
        self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
 
1544
        del self._benchcalls[:]
1483
1545
 
1484
1546
    def test_knownFailure(self):
1485
1547
        """Self.knownFailure() should raise a KnownFailure exception."""
1742
1804
        tree = self.make_branch_and_memory_tree('a')
1743
1805
        self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1744
1806
 
1745
 
 
1746
 
class TestSFTPMakeBranchAndTree(test_sftp_transport.TestCaseWithSFTPServer):
1747
 
 
1748
 
    def test_make_tree_for_sftp_branch(self):
1749
 
        """Transports backed by local directories create local trees."""
1750
 
        # NB: This is arguably a bug in the definition of make_branch_and_tree.
 
1807
    def test_make_tree_for_local_vfs_backed_transport(self):
 
1808
        # make_branch_and_tree has to use local branch and repositories
 
1809
        # when the vfs transport and local disk are colocated, even if
 
1810
        # a different transport is in use for url generation.
 
1811
        from bzrlib.transport.fakevfat import FakeVFATServer
 
1812
        self.transport_server = FakeVFATServer
 
1813
        self.assertFalse(self.get_url('t1').startswith('file://'))
1751
1814
        tree = self.make_branch_and_tree('t1')
1752
1815
        base = tree.bzrdir.root_transport.base
1753
 
        self.failIf(base.startswith('sftp'),
1754
 
                'base %r is on sftp but should be local' % base)
 
1816
        self.assertStartsWith(base, 'file://')
1755
1817
        self.assertEquals(tree.bzrdir.root_transport,
1756
1818
                tree.branch.bzrdir.root_transport)
1757
1819
        self.assertEquals(tree.bzrdir.root_transport,
1817
1879
        self.assertNotContainsRe("Test.b", output.getvalue())
1818
1880
        self.assertLength(2, output.readlines())
1819
1881
 
 
1882
    def test_lsprof_tests(self):
 
1883
        self.requireFeature(test_lsprof.LSProfFeature)
 
1884
        calls = []
 
1885
        class Test(object):
 
1886
            def __call__(test, result):
 
1887
                test.run(result)
 
1888
            def run(test, result):
 
1889
                self.assertIsInstance(result, tests.ForwardingResult)
 
1890
                calls.append("called")
 
1891
            def countTestCases(self):
 
1892
                return 1
 
1893
        self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
 
1894
        self.assertLength(1, calls)
 
1895
 
1820
1896
    def test_random(self):
1821
1897
        # test randomising by listing a number of tests.
1822
1898
        output_123 = self.run_selftest(test_suite_factory=self.factory,
1877
1953
    def test_transport_sftp(self):
1878
1954
        try:
1879
1955
            import bzrlib.transport.sftp
1880
 
        except ParamikoNotPresent:
1881
 
            raise TestSkipped("Paramiko not present")
 
1956
        except errors.ParamikoNotPresent:
 
1957
            raise tests.TestSkipped("Paramiko not present")
1882
1958
        self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
1883
1959
 
1884
1960
    def test_transport_memory(self):
2072
2148
        return self.out, self.err
2073
2149
 
2074
2150
 
2075
 
class TestRunBzrSubprocess(tests.TestCaseWithTransport):
 
2151
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
 
2152
    """Base class for tests testing how we might run bzr."""
2076
2153
 
2077
2154
    def setUp(self):
2078
2155
        tests.TestCaseWithTransport.setUp(self)
2089
2166
            'working_dir':working_dir, 'allow_plugins':allow_plugins})
2090
2167
        return self.next_subprocess
2091
2168
 
 
2169
 
 
2170
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
 
2171
 
2092
2172
    def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2093
2173
        """Run run_bzr_subprocess with args and kwargs using a stubbed process.
2094
2174
 
2157
2237
            StubProcess(), '', allow_plugins=True)
2158
2238
 
2159
2239
 
 
2240
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
 
2241
 
 
2242
    def test_finish_bzr_subprocess_with_error(self):
 
2243
        """finish_bzr_subprocess allows specification of the desired exit code.
 
2244
        """
 
2245
        process = StubProcess(err="unknown command", retcode=3)
 
2246
        result = self.finish_bzr_subprocess(process, retcode=3)
 
2247
        self.assertEqual('', result[0])
 
2248
        self.assertContainsRe(result[1], 'unknown command')
 
2249
 
 
2250
    def test_finish_bzr_subprocess_ignoring_retcode(self):
 
2251
        """finish_bzr_subprocess allows the exit code to be ignored."""
 
2252
        process = StubProcess(err="unknown command", retcode=3)
 
2253
        result = self.finish_bzr_subprocess(process, retcode=None)
 
2254
        self.assertEqual('', result[0])
 
2255
        self.assertContainsRe(result[1], 'unknown command')
 
2256
 
 
2257
    def test_finish_subprocess_with_unexpected_retcode(self):
 
2258
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
2259
        not the expected one.
 
2260
        """
 
2261
        process = StubProcess(err="unknown command", retcode=3)
 
2262
        self.assertRaises(self.failureException, self.finish_bzr_subprocess,
 
2263
                          process)
 
2264
 
 
2265
 
2160
2266
class _DontSpawnProcess(Exception):
2161
2267
    """A simple exception which just allows us to skip unnecessary steps"""
2162
2268
 
2240
2346
        self.assertEqual(['foo', 'current'], chdirs)
2241
2347
 
2242
2348
 
2243
 
class TestBzrSubprocess(tests.TestCaseWithTransport):
2244
 
 
2245
 
    def test_start_and_stop_bzr_subprocess(self):
2246
 
        """We can start and perform other test actions while that process is
2247
 
        still alive.
2248
 
        """
2249
 
        process = self.start_bzr_subprocess(['--version'])
2250
 
        result = self.finish_bzr_subprocess(process)
2251
 
        self.assertContainsRe(result[0], 'is free software')
2252
 
        self.assertEqual('', result[1])
2253
 
 
2254
 
    def test_start_and_stop_bzr_subprocess_with_error(self):
2255
 
        """finish_bzr_subprocess allows specification of the desired exit code.
2256
 
        """
2257
 
        process = self.start_bzr_subprocess(['--versionn'])
2258
 
        result = self.finish_bzr_subprocess(process, retcode=3)
2259
 
        self.assertEqual('', result[0])
2260
 
        self.assertContainsRe(result[1], 'unknown command')
2261
 
 
2262
 
    def test_start_and_stop_bzr_subprocess_ignoring_retcode(self):
2263
 
        """finish_bzr_subprocess allows the exit code to be ignored."""
2264
 
        process = self.start_bzr_subprocess(['--versionn'])
2265
 
        result = self.finish_bzr_subprocess(process, retcode=None)
2266
 
        self.assertEqual('', result[0])
2267
 
        self.assertContainsRe(result[1], 'unknown command')
2268
 
 
2269
 
    def test_start_and_stop_bzr_subprocess_with_unexpected_retcode(self):
2270
 
        """finish_bzr_subprocess raises self.failureException if the retcode is
2271
 
        not the expected one.
2272
 
        """
2273
 
        process = self.start_bzr_subprocess(['--versionn'])
2274
 
        self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2275
 
                          process)
 
2349
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
 
2350
    """Tests that really need to do things with an external bzr."""
2276
2351
 
2277
2352
    def test_start_and_stop_bzr_subprocess_send_signal(self):
2278
2353
        """finish_bzr_subprocess raises self.failureException if the retcode is
2286
2361
        self.assertEqual('', result[0])
2287
2362
        self.assertEqual('bzr: interrupted\n', result[1])
2288
2363
 
2289
 
    def test_start_and_stop_working_dir(self):
2290
 
        cwd = osutils.getcwd()
2291
 
        self.make_branch_and_tree('one')
2292
 
        process = self.start_bzr_subprocess(['root'], working_dir='one')
2293
 
        result = self.finish_bzr_subprocess(process, universal_newlines=True)
2294
 
        self.assertEndsWith(result[0], 'one\n')
2295
 
        self.assertEqual('', result[1])
2296
 
 
2297
2364
 
2298
2365
class TestKnownFailure(tests.TestCase):
2299
2366
 
2681
2748
 
2682
2749
class TestTestSuite(tests.TestCase):
2683
2750
 
 
2751
    def test__test_suite_testmod_names(self):
 
2752
        # Test that a plausible list of test module names are returned
 
2753
        # by _test_suite_testmod_names.
 
2754
        test_list = tests._test_suite_testmod_names()
 
2755
        self.assertSubset([
 
2756
            'bzrlib.tests.blackbox',
 
2757
            'bzrlib.tests.per_transport',
 
2758
            'bzrlib.tests.test_selftest',
 
2759
            ],
 
2760
            test_list)
 
2761
 
 
2762
    def test__test_suite_modules_to_doctest(self):
 
2763
        # Test that a plausible list of modules to doctest is returned
 
2764
        # by _test_suite_modules_to_doctest.
 
2765
        test_list = tests._test_suite_modules_to_doctest()
 
2766
        self.assertSubset([
 
2767
            'bzrlib.timestamp',
 
2768
            ],
 
2769
            test_list)
 
2770
 
2684
2771
    def test_test_suite(self):
2685
 
        # This test is slow - it loads the entire test suite to operate, so we
2686
 
        # do a single test with one test in each category
2687
 
        test_list = [
 
2772
        # test_suite() loads the entire test suite to operate. To avoid this
 
2773
        # overhead, and yet still be confident that things are happening,
 
2774
        # we temporarily replace two functions used by test_suite with 
 
2775
        # test doubles that supply a few sample tests to load, and check they
 
2776
        # are loaded.
 
2777
        calls = []
 
2778
        def _test_suite_testmod_names():
 
2779
            calls.append("testmod_names")
 
2780
            return [
 
2781
                'bzrlib.tests.blackbox.test_branch',
 
2782
                'bzrlib.tests.per_transport',
 
2783
                'bzrlib.tests.test_selftest',
 
2784
                ]
 
2785
        original_testmod_names = tests._test_suite_testmod_names
 
2786
        def _test_suite_modules_to_doctest():
 
2787
            calls.append("modules_to_doctest")
 
2788
            return ['bzrlib.timestamp']
 
2789
        orig_modules_to_doctest = tests._test_suite_modules_to_doctest
 
2790
        def restore_names():
 
2791
            tests._test_suite_testmod_names = original_testmod_names
 
2792
            tests._test_suite_modules_to_doctest = orig_modules_to_doctest
 
2793
        self.addCleanup(restore_names)
 
2794
        tests._test_suite_testmod_names = _test_suite_testmod_names
 
2795
        tests._test_suite_modules_to_doctest = _test_suite_modules_to_doctest
 
2796
        expected_test_list = [
2688
2797
            # testmod_names
2689
2798
            'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2690
2799
            ('bzrlib.tests.per_transport.TransportTests'
2695
2804
            # plugins can't be tested that way since selftest may be run with
2696
2805
            # --no-plugins
2697
2806
            ]
2698
 
        suite = tests.test_suite(test_list)
2699
 
        self.assertEquals(test_list, _test_ids(suite))
 
2807
        suite = tests.test_suite()
 
2808
        self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
 
2809
            set(calls))
 
2810
        self.assertSubset(expected_test_list, _test_ids(suite))
2700
2811
 
2701
2812
    def test_test_suite_list_and_start(self):
2702
2813
        # We cannot test this at the same time as the main load, because we want
2703
 
        # to know that starting_with == None works. So a second full load is
2704
 
        # incurred.
 
2814
        # to know that starting_with == None works. So a second load is
 
2815
        # incurred - note that the starting_with parameter causes a partial load
 
2816
        # rather than a full load so this test should be pretty quick.
2705
2817
        test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2706
2818
        suite = tests.test_suite(test_list,
2707
2819
                                 ['bzrlib.tests.test_selftest.TestTestSuite'])
2853
2965
                                                self.verbosity)
2854
2966
        tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2855
2967
        self.assertLength(1, calls)
2856
 
 
2857
 
    def test_done(self):
2858
 
        """run_suite should call result.done()"""
2859
 
        self.calls = 0
2860
 
        def one_more_call(): self.calls += 1
2861
 
        def test_function():
2862
 
            pass
2863
 
        test = unittest.FunctionTestCase(test_function)
2864
 
        class InstrumentedTestResult(tests.ExtendedTestResult):
2865
 
            def done(self): one_more_call()
2866
 
        class MyRunner(tests.TextTestRunner):
2867
 
            def run(self, test):
2868
 
                return InstrumentedTestResult(self.stream, self.descriptions,
2869
 
                                              self.verbosity)
2870
 
        tests.run_suite(test, runner_class=MyRunner, stream=StringIO())
2871
 
        self.assertEquals(1, self.calls)