def main():
    """Run tests when called directly"""
    import nose
    print("-----------------")
    print("Running the tests")
    print("-----------------")
    nose.main()
Beispiel #2
0
def main():
    #logging.basicConfig(level=logging.DEBUG)
    sys.path.insert(0, SDK_PATH)
    sys.path.insert(0, "stashboard")
    import dev_appserver
    dev_appserver.fix_sys_path()
    nose.main()
Beispiel #3
0
def main():
    """Runs the testsuite as command line application."""
    import nose
    try:
        nose.main(defaultTest="")
    except Exception, e:
        print 'Error: %s' % e
Beispiel #4
0
def test():
    r"""
    Run all the doctests available.
    """
    path = os.path.split(__file__)[0]
    print("Path: "+path)
    nose.main(argv=['-w', path, '--with-doctest'])
Beispiel #5
0
def main():
    #logcat()
    def is_plugin(c):
        try: return issubclass(c,nose.plugins.Plugin)
        except TypeError: return False

    plugins = [ ]

    def listdir(dir):
        try: return os.listdir(dir)
        except OSError: return []

    for p in [    os.path.join(PLUGINS_DIRECTORY,_)
                for _ in listdir(PLUGINS_DIRECTORY) if _.endswith('.py') ]:
        print ('Loading plugin %s' % p)

        l={}
        c=open(p,'rt').read()    # Windows or Unix line endings
        if hasattr(c,'decode'):
            c=c.decode('utf-8') # Python 2.x
        _exec(compile(c, p, 'exec'), globals(), l)

        plugins += [ c() for c in l.values() if is_plugin(c) ]

    plugins = [ c() for c in globals().values() if is_plugin(c) ] + plugins

    nose.main(argv=sys.argv + ['-s','-d'], config=nose.config.Config(
            plugins=nose.plugins.manager.DefaultPluginManager(plugins=plugins)))
def test(nose_arguments):
    """Run nosetests with the given arguments and report coverage"""
    assert nose_arguments[0] == ""
    import nose
    from nose.plugins.cover import Coverage

    nose.main(argv=nose_arguments, addplugins=[Coverage()])
Beispiel #7
0
def main():
  sys.path = extra_paths + sys.path
  os.environ['SERVER_SOFTWARE'] = 'Development via nose'
  os.environ['SERVER_NAME'] = 'Foo'
  os.environ['SERVER_PORT'] = '8080'
  os.environ['APPLICATION_ID'] = 'test-app-run'
  os.environ['USER_EMAIL'] = '*****@*****.**'
  os.environ['CURRENT_VERSION_ID'] = 'testing-version'
  import main as app_main
  from google.appengine.api import apiproxy_stub_map
  from google.appengine.api import datastore_file_stub
  from google.appengine.api import mail_stub
  from google.appengine.api import user_service_stub
  from google.appengine.api import urlfetch_stub
  from google.appengine.api.memcache import memcache_stub
  apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
  apiproxy_stub_map.apiproxy.RegisterStub('urlfetch',
                                          urlfetch_stub.URLFetchServiceStub())
  apiproxy_stub_map.apiproxy.RegisterStub('user',
                                          user_service_stub.UserServiceStub())
  apiproxy_stub_map.apiproxy.RegisterStub('datastore',
    datastore_file_stub.DatastoreFileStub('test-app-run', None, None))
  apiproxy_stub_map.apiproxy.RegisterStub('memcache',
    memcache_stub.MemcacheServiceStub())
  apiproxy_stub_map.apiproxy.RegisterStub('mail', mail_stub.MailServiceStub())
  import django.test.utils
  django.test.utils.setup_test_environment()
  
  from nose.plugins import cover
  plugin = cover.Coverage()
  nose.main(plugins=[AppEngineDatastoreClearPlugin(), plugin])
def main():
    """run nose tests on "<package-name>" where <package-name is ".." dir"""

    path = os.path.abspath(os.path.join('..'))

    package_name = os.path.basename(path)

    try:
        my_module = importlib.import_module(package_name)
    except ImportError:
        raise ImportError('Cound not import {} so cannot '
                          'run nose tests'.format(package_name))

    # need to change the working directory to the installed package
    # otherwise nose will just find <package-name> based on the current
    # directory
    cwd = os.getcwd()
    package_path = os.path.dirname(my_module.__file__)
    os.chdir(package_path)


    print('nose tests on "{}" package.'.format(package_name))
    #'nose ignores 1st argument http://stackoverflow.com/a/7070571/2530083'
    nose.main(argv=['nose_ignores_1st_arg',
                    package_name,
                    '-v',
                    '--with-doctest',
                    '--doctest-options=+ELLIPSIS',
                    '--doctest-options=+IGNORE_EXCEPTION_DETAIL'])

    os.chdir(cwd)
