/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

  • Committer: Aaron Bentley
  • Date: 2008-02-24 16:42:13 UTC
  • mfrom: (3234 +trunk)
  • mto: This revision was merged to the branch mainline in revision 3235.
  • Revision ID: aaron@aaronbentley.com-20080224164213-eza1lzru5bwuwmmj
Merge 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:
1200
1227
            'BZREMAIL': None, # may still be present in the environment
1201
1228
            'EMAIL': None,
1202
1229
            'BZR_PROGRESS_BAR': None,
 
1230
            'BZR_LOG': None,
1203
1231
            # SSH Agent
1204
1232
            'SSH_AUTH_SOCK': None,
1205
1233
            # Proxies
1311
1339
        import bzrlib.trace
1312
1340
        bzrlib.trace._trace_file.flush()
1313
1341
        if self._log_contents:
 
1342
            # XXX: this can hardly contain the content flushed above --vila
 
1343
            # 20080128
1314
1344
            return self._log_contents
1315
1345
        if self._log_file_name is not None:
1316
1346
            logfile = open(self._log_file_name)
2084
2114
    def build_tree_contents(self, shape):
2085
2115
        build_tree_contents(shape)
2086
2116
 
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
2117
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2114
2118
        """Assert whether path or paths are in the WorkingTree"""
2115
2119
        if tree is None:
2261
2265
    return condition
2262
2266
 
2263
2267
 
 
2268
def condition_id_in_list(id_list):
 
2269
    """Create a condition filter which verify that test's id in a list.
 
2270
    
 
2271
    :param name: A TestIdList object.
 
2272
    :return: A callable that returns True if the test's id appears in the list.
 
2273
    """
 
2274
    def condition(test):
 
2275
        return id_list.test_in(test.id())
 
2276
    return condition
 
2277
 
 
2278
 
2264
2279
def exclude_tests_by_condition(suite, condition):
2265
2280
    """Create a test suite which excludes some tests from suite.
2266
2281
 
2324
2339
    return result_suite
2325
2340
 
2326
2341
 
 
2342
def filter_suite_by_id_list(suite, test_id_list):
 
2343
    """Create a test suite by filtering another one.
 
2344
 
 
2345
    :param suite: The source suite.
 
2346
    :param test_id_list: A list of the test ids to keep as strings.
 
2347
    :returns: the newly created suite
 
2348
    """
 
2349
    condition = condition_id_in_list(test_id_list)
 
2350
    result_suite = filter_suite_by_condition(suite, condition)
 
2351
    return result_suite
 
2352
 
 
2353
 
2327
2354
def exclude_tests_by_re(suite, pattern):
2328
2355
    """Create a test suite which excludes some tests from suite.
2329
2356
 
2425
2452
              list_only=False,
2426
2453
              random_seed=None,
2427
2454
              exclude_pattern=None,
2428
 
              strict=False,
2429
 
              coverage_dir=None,
2430
 
              ):
 
2455
              strict=False):
2431
2456
    TestCase._gather_lsprof_in_benchmarks = lsprof_timed
2432
2457
    if verbose:
2433
2458
        verbosity = 2
2470
2495
        else:
2471
2496
            suite = order_changer(filter_suite_by_re(suite, pattern))
2472
2497
 
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
2498
    result = runner.run(suite)
2479
2499
 
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
2500
    if strict:
2487
2501
        return result.wasStrictlySuccessful()
2488
2502
 
2499
2513
             random_seed=None,
2500
2514
             exclude_pattern=None,
2501
2515
             strict=False,
2502
 
             coverage_dir=None,
 
2516
             load_list=None,
2503
2517
             ):
2504
2518
    """Run the whole test suite under the enhanced runner"""
2505
2519
    # XXX: Very ugly way to do this...
2514
2528
    old_transport = default_transport
2515
2529
    default_transport = transport
2516
2530
    try:
 
2531
        if load_list is None:
 
2532
            keep_only = None
 
2533
        else:
 
2534
            keep_only = load_test_id_list(load_list)
2517
2535
        if test_suite_factory is None:
2518
 
            suite = test_suite()
 
2536
            suite = test_suite(keep_only)
2519
2537
        else:
