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)
python类run()的实例源码
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, 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 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', '-v', 'pathspider'])
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 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_buffered(*arg, **kw):
kw['buffer_all'] = True
run(*arg, **kw)
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, lineno, name))
if line:
stack_trace.append(" %s" % (line.strip()))
stack_trace.append('\n=============================== END Thread Dump ===============================')
sys.stderr.write('\n'.join(stack_trace))
nosetester.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
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 _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 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, 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 run(self):
args = ['make', '-C', self.docker_submodule_path, 'build']
retcode = call(args)
self._check_retcode(retcode, args)
def run(self):
args = ['make', '-C', self.docker_submodule_path, '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', '-C', self.docker_submodule_path, '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