Beispiel #9
0
    def run_tests(self):
        try:
            import matplotlib
            matplotlib.use('agg')
            import nose
            from matplotlib.testing.noseclasses import KnownFailure
            from matplotlib import default_test_modules
            from matplotlib import font_manager
            import time
            # Make sure the font caches are created before starting any possibly
            # parallel tests
            if font_manager._fmcache is not None:
                while not os.path.exists(font_manager._fmcache):
                    time.sleep(0.5)
            plugins = [KnownFailure]

            # Nose doesn't automatically instantiate all of the plugins in the
            # child processes, so we have to provide the multiprocess plugin
            # with a list.
            from nose.plugins import multiprocess
            multiprocess._instantiate_plugins = plugins

            if '--no-pep8' in sys.argv:
                default_test_modules.remove('matplotlib.tests.test_coding_standards')
                sys.argv.remove('--no-pep8')
            elif '--pep8' in sys.argv:
                default_test_modules = ['matplotlib.tests.test_coding_standards']
                sys.argv.remove('--pep8')
            nose.main(addplugins=[x() for x in plugins],
                      defaultTest=default_test_modules,
                      argv=['nosetests'],
                      exit=False)
        except ImportError:
            sys.exit(-1)
Beispiel #10
0
def main(operation=None):
    if operation == 'run':
        logger.info('Running the application.')
        cherrypy.config.update({
            'tools.staticdir.root': settings.PROJECT_ROOT,
            'error_page.404': app.error_404
        })
        cherrypy.quickstart(app.FlyingFist(), config='config.conf')
    elif operation == 'create_storage':
        logger.info('Creating the RDF storage.')
        st = storage.StorageCreator()
        st.create()
        st.save(settings.ONTOLOGY_FILE, settings.INSTANCES_FILE)
    elif operation == 'create_index':
        logger.info('Creating the Lucene index.')
        ic = storage.IndexCreator()
        ic.create_index()
    elif operation == 'test':
        logger.info('Running tests.')
        import nose
        nose.main(argv=['-w', 'tests'])
    else:
        sys.stderr.write('Unknown argument: %s\r\n' % operation)
        print __doc__
        return 2
    return 0
Beispiel #11
0
def execute_command(argument_values):
    """ Entry point for manage.py utility.

    Execute proper manage.py command based on passed argv.
    :param argument_values: sys.argv
    :return:
    """
    parser = argparse.ArgumentParser(description='Management tool.')
    parser.add_argument('--add-tests', type=str, nargs="*", help='Add tests to the project.')
    parser.add_argument('--settings', type=str, help='Declaring location of settings module.')
    parser.add_argument('--pythonpath', type=str, help='Declaring location of project.')
    parser.add_argument('--run', action='store_true', help='Execute nose test run.')
    args, nose_arg = parser.parse_known_args(argument_values[1:])  # sys.argv[1:]

    if args.settings:
        os.environ["POLON_SETTINGS_MODULE"] = args.settings

    if args.pythonpath:
        sys.path.insert(0, args.pythonpath)

    if args.add_tests:
        from polon.core.management.commands import add_tests
        add_tests(*args.add_tests)

    if args.run:
        import nose
        from polon.plugins import PolonInterceptor
        nose.main(argv=[argument_values[0], "--with-polon-interceptor"] + nose_arg,
                  addplugins=[PolonInterceptor()])
Beispiel #12
0
def main():
    env = os.environ.copy()
    if "NOSE_IGNORE_FILES" not in env:
        env["NOSE_IGNORE_FILES"] = ignorefiles
    if "NOSE_WITH_DOCTEST" not in env:
        env["NOSE_WITH_DOCTEST"] = "t"
    nose.main(env=env, addplugins=[nosecaptureexc.CaptureExcPlugin(), nosehgenv.HgEnvPlugin()])
Beispiel #13
0
    def run_tests(self):
        import matplotlib
        matplotlib.use('agg')
        import nose
        from matplotlib.testing.noseclasses import KnownFailure
        from matplotlib import default_test_modules as testmodules
        from matplotlib import font_manager
        import time
        # Make sure the font caches are created before starting any possibly
        # parallel tests
        if font_manager._fmcache is not None:
            while not os.path.exists(font_manager._fmcache):
                time.sleep(0.5)
        plugins = [KnownFailure]

        # Nose doesn't automatically instantiate all of the plugins in the
        # child processes, so we have to provide the multiprocess plugin
        # with a list.
        from nose.plugins import multiprocess
        multiprocess._instantiate_plugins = plugins

        if self.omit_pep8:
            testmodules.remove('matplotlib.tests.test_coding_standards')
        elif self.pep8_only:
            testmodules = ['matplotlib.tests.test_coding_standards']

        nose.main(addplugins=[x() for x in plugins],
                  defaultTest=testmodules,
                  argv=['nosetests'] + self.test_args,
                  exit=True)
