• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python unittest2.main函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中unittest2.main函数的典型用法代码示例。如果您正苦于以下问题:Python main函数的具体用法?Python main怎么用?Python main使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了main函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: main

def main(filepath, profile=False, lineProfile=False, numProcs=1):
    """Run tests defined in the given Python file.

    :param profile: whether to enable profiling of the test execution using cProfile.
    :param lineProfile: whether to enable profiling of the test execution using line_profiler.
    :param numProcs: maximum number of processes to use, if a test supports running in parallel.
    """
    if not os.path.isfile(filepath):
        raise ValueError(filepath + ' is not a file')
    base, ext = os.path.splitext(os.path.basename(filepath))
    if ext != '.py':
        raise ValueError(filepath + ' is not a Python source file')
    # Load Python file
    dirpath = os.path.dirname(filepath)
    (file, pathname, desc) = imp.find_module(base, [dirpath])
    try:
        module = imp.load_module(base, file, pathname, desc)
    except ImportError:
        print "Python module search path:", sys.path, os.environ.get('PYTHONPATH')
        raise
    finally:
        file.close()
    # Extract and run its tests
    SetTestOutput(module)
    module.CHASTE_NUM_PROCS = numProcs
    runner = ChasteTestRunner(profile=profile, lineProfile=lineProfile)
    if hasattr(module, 'MakeTestSuite') and callable(module.MakeTestSuite):
        suite = module.MakeTestSuite()
        result = runner.run(suite)
        sys.exit(not result.wasSuccessful())
    else:
        unittest.main(module=module, argv=[sys.argv[0]], testRunner=runner, testLoader=ChasteTestLoader())
开发者ID:ktunya,项目名称:ChasteMod,代码行数:32,代码来源:TestPythonCode.py


示例2: run_suite

def run_suite(remove=None, folder=None, suite=None):
    """Runs a particular test suite or simply unittest.main.

    Takes care that all temporary data in `folder` is removed if `remove=True`.

    """
    if remove is not None:
        testParams['remove'] = remove

    testParams['user_tempdir'] = folder

    prepare_log_config()

    # Just signal if make_temp_dir works
    make_temp_dir('tmp.txt', signal=True)

    success = False
    try:
        if suite is None:
            unittest.main(verbosity=2)
        else:
            runner = unittest.TextTestRunner(verbosity=2)
            result = runner.run(suite)
            success = result.wasSuccessful()
    finally:
        remove_data()

    if not success:
        # Exit with 1 if tests were not successful
        sys.exit(1)
开发者ID:femtotrader,项目名称:pypet,代码行数:30,代码来源:ioutils.py


示例3: run

def run():

    parser = argparse.ArgumentParser()
    parser.add_argument('--print-log', action='store_true',
                        help='Print the log.')
    parser.add_argument('--port-base', help='The port number to start looking '
                        'for open ports. The default is %i.' % narwhal.port_base,
                        default=narwhal.port_base, type=int)
    args = parser.parse_args()

    if args.print_log:
        logging.basicConfig(level=logging.DEBUG,
                            format=('%(asctime)s %(levelname)s:%(name)s:'
                                    '%(funcName)s:'
                                    '%(filename)s(%(lineno)d):'
                                    '%(threadName)s(%(thread)d):%(message)s'))

    narwhal.port_base = args.port_base

    test_runner = xmlrunner.XMLTestRunner(output='test-reports')

    try:
        setUpModule()
        unittest.main(argv=[''], testRunner=test_runner)
    finally:
        tearDownModule()
开发者ID:CoderLisa,项目名称:repose,代码行数:26,代码来源:test_multimatch.py