2520
2538
            suite = test_suite_factory()
2521
2539
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
2527
2545
                     list_only=list_only,
2528
2546
                     random_seed=random_seed,
2529
2547
                     exclude_pattern=exclude_pattern,
2530
 
                     strict=strict,
2531
 
                     coverage_dir=coverage_dir)
 
2548
                     strict=strict)
2532
2549
    finally:
2533
2550
        default_transport = old_transport
2534
2551
 
2535
2552
 
2536
 
def test_suite():
 
2553
def load_test_id_list(file_name):
 
2554
    """Load a test id list from a text file.
 
2555
 
 
2556
    The format is one test id by line.  No special care is taken to impose
 
2557
    strict rules, these test ids are used to filter the test suite so a test id
 
2558
    that do not match an existing test will do no harm. This allows user to add
 
2559
    comments, leave blank lines, etc.
 
2560
    """
 
2561
    test_list = []
 
2562
    try:
 
2563
        ftest = open(file_name, 'rt')
 
2564
    except IOError, e:
 
2565
        if e.errno != errno.ENOENT:
 
2566
            raise
 
2567
        else:
 
2568
            raise errors.NoSuchFile(file_name)
 
2569
 
 
2570
    for test_name in ftest.readlines():
 
2571
        test_list.append(test_name.strip())
 
2572
    ftest.close()
 
2573
    return test_list
 
2574
 
 
2575
 
 
2576
class TestIdList(object):
 
2577
    """Test id list to filter a test suite.
 
2578
 
 
2579
    Relying on the assumption that test ids are built as:
 
2580
    <module>[.<class>.<method>][(<param>+)], <module> being in python dotted
 
2581
    notation, this class offers methods to :
 
2582
    - avoid building a test suite for modules not refered to in the test list,
 
2583
    - keep only the tests listed from the module test suite.
 
2584
    """
 
2585
 
 
2586
    def __init__(self, test_id_list):
 
2587
        # When a test suite needs to be filtered against us we compare test ids
 
2588
        # for equality, so a simple dict offers a quick and simple solution.
 
2589
        self.tests = dict().fromkeys(test_id_list, True)
 
2590
 
 
2591
        # While unittest.TestCase have ids like:
 
2592
        # <module>.<class>.<method>[(<param+)],
 
2593
        # doctest.DocTestCase can have ids like:
 
2594
        # <module>
 
2595
        # <module>.<class>
 
2596
        # <module>.<function>
 
2597
        # <module>.<class>.<method>
 
2598
 
 
2599
        # Since we can't predict a test class from its name only, we settle on
 
2600
        # a simple constraint: a test id always begins with its module name.
 
2601
 
 
2602
        modules = {}
 
2603
        for test_id in test_id_list:
 
2604
            parts = test_id.split('.')
 
2605
            mod_name = parts.pop(0)
 
2606
            modules[mod_name] = True
 
2607
            for part in parts:
 
2608
                mod_name += '.' + part
 
2609
                modules[mod_name] = True
 
2610
        self.modules = modules
 
2611
 
 
2612
    def is_module_name_used(self, module_name):
 
2613
        """Is there tests for the module or one of its sub modules."""
 
2614
        return self.modules.has_key(module_name)
 
2615
 
 
2616
    def test_in(self, test_id):
 
2617
        return self.tests.has_key(test_id)
 
2618
 
 
2619
 
 
2620
def test_suite(keep_only=None):
2537
2621
    """Build and return TestSuite for the whole of bzrlib.
2538
 
    
 
2622
 
 
2623
    :param keep_only: A list of test ids limiting the suite returned.
 
2624
 
2539
2625
    This function can be replaced if you need to change the default test
2540
2626
    suite on a global basis, but it is not encouraged.
2541
2627
    """
2580
2666
                   'bzrlib.tests.test_help',
2581
2667
                   'bzrlib.tests.test_hooks',
2582
2668
                   'bzrlib.tests.test_http',
 
2669
                   'bzrlib.tests.test_http_implementations',
2583
2670
                   'bzrlib.tests.test_http_response',
2584
2671
                   'bzrlib.tests.test_https_ca_bundle',
2585
2672
                   'bzrlib.tests.test_identitymap',
