/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/__init__.py

Merge up with bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008 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
43
43
import sys
44
44
import tempfile
45
45
import time
46
 
import trace
47
46
import unittest
48
47
import warnings
49
48
 
94
93
from bzrlib.transport.readonly import ReadonlyServer
95
94
from bzrlib.trace import mutter, note
96
95
from bzrlib.tests import TestUtil
97
 
from bzrlib.tests.HttpServer import HttpServer
 
96
from bzrlib.tests.http_server import HttpServer
98
97
from bzrlib.tests.TestUtil import (
99
98
                          TestSuite,
100
99
                          TestLoader,
276
275
        elif isinstance(err[1], UnavailableFeature):
277
276
            return self.addNotSupported(test, err[1].args[0])
278
277
        else:
 
278
            self._cleanupLogFile(test)
279
279
            unittest.TestResult.addError(self, test, err)
280
280
            self.error_count += 1
281
281
            self.report_error(test, err)
292
292
        if isinstance(err[1], KnownFailure):
293
293
            return self._addKnownFailure(test, err)
294
294
        else:
 
295
            self._cleanupLogFile(test)
295
296
            unittest.TestResult.addFailure(self, test, err)
296
297
            self.failure_count += 1
297
298
            self.report_failure(test, err)
311
312
                    self._formatTime(benchmark_time),
312
313
                    test.id()))
313
314
        self.report_success(test)
 
315
        self._cleanupLogFile(test)
314
316
        unittest.TestResult.addSuccess(self, test)
315
317
 
316
318
    def _testConcluded(self, test):
318
320
 
319
321
        Called regardless of whether it succeded, failed, etc.
320
322
        """
321
 
        self._cleanupLogFile(test)
 
323
        pass
322
324
 
323
325
    def _addKnownFailure(self, test, err):
324
326
        self.known_failure_count += 1
795
797
    def setUp(self):
796
798
        unittest.TestCase.setUp(self)
797
799
        self._cleanEnvironment()
798
 
        bzrlib.trace.disable_default_logging()
799
800
        self._silenceUI()
800
801
        self._startLogFile()
801
802
        self._benchcalls = []
1039
1040
        else:
1040
1041
            self.fail('Unexpected success.  Should have failed: %s' % reason)
1041
1042
 
 
1043
    def assertFileEqual(self, content, path):
 
1044
        """Fail if path does not contain 'content'."""
 
1045
        self.failUnlessExists(path)
 
1046
        f = file(path, 'rb')
 
1047
        try:
 
1048
            s = f.read()
 
1049
        finally:
 
1050
            f.close()
 
1051
        self.assertEqualDiff(content, s)
 
1052
 
 
1053
    def failUnlessExists(self, path):
 
1054
        """Fail unless path or paths, which may be abs or relative, exist."""
 
1055
        if not isinstance(path, basestring):
 
1056
            for p in path:
 
1057
                self.failUnlessExists(p)
 
1058
        else:
 
1059
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1060
 
 
1061
    def failIfExists(self, path):
 
1062
        """Fail if path or paths, which may be abs or relative, exist."""
 
1063
        if not isinstance(path, basestring):
 
1064
            for p in path:
 
1065
                self.failIfExists(p)
 
1066
        else:
 
1067
            self.failIf(osutils.lexists(path),path+" exists")
 
1068
 
1042
1069
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1043
1070
        """A helper for callDeprecated and applyDeprecated.
1044
1071
 
1157
1184
        """
1158
1185
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
1159
1186
        self._log_file = os.fdopen(fileno, 'w+')
1160
 
        self._log_nonce = bzrlib.trace.enable_test_log(self._log_file)
 
1187
        self._log_memento = bzrlib.trace.push_log_file(self._log_file)
1161
1188
        self._log_file_name = name
1162
1189
        self.addCleanup(self._finishLogFile)
1163
1190
 
1168
1195
        """
1169
1196
        if self._log_file is None:
1170
1197
            return
1171
 
        bzrlib.trace.disable_test_log(self._log_nonce)
 
1198
        bzrlib.trace.pop_log_file(self._log_memento)
1172
1199
        self._log_file.close()
1173
1200
        self._log_file = None
1174
1201
        if not self._keep_log_file:
1311
1338
        import bzrlib.trace
1312
1339
        bzrlib.trace._trace_file.flush()
1313
1340
        if self._log_contents:
 
1341
            # XXX: this can hardly contain the content flushed above --vila
 
1342
            # 20080128
1314
1343
            return self._log_contents
