本文整理汇总了Python中unittest2.main函数的典型用法代码示例。如果您正苦于以下问题:Python main函数的具体用法?Python main怎么用?Python main使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了main函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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())
示例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)
示例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()
示例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())
示例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)
示例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)
示例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)
示例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
)
示例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)
示例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=[''])
示例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)
示例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)
示例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
示例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)
示例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'))