Beispiel #14
0
def main():
    """Run tests when called directly"""
    import nose
    print "-----------------"
    print "Running the tests"
    print "-----------------"
    nose.main()
Beispiel #15
0
def run_tests(verbosity=1, interactive=False):
    from django.conf import settings
    from django.core import management
    from django.db import connection
    from django.test.utils import setup_test_environment, \
                                  teardown_test_environment

    setup_test_environment()
    settings.DEBUG = False

    if not os.path.exists(settings.EXTENSIONS_MEDIA_ROOT):
        os.mkdir(settings.EXTENSIONS_MEDIA_ROOT, 0755)

    old_db_name = 'default'
    connection.creation.create_test_db(verbosity, autoclobber=not interactive)
    management.call_command('syncdb', verbosity=verbosity,
                            interactive=interactive)

    nose_argv = ['runtests.py', '-v',
                 '--with-coverage',
                 '--with-doctest',
                 '--doctest-extension=.txt',
                 '--cover-package=djblets']

    if len(sys.argv) > 2:
        node_argv += sys.argv[2:]

    nose.main(argv=nose_argv)

    connection.creation.destroy_test_db(old_name, verbosity)
    teardown_test_environment()
Beispiel #16
0
def runtests():
    import nose
    argv = []
    argv.insert(1, '')
    argv.insert(2, '--with-coverage')
    argv.insert(3, '--cover-package=facio')
    nose.main(argv=argv)
Beispiel #17
0
def nose_test(module=None, extraArgs=None, pymelDir=None):
    """
    Run pymel unittests / doctests
    """
    if pymelDir:
        os.chdir(pymelDir)
            
    os.environ['MAYA_PSEUDOTRANS_MODE']='5'
    os.environ['MAYA_PSEUDOTRANS_VALUE']=','
    
    noseKwArgs={}
    noseArgv = "dummyArg0 --with-doctest -vv".split()
    if module is None:
        #module = 'pymel' # if you don't set a module, nose will search the cwd
                    
        exclusion = '^windows ^tools ^example1 ^testingutils ^pmcmds ^testPa ^maya ^maintenance ^pymel_test ^TestPymel ^testPassContribution$'
        noseArgv += ['--exclude', '|'.join( [ '(%s)' % x for x in exclusion.split() ] )  ]
           
    if inspect.ismodule(module):
        noseKwArgs['module']=module
    elif module:
        noseArgv.append(module)
    if extraArgs is not None:
        noseArgv.extend(extraArgs)
    noseKwArgs['argv'] = noseArgv
    
    patcher = DocTestPatcher()
    try:
        print noseKwArgs
        nose.main( **noseKwArgs)
    finally:
        patcher.reset()
Beispiel #18
0
def main():
    # First of all add current work directory to ``sys.path`` if it not there
    cwd = os.getcwd()

    if not cwd in sys.path or not cwd.strip(os.sep) in sys.path:
        sys.path.append(cwd)

    # Try to find that DjangoPlugin loaded from entry_points or not
    found, kwargs = False, {}

    manager = EntryPointPluginManager()
    manager.loadPlugins()

    for plugin in manager.plugins:
        if isinstance(plugin, DjangoPlugin):
            found = True
            break

    # If not manually add
    if not found:
        kwargs = {'addplugins': [DjangoPlugin()]}

    # Enable DjangoPlugin
    os.environ['NOSE_WITH_DJANGO'] = '1'

    # Run ``nosetests``
    nose.main(**kwargs)
Beispiel #19
0
    def run(self):
        test.run(self)

        import nose
        import logging
        logging.disable(logging.CRITICAL)
        nose.main(argv=['tests', '-v'])
Beispiel #20
0
def do_test():
    do_uic()
    do_rcc()
    call(py_script('flake8'), 'mozregui', 'build.py', 'tests')
    print('Running tests...')
    import nose
    nose.main(argv=['-s', 'tests'])
Beispiel #21
0
    def run(self, project, args, unknown_args):
        try:
            import nose

            argv = ["discover"]

            print("Running tests for:")

            if args.include_forecast:
                print("   forecast")
                argv.append("forecast")

            for application in project.applications.keys():
                if application.startswith("forecast."):
                    continue

                argv.append(application)
                print("   %s" % (application,))

            print()

            argv.extend(unknown_args)
            nose.main(argv=argv)

        except ImportError:
            raise ForecastError("nosetests required for test running.")
Beispiel #22
0
def start():
    global pulsar
    argv = sys.argv
    if len(argv) > 1 and argv[1] == 'nose':
        pulsar = None
        sys.argv.pop(1)
    
    if pulsar:
        from pulsar.apps.test import TestSuite
        from pulsar.apps.test.plugins import bench, profile
        
        os.environ['stdnet_test_suite'] = 'pulsar'
        suite = TestSuite(
                description='Dynts Asynchronous test suite',
                    plugins=(profile.Profile(),
                             bench.BenchMark(),)
                  )
        suite.start()
    elif nose:
        os.environ['stdnet_test_suite'] = 'nose'
        argv = list(sys.argv)
        noseoption(argv, '-w', value = 'tests/regression')
        noseoption(argv, '--all-modules')
        nose.main(argv=argv, addplugins=[NoseHttpProxy()])
    else:
        print('To run tests you need either pulsar or nose.')
        exit(0)