1315
1344
        if self._log_file_name is not None:
1316
1345
            logfile = open(self._log_file_name)
2084
2113
    def build_tree_contents(self, shape):
2085
2114
        build_tree_contents(shape)
2086
2115
 
2087
 
    def assertFileEqual(self, content, path):
2088
 
        """Fail if path does not contain 'content'."""
2089
 
        self.failUnlessExists(path)
2090
 
        f = file(path, 'rb')
2091
 
        try:
2092
 
            s = f.read()
2093
 
        finally:
2094
 
            f.close()
2095
 
        self.assertEqualDiff(content, s)
2096
 
 
2097
 
    def failUnlessExists(self, path):
2098
 
        """Fail unless path or paths, which may be abs or relative, exist."""
2099
 
        if not isinstance(path, basestring):
2100
 
            for p in path:
2101
 
                self.failUnlessExists(p)
2102
 
        else:
2103
 
            self.failUnless(osutils.lexists(path),path+" does not exist")
2104
 
 
2105
 
    def failIfExists(self, path):
2106
 
        """Fail if path or paths, which may be abs or relative, exist."""
2107
 
        if not isinstance(path, basestring):
2108
 
            for p in path:
2109
 
                self.failIfExists(p)
2110
 
        else:
2111
 
            self.failIf(osutils.lexists(path),path+" exists")
2112
 
 
2113
2116
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2114
2117
        """Assert whether path or paths are in the WorkingTree"""
2115
2118
        if tree is None:
2261
2264
    return condition
2262
2265
 
2263
2266
 
 
2267
def condition_id_in_list(id_list):
 
2268
    """Create a condition filter which verify that test's id in a list.
 
2269
    
 
2270
    :param name: A TestIdList object.
 
2271
    :return: A callable that returns True if the test's id appears in the list.
 
2272
    """
 
2273
    def condition(test):
 
2274
        return id_list.test_in(test.id())
 
2275
    return condition
 
2276
 
 
2277
 
2264
2278
def exclude_tests_by_condition(suite, condition):
2265
2279
    """Create a test suite which excludes some tests from suite.
2266
2280
 
2324
2338
    return result_suite
2325
2339
 
2326
2340
 
 
2341
def filter_suite_by_id_list(suite, test_id_list):
 
2342
    """Create a test suite by filtering another one.
 
2343
 
 
2344
    :param suite: The source suite.
 
2345
    :param test_id_list: A list of the test ids to keep as strings.
 
2346
    :returns: the newly created suite
 
2347
    """
 
2348
    condition = condition_id_in_list(test_id_list)
 
2349
    result_suite = filter_suite_by_condition(suite, condition)
 
2350
    return result_suite
 
2351
 
 
2352
 
2327
2353
def exclude_tests_by_re(suite, pattern):
2328
2354
    """Create a test suite which excludes some tests from suite.
2329
2355
 
2425
2451
              list_only=False,
2426
2452
              random_seed=None,
2427
2453
              exclude_pattern=None,
2428
 
              strict=False,
2429
 
              coverage_dir=None,
2430
 
              ):
 
2454
              strict=False):
2431
2455
    TestCase._gather_lsprof_in_benchmarks = lsprof_timed
2432
2456
    if verbose:
2433
2457
        verbosity = 2
2470
2494
        else:
2471
2495
            suite = order_changer(filter_suite_by_re(suite, pattern))
2472
2496
 
2473
 
    # Activate code coverage.
2474
 
    if coverage_dir is not None:
2475
 
        tracer = trace.Trace(count=1, trace=0)
2476
 
        sys.settrace(tracer.globaltrace)
2477
 
 
2478
2497
    result = runner.run(suite)
2479
2498
 
2480
 
    if coverage_dir is not None:
2481
 
        sys.settrace(None)
2482
 
        results = tracer.results()
2483
 
        results.write_results(show_missing=1, summary=False,
2484
 
                              coverdir=coverage_dir)
2485
 
 
2486
2499
    if strict:
2487
2500
        return result.wasStrictlySuccessful()
2488
2501
 
2499
2512
             random_seed=None,
2500
2513
             exclude_pattern=None,
2501
2514
             strict=False,
2502
 
             coverage_dir=None,
 
2515
             load_list=None,
2503
2516
             ):
2504
2517
    """Run the whole test suite under the enhanced runner"""
2505
2518
    # XXX: Very ugly way to do this...
2514
2527
    old_transport = default_transport
2515
2528
    default_transport = transport
2516
2529
    try:
 
2530
        if load_list is None:
 
