How to use the nose2.events.Plugin function in nose2

To help you get started, we’ve selected a few nose2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nose-devs / nose2 / nose2 / plugins / testid.py View on Github external
:func:`loadTestsFromName`, :func:`loadTestsFromNames` and
:func:`stopTest`.

"""
import os
import pickle
import re

from nose2.events import Plugin
from nose2 import util


__unittest = True


class TestId(Plugin):

    """Allow easy test select with ids"""

    configSection = 'testid'
    commandLineSwitch = ('I', 'with-id', 'Add test ids to output')
    idpat = re.compile(r'(\d+)')

    def __init__(self):
        self.idfile = self.config.as_str('id-file', '.noseids')
        self.ids = {}
        self.tests = {}
        if not os.path.isabs(self.idfile):
            # FIXME expand-user?
            self.idfile = os.path.join(os.getcwd(), self.idfile)
        self.id = 0
        self._loaded = False
github Stratoscale / docker-test-tools / docker_test_tools / plugin.py View on Github external
# pylint: disable=unused-argument
from nose2.events import Plugin

from docker_test_tools.config import Config
from docker_test_tools.environment import EnvironmentController


class EnvironmentPlugin(Plugin):
    """Nose2 plugin, used for managing docker environment operations."""
    configSection = 'environment'
    commandLineSwitch = (None, 'environment', 'Enable docker test tools environment')

    def __init__(self, *args, **kwargs):
        self.controller = None
        super(EnvironmentPlugin, self).__init__(*args, **kwargs)

    def startTestRun(self, event):
        """Sets up the environment using docker commands."""
        config = Config(
            log_path=self.config.as_str('log-path', Config.DEFAULT_LOG_PATH),
            project_name=self.config.as_str('project-name', Config.DEFAULT_PROJECT_NAME),
            collect_stats=self.config.as_bool('collect-stats', Config.DEFAULT_COLLECT_STATS),
            reuse_containers=self.config.as_bool('reuse-containers', Config.DEFAULT_REUSE_CONTAINERS),
            docker_compose_path=self.config.as_str('docker-compose-path', Config.DEFAULT_DOCKER_COMPOSE_PATH)
github nose-devs / nose2 / nose2 / plugins / loader / testcases.py View on Github external
# unittest2 is Copyright (c) 2001-2010 Python Software Foundation; All
# Rights Reserved. See: http://docs.python.org/license.html
import sys
import logging
import unittest

from nose2 import events, util


__unittest = True


log = logging.getLogger(__name__)


class TestCaseLoader(events.Plugin):

    """Loader plugin that loads from test cases"""
    alwaysOn = True
    configSection = 'testcases'

    def registerInSubprocess(self, event):
        event.pluginClasses.append(self.__class__)

    def loadTestsFromModule(self, event):
        """Load tests in :class:`unittest.TestCase` subclasses"""
        seen = set()
        module = event.module
        for name in dir(module):
            obj = getattr(module, name)
            if id(obj) in seen:
                continue
github nose-devs / nose2 / nose2 / plugins / layers.py View on Github external
except TypeError:
                out.append(test)
        return out

    @staticmethod
    def get_layer_position(layer):
        pos = getattr(layer, 'position', None)
        # ... lame
        if pos is not None:
            key = six.u("%04d") % pos
        else:
            key = layer.__name__
        return key


class LayerReporter(events.Plugin):
    commandLineSwitch = (
        None, 'layer-reporter', 'Add layer information to test reports')
    configSection = 'layer-reporter'

    def __init__(self):
        self.indent = self.config.as_str('indent', '  ')
        self.colors = self.config.as_bool('colors', False)
        self.highlight_words = self.config.as_list('highlight-words',
                                                   ['A', 'having', 'should'])
        self.highlight_re = re.compile(
            r'\b(%s)\b' % '|'.join(self.highlight_words))
        self.layersReported = set()

    def reportStartTest(self, event):
        if self.session.verbosity < 2:
            return
github nose-devs / nose2 / nose2 / plugins / collect.py View on Github external
"""
This plugin implements :func:`startTestRun`, setting a test executor
(``event.executeTests``) that just collects tests without executing
them. To do so it calls result.startTest, result.addSuccess and
result.stopTest for each test, without calling the test itself.
"""
from nose2.events import Plugin
import unittest


__unittest = True


class CollectOnly(Plugin):

    """Collect but don't run tests"""

    configSection = 'collect-only'
    commandLineSwitch = (None, 'collect-only',
                         'Collect and output test names; do not run any tests')
    _mpmode = False

    def registerInSubprocess(self, event):
        event.pluginClasses.append(self.__class__)
        self._mpmode = True

    def startTestRun(self, event):
        """Replace ``event.executeTests``"""
        if self._mpmode:
            return