Beispiel #23
0
def start(argv=None, modules=None, nose_options=None, description=None,
          version=None, plugins=None):
    '''Start djpcms tests. Use this function to start tests for
djpcms aor djpcms applications. It check for pulsar and nose
and add testing plugins.'''
    use_nose = False
    argv = argv or sys.argv
    description = description or 'Djpcms Asynchronous test suite'
    version = version or djpcms.__version__
    if len(argv) > 1 and argv[1] == 'nose':
        use_nose = True
        sys.argv.pop(1)
    if use_nose:
        os.environ['djpcms_test_suite'] = 'nose'
        if stdnet_test and plugins is None:
            plugins = [stdnet_test.NoseStdnetServer()]
        argv = list(argv)
        if nose_options:
            nose_options(argv)
        nose.main(argv=argv, addplugins=plugins)
    else:
        os.environ['djpcms_test_suite'] = 'pulsar'
        from pulsar.apps.test import TestSuite
        from pulsar.apps.test.plugins import bench, profile
        if stdnet_test and plugins is None:
            plugins = (stdnet_test.PulsarStdnetServer(),
                       bench.BenchMark(),
                       profile.Profile())
        suite = TestSuite(modules=modules,
                          plugins=plugins,
                          description=description,
                          version=version)
        suite.start()
Beispiel #24
0
def run():
    p.start()
    print(p)
    try:
        nose.main(addplugins=[x() for x in plugins], env=env)
    finally:
        os.kill(p.pid, signal.SIGINT)
        p.join()
Beispiel #25
0
def run_tests(nosetest):
    """
    Run Tests using nose
    """
    args = [sys.argv[0]] + nosetest if nosetest else [sys.argv[0]]

    with current_app.app_context():
        nose.main(argv=args)
Beispiel #26
0
 def run(cls, *args, **kwargs):
     nc = nose.config.Config()
     nc.verbosity = 3
     nc.plugins = PluginManager(plugins=[Xunit()])
     nose.main(module=test, config=nc, argv=[
         __file__,
         "--with-xunit",
         "--xunit-file=nosetests.xml"
     ])
Beispiel #27
0
def run():
    if p is not None:
        p.start()
    try:
        nose.main(addplugins=[x() for x in plugins], env=env)
    finally:
        if p is not None:
            os.kill(p.pid, signal.SIGINT)
            p.join()
Beispiel #28
0
def setup_py_test():
    """Runner to use for the 'test_suite' entry of your setup.py.

    Prevents any name clash shenanigans from the command line
    argument "test" that the "setup.py test" command sends
    to nose.

    """
    nose.main(addplugins=[NoseSQLAlchemy()], argv=['runner'])
Beispiel #29
0
def test():
    """
    Run git-sweep's test suite.
    """
    import nose

    import sys

    nose.main(argv=['nose'] + sys.argv[1:])
Beispiel #30
0
 def run(self, parser, args):
     import nose
     sys.argv = [sys.argv[0]] + args.nose_args
     if 'RELENGAPI_SETTINGS' in os.environ:
         del os.environ['RELENGAPI_SETTINGS']
     # push a fake app context to avoid tests accidentally using the
     # runtime app context (for example, the development DB)
     with Flask(__name__).app_context():
         nose.main()
import nose
import os, glob
from os import path
from nose.tools import raises
from app.storepick_menu_convertor import *

if __name__ == '__main__':
    nose.main(exit=False)


def test_process():
    with open("tests/data/data.csv", encoding='utf-8') as csvf:
        csv_reader = csv.DictReader(csvf)

        headers = csv_reader.fieldnames
        headers.pop(0)

        num_of_levels = int((len(headers)) / 3)

        assert True, process(csv_reader, num_of_levels)


def test_process_empty_file():
    with open("tests/data/test_data_empty_file.csv", encoding='utf-8') as csvf:
        csv_reader = csv.DictReader(csvf)

        headers = csv_reader.fieldnames
        headers.pop(0)

        num_of_levels = int((len(headers)) / 3)
Beispiel #32
0
#!/usr/bin/env python
from nose import main

