def run(self, test):
"""Overrides to provide plugin hooks and defer all output to
the test result class.
"""
wrapper = self.config.plugins.prepareTest(test)
if wrapper is not None:
test = wrapper
# plugins can decorate or capture the output stream
wrapped = self.config.plugins.setOutputStream(self.stream)
if wrapped is not None:
self.stream = wrapped
result = self._makeResult()
start = time.time()
try:
test(result)
except KeyboardInterrupt:
pass
stop = time.time()
result.printErrors()
result.printSummary(start, stop)
self.config.plugins.finalize(result)
return result
python类config()的实例源码
def runTests(self):
"""Run Tests. Returns true on success, false on failure, and sets
self.success to the same value.
"""
log.debug("runTests called")
if self.testRunner is None:
self.testRunner = TextTestRunner(stream=self.config.stream,
verbosity=self.config.verbosity,
config=self.config)
plug_runner = self.config.plugins.prepareTestRunner(self.testRunner)
if plug_runner is not None:
self.testRunner = plug_runner
result = self.testRunner.run(self.test)
self.success = result.wasSuccessful()
if self.exit:
sys.exit(not self.success)
return self.success
def run(self, test):
"""Overrides to provide plugin hooks and defer all output to
the test result class.
"""
wrapper = self.config.plugins.prepareTest(test)
if wrapper is not None:
test = wrapper
# plugins can decorate or capture the output stream
wrapped = self.config.plugins.setOutputStream(self.stream)
if wrapped is not None:
self.stream = wrapped
result = self._makeResult()
start = time.time()
try:
test(result)
except KeyboardInterrupt:
pass
stop = time.time()
result.printErrors()
result.printSummary(start, stop)
self.config.plugins.finalize(result)
return result
def runTests(self):
"""Run Tests. Returns true on success, false on failure, and sets
self.success to the same value.
"""
log.debug("runTests called")
if self.testRunner is None:
self.testRunner = TextTestRunner(stream=self.config.stream,
verbosity=self.config.verbosity,
config=self.config)
plug_runner = self.config.plugins.prepareTestRunner(self.testRunner)
if plug_runner is not None:
self.testRunner = plug_runner
result = self.testRunner.run(self.test)
self.success = result.wasSuccessful()
if self.exit:
sys.exit(not self.success)
return self.success
def run_tests(c=None):
logger = logging.getLogger()
hdlr = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
# NOTE(bgh): I'm not entirely sure why but nose gets confused here when
# calling run_tests from a plugin directory run_tests.py (instead of the
# main run_tests.py). It will call run_tests with no arguments and the
# testing of run_tests will fail (though the plugin tests will pass). For
# now we just return True to let the run_tests test pass.
if not c:
return True
runner = RyuTestRunner(stream=c.stream,
verbosity=c.verbosity,
config=c)
return not core.run(config=c, testRunner=runner)
def run_tests(c=None):
logger = logging.getLogger()
hdlr = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
# NOTE(bgh): I'm not entirely sure why but nose gets confused here when
# calling run_tests from a plugin directory run_tests.py (instead of the
# main run_tests.py). It will call run_tests with no arguments and the
# testing of run_tests will fail (though the plugin tests will pass). For
# now we just return True to let the run_tests test pass.
if not c:
return True
runner = RyuTestRunner(stream=c.stream,
verbosity=c.verbosity,
config=c)
return not core.run(config=c, testRunner=runner)
def configure(self, options, config):
pass
def configure(self, options, config):
"""Configure the set of plugins with the given options
and config instance. After configuration, disabled plugins
are removed from the plugins list.
"""
log.debug("Configuring plugins")
self.config = config
cfg = PluginProxy('configure', self._plugins)
cfg(options, config)
enabled = [plug for plug in self._plugins if plug.enabled]
self.plugins = enabled
self.sort()
log.debug("Plugins enabled: %s", enabled)
def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1,
config=None):
if config is None:
config = Config()
self.config = config
unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
def _makeResult(self):
return TextTestResult(self.stream,
self.descriptions,
self.verbosity,
self.config)
def makeConfig(self, env, plugins=None):
"""Load a Config, pre-filled with user config files if any are
found.
"""
cfg_files = self.getAllConfigFiles(env)
if plugins:
manager = PluginManager(plugins=plugins)
else:
manager = DefaultPluginManager()
return Config(
env=env, files=cfg_files, plugins=manager)
def parseArgs(self, argv):
"""Parse argv and env and configure running environment.
"""
self.config.configure(argv, doc=self.usage())
log.debug("configured %s", self.config)
# quick outs: version, plugins (optparse would have already
# caught and exited on help)
if self.config.options.version:
from nose import __version__
sys.stdout = sys.__stdout__
print "%s version %s" % (os.path.basename(sys.argv[0]), __version__)
sys.exit(0)
if self.config.options.showPlugins:
self.showPlugins()
sys.exit(0)
if self.testLoader is None:
self.testLoader = defaultTestLoader(config=self.config)
elif isclass(self.testLoader):
self.testLoader = self.testLoader(config=self.config)
plug_loader = self.config.plugins.prepareTestLoader(self.testLoader)
if plug_loader is not None:
self.testLoader = plug_loader
log.debug("test loader is %s", self.testLoader)
# FIXME if self.module is a string, add it to self.testNames? not sure
if self.config.testNames:
self.testNames = self.config.testNames
else:
self.testNames = tolist(self.defaultTest)
log.debug('defaultTest %s', self.defaultTest)
log.debug('Test names are %s', self.testNames)
if self.config.workingDir is not None:
os.chdir(self.config.workingDir)
self.createTests()
def showPlugins(self):
"""Print list of available plugins.
"""
import textwrap
class DummyParser:
def __init__(self):
self.options = []
def add_option(self, *arg, **kw):
self.options.append((arg, kw.pop('help', '')))
v = self.config.verbosity
self.config.plugins.sort()
for p in self.config.plugins:
print "Plugin %s" % p.name
if v >= 2:
print " score: %s" % p.score
print '\n'.join(textwrap.wrap(p.help().strip(),
initial_indent=' ',
subsequent_indent=' '))
if v >= 3:
parser = DummyParser()
p.addOptions(parser)
if len(parser.options):
print
print " Options:"
for opts, help in parser.options:
print ' %s' % (', '.join(opts))
if help:
print '\n'.join(
textwrap.wrap(help.strip(),
initial_indent=' ',
subsequent_indent=' '))
print
def run(*arg, **kw):
"""Collect and run tests, returning success or failure.
The arguments to `run()` are the same as to `main()`:
* module: All tests are in this module (default: None)
* defaultTest: Tests to load (default: '.')
* argv: Command line arguments (default: None; sys.argv is read)
* testRunner: Test runner instance (default: None)
* testLoader: Test loader instance (default: None)
* env: Environment; ignored if config is provided (default: None;
os.environ is read)
* config: :class:`nose.config.Config` instance (default: None)
* suite: Suite or list of tests to run (default: None). Passing a
suite or lists of tests will bypass all test discovery and
loading. *ALSO NOTE* that if you pass a unittest.TestSuite
instance as the suite, context fixtures at the class, module and
package level will not be used, and many plugin hooks will not
be called. If you want normal nose behavior, either pass a list
of tests, or a fully-configured :class:`nose.suite.ContextSuite`.
* plugins: List of plugins to use; ignored if config is provided
(default: load plugins with DefaultPluginManager)
* addplugins: List of **extra** plugins to use. Pass a list of plugin
instances in this argument to make custom plugins available while
still using the DefaultPluginManager.
With the exception that the ``exit`` argument is always set
to False.
"""
kw['exit'] = False
return TestProgram(*arg, **kw).success
def setUpClass(cls):
"""
????????http_session??
:return:
"""
env = None
nose_cfg = None
argvs = sys.argv[1:]
for idx, arg in enumerate(argvs):
# ????case??????
if '-env=' in arg:
env = arg.split('=')[-1]
break
# ??nose?????
if '--config=' in arg:
nose_cfg = arg.split('=')[-1]
if '-c' == arg:
nose_cfg = argvs[idx + 1]
# ????case??????????nose???????
nose_config_files = nose.config.all_config_files()
if env is None and (nose_cfg is not None or len(nose_config_files) > 0):
if nose_cfg is None:
# ?????nose??????????????????
nose_cfg = nose_config_files[-1]
if not os.path.isabs(nose_cfg):
nose_cfg = os.getcwd() + '/' + nose_cfg
cf = ConfigParser.ConfigParser()
cf.read(nose_cfg)
try:
env = cf.get('others', 'env')
except ConfigParser.Error:
env = None
if env is not None:
# ????????
if not os.path.isabs(env):
# ???????????????
env = os.getcwd() + '/' + env
with open(env) as f:
inp = f.read()
cls.config = ruamel.yaml.safe_load(inp)
def configure(self, options, config):
pass
def configure(self, options, config):
"""Configure the set of plugins with the given options
and config instance. After configuration, disabled plugins
are removed from the plugins list.
"""
log.debug("Configuring plugins")
self.config = config
cfg = PluginProxy('configure', self._plugins)
cfg(options, config)
enabled = [plug for plug in self._plugins if plug.enabled]
self.plugins = enabled
self.sort()
log.debug("Plugins enabled: %s", enabled)
def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1,
config=None):
if config is None:
config = Config()
self.config = config
unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
def _makeResult(self):
return TextTestResult(self.stream,
self.descriptions,
self.verbosity,
self.config)
def makeConfig(self, env, plugins=None):
"""Load a Config, pre-filled with user config files if any are
found.
"""
cfg_files = self.getAllConfigFiles(env)
if plugins:
manager = PluginManager(plugins=plugins)
else:
manager = DefaultPluginManager()
return Config(
env=env, files=cfg_files, plugins=manager)
def parseArgs(self, argv):
"""Parse argv and env and configure running environment.
"""
self.config.configure(argv, doc=self.usage())
log.debug("configured %s", self.config)
# quick outs: version, plugins (optparse would have already
# caught and exited on help)
if self.config.options.version:
from nose import __version__
sys.stdout = sys.__stdout__
print "%s version %s" % (os.path.basename(sys.argv[0]), __version__)
sys.exit(0)
if self.config.options.showPlugins:
self.showPlugins()
sys.exit(0)
if self.testLoader is None:
self.testLoader = defaultTestLoader(config=self.config)
elif isclass(self.testLoader):
self.testLoader = self.testLoader(config=self.config)
plug_loader = self.config.plugins.prepareTestLoader(self.testLoader)
if plug_loader is not None:
self.testLoader = plug_loader
log.debug("test loader is %s", self.testLoader)
# FIXME if self.module is a string, add it to self.testNames? not sure
if self.config.testNames:
self.testNames = self.config.testNames
else:
self.testNames = tolist(self.defaultTest)
log.debug('defaultTest %s', self.defaultTest)
log.debug('Test names are %s', self.testNames)
if self.config.workingDir is not None:
os.chdir(self.config.workingDir)
self.createTests()
def showPlugins(self):
"""Print list of available plugins.
"""
import textwrap
class DummyParser:
def __init__(self):
self.options = []
def add_option(self, *arg, **kw):
self.options.append((arg, kw.pop('help', '')))
v = self.config.verbosity
self.config.plugins.sort()
for p in self.config.plugins:
print "Plugin %s" % p.name
if v >= 2:
print " score: %s" % p.score
print '\n'.join(textwrap.wrap(p.help().strip(),
initial_indent=' ',
subsequent_indent=' '))
if v >= 3:
parser = DummyParser()
p.addOptions(parser)
if len(parser.options):
print
print " Options:"
for opts, help in parser.options:
print ' %s' % (', '.join(opts))
if help:
print '\n'.join(
textwrap.wrap(help.strip(),
initial_indent=' ',
subsequent_indent=' '))
print
def run(*arg, **kw):
"""Collect and run tests, returning success or failure.
The arguments to `run()` are the same as to `main()`:
* module: All tests are in this module (default: None)
* defaultTest: Tests to load (default: '.')
* argv: Command line arguments (default: None; sys.argv is read)
* testRunner: Test runner instance (default: None)
* testLoader: Test loader instance (default: None)
* env: Environment; ignored if config is provided (default: None;
os.environ is read)
* config: :class:`nose.config.Config` instance (default: None)
* suite: Suite or list of tests to run (default: None). Passing a
suite or lists of tests will bypass all test discovery and
loading. *ALSO NOTE* that if you pass a unittest.TestSuite
instance as the suite, context fixtures at the class, module and
package level will not be used, and many plugin hooks will not
be called. If you want normal nose behavior, either pass a list
of tests, or a fully-configured :class:`nose.suite.ContextSuite`.
* plugins: List of plugins to use; ignored if config is provided
(default: load plugins with DefaultPluginManager)
* addplugins: List of **extra** plugins to use. Pass a list of plugin
instances in this argument to make custom plugins available while
still using the DefaultPluginManager.
With the exception that the ``exit`` argument is always set
to False.
"""
kw['exit'] = False
return TestProgram(*arg, **kw).success
def _makeResult(self):
return RyuTestResult(self.stream,
self.descriptions,
self.verbosity,
self.config)
def _makeResult(self):
return RyuTestResult(self.stream,
self.descriptions,
self.verbosity,
self.config)
def __init__(self, name, app):
"""
Init command
:param name: Name of the command
:type name: str
:param app: The application
:type app: edmunds.application.Application
"""
super(TestCommand, self).__init__(name, app)
# Fetch nose options
config = Config(env=os.environ, files=all_config_files(), plugins=DefaultPluginManager())
nose_options = config.getParser(doc=TestProgram.usage()).option_list
# Override run-function to be able to load the click-options dynamically
# Dynamic click.option does not work for class-methods because of __click_params__
original_function = self.run
def run_wrapper(**kwargs):
return original_function(**kwargs)
self.run = run_wrapper
# Don't show --help
nose_options = filter(lambda nose_option: '--help' not in nose_option._long_opts, nose_options)
for nose_option in nose_options:
args = nose_option._short_opts + nose_option._long_opts
if not args:
continue
type_mapping = {
'string': str,
'int': int,
'long': int,
'float': float,
# 'complex': str,
# 'choice': str,
}
unsupported_attr = ['action', 'dest', 'const']
kwargs = {}
for attr in OptParseOption.ATTRS:
if attr in unsupported_attr:
continue
attr_value = getattr(nose_option, attr)
if attr_value is None:
continue
if attr == 'type':
attr_value = type_mapping[attr_value]
if nose_option.nargs > 1:
attr_value = click.Tuple([attr_value])
if attr == 'default':
if attr_value == optparse.NO_DEFAULT:
continue
kwargs[attr] = attr_value
click.option(*args[:2], **kwargs)(run_wrapper)