示例4: run_tests

    def run_tests(self):

        # Add test modules
        sys.path.insert(0, os.path.join(basedir, 'tests'))
        import unittest2 as unittest
        import _common
        from s3ql.common import (setup_excepthook, add_stdout_logging, LoggerFilter)

        # Initialize logging if not yet initialized
        root_logger = logging.getLogger()
        if not root_logger.handlers:
            add_stdout_logging(quiet=True)
            handler = logging.handlers.RotatingFileHandler("setup.log",
                                                           maxBytes=10*1024**2, backupCount=0)
            formatter = logging.Formatter('%(asctime)s.%(msecs)03d [%(process)s] %(threadName)s: '
                                          '[%(name)s] %(message)s', datefmt="%Y-%m-%d %H:%M:%S")
            handler.setFormatter(formatter)                                                
            root_logger.addHandler(handler)
            setup_excepthook()  
            if self.debug:
                root_logger.setLevel(logging.DEBUG)
                if 'all' not in self.debug:
                    root_logger.addFilter(LoggerFilter(self.debug, logging.INFO))
            else:
                root_logger.setLevel(logging.INFO) 
        else:
            root_logger.debug("Logging already initialized.")

        # Define our own test loader to order modules alphabetically
        from pkg_resources import resource_listdir, resource_exists
        class ScanningLoader(unittest.TestLoader):
            # Yes, this is a nasty hack
            # pylint: disable=W0232,W0221,W0622
            def loadTestsFromModule(self, module):
                """Return a suite of all tests cases contained in the given module"""
                tests = []
                if module.__name__!='setuptools.tests.doctest':  # ugh
                    tests.append(unittest.TestLoader.loadTestsFromModule(self,module))
                if hasattr(module, "additional_tests"):
                    tests.append(module.additional_tests())
                if hasattr(module, '__path__'):
                    for file in sorted(resource_listdir(module.__name__, '')):
                        if file.endswith('.py') and file!='__init__.py':
                            submodule = module.__name__+'.'+file[:-3]
                        else:
                            if resource_exists(
                                module.__name__, file+'/__init__.py'
                            ):
                                submodule = module.__name__+'.'+file
                            else:
                                continue
                        tests.append(self.loadTestsFromName(submodule))
                if len(tests)!=1:
                    return self.suiteClass(tests)
                else:
                    return tests[0] # don't create a nested suite for only one return
                
        unittest.main(
            None, None, [unittest.__file__]+self.test_args,
            testLoader = ScanningLoader())
开发者ID:drewlu,项目名称:ossql,代码行数:60,代码来源:setup.py


示例5: main

def main():
    """Runs the testsuite as command line application."""
    try:
        unittest.main(testLoader=BetterLoader(), defaultTest='suite')
    except Exception:
        import traceback
        traceback.print_exc()
        sys.exit(1)
开发者ID:Alpus,项目名称:Eth,代码行数:8,代码来源:__init__.py


示例6: agentMain

	def agentMain(cls, level=logging.DEBUG):
		hdlr = logging.StreamHandler()
		hdlr.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s', '%m-%d %H:%M:%S'))
		root = logging.getLogger()
		root.handlers = []
		root.addHandler(hdlr)
		root.setLevel(level)
		unittest2.main(verbosity=2)
开发者ID:deter-project,项目名称:magi,代码行数:8,代码来源:util.py


示例7: test_main

def test_main():
    verbosity = os.getenv('SILENT') and 1 or 2
    try:
        unittest.main(verbosity=verbosity)
    finally:
        cleanup()
        # force interpreter exit in case the FTP server thread is hanging
        os._exit(0)
开发者ID:Heribertosgp,项目名称:pyftpdlib,代码行数:8,代码来源:test_contrib.py


示例8: run_tests

def run_tests(self):
    try:
        import unittest2 as unittest
    except ImportError:
        import unittest
    unittest.main(
        None, None, [unittest.__file__]+self.test_args,
        testLoader=unittest.loader.defaultTestLoader,
        buffer = True
    )
开发者ID:vincentbernat,项目名称:Kitero,代码行数:10,代码来源:setup.py


示例9: test_given

def test_given(tests):
    module = sys.modules[__name__]
    if tests == None:
        defaultTest = None
    else:
        loader = TestLoader()
        defaultTest = TestSuite()
        tests = loader.loadTestsFromNames(tests, module)
        defaultTest.addTests(tests)
    main(defaultTest=defaultTest)
开发者ID:adrianveres,项目名称:bein,代码行数:10,代码来源:test.py


示例10: run

