def process_args():
  tests = []

  opts = None
  if sys.argv[-1].startswith("-"):
    test_names = sys.argv[1:-1]
    opts = sys.argv[-1]
  else:
    test_names = sys.argv[1:]

  for arg in test_names:
    arg = arg.strip()
    if len(arg) == 0:
      return

    a = arg.split("::")
    if len(a) == 1:
      # From module or folder
      a_splitted = a[0].split(";")
      if len(a_splitted) != 1:
        # means we have pattern to match against
        if a_splitted[0].endswith("/"):
          debug("/ from folder " + a_splitted[0] + ". Use pattern: " + a_splitted[1])
          tests.append(a_splitted[0])
      else:
        if a[0].endswith("/"):
          debug("/ from folder " + a[0])
          tests.append(a[0])
        else:
          debug("/ from module " + a[0])
          tests.append(a[0])

    elif len(a) == 2:
      # From testcase
      debug("/ from testcase " + a[1] + " in " + a[0])
      tests.append(a[0] + ":" + a[1])
    else:
      # From method in class or from function
      debug("/ from method " + a[2] + " in testcase " +  a[1] + " in " + a[0])
      if a[1] == "":
        # test function, not method
        tests.append(a[0] + ":" + a[2])
      else:
        tests.append(a[0] + ":" + a[1] + "." + a[2])

  argv = ['nosetests']

  argv.extend(tests)


  if opts:
    options = shlex.split(opts)
    argv.extend(options)

  manager = DefaultPluginManager()
  manager.addPlugin(teamcity_plugin)
  config = MyConfig(plugins=manager)
  config.configure(argv)

  TestProgram(argv=argv, config=config, exit=False)
Example #2
0
def process_args():
  tests = []

  opts = None
  if sys.argv[-1].startswith("-"):
    test_names = sys.argv[1:-1]
    opts = sys.argv[-1]
  else:
    test_names = sys.argv[1:]

  for arg in test_names:
    arg = arg.strip()
    if len(arg) == 0:
      return

    a = arg.split("::")
    if len(a) == 1:
      # From module or folder
      a_splitted = a[0].split(";")
      if len(a_splitted) != 1:
        # means we have pattern to match against
        if a_splitted[0].endswith("/"):
          debug("/ from folder " + a_splitted[0] + ". Use pattern: " + a_splitted[1])
          tests.append(a_splitted[0])
      else:
        if a[0].endswith("/"):
          debug("/ from folder " + a[0])
          tests.append(a[0])
        else:
          debug("/ from module " + a[0])
          tests.append(a[0])

    elif len(a) == 2:
      # From testcase
      debug("/ from testcase " + a[1] + " in " + a[0])
      tests.append(a[0] + ":" + a[1])
    else:
      # From method in class or from function
      debug("/ from method " + a[2] + " in testcase " +  a[1] + " in " + a[0])
      if a[1] == "":
        # test function, not method
        tests.append(a[0] + ":" + a[2])
      else:
        tests.append(a[0] + ":" + a[1] + "." + a[2])

  argv = ['nosetests']

  argv.extend(tests)


  if opts:
    options = shlex.split(opts)
    argv.extend(options)

  manager = DefaultPluginManager()
  manager.addPlugin(teamcity_plugin)
  config = MyConfig(plugins=manager)
  config.configure(argv)

  TestProgram(argv=argv, config=config, exit=False)
 def test_extraplugins_override_builtins(self):
     pm = DefaultPluginManager()
     pm.addPlugins(extraplugins=[OverridesSkip()])
     pm.loadPlugins()
     for plugin in pm.plugins:
         if plugin.name == "skip":
             break
     overridden = getattr(plugin, 'is_overridden', False)
     self.assertTrue(overridden)
Example #4
0
    def run_suite(self, nose_argv):
        signals.before_suite_run.send(sender=self)
        result_plugin = ResultPlugin()
        plugins_to_add = [
            DjangoSetUpPlugin(self), result_plugin,
            TestReorderer()
        ]

        for plugin in _get_plugins_from_settings():
            plugins_to_add.append(plugin)

        cfg_files = all_config_files()
        manager = DefaultPluginManager()
        config = Config(env=os.environ, files=cfg_files, plugins=manager)
        config.plugins.addPlugins(plugins=plugins_to_add)
        text_test_runner = XMLTextNoseTestRunner(config=config,
                                                 verbosity=self.verbosity)
        nose.core.TestProgram(argv=nose_argv,
                              exit=False,
                              config=config,
                              testRunner=text_test_runner)
        result = result_plugin.result

        if self.with_reports:
            result.dump_xml(self.output_dir)
        signals.after_suite_run.send(sender=self)
        return result
def makeNoseConfig(env):
    """Load a Config, pre-filled with user config files if any are
    found.
    """
    cfg_files = all_config_files()
    manager = DefaultPluginManager()
    return Config(env=env, files=cfg_files, plugins=manager)