main()
Beispiel #33
0
    Have only rank 0 report test results. Test results are aggregated
    across processes, i.e., if an exception happens in a single
    process then that is reported, otherwise if an assertion failed in any
    process then that is reported, otherwise it's a success.
    """
    # Required attributes:

    name = 'mpi'
    enabled = True

    def setOutputStream(self, stream):
        if not is_root:
            return NoopStream()


if __name__ == '__main__':
    import sys

    # This didn't work, mpich2 would tend to crash *shrug*
    #if MPI.COMM_WORLD.Get_size() == 1:
    #    # Launch using mpiexec
    #    args = [sys.argv[0], '1']
    #    print args
    #    sys.stderr.write('Launched without mpiexec; '
    #                     'calling with "mpiexec -np %d ..."\n' % WANTED_COMM_SIZE)
    #    os.execlp('mpiexec', 'mpiexec', '-np', str(WANTED_COMM_SIZE),
    #              sys.executable, *args)
    #    # Does not return!

    nose.main(addplugins=[MpiOutput()], argv=sys.argv)
Beispiel #34
0
@with_setup(setup, teardown)
def test_simple_embedded():
    os.chdir('examples')
    os.chdir('simple_embedded')
    build_and_run_pydexe("hello")


@with_setup(setup, teardown)
def test_interpcontext():
    os.chdir('examples')
    os.chdir('interpcontext')
    build_and_run_pydexe("interpcontext")


@with_setup(setup, teardown)
def test_def():
    os.chdir('examples')
    os.chdir('def')
    build_and_run()


@with_setup(setup, teardown)
def test_pydobject():
    os.chdir('examples')
    os.chdir('pydobject')
    build_and_run_pydexe("example")


nose.main(addplugins=[OurPlugin()])
Beispiel #35
0
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# * Neither the name of paramax nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#===============================================================================

#!/usr/bin/env python

import nose
nose.main('paramz', defaultTest='paramz/tests')
Beispiel #36
0
def test():
    r"""
    Run all the doctests available.
    """
    path = os.path.split(__file__)[0]
    nose.main(argv=['-w', path, '--with-doctest'])
Beispiel #37
0
    def release(self, priority=None, delay=0):
        """Release this job back into the ready queue."""
        if self.reserved:
            self.conn.release(self.jid, priority or self._priority(), delay)
            self.reserved = False

    def bury(self, priority=None):
        """Bury this job."""
        if self.reserved:
            self.conn.bury(self.jid, priority or self._priority())
            self.reserved = False

    def kick(self):
        """Kick this job alive."""
        self.conn.kick_job(self.jid)

    def touch(self):
        """Touch this reserved job, requesting more time to work on it before
        it expires."""
        if self.reserved:
            self.conn.touch(self.jid)

    def stats(self):
        """Return a dict of stats about this job."""
        return self.conn.stats_job(self.jid)


if __name__ == '__main__':
    import nose
    nose.main(argv=['nosetests', '-c', '.nose.cfg'])
Beispiel #38
0
@raises(IndexError)
def test_too_high_index():
    """Test IndexError is raised for a too high index."""
    result = cs.search('glucose')[7843]


def test_search_failed():
    """Test ChemSpiPyServerError is raised for an invalid SMILES."""
    results = cs.search('O=C(OCC)C*')
    results.wait()
    ok_(isinstance(results.exception, ChemSpiPyServerError))
    eq_(results.status, 'Failed')
    eq_(repr(results), 'Results(Failed)')
    eq_(results.ready(), True)
    eq_(results.success(), False)
    eq_(results.count, 0)
    ok_(results.duration.total_seconds() > 0)


@raises(ChemSpiPyServerError)
def test_search_exception():
    """Test ChemSpiPyServerError is raised for an invalid SMILES."""
    results = cs.search('O=C(OCC)C*', raise_errors=True)
    results.wait()


# ordered search - ascending/descending, different sort orders

if __name__ == '__main__':
    nose.main()
Beispiel #39
0
    # allow passing extra options and running individual tests
    # Examples:
    #
    #    python runtests.py semantics.doctest
    #    python runtests.py --with-id -v
    #    python runtests.py --with-id -v nltk.featstruct

    args = sys.argv[1:]
    if not args:
        args = [NLTK_TEST_DIR]

    if all(arg.startswith('-') for arg in args):
        # only extra options were passed
        args += [NLTK_TEST_DIR]

    arguments = [
        '--exclude=',  # why is this needed?
        #'--with-xunit',
        #'--xunit-file=$WORKSPACE/nosetests.xml',
        #'--nocapture',
        '--with-doctest',
        #'--doctest-tests',
        #'--debug=nose,nose.importer,nose.inspector,nose.plugins,nose.result,nose.selector',
        '--doctest-extension=.doctest',
        '--doctest-fixtures=_fixt',
        '--doctest-options=+ELLIPSIS,+NORMALIZE_WHITESPACE,+IGNORE_EXCEPTION_DETAIL,+ALLOW_UNICODE,doctestencoding=utf-8',
        #'--verbosity=3',
    ] + args

    nose.main(argv=arguments, plugins=manager.plugins)
Beispiel #40
0
    for o in g.objects(NS.s, NS.p):
        assert turtle_serializer.isValidList(o)


def test_turtle_namespace():
    graph = Graph()
    graph.bind("OBO", "http://purl.obolibrary.org/obo/")
    graph.bind("GENO", "http://purl.obolibrary.org/obo/GENO_")
    graph.bind("RO", "http://purl.obolibrary.org/obo/RO_")
    graph.bind("RO_has_phenotype", "http://purl.obolibrary.org/obo/RO_0002200")
    graph.add((
        URIRef("http://example.org"),
        URIRef("http://purl.obolibrary.org/obo/RO_0002200"),
        URIRef("http://purl.obolibrary.org/obo/GENO_0000385"),
    ))
    output = [
        val for val in graph.serialize(format="turtle").splitlines()
        if not val.startswith("@prefix")
    ]
    output = " ".join(output)
    assert "RO_has_phenotype:" in output
    assert "GENO:0000385" in output


if __name__ == "__main__":
    import nose
    import sys

    nose.main(defaultTest=sys.argv[0])
    true_fval = 5.0
    true_xf = -0.0
    xf, fval, info = brent_max(g, -10, 10, args=(y, ))
    assert_almost_equal(true_fval, fval, decimal=4)
    assert_almost_equal(true_xf, xf, decimal=4)


@raises(ValueError)
def test_invalid_a_brent_max():
    brent_max(f, -np.inf, 2)


@raises(ValueError)
def test_invalid_b_brent_max():
    brent_max(f, -2, np.inf)


@raises(ValueError)
def test_invalid_a_b_brent_max():
    brent_max(f, 1, 0)


if __name__ == '__main__':
    import sys
    import nose

    argv = sys.argv[:]
    argv.append('--verbose')
    argv.append('--nocapture')
    nose.main(argv=argv, defaultTest=__file__)
Beispiel #42
0
        wait_for_completion(lambda: len(self.g3.get_global_rib(rf="vpnv4")) == 2)
        wait_for_completion(lambda: len(self.g2.get_global_rib()) == 1)
        wait_for_completion(lambda: len(self.g5.get_global_rib()) == 1)

    def test_05_softreset_out(self):
        self.g3.softreset(self.g2, type='out')
        wait_for_completion(lambda: len(self.g3.get_global_rib()) == 0)
        wait_for_completion(lambda: len(self.g3.get_global_rib(rf="vpnv4")) == 2)
        wait_for_completion(lambda: len(self.g2.get_global_rib()) == 1)
        wait_for_completion(lambda: len(self.g5.get_global_rib()) == 1)

    def test_06_graceful_restart(self):
        self.g1.stop_gobgp()
        self.g3.wait_for(expected_state=BGP_FSM_ACTIVE, peer=self.g1)

        wait_for_completion(lambda: len(self.g3.get_global_rib(rf="vpnv4")) == 2)
        wait_for_completion(lambda: len(self.g2.get_global_rib()) == 1)

        wait_for_completion(lambda: len(self.g3.get_global_rib(rf="vpnv4")) == 1)
        wait_for_completion(lambda: len(self.g2.get_global_rib()) == 0)


if __name__ == '__main__':
    output = local("which docker 2>&1 > /dev/null ; echo $?", capture=True)
    if int(output) is not 0:
        print("docker not found")
        sys.exit(1)

    nose.main(argv=sys.argv, addplugins=[OptionParser()],
              defaultTest=sys.argv[0])
Beispiel #43
0
    m.initialize_parameter()
    m[:] = pars['bgplvm_p']
    m.update_model(True)

    #m.optimize(messages=0)
    np.random.seed(111)
    m.plot_inducing(projection='2d')
    np.random.seed(111)
    m.plot_inducing(projection='3d')
    np.random.seed(111)
    m.plot_latent(projection='2d', labels=labels)
    np.random.seed(111)
    m.plot_scatter(projection='3d', labels=labels)
    np.random.seed(111)
    m.plot_magnification(labels=labels)
    np.random.seed(111)
    m.plot_steepest_gradient_map(resolution=10, data_labels=labels)
    for do_test in _image_comparison(baseline_images=[
            'bayesian_gplvm_{}'.format(sub) for sub in [
                "inducing", "inducing_3d", "latent", "latent_3d",
                "magnification", 'gradient'
            ]
    ],
                                     extensions=extensions):
        yield (do_test, )


if __name__ == '__main__':
    import nose
    nose.main(defaultTest='./plotting_tests.py')
Beispiel #44
0
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# * Neither the name of paramax nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#===============================================================================
import matplotlib
matplotlib.use('agg')

import nose
nose.main('topslam', defaultTest='topslam/tests')

Beispiel #45
0
        os.path.dirname(
            os.path.dirname(
                os.path.dirname(
                    os.path.dirname(os.path.dirname(
                        os.path.realpath(__file__))))))), 'pyogp.lib.client')

base_package_path = os.path.join(
    os.path.dirname(
        os.path.dirname(
            os.path.dirname(
                os.path.dirname(
                    os.path.dirname(os.path.dirname(
                        os.path.realpath(__file__))))))), 'pyogp.lib.base')

sys.path.append(client_package_path)
sys.path.append(base_package_path)

if os.path.exists(eggs_dir):

    print 'Adding eggs to sys.path...'

    for directory in os.listdir(eggs_dir):
        sys.path.append(os.path.join(eggs_dir, directory))

else:

    print 'No eggs dir to add to path. Make sure to add the necessary module dependencies to your python path prior to running.'

if __name__ == '__main__':
    nose.main(argv=['nose'] + sys.argv[1:])
Beispiel #46
0
                              coords[0][2] - coords[3][2],
                              coords[1][2] - coords[3][2],
                              coords[2][2] - coords[3][2]
                          ]])
        invJ = J.I
        detJ = numpy.linalg.det(J)
        gradPhi_h = 0
        for k in range(len(elementQuadrature.points)):
            tempQpt = 0
            zCoord = elementQuadrature.points[k][0]*coords[0][2] \
                +elementQuadrature.points[k][1]*coords[1][2] \
                +elementQuadrature.points[k][2]*coords[2][2] \
                +(1-elementQuadrature.points[k][0]-elementQuadrature.points[k][1]-elementQuadrature.points[k][2])*coords[3][2]
            for i in range(mesh.nNodes_element):
                temp = 0
                for j in range(domain.nd):
                    temp = temp + derivativeArrayRef[i][j] * invJ[j, 2]
                tempQpt = tempQpt + vector[nodes[i]][1] * temp
            exactgradPhi = dvOfXdz([0, 0, zCoord])
            gradPhi_h = gradPhi_h + tempQpt
            error = error + (exactgradPhi - gradPhi_h
                             )**2 * elementQuadrature.weights[k] * abs(detJ)

    error = sqrt(error)
    ok(error < errorTotal)


if __name__ == '__main__':
    import nose
    nose.main(defaultTest='test_poiseuilleError:test_poiseuilleError')
from nose.tools import eq_ as eq
from nose.tools import ok_ as ok
import subprocess
import os
import pytest


@pytest.mark.slowTest
def test_workflowPUMI(verbose=0):
    """Test serial workflow: load model and mesh, solve within proteus 
    estimate error, adapt, solve again. It's not so important if the
    problem isn't setup properly"""
    subprocess.call("parun couette_so.py", shell=True)
    assert (True)