def run():
    parser = argparse.ArgumentParser()
    parser.add_argument('--print-log', help="Print the log to STDERR.",
                        action='store_true')
    args = parser.parse_args()

    if args.print_log:
        logging.basicConfig(level=logging.DEBUG,
                            format=('%(asctime)s %(levelname)s:%(name)s:'
                                    '%(funcName)s:'
                                    '%(filename)s(%(lineno)d):'
                                    '%(threadName)s(%(thread)d):%(message)s'))

    unittest.main(argv=[''])
开发者ID:izrik,项目名称:narwhal,代码行数:14,代码来源:test_narwhal.py


示例11: make_run

def make_run(remove=None, folder=None):

    if remove is None:
        remove = REMOVE

    global user_tempdir
    user_tempdir=folder

    global actual_tempdir
    try:
        unittest.main()
    finally:
        if remove:
            shutil.rmtree(actual_tempdir,True)
开发者ID:lsolanka,项目名称:pypet,代码行数:14,代码来源:test_helpers.py


示例12: run

 def run(self):
     """ 
         Invokes all tests this runner knows about or the default unittest 
         main to discover other tests if this runner is empty.
     """
     
     count  = self._suite.countTestCases()
     runner = unittest.TextTestRunner(verbosity=self._verbosity)
     
     if 0 == count:
         unittest.main(testRunner=runner)
     else:
         print
         print "----------------------------------------------------------------------"
         runner.run(self._suite)
开发者ID:Stamped,项目名称:Stamped,代码行数:15,代码来源:StampedTestUtils.py


示例13: test_main

def test_main():
    """
    Counts errors and successes from tests.
    """ 
    try:
        test = unittest.main(verbosity=2, exit=False)
    except:
        test = unittest.main()
    # Retrieve errors
    #test_passed = test.result.wasSuccessful()
    #test_total = test.result.testsRun
    test_errors = len(test.result.errors)
    test_failures = len(test.result.failures)
    # Return code for exiting program with it
    test_result = True if test_errors + test_failures == 0 else False
    return test_result
开发者ID:HalasNet,项目名称:felix,代码行数:16,代码来源:testcase.py


示例14: run

def run():
    parser = argparse.ArgumentParser()
    parser.add_argument('--print-log', action='store_true',
                        help='Print the log.')
    args = parser.parse_args()

    if args.print_log:
        logging.basicConfig(level=logging.DEBUG,
                            format=('%(asctime)s %(levelname)s:%(name)s:'
                                    '%(funcName)s:'
                                    '%(filename)s(%(lineno)d):'
                                    '%(threadName)s(%(thread)d):%(message)s'))

    test_runner = xmlrunner.XMLTestRunner(output='test-reports')

    unittest.main(argv=[''], testRunner=test_runner, verbosity=2)
开发者ID:smile921,项目名称:repose,代码行数:16,代码来源:test_config_loading_reloading.py


示例15: test_NonExit

 def test_NonExit(self):
     program = unittest2.main(
         exit=False,
         argv=["foobar"],
         testRunner=unittest2.TextTestRunner(
             stream=StringIO()),
         testLoader=self.FooBarLoader())
     self.assertTrue(hasattr(program, 'result'))
开发者ID:CodaFi,项目名称:swift-lldb,代码行数:8,代码来源:test_program.py


示例16: run

def run():
    global deproxy_port
    global stop_port
    global repose_port

    parser = argparse.ArgumentParser()
    parser.add_argument('--repose-port', help='The port Repose will listen on '
                        'for requests. The default is %i.' % repose_port,
                        default=repose_port, type=int)
    parser.add_argument('--stop-port', help='The port Repose will listen on '
                        'for the stop command. The default is %i.' % stop_port,
                        default=stop_port, type=int)
    parser.add_argument('--deproxy-port', help='The port Deproxy will listen '
                        'on for requests forwarded from Repose. The default '
                        'is %i.' % deproxy_port, default=deproxy_port,
                        type=int)
    parser.add_argument('--print-log', action='store_true',
                        help='Print the log.')
    args = parser.parse_args()

    if args.print_log:
        logging.basicConfig(level=logging.DEBUG,
                            format=('%(asctime)s %(levelname)s:%(name)s:'
                                    '%(funcName)s:'
                                    '%(filename)s(%(lineno)d):'
                                    '%(threadName)s(%(thread)d):%(message)s'))

    deproxy_port = args.deproxy_port
    repose_port = args.repose_port
    stop_port = args.stop_port

    test_runner = xmlrunner.XMLTestRunner(output='test-reports')

    try:
        setUpModule()
        unittest.main(argv=[''], testRunner=test_runner)
    finally:
        tearDownModule()