2673
2760
        ]
2674
2761
    suite = TestUtil.TestSuite()
2675
2762
    loader = TestUtil.TestLoader()
2676
 
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
 
2763
 
 
2764
    if keep_only is not None:
 
2765
        id_filter = TestIdList(keep_only)
 
2766
 
 
2767
    # modules building their suite with loadTestsFromModuleNames
 
2768
    if keep_only is None:
 
2769
        suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
 
2770
    else:
 
2771
        for mod in [m for m in testmod_names
 
2772
                    if id_filter.is_module_name_used(m)]:
 
2773
            mod_suite = loader.loadTestsFromModuleNames([mod])
 
2774
            mod_suite = filter_suite_by_id_list(mod_suite, id_filter)
 
2775
            suite.addTest(mod_suite)
 
2776
 
 
2777
    # modules adapted for transport implementations
2677
2778
    from bzrlib.tests.test_transport_implementations import TransportTestProviderAdapter
2678
2779
    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:
 
2780
    if keep_only is None:
 
2781
        adapt_modules(test_transport_implementations, adapter, loader, suite)
 
2782
    else:
 
2783
        for mod in [m for m in test_transport_implementations
 
2784
                    if id_filter.is_module_name_used(m)]:
 
2785
            mod_suite = TestUtil.TestSuite()
 
2786
            adapt_modules([mod], adapter, loader, mod_suite)
 
2787
            mod_suite = filter_suite_by_id_list(mod_suite, id_filter)
 
2788
            suite.addTest(mod_suite)
 
2789
 
 
2790
    # modules defining their own test_suite()
 
2791
    for package in [p for p in packages_to_test()
 
2792
                    if (keep_only is None
 
2793
                        or id_filter.is_module_name_used(p.__name__))]:
 
2794
        pack_suite = package.test_suite()
 
2795
        if keep_only is not None:
 
2796
            pack_suite = filter_suite_by_id_list(pack_suite, id_filter)
 
2797
        suite.addTest(pack_suite)
 
2798
 
 
2799
    # XXX: MODULES_TO_TEST should be obsoleted ?
 
2800
    for mod in [m for m in MODULES_TO_TEST
 
2801
                if keep_only is None or id_filter.is_module_name_used(m)]:
 
2802
        mod_suite = loader.loadTestsFromModule(mod)
 
2803
        if keep_only is not None:
 
2804
            mod_suite = filter_suite_by_id_list(mod_suite, id_filter)
 
2805
        suite.addTest(mod_suite)
 
2806
 
 
2807
    for mod in MODULES_TO_DOCTEST:
2685
2808
        try:
2686
 
            suite.addTest(doctest.DocTestSuite(m))
 
2809
            doc_suite = doctest.DocTestSuite(mod)
2687
2810
        except ValueError, e:
2688
 
            print '**failed to get doctest for: %s\n%s' %(m,e)
 
2811
            print '**failed to get doctest for: %s\n%s' % (mod, e)
2689
2812
            raise
 
2813
        if keep_only is not None:
 
2814
            # DocTests may use ids which doesn't contain the module name
 
2815
            doc_suite = filter_suite_by_id_list(doc_suite, id_filter)
 
2816
        suite.addTest(doc_suite)
 
2817
 
2690
2818
    default_encoding = sys.getdefaultencoding()
2691
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
2819
    for name, plugin in  [(n, p) for (n, p) in bzrlib.plugin.plugins().items()
 
2820
                          if (keep_only is None
 
2821
                              or id_filter.is_module_name_used(
 
2822
                p.module.__name__))]:
2692
2823
        try:
2693
2824
            plugin_suite = plugin.test_suite()
2694
2825
        except ImportError, e:
2696
2827
                'Unable to test plugin "%s": %s', name, e)
2697
2828
        else:
2698
2829
            if plugin_suite is not None:
 
2830
                if keep_only is not None:
 
2831
                    plugin_suite = filter_suite_by_id_list(plugin_suite,
 
2832
                                                           id_filter)
2699
2833
                suite.addTest(plugin_suite)
2700
2834
        if default_encoding != sys.getdefaultencoding():
2701
2835
            bzrlib.trace.warning(