2531
            keep_only = None
 
2532
        else:
 
2533
            keep_only = load_test_id_list(load_list)
2517
2534
        if test_suite_factory is None:
2518
 
            suite = test_suite()
 
2535
            suite = test_suite(keep_only)
2519
2536
        else:
2520
2537
            suite = test_suite_factory()
2521
2538
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
2527
2544
                     list_only=list_only,
2528
2545
                     random_seed=random_seed,
2529
2546
                     exclude_pattern=exclude_pattern,
2530
 
                     strict=strict,
2531
 
                     coverage_dir=coverage_dir)
 
2547
                     strict=strict)
2532
2548
    finally:
2533
2549
        default_transport = old_transport
2534
2550
 
2535
2551
 
2536
 
def test_suite():
 
2552
def load_test_id_list(file_name):
 
2553
    """Load a test id list from a text file.
 
2554
 
 
2555
    The format is one test id by line.  No special care is taken to impose
 
2556
    strict rules, these test ids are used to filter the test suite so a test id
 
2557
    that do not match an existing test will do no harm. This allows user to add
 
2558
    comments, leave blank lines, etc.
 
2559
    """
 
2560
    test_list = []
 
2561
    try:
 
2562
        ftest = open(file_name, 'rt')
 
2563
    except IOError, e:
 
2564
        if e.errno != errno.ENOENT:
 
2565
            raise
 
2566
        else:
 
2567
            raise errors.NoSuchFile(file_name)
 
2568
 
 
2569
    for test_name in ftest.readlines():
 
2570
        test_list.append(test_name.strip())
 
2571
    ftest.close()
 
2572
    return test_list
 
2573
 
 
2574
 
 
2575
class TestIdList(object):
 
2576
    """Test id list to filter a test suite.
 
2577
 
 
2578
    Relying on the assumption that test ids are built as:
 
2579
    <module>[.<class>.<method>][(<param>+)], <module> being in python dotted
 
2580
    notation, this class offers methods to :
 
2581
    - avoid building a test suite for modules not refered to in the test list,
 
2582
    - keep only the tests listed from the module test suite.
 
2583
    """
 
2584
 
 
2585
    def __init__(self, test_id_list):
 
2586
        # When a test suite needs to be filtered against us we compare test ids
 
2587
        # for equality, so a simple dict offers a quick and simple solution.
 
2588
        self.tests = dict().fromkeys(test_id_list, True)
 
2589
 
 
2590
        # While unittest.TestCase have ids like:
 
2591
        # <module>.<class>.<method>[(<param+)],
 
2592
        # doctest.DocTestCase can have ids like:
 
2593
        # <module>
 
2594
        # <module>.<class>
 
2595
        # <module>.<function>
 
2596
        # <module>.<class>.<method>
 
2597
 
 
2598
        # Since we can't predict a test class from its name only, we settle on
 
2599
        # a simple constraint: a test id always begins with its module name.
 
2600
 
 
2601
        modules = {}
 
2602
        for test_id in test_id_list:
 
2603
            parts = test_id.split('.')
 
2604
            mod_name = parts.pop(0)
 
2605
            modules[mod_name] = True
 
2606
            for part in parts:
 
2607
                mod_name += '.' + part
 
2608
                modules[mod_name] = True
 
2609
        self.modules = modules
 
2610
 
 
2611
    def is_module_name_used(self, module_name):
 
2612
        """Is there tests for the module or one of its sub modules."""
 
2613
        return self.modules.has_key(module_name)
 
2614
 
 
2615
    def test_in(self, test_id):
 
2616
        return self.tests.has_key(test_id)
 
2617
 
 
2618
 
 
2619
def test_suite(keep_only=None):
2537
2620
    """Build and return TestSuite for the whole of bzrlib.
2538
 
    
 
2621
 
 
2622
    :param keep_only: A list of test ids limiting the suite returned.
 
2623
 
2539
2624
    This function can be replaced if you need to change the default test
2540
2625
    suite on a global basis, but it is not encouraged.
2541
2626
    """
2580
2665
                   'bzrlib.tests.test_help',
2581
2666
                   'bzrlib.tests.test_hooks',
2582
2667
                   'bzrlib.tests.test_http',
 
2668
                   'bzrlib.tests.test_http_implementations',
2583
2669
                   'bzrlib.tests.test_http_response',
2584
2670
                   'bzrlib.tests.test_https_ca_bundle',
2585
2671
                   'bzrlib.tests.test_identitymap',
2673
2759
        ]