if __name__ == '__main__':
    import nose
    nose.main(defaultTest='test_workflowPUMI:test_workflowPUMI')
Beispiel #48
0
#!/usr/bin/python3

import nose
import os
import sys
import glob

from gladecheck import GladePlugin

# Check for prerequisites
# used in check_icons.py via tests/lib/iconcheck.py
if os.system("rpm -q adwaita-icon-theme >/dev/null 2>&1") != 0:
    print("adwaita-icon-theme must be installed")
    sys.exit(99)

# If no test scripts were specified on the command line, select check_*.py
if len(sys.argv) <= 1 or not sys.argv[-1].endswith('.py'):
    sys.argv.extend(glob.glob(os.path.dirname(sys.argv[0]) + "/check_*.py"))

# Run in verbose mode
sys.argv.append('-v')

# Run nose with the glade plugin
nose.main(addplugins=[GladePlugin()])
Beispiel #49
0
 def run_nose(self):
     self.result = nose.main(argv=self.nose_argv, exit=False)
Beispiel #50
0
def main():
    """Run main."""
    import nose
    nose.main()
    return 0
Beispiel #51
0
"""

import nose
import sys

import numpy as np
np.seterr(all='ignore')


def dummy_start_vm(args, run_headless=False):
    pass


if '--noguitests' in sys.argv:
    sys.argv.remove('--noguitests')
    sys.modules['wx'] = None
    import matplotlib
    matplotlib.use('agg')

if '--nojavatests' in sys.argv:
    sys.argv.remove('--nojavatests')
    import javabridge
    javabridge.start__vm = dummy_start_vm

if len(sys.argv) == 0:
    args = ['--testmatch=(?:^)test_.*']
else:
    args = sys.argv

nose.main(argv=args + ['-w', 'cpa/tests'])
Beispiel #52
0
                             shape).astype(numpy.float32), order)
            yield self._test_timing, data, in2d

    def _test_timing(self, data, in2d):
        self.opFeatures.ComputeIn2d.setValue([in2d] * 6)
        self.opFeatures.InputImage[0].setValue(data)
        self.opFeaturesOld.InputImage[0].setValue(data)
        timeNew = 0
        timeOld = 0
        t0 = time.time()
        self.opFeatures.OutputImage[0][:].wait()
        t1 = time.time()
        self.opFeaturesOld.OutputImage[0][:].wait()
        t2 = time.time()
        timeNew += t1 - t0
        timeOld += t2 - t1

        # The new code should (within a tolerance) run faster!
        assert timeNew <= 1.1 * timeOld + .05, f'{timeNew:.2f} !<= {timeOld:.2f}'
        logger.debug(f'{timeNew:.2f} <= {timeOld:.2f}')


if __name__ == "__main__":
    import sys
    import nose
    sys.argv.append(
        '--nocapture')  # Don't steal stdout.  Show it on the console as usual.
    sys.argv.append('--nologcapture'
                    )  # Don't set the logging level to DEBUG.  Leave it alone.
    nose.main(defaultTest=__file__)
Beispiel #53
0
def run_test():
    nose.main(addplugins=[AutoTestRunner(),
                          AttributeSelector(),
                          Xunit(),
                          Coverage()])
Beispiel #54
0
def main():
    sys.path.insert(0, os.path.dirname(__file__))
    nose.main()
    sys.exit(0)
Beispiel #55
0
#!/usr/bin/env python
import nose
nose.main(['nosetests', '-w', 'tests'])
Beispiel #56
0
def test_inject_params__illegal_placeholder__no_spaces_on_the_both_sides():
    assert_equal(
        inject_params('abcde\n__{{fghij}}__\nklmno\n', {'fghij': '__fghij__'}),
        ['abcde\n', '__{{fghij}}__\n', 'klmno\n', '\n'])


def test_inject_params__illegal_placeholder__space_between_left_parens():
    assert_equal(
        inject_params('abcde\n__{ { fghij }}__\nklmno\n',
                      {'fghij': '__fghij__'}),
        ['abcde\n', '__{ { fghij }}__\n', 'klmno\n', '\n'])


def test_inject_params__illegal_placeholder__space_between_right_parns():
    assert_equal(
        inject_params('abcde\n__{{ fghij } }__\nklmno\n',
                      {'fghij': '__fghij__'}),
        ['abcde\n', '__{{ fghij } }__\n', 'klmno\n', '\n'])


def test_inject_params__multi_placeholders_in_one_line():
    assert_equal(
        inject_params('abcde__{{ fghij }}__{{ klmno }}__pqrst', {
            'fghij': '__fghij__',
            'klmno': '__klmno__'
        }), ['abcde__', '__fghij__', '__', '__klmno__', '__pqrst\n'])


if __name__ == '__main__':
    nose.main(argv=['nosetests', '-s', '-v'], defaultTest=__file__)
Beispiel #57
0
        # we want all directories
        return True

    def find_examples(self, name):
        examples = []
        if os.path.isdir(name):
            for subname in os.listdir(name):
                examples.extend(self.find_examples(os.path.join(name,
                                                                subname)))
            return examples
        elif name.endswith('.py'):  # only execute Python scripts
            return [name]
        else:
            return []

    def loadTestsFromName(self, name, module=None, discovered=False):
        all_examples = self.find_examples(name)
        all_tests = []
        for target in ['cython']:
            for example in all_examples:
                all_tests.append(RunTestCase(example, target))
        return all_tests


if __name__ == '__main__':
    argv = [
        __file__, '-v', '--with-xunit', '--verbose', '--exe', '../../examples'
    ]

    nose.main(argv=argv, plugins=[SelectFilesPlugin(), Capture(), Xunit()])
Beispiel #58
0
import nose
from os import path

file_path = path.abspath(__file__)
tests_path = path.join(path.abspath(path.dirname(file_path)), "tests")
nose.main(argv=[
    path.abspath(__file__), "--with-coverage", "--cover-erase",
    "--cover-package=frapalyzer", tests_path
])
Beispiel #59
0
def test_n3():
    global formats
    if not formats:
        serializers = set(
            x.name
            for x in rdflib.plugin.plugins(None, rdflib.plugin.Serializer))
        parsers = set(
            x.name for x in rdflib.plugin.plugins(None, rdflib.plugin.Parser))
        formats = parsers.intersection(serializers)

    for testfmt in formats:
        if "/" in testfmt:
            continue  # skip double testing
        for f, infmt in all_n3_files():
            if (testfmt, f) not in SKIP:
                yield roundtrip, (infmt, testfmt, f)


if __name__ == "__main__":
    import nose

    if len(sys.argv) == 1:
        nose.main(defaultTest=sys.argv[0])
    elif len(sys.argv) == 2:
        import test.test_roundtrip

        test.test_roundtrip.formats = [sys.argv[1]]
        nose.main(defaultTest=sys.argv[0], argv=sys.argv[:1])
    else:
        roundtrip((sys.argv[2], sys.argv[1], sys.argv[3]), verbose=True)
def test():
    """Run the tests."""
    import nose
    rv = nose.main(argv=[TEST_PATH])
    exit(rv)