How to use the nose2.events 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 / loader / testcases.py View on Github external
def _getTestCaseNames(self, event, testCaseClass):
        excluded = set()

        def isTestMethod(attrname, testCaseClass=testCaseClass,
                         excluded=excluded):
            prefix = evt.testMethodPrefix or self.session.testMethodPrefix
            return (
                attrname.startswith(prefix) and
                hasattr(getattr(testCaseClass, attrname), '__call__') and
                attrname not in excluded
            )
        evt = events.GetTestCaseNamesEvent(
            event.loader, testCaseClass, isTestMethod)
        result = self.session.hooks.getTestCaseNames(evt)
        if evt.handled:
            test_names = result or []
        else:
            excluded.update(evt.excludedNames)
            test_names = [entry for entry in dir(testCaseClass)
                          if isTestMethod(entry)]
        if evt.extraNames:
            test_names.extend(evt.extraNames)
        sortkey = getattr(
            testCaseClass, 'sortTestMethodsUsing',
            event.loader.sortTestMethodsUsing)
        if sortkey:
            test_names.sort(
                key=sortkey)
github nose-devs / nose2 / nose2 / session.py View on Github external
def __init__(self):
        self.argparse = argparse.ArgumentParser(prog='nose2', add_help=False)
        self.pluginargs = self.argparse.add_argument_group(
            'plugin arguments',
            'Command-line arguments added by plugins:')
        self.config = ConfigParser()
        self.hooks = events.PluginInterface()
        self.plugins = []
        # this will be reset later, whenever handleCfgArgs happens, but it
        # starts at 1 so that it always has a non-negative integer value
        self.verbosity = 1
        self.startDir = None
        self.topLevelDir = None
        self.testResult = None
        self.testLoader = None
        self.logLevel = logging.WARN
        self.configCache = dict()
github nose-devs / nose2 / nose2 / main.py View on Github external
def createTests(self):
        """Create top-level test suite"""
        event = events.CreateTestsEvent(
            self.testLoader, self.testNames, self.module)
        result = self.session.hooks.createTests(event)
        if event.handled:
            test = result
        else:
            log.debug("Create tests from %s/%s", self.testNames, self.module)
            test = self.testLoader.loadTestsFromNames(
                self.testNames, self.module)

        event = events.CreatedTestSuiteEvent(test)
        result = self.session.hooks.createdTestSuite(event)
        if event.handled:
            test = result
        self.test = test
github nose-devs / nose2 / nose2 / runner.py View on Github external
def run(self, test):
        """Run tests.

        :param test: A unittest :class:`TestSuite`` or :class:`TestClass`.
        :returns: Test result

        Fires :func:`startTestRun` and :func:`stopTestRun` hooks.

        """
        result = self._makeResult()
        executor = lambda suite, result: suite(result)
        startTime = time.time()
        event = events.StartTestRunEvent(
            self, test, result, startTime, executor)
        self.session.hooks.startTestRun(event)

        # allows startTestRun to modify test suite
        test = event.suite
        # ... and test execution
        executor = event.executeTests
        try:
            if not event.handled:
                executor(test, result)
        finally:
            stopTime = time.time()
            timeTaken = stopTime - startTime
            event = events.StopTestRunEvent(self, result, stopTime, timeTaken)
            self.session.hooks.stopTestRun(event)
            self.session.hooks.afterTestRun(event)
github nose-devs / nose2 / nose2 / collector.py View on Github external
#
            # this is the disabled feature:
            # ssn.hooks.handleArgs(events.CommandLineArgsEvent(...))
            #
            # this means that there may be plugins which don't work under
            # setuptools invocation because they expect to get handleArgs
            # triggered (e.g. older versions of the coverage plugin)

            # FIXME: this is all a great-big DRY violation when compared with
            # PluggableTestProgram

            # create the testsuite, and make sure the createTests event gets
            # triggered, as some plugins expect it
            # just doing `ldr.loadTestsFromNames` works, but leaves some
            # plugins in the lurch
            event = events.CreateTestsEvent(ldr, [], None)
            result = ssn.hooks.createTests(event)
            if event.handled:
                test = event
            else:
                test = ldr.loadTestsFromNames([], None)

            # fire the "createdTestSuite" event for plugins to handle
            # as above, we can get away without this, but some plugins will
            # expect it
            event = events.CreatedTestSuiteEvent(test)
            result = ssn.hooks.createdTestSuite(event)
            if event.handled:
                test = result

            rslt = rnr.run(test)
            return rslt.wasSuccessful()
github nose-devs / nose2 / nose2 / plugins / debugger.py View on Github external
def testOutcome(self, event):
        """Drop into pdb on unexpected errors or failures"""
        if not event.exc_info or event.expected:
            # skipped tests, unexpected successes, expected failures
            return

        value, tb = event.exc_info[1:]
        test = event.test
        if self.errorsOnly and isinstance(value, test.failureException):
            return
        evt = events.UserInteractionEvent()
        result = self.session.hooks.beforeInteraction(evt)
        try:
            if not result and evt.handled:
                log.warning(
                    "Skipping pdb for %s, user interaction not allowed", event)
                return
            self.pdb.post_mortem(tb)
        finally:
            self.session.hooks.afterInteraction(evt)
github nose-devs / nose2 / nose2 / plugins / printhooks.py View on Github external
Replaces :class:`~nose2.events.Hook` instances in ``self.session.hooks.hooks`` with
        noisier objects.

        """
        super(PrintHooks, self).register()
        # now we can be sure that all other plugins have loaded
        # and this plugin is active, patch in our hook class
        self.session.hooks.hookClass = NoisyHook
        for attr, hook in self.session.hooks.hooks.items():
            newhook = NoisyHook(attr)
            newhook.plugins = hook.plugins
            self.session.hooks.hooks[attr] = newhook


class NoisyHook(events.Hook):

    def __call__(self, event):
        _report(self.method, event)
        _indent()
        try:
            return super(NoisyHook, self).__call__(event)
        finally:
            _dedent()


def _report(method, event):
    sys.stderr.write("\n%s%s: %s" % (''.join(INDENT), method, event))


def _indent():
    INDENT.append('  ')
github nose-devs / nose2 / nose2 / plugins / loader / discovery.py View on Github external
def _find_tests_in_file(self, event, filename, full_path, top_level, module_name=None):
        log.debug("find in file %s (%s)", full_path, top_level)
        pattern = self.session.testFilePattern
        loader = event.loader
        evt = events.HandleFileEvent(
            loader, filename, full_path, pattern, top_level)
        result = self.session.hooks.handleFile(evt)
        if evt.extraTests:
            yield loader.suiteClass(evt.extraTests)

        if evt.handled:
            if result:
                yield result
            return

        if not util.valid_module_name(filename):
            # valid Python identifiers only
            return

        evt = events.MatchPathEvent(filename, full_path, pattern)
        result = self.session.hooks.matchPath(evt)