Example #6
0
    def test_issue_130(self):
        """Collect and run tests in support/issue130 without error.

        This tests that the result and error classes can handle string
        exceptions.
        """
        import warnings
        warnings.filterwarnings('ignore',
                                category=DeprecationWarning,
                                module='test')

        stream = StringIO()
        runner = TestRunner(stream=stream, verbosity=2)

        prog = TestProgram(defaultTest=os.path.join(support, 'issue130'),
                           argv=['test_issue_130'],
                           testRunner=runner,
                           config=Config(stream=stream,
                                         plugins=DefaultPluginManager()),
                           exit=False)
        res = runner.result
        print
        stream.getvalue()
        self.assertEqual(res.testsRun, 0)  # error is in setup
        assert not res.wasSuccessful()
        assert res.errors
        assert not res.failures
Example #7
0
    def run_nose(self, params):
        """
        :type params: Params
        """
        thread.set_index(params.thread_index)
        log.debug("[%s] Starting nose iterations: %s", params.worker_index,
                  params)
        assert isinstance(params.tests, list)
        # argv.extend(['--with-apiritif', '--nocapture', '--exe', '--nologcapture'])

        end_time = self.params.ramp_up + self.params.hold_for
        end_time += time.time() if end_time else 0
        time.sleep(params.delay)

        plugin = ApiritifPlugin()
        store.writer.concurrency += 1

        config = Config(env=os.environ,
                        files=all_config_files(),
                        plugins=DefaultPluginManager())
        config.plugins.addPlugins(extraplugins=[plugin])
        config.testNames = params.tests
        config.verbosity = 3 if params.verbose else 0
        if params.verbose:
            config.stream = open(
                os.devnull,
                "w")  # FIXME: use "with", allow writing to file/log

        iteration = 0
        try:
            while True:
                log.debug("Starting iteration:: index=%d,start_time=%.3f",
                          iteration, time.time())
                thread.set_iteration(iteration)
                ApiritifTestProgram(config=config)
                log.debug("Finishing iteration:: index=%d,end_time=%.3f",
                          iteration, time.time())

                iteration += 1

                # reasons to stop
                if plugin.stop_reason:
                    log.debug("[%s] finished prematurely: %s",
                              params.worker_index, plugin.stop_reason)
                elif 0 < params.iterations <= iteration:
                    log.debug("[%s] iteration limit reached: %s",
                              params.worker_index, params.iterations)
                elif 0 < end_time <= time.time():
                    log.debug("[%s] duration limit reached: %s",
                              params.worker_index, params.hold_for)
                else:
                    continue  # continue if no one is faced

                break
        finally:
            store.writer.concurrency -= 1

            if params.verbose:
                config.stream.close()
Example #8
0
 def test_verbosity_1_config(self):
     stream = StringIO()
     result = run(suite=mksuite(),
                  config=Config(verbosity=1,
                                stream=stream,
                                plugins=DefaultPluginManager()))
     self.assertEqual(".", stream.getvalue().split("\n")[0])
     self.assertTrue(result)
Example #9
0
    def run_nose(self, params):
        """
        :type params: Params
        """
        log.debug("[%s] Starting nose iterations: %s", params.worker_index,
                  params)
        print("%s:%s" % (params.worker_index, params.thread_index))
        assert isinstance(params.tests, list)
        # argv.extend(['--with-apiritif', '--nocapture', '--exe', '--nologcapture'])

        end_time = self.params.ramp_up + self.params.hold_for
        end_time += time.time() if end_time else 0
        time.sleep(params.delay)

        iteration = 0

        local_data.total_concurrency = params.total_concurrency
        local_data.thread_index = params.thread_index

        plugin = ApiritifPlugin(self._writer)
        self._writer.concurrency += 1

        config = Config(env=os.environ,
                        files=all_config_files(),
                        plugins=DefaultPluginManager())
        config.plugins.addPlugins(extraplugins=[plugin])
        config.testNames = params.tests
        config.verbosity = 3 if params.verbose else 0
        if params.verbose:
            config.stream = open(
                os.devnull,
                "w")  # FIXME: use "with", allow writing to file/log
        try:
            while True:
                local_data.iteration = iteration
                iteration += 1

                log.debug("Starting iteration:: index=%d,start_time=%.3f",
                          iteration, time.time())
                ApiritifTestProgram(config=config)
                log.debug("Finishing iteration:: index=%d,end_time=%.3f",
                          iteration, time.time())

                if iteration >= params.iterations:
                    log.debug("[%s] iteration limit reached: %s",
                              params.worker_index, params.iterations)
                    break

                if 0 < end_time <= time.time():
                    log.debug("[%s] duration limit reached: %s",
                              params.worker_index, params.hold_for)
                    break
        finally:
            self._writer.concurrency -= 1
            if params.verbose:
                config.stream.close()
Example #10
0
 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)