开发者ID:BigData-Tools,项目名称:repose,代码行数:38,代码来源:test_multimatch.py


示例17: run

def run():
    global port_base

    parser = argparse.ArgumentParser()
    parser.add_argument('--print-log', help="Print the log to STDERR.",
                        action='store_true')
    parser.add_argument('--port-base', help='The port number to start looking '
                        'for open ports. The default is %i.' % port_base,
                        default=port_base, type=int)
    args = parser.parse_args()

    if args.print_log:
        logging.basicConfig(level=logging.DEBUG,
                            format=('%(asctime)s %(levelname)s:%(name)s:'
                                    '%(funcName)s:'
                                    '%(filename)s(%(lineno)d):'
                                    '%(threadName)s(%(thread)d):%(message)s'))

    port_base = args.port_base

    test_runner = _xmlrunner.XMLTestRunner(output='test-reports')

    unittest.main(argv=[''], testRunner=test_runner)
开发者ID:CoderLisa,项目名称:repose,代码行数:23,代码来源:test_connection_framework.py


示例18: _main

def _main(argv):
    parser = argparse.ArgumentParser(prog='conveyor-test')
    parser.add_argument(
        '--logging',
        default=None,
        metavar='FILE')
    parser.add_argument(
        '--xml',
        action='store_true',
        default=False)
    parser.add_argument('args', nargs=argparse.REMAINDER)
    args = parser.parse_args(argv[1:])
    testrunner = None
    if None is not args.logging:
        logging.config.fileConfig(args.logging)
    if args.xml:
        import xmlrunner
        testrunner = xmlrunner.XMLTestRunner(output=str('obj/'))
    if 0 != len(args.args) and '--' == args.args[0]:
        args.args = args.args[1:]
    sys.argv[1:] = args.args
    code = unittest.main(module=None, testRunner=testrunner)
    return code
开发者ID:Jnesselr,项目名称:conveyor,代码行数:23,代码来源:test.py


示例19: NestedNamespace

        new_template = NestedNamespace('joe')
        self.assertTrue(new_template.__class__ in
                        [t.__class__ for t in stack], "%s" % stack)

        errmsg = "%s does not appear to be a subclass of %s"
        for c in [t.__class__ for t in stack]:
            self.assertTrue(isinstance(new_template, c),
                            errmsg % (new_template, c))

    def test_should_print_subcommands(self):
        """ Subcommands should be printed after the template runs
        """
        b_template = BasicNamespace('tom')
        n_template = NestedNamespace('bob')
        # pretend the nested_namespace template provides localcommands (it
        # doesn't have to actually provide them, just claim that it does)
        n_template.use_local_commands = True

        self.assertFalse(b_template.should_print_subcommands(self.command))
        self.assertTrue(n_template.should_print_subcommands(self.command))


def test_suite():
    suite = unittest.TestSuite([
        unittest.makeSuite(test_base_template),
    ])
    return suite

if __name__ == '__main__':
    unittest.main(defaultTest='test_suite')
开发者ID:Vinsurya,项目名称:Plone,代码行数:30,代码来源:test_base.py


示例20: main

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
from unittest2 import main

if __name__ == '__main__':
    current_dir = os.path.dirname(os.path.abspath(__file__))
    tests_dir = os.path.join(current_dir, 'tests')
    sys.path += [current_dir, tests_dir]
    os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
    main(argv=[sys.argv[0]] + ['discover', '-s', tests_dir, '-t',
                               current_dir] + \
              sys.argv[1:])
开发者ID:alvaromartin,项目名称:baph,代码行数:15,代码来源:runtests.py



注:本文中的unittest2.main函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python unittest2.makeSuite函数代码示例发布时间:2022-05-27
下一篇:
Python unittest2.installHandler函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap