Python nose 模块,run() 实例源码
我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用nose.run()。
def main():
argv = [
"", "--with-coverage",
(
"--cover-package="
"girlfriend.workflow,"
"girlfriend.data,"
"girlfriend.util"
),
]
for importer, modname, ispkg in pkgutil.walk_packages(
path=girlfriend.testing.__path__,
prefix="girlfriend.testing."):
if ispkg:
continue
if modname in excludes:
continue
argv.append(modname)
nose.run(argv=argv)
def makeSuite(self):
"""returns a suite object of tests to run (unittest.TestSuite())
If self.suitepath is None,this must be implemented. The returned suite
object will be executed with all plugins activated. It may return
None.
Here is an example of a basic suite object you can return ::
>>> import unittest
>>> class SomeTest(unittest.TestCase):
... def runTest(self):
... raise ValueError("Now do something,plugin!")
...
>>> unittest.TestSuite([SomeTest()]) # doctest: +ELLIPSIS
<unittest...TestSuite tests=[<...SomeTest testMethod=runTest>]>
"""
raise NotImplementedError
def run(self):
proc_name = self.name
while True:
next_task = self.task_queue.get()
if next_task is None:
print("%s: Exiting" % proc_name)
self.task_queue.task_done()
break
print('%s: %s' % (proc_name, next_task))
result = next_task()
self.task_queue.task_done()
self.result_queue.put(result)
if next_task.exclusive:
print("%s: Exiting (exclusive)" % proc_name)
break
return
def makeSuite(self):
"""returns a suite object of tests to run (unittest.TestSuite())
If self.suitepath is None,plugin!")
...
>>> unittest.TestSuite([SomeTest()]) # doctest: +ELLIPSIS
<unittest...TestSuite tests=[<...SomeTest testMethod=runTest>]>
"""
raise NotImplementedError
def get_nose_runner(report_folder, parallel=True, process_timeout=600, process_restart=True):
"""Create a nose execution method"""
def _run_nose(test_folders):
import nose
import os.path
if not report_folder or not os.path.exists(report_folder) or not os.path.isdir(report_folder):
raise ValueError('Report folder {} does not exist'.format(report_folder))
arguments = [__file__, '-v', '-c', os.path.join(get_repo_root(), 'nose.cfg')]
if parallel:
arguments += ['--processes=-1', '--process-timeout={}'.format(process_timeout)]
if process_restart:
arguments += ['--process-restartworker']
arguments.extend(test_folders)
result = nose.run(argv=arguments)
return result
return _run_nose
def print_attributes(obj):
for attr in obj.__dict__:
print attr, getattr(obj, attr)
## pdb:
# https://docs.python.org/2/library/pdb.html
# http://web.archive.org/web/20120819135307/http://aymanh.com/python-debugging-techniques
## commands:
# help
# p pp # print,pretty print
# list args
# continue step next
# run restart
# where down up # print stack trace and move frame
# quit
# ;; (separator)
# [!]statement
# Commands that the debugger doesn’t recognize are assumed to be Python statements
# and are executed in the context of the program being debugged.
# Python statements can also be prefixed with an exclamation point (!).
## 1- in IPython,use %debug or %pdb
## 2- at the console prompt:
def run():
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))
# We write to stderr since nose does all of its output on stderr as well
sys.stderr.write('Running tests in "%s" ' % dirname)
success = []
argv = ['nosetests', dirname]
success.append(nose.run(argv=argv))
all_success = all(success)
if not all_success:
sys.stderr.write(('ERROR: %d/%d test suite(s) did not complete '
'successfully (see above).\n') % (len(success) - sum(success),
len(success)))
else:
sys.stderr.write(('OK: %d/%d test suite(s) did complete '
'successfully.\n') % (len(success), len(success)))
def run_buffered(*arg, **kw):
kw['buffer_all'] = True
run(*arg, **kw)
def main():
import os
import sys
from ptvsd.visualstudio_py_debugger import DONT_DEBUG, DEBUG_ENTRYPOINTS, get_code
from ptvsd.attach_server import DEFAULT_PORT, enable_attach, wait_for_attach
sys.path[0] = os.getcwd()
os.chdir(sys.argv[1])
secret = sys.argv[2]
port = int(sys.argv[3])
testFx = sys.argv[4]
args = sys.argv[5:]
DONT_DEBUG.append(os.path.normcase(__file__))
DEBUG_ENTRYPOINTS.add(get_code(main))
enable_attach(secret, ('127.0.0.1', port), redirect_output = False)
sys.stdout.flush()
print('READY')
sys.stdout.flush()
wait_for_attach()
try:
if testFx == 'pytest':
import pytest
pytest.main(args)
else:
import nose
nose.run(argv=args)
sys.exit()
finally:
pass
def _test_argv(self, label, verbose, extra_argv):
''' Generate argv for nosetest command
Parameters
----------
label : {'fast','full','',attribute identifier},optional
see ``test`` docstring
verbose : int,optional
Verbosity value for test outputs,in the range 1-10. Default is 1.
extra_argv : list,optional
List with any extra arguments to pass to nosetests.
Returns
-------
argv : list
command line arguments that will be passed to nose
'''
argv = [__file__, self.package_path, '-s']
if label and label != 'full':
if not isinstance(label, basestring):
raise TypeError('Selection label should be a string')
if label == 'fast':
label = 'not slow'
argv += ['-A', label]
argv += ['--verbosity', str(verbose)]
# When installing with setuptools,and also in some other cases,the
# test_*.py files end up marked +x executable. Nose,by default,does
# not run files marked with +x as they might be scripts. However,in
# our case nose only looks for test_*.py files under the package
# directory,which should be safe.
argv += ['--exe']
if extra_argv:
argv += extra_argv
return argv
def runtestsuite(args):
# Undo the logging basic config to allow for log capture
root_logger = logging.getLogger()
for handler in list(root_logger.handlers):
root_logger.removeHandler(handler)
# Collect and run tests
nose.run(argv=['nosetests', 'pathspider'])
def _test_argv(self,which should be safe.
argv += ['--exe']
if extra_argv:
argv += extra_argv
return argv
def run(self):
if self._run is None:
try:
from nose import run
except ImportError:
run = NotAModule(self._name)
self._run = run
return self._run
def __call__(self):
old_stderr = sys.stderr
sys.stderr = mystderr = StringIO()
test_dir = ytcfg.get("yt", "test_data_dir")
answers_dir = os.path.join(test_dir, "answers")
if '--with-answer-testing' in self.argv and \
not os.path.isdir(os.path.join(answers_dir, self.name)):
nose.run(argv=self.argv + ['--answer-store'],
addplugins=[AnswerTesting()], exit=False)
if os.path.isfile("{}.xml".format(self.name)):
os.remove("{}.xml".format(self.name))
nose.run(argv=self.argv, addplugins=[AnswerTesting()], exit=False)
sys.stderr = old_stderr
return mystderr.getvalue()
def run():
import nose
# runs tests in qutip.tests module only
nose.run(defaultTest="tncontract.tests", argv=['nosetests', '-v'])
def run_tests(plugins, config):
"""Run nosetests"""
nose.run(plugins=plugins.values(),
defaultTest=config.TESTS_DIR)
return plugins["timer"]._timed_tests # Benchmarking results
def run(self):
time.sleep(10)
thread_id_to_name = {}
try:
for t in threading.enumerate():
thread_id_to_name[t.ident] = '%s (daemon: %s)' % (t.name, t.daemon)
except:
pass
stack_trace = [
'===============================================================================',
'pydev pyunit runner: Threads still found running after tests finished',
'================================= Thread Dump =================================']
for thread_id, stack in sys._current_frames().items():
stack_trace.append('\n-------------------------------------------------------------------------------')
stack_trace.append(" Thread %s" % thread_id_to_name.get(thread_id, thread_id))
stack_trace.append('')
if 'self' in stack.f_locals:
sys.stderr.write(str(stack.f_locals['self']) + '\n')
for filename, lineno, name, line in traceback.extract_stack(stack):
stack_trace.append(' File "%s",line %d,in %s' % (filename, name))
if line:
stack_trace.append(" %s" % (line.strip()))
stack_trace.append('\n=============================== END Thread Dump ===============================')
sys.stderr.write('\n'.join(stack_trace))
def _test_argv(self,which should be safe.
argv += ['--exe']
if extra_argv:
argv += extra_argv
return argv
def _test_argv(self,which should be safe.
argv += ['--exe']
if extra_argv:
argv += extra_argv
return argv
def run(coverage=False):
"""
This runs the complete set of PyDiatomic tests.
"""
import nose
argv=['', '-s', '--where={}'.format(_base_dir), '--verbosity=2']
if coverage:
argv += ['--with-coverage', '--cover-package=abel']
result = nose.run(argv=argv)
status = int(not result)
return status
def run_cli(coverage=False):
"""
This also runs the complete set of PyDiatomic tests.
But uses sys.exit(status) instead of simply returning the status.
"""
status = run(coverage=coverage)
print('Exit status: {}'.format(status))
sys.exit(status)
def _test_argv(self,which should be safe.
argv += ['--exe']
if extra_argv:
argv += extra_argv
return argv
def run(self):
args = ['make', '-C', self.docker_submodule_path, 'build']
retcode = call(args)
self._check_retcode(retcode, args)
def run(self):
args = ['make', 'start-cluster']
retcode = call(args)
if self._check_retcode(retcode, args):
time.sleep(3)
def run(self):
if self.use_docker() and self.cluster_is_started():
args = ['make', 'stop-cluster']
retcode = call(args)
self._check_retcode(retcode, args)
def run(self):
for name in self._props:
self._create_and_activate_type(name, self._props[name])
def run(self):
bucket = self.distribution.get_command_obj('create_bucket_types')
bucket.riak_admin = self.riak_admin
for cmd_name in self.get_sub_commands():
self.run_command(cmd_name)
def run(self, **kwargs):
"""
Run the command
:param kwargs: kwargs
:return: void
"""
argv = sys.argv[:]
while len(argv) and argv[0] != self.name:
del argv[0]
success = nose.run(argv=argv)
if not success:
sys.exit(1)
def run(self):
f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
f.write(self.infile)
f.close()
print 'Finished background zip of: ', self.infile
def _test_argv(self,which should be safe.
argv += ['--exe']
if extra_argv:
argv += extra_argv
return argv
def run(*arg, **kw):
"""
Specialized version of nose.run for use inside of doctests that
test test runs.
This version of run() prints the result output to stdout. Before
printing,the output is processed by replacing the timing
information with an ellipsis (...),removing traceback stacks,and
removing trailing whitespace.
Use this version of run wherever you are writing a doctest that
tests nose (or unittest) test result output.
Note: do not use doctest: +ELLIPSIS when testing nose output,
since ellipses ("test_foo ... ok") in your expected test runner
output may match multiple lines of output,causing spurious test
passes!
"""
from nose import run
from nose.config import Config
from nose.plugins.manager import PluginManager
buffer = Buffer()
if 'config' not in kw:
plugins = kw.pop('plugins', [])
if isinstance(plugins, list):
plugins = PluginManager(plugins=plugins)
env = kw.pop('env', {})
kw['config'] = Config(env=env, plugins=plugins)
if 'argv' not in kw:
kw['argv'] = ['nosetests', '-v']
kw['config'].stream = buffer
# Set up buffering so that all output goes to our buffer,
# or warn user if deprecated behavior is active. If this is not
# done,prints and warnings will either be out of place or
# disappear.
stderr = sys.stderr
stdout = sys.stdout
if kw.pop('buffer_all', False):
sys.stdout = sys.stderr = buffer
restore = True
else:
restore = False
warn("The behavior of nose.plugins.plugintest.run() will change in "
"the next release of nose. The current behavior does not "
"correctly account for output to stdout and stderr. To enable "
"correct behavior,use run_buffered() instead,or pass "
"the keyword argument buffer_all=True to run().",
DeprecationWarning, stacklevel=2)
try:
run(*arg, **kw)
finally:
if restore:
sys.stderr = stderr
sys.stdout = stdout
out = buffer.getvalue()
print munge_nose_output_for_doctest(out)
def run_module_suite(file_to_run=None, argv=None):
"""
Run a test module.
Equivalent to calling ``$ nosetests <argv> <file_to_run>`` from
the command line
Parameters
----------
file_to_run : str,optional
Path to test module,or None.
By default,run the module from which this function is called.
argv : list of strings
Arguments to be passed to the nose test runner. ``argv[0]`` is
ignored. All command line arguments accepted by ``nosetests``
will work. If it is the default value None,sys.argv is used.
.. versionadded:: 1.9.0
Examples
--------
Adding the following::
if __name__ == "__main__" :
run_module_suite(argv=sys.argv)
at the end of a test module will run the tests when that module is
called in the python interpreter.
Alternatively,calling::
>>> run_module_suite(file_to_run="numpy/tests/test_matlib.py")
from an interpreter will run all the test routine in 'test_matlib.py'.
"""
if file_to_run is None:
f = sys._getframe(1)
file_to_run = f.f_locals.get('__file__', None)
if file_to_run is None:
raise AssertionError
if argv is None:
argv = sys.argv + [file_to_run]
else:
argv = argv + [file_to_run]
nose = import_nose()
from .noseclasses import KnownFailurePlugin
nose.run(argv=argv, addplugins=[KnownFailurePlugin()])
def run_module_suite(file_to_run=None, addplugins=[KnownFailurePlugin()])
def run(*arg, **kw)
finally:
if restore:
sys.stderr = stderr
sys.stdout = stdout
out = buffer.getvalue()
print munge_nose_output_for_doctest(out)
def run_module_suite(file_to_run=None, None)
if file_to_run is None:
raise AssertionError
if argv is None:
argv = sys.argv + [file_to_run]
else:
argv = argv + [file_to_run]
nose = import_nose()
from .noseclasses import KnownFailure
nose.run(argv=argv, addplugins=[KnownFailure()])
def run_module_suite(file_to_run=None, addplugins=[KnownFailure()])
def run_module_suite(file_to_run=None, addplugins=[KnownFailurePlugin()])
def __init__(self, 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)
def get_nose_runner(report_folder, process_restart=True,
xunit_report=False, exclude_integration=True, code_coverage=False):
"""Create a nose execution method"""
def _run_nose(name, working_dir):
import nose
import os.path
if not report_folder \
or not os.path.exists(report_folder) \
or not os.path.isdir(report_folder):
raise ValueError('Report folder {} does not exist'.format(report_folder))
arguments = ['-w', working_dir, '-v']
if parallel:
arguments += ['--processes=-1', '--process-timeout={}'.format(process_timeout)]
if process_restart:
arguments += ['--process-restartworker']
if xunit_report:
log_file = os.path.join(report_folder, name + '-report.xml')
arguments += ['--with-xunit', '--xunit-file', log_file]
else:
log_file = ''
if exclude_integration:
arguments += ['--ignore-files=integration*']
if code_coverage:
# coverage_config = os.path.join(os.path.dirname(__file__),'.coveragerc')
# coverage_folder = os.path.join(report_folder,'code_coverage')
# make_dirs(coverage_folder)
# if not os.path.exists(coverage_folder) or not os.path.isdir(coverage_folder):
# raise Exception('Failed to create folder {} for code coverage result'
# .format(coverage_folder))
arguments += ['--with-coverage']
debug_file = os.path.join(report_folder, name + '-debug.log')
arguments += ['--debug-log={}'.format(debug_file)]
print('\n')
print('<<< Run {} >>>'.format(name))
start = datetime.now()
result = nose.run(argv=arguments)
end = datetime.now()
return result, start, end, log_file
return _run_nose
def run_module_suite(file_to_run=None, addplugins=[KnownFailurePlugin()])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。