2674
2760
    suite = TestUtil.TestSuite()
2675
2761
    loader = TestUtil.TestLoader()
2676
 
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
 
2762
 
 
2763
    if keep_only is not None:
 
2764
        id_filter = TestIdList(keep_only)
 
2765
 
 
2766
    # modules building their suite with loadTestsFromModuleNames
 
2767
    if keep_only is None:
 
2768
        suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
 
2769
    else:
 
2770
        for mod in [m for m in testmod_names
 
2771
                    if id_filter.is_module_name_used(m)]:
 
2772
            mod_suite = loader.loadTestsFromModuleNames([mod])
 
2773
            mod_suite = filter_suite_by_id_list(mod_suite, id_filter)
 
2774
            suite.addTest(mod_suite)
 
2775
 
 
2776
    # modules adapted for transport implementations
2677
2777
    from bzrlib.tests.test_transport_implementations import TransportTestProviderAdapter
2678
2778
    adapter = TransportTestProviderAdapter()
2679
 
    adapt_modules(test_transport_implementations, adapter, loader, suite)
2680
 
    for package in packages_to_test():
2681
 
        suite.addTest(package.test_suite())
2682
 
    for m in MODULES_TO_TEST:
2683
 
        suite.addTest(loader.loadTestsFromModule(m))
2684
 
    for m in MODULES_TO_DOCTEST:
 
2779
    if keep_only is None:
 
2780
        adapt_modules(test_transport_implementations, adapter, loader, suite)
 
2781
    else:
 
2782
        for mod in [m for m in test_transport_implementations
 
2783
                    if id_filter.is_module_name_used(m)]:
 
2784
            mod_suite = TestUtil.TestSuite()
 
2785
            adapt_modules([mod], adapter, loader, mod_suite)
 
2786
            mod_suite = filter_suite_by_id_list(mod_suite, id_filter)
 
2787
            suite.addTest(mod_suite)
 
2788
 
 
2789
    # modules defining their own test_suite()
 
2790
    for package in [p for p in packages_to_test()
 
2791
                    if (keep_only is None
 
2792
                        or id_filter.is_module_name_used(p.__name__))]:
 
2793
        pack_suite = package.test_suite()
 
2794
        if keep_only is not None:
 
2795
            pack_suite = filter_suite_by_id_list(pack_suite, id_filter)
 
2796
        suite.addTest(pack_suite)
 
2797
 
 
2798
    # XXX: MODULES_TO_TEST should be obsoleted ?
 
2799
    for mod in [m for m in MODULES_TO_TEST
 
2800
                if keep_only is None or id_filter.is_module_name_used(m)]:
 
2801
        mod_suite = loader.loadTestsFromModule(mod)
 
2802
        if keep_only is not None:
 
2803
            mod_suite = filter_suite_by_id_list(mod_suite, id_filter)
 
2804
        suite.addTest(mod_suite)
 
2805
 
 
2806
    for mod in MODULES_TO_DOCTEST:
2685
2807
        try:
2686
 
            suite.addTest(doctest.DocTestSuite(m))
 
2808
            doc_suite = doctest.DocTestSuite(mod)
2687
2809
        except ValueError, e:
2688
 
            print '**failed to get doctest for: %s\n%s' %(m,e)
 
2810
            print '**failed to get doctest for: %s\n%s' % (mod, e)
2689
2811
            raise
 
2812
        if keep_only is not None:
 
2813
            # DocTests may use ids which doesn't contain the module name
 
2814
            doc_suite = filter_suite_by_id_list(doc_suite, id_filter)
 
2815
        suite.addTest(doc_suite)
 
2816
 
2690
2817
    default_encoding = sys.getdefaultencoding()
2691
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
2818
    for name, plugin in  [(n, p) for (n, p) in bzrlib.plugin.plugins().items()
 
2819
                          if (keep_only is None
 
2820
                              or id_filter.is_module_name_used(
 
2821
                p.module.__name__))]:
2692
2822
        try:
2693
2823
            plugin_suite = plugin.test_suite()
2694
2824
        except ImportError, e:
2696
2826
                'Unable to test plugin "%s": %s', name, e)
2697
2827
        else:
2698
2828
            if plugin_suite is not None:
 
2829
                if keep_only is not None:
 
2830
                    plugin_suite = filter_suite_by_id_list(plugin_suite,
 
2831
                                                           id_filter)
2699
2832
                suite.addTest(plugin_suite)
2700
2833
        if default_encoding != sys.getdefaultencoding():
2701
2834
            bzrlib.trace.warning(