Example #11
0
 def run(self):
     import nose
     from nose.plugins.manager import DefaultPluginManager
     excludes = [r'^examples$', r'^deprecated$']
     config = nose.config.Config(exclude=map(re.compile, excludes),
                                 plugins=DefaultPluginManager(),
                                 env=os.environ)
     nose.run(defaultTest='pysb',
              config=config,
              argv=['', '--with-doctest'])
Example #12
0
 def test_pickle_configured(self):
     if 'java' in sys.version.lower():
         raise SkipTest("jython has no profiler plugin")
     c = nose.config.Config(plugins=DefaultPluginManager())
     c.configure([
         '--with-doctest', '--with-coverage', '--with-profile', '--with-id',
         '--attr=A', '--collect', '--all', '--with-isolation', '-d',
         '--with-xunit', '--processes=2', '--pdb'
     ])
     cp = pickle.dumps(c)
     cc = pickle.loads(cp)
     assert cc.plugins._plugins
Example #13
0
 def test_extraplugins_override_builtins(self):
     pm = DefaultPluginManager()
     pm.addPlugins(extraplugins=[OverridesSkip()])
     pm.loadPlugins()
     for plugin in pm.plugins:
         if plugin.name == "skip":
             break
     overridden = getattr(plugin, 'is_overridden', False)
     self.assertTrue(overridden)
Example #14
0
def coverage():
    """Make coverage.flexget.com"""
    # --with-coverage --cover-package=flexget --cover-html --cover-html-dir /var/www/flexget_coverage/
    import nose
    from nose.plugins.manager import DefaultPluginManager

    cfg = nose.config.Config(plugins=DefaultPluginManager(), verbosity=2)
    argv = ['bin/paver']
    argv.extend(['--attr=!online'])
    argv.append('--with-coverage')
    argv.append('--cover-html')
    argv.extend(['--cover-package', 'flexget'])
    argv.extend(['--cover-html-dir', '/var/www/flexget_coverage/'])
    nose.run(argv=argv, config=cfg)
    print 'Coverage generated'
Example #15
0
    def test_illegal_packages_not_selected(self):
        stream = StringIO()
        runner = TestRunner(stream=stream, verbosity=2)

        prog = TestProgram(defaultTest=os.path.join(support, 'issue143'),
                           argv=['test_issue_143'],
                           testRunner=runner,
                           config=Config(stream=stream,
                                         plugins=DefaultPluginManager()),
                           exit=False)
        res = runner.result
        print stream.getvalue()
        self.assertEqual(res.testsRun, 0)
        assert res.wasSuccessful()
        assert not res.errors
        assert not res.failures
Example #16
0
    def begin(self):
        # extra arguments for nose can be passed as a string or list
        extra_args = self.config.get('args', [])
        if not isinstance(extra_args, list):
            extra_args = [extra_args]
        argv = [__name__] + extra_args

        log.info("running rgw multisite tests on '%s' with args=%r",
                 self.module_path, extra_args)

        # run nose tests in the module path
        conf = nose.config.Config(stream=get_log_stream(),
                                  verbosity=2,
                                  workingDir=self.module_path)
        conf.plugins = DefaultPluginManager(
        )  # overrides default = NoPlugins()
        assert nose.run(argv=argv, config=conf), 'rgw multisite test failures'
Example #17
0
def test(options):
    """Run FlexGet unit tests"""
    options.setdefault('test', Bunch())
    import nose
    from nose.plugins.manager import DefaultPluginManager

    cfg = nose.config.Config(plugins=DefaultPluginManager(), verbosity=2)

    args = []
    # Adding the -v flag makes the tests fail in python 2.7
    #args.append('-v')
    args.append('--processes=4')
    args.append('-x')
    if not options.test.get('online'):
        args.append('--attr=!online')
    args.append('--where=tests')

    # Store current path since --where changes it, restore when leaving
    cwd = os.getcwd()
    try:
        return nose.run(argv=args, config=cfg)
    finally:
        os.chdir(cwd)
Example #18
0
    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)
Example #19
0
    standalone.initialize(name='python')
    from maya import cmds

elif app_name == 'nuke':
    from units import nuke as app_specific
    import nuke
elif app_name == 'houdini':
    pass

os.environ['KIKO_APP_NAME'] = app_name

kiko.initialize()

current_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
nose_config = os.path.join(current_dir, 'config', 'nose.cfg')
config_files = [nose_config] + all_config_files()
c = Config(env=os.environ, files=config_files, plugins=DefaultPluginManager())

app_s_loader = nose.loader.TestLoader()
if unit_test is None:
    app_s_suite = app_s_loader.loadTestsFromModule(app_specific)
else:
    app_s_suite = app_s_loader.loadTestsFromName(unit_test)

test_suite = nose.suite.ContextSuite()
test_suite.addTest(app_s_suite)

sys.exit(nose.main(config=c, suite=test_suite))


Example #20
0
import sys

import nose
import nose.config
from nose.plugins.manager import DefaultPluginManager

c = nose.config.Config()
c.plugins = DefaultPluginManager()
if not nose.run(config=c):
    sys.exit(1)