github nose-devs / nose2 / nose2 / plugins / failfast.py View on Github external
"""
Stop the test run after the first error or failure.

This plugin implements :func:`testOutcome` and sets
``event.result.shouldStop`` if it sees an outcome with exc_info that
is not expected.

"""

from nose2 import events


__unittest = True


class FailFast(events.Plugin):

    """Stop the test run after error or failure"""
    commandLineSwitch = (
        'F', 'fail-fast', 'Stop the test run after the first error or failure')

    def testOutcome(self, event):
        """Stop on unexpected error or failure"""
        if event.exc_info and not event.expected:
            event.result.shouldStop = True
github nose-devs / nose2 / nose2 / plugins / outcomes.py View on Github external
[outcomes]
  always-on = True
  treat-as-fail = NotImplementedError
  treat-as-skip = TodoError
                  IOError

"""

from nose2.events import Plugin


__unittest = True


class Outcomes(Plugin):

    """Map exceptions to other test outcomes"""

    configSection = 'outcomes'
    commandLineSwitch = (None, 'set-outcomes',
                         'Treat some configured exceptions as failure or skips')

    def __init__(self):
        self.treatAsFail = set(self.config.as_list('treat-as-fail', []))
        self.treatAsSkip = set(self.config.as_list('treat-as-skip', []))

    def setTestOutcome(self, event):
        """Update outcome, exc_info and reason based on configured mappings"""
        if event.exc_info:
            ec, ev, tb = event.exc_info
            classname = ec.__name__
github nose-devs / nose2 / nose2 / plugins / loader / eggdiscovery.py View on Github external
import os

from nose2 import events

from nose2.plugins.loader import discovery

__unittest = True
log = logging.getLogger(__name__)

try:
    import pkg_resources
except ImportError:
    pkg_resources = None


class EggDiscoveryLoader(events.Plugin, discovery.Discoverer):
    """Loader plugin that can discover tests inside Egg Files"""
    alwaysOn = True
    configSection = 'discovery'

    def registerInSubprocess(self, event):
        event.pluginClasses.append(self.__class__)

    def loadTestsFromName(self, event):
        """Load tests from module named by event.name"""
        return discovery.Discoverer.loadTestsFromName(self, event)

    def loadTestsFromNames(self, event):
        """Discover tests if no test names specified"""
        return discovery.Discoverer.loadTestsFromNames(self, event)

    def _checkIfPathIsOK(self, start_dir):
github nose-devs / nose2 / nose2 / plugins / debugger.py View on Github external
:func:`afterInteraction` after. Other plugins may implement
:func:`beforeInteraction` to return ``False`` and set ``event.handled`` to
prevent this plugin from launching pdb.

"""
import logging
import pdb

from nose2 import events


__unittest = True
log = logging.getLogger(__name__)


class Debugger(events.Plugin):

    """Enter pdb on test error or failure

    .. attribute :: pdb

       For ease of mocking and using different pdb implementations, pdb
       is aliased as a class attribute.

    """
    configSection = 'debugger'
    commandLineSwitch = ('D', 'debugger', 'Enter pdb on test fail or error')
    # allow easy mocking and replacment of pdb
    pdb = pdb

    def __init__(self):
        self.errorsOnly = self.config.as_bool('errors-only', default=False)
github nose-devs / nose2 / nose2 / session.py View on Github external
def loadPluginsFromModule(self, module):
        """Load plugins from a module.

        :param module: A python module containing zero or more plugin
                       classes.

        """
        avail = []
        for entry in dir(module):
            try:
                item = getattr(module, entry)
            except AttributeError:
                pass
            try:
                if issubclass(item, events.Plugin):
                    avail.append(item)
            except TypeError:
                pass
        for cls in avail:
            log.debug("Plugin is available: %s", cls)
            plugin = cls(session=self)
            self.plugins.append(plugin)
            for method in self.hooks.preRegistrationMethods:
                if hasattr(plugin, method):
                    self.hooks.register(method, plugin)