示例#1
0
    def __new__(cls, *args, **kw):
        instance = object.__new__(cls)
        pluginInstances.add(instance)
        if cls.instance is None:
            cls.instance = instance

        alwaysOn = False
        configSection = getattr(instance, 'configSection', None)
        commandLineSwitch = getattr(instance, 'commandLineSwitch', None)

        if configSection is not None:
            instance.config = getConfig(configSection)
            alwaysOn = instance.config.as_bool('always-on', default=False)

        if alwaysOn:
            instance.register()
        else:
            if commandLineSwitch is not None:
                opt, longOpt, help_text = commandLineSwitch
                addOption(instance.register, opt, longOpt, help_text)

        return instance
from unittest2.events import hooks, addDiscoveryOption

import re

REGEXP_PATTERN = r'test.*\.py$'

def matchRegexp(event):
    event.handled = True
    if matchFullPath:
        return re.match(event.pattern, event.path)
    return re.match(event.pattern, event.name)


def enable():
    hooks.matchPath += matchRegexp
    if not pattern:
        pattern = REGEXP_PATTERN
    unittest2.loader.DEFAULT_PATTERN = pattern

ourOptions = getConfig('matchregexp')
alwaysOn = ourOptions.as_bool('always-on', default=False)
matchFullPath = ourOptions.as_bool('full-path', default=False)
pattern = ourOptions.as_str('pattern', default=None)

if alwaysOn:
    enable()
else:
    help_text = ('Match filenames during test discovery'
                 ' with regular expressions instead of glob')
    addDiscoveryOption(enable, 'R', 'match-regexp', help_text)
示例#3
0
    def _parseArgs(self, argv, forDiscovery):
        pluginsDisabled = self._getConfigOptions(argv)
        
        parser = optparse.OptionParser(version='unittest2 %s' % __version__)

        if forDiscovery:
            parser.usage = '%prog [options] [...]'
        else:
            parser.description = DESCRIPTION
            parser.usage = '%prog [options] [tests]'
        parser.prog = self.progName
        parser.add_option('-v', '--verbose', dest='verbose', default=False,
                          help='Verbose output', action='store_true')
        parser.add_option('-q', '--quiet', dest='quiet', default=False,
                          help='Quiet output', action='store_true')
        
        parser.add_option('--config', dest='configLocations', action='append',
                          help='Specify local config file location')
        parser.add_option('--no-user-config', dest='noUserConfig', default=False,
                          action='store_true',
                          help="Don't use user config file")
        parser.add_option('--no-plugins', dest='pluginsDisabled', default=False,
                          action='store_true', help="Disable all plugins")
        
        if self.failfast != False:
            parser.add_option('-f', '--failfast', dest='failfast', default=None,
                              help='Stop on first fail or error', 
                              action='store_true')
        if self.catchbreak != False and installHandler is not None:
            parser.add_option('-c', '--catch', dest='catchbreak', default=None,
                              help='Catch ctrl-C and display results so far', 
                              action='store_true')
        if self.buffer != False:
            parser.add_option('-b', '--buffer', dest='buffer', default=None,
                              help='Buffer stdout and stderr during tests', 
                              action='store_true')

        if forDiscovery:
            parser.add_option('-s', '--start-directory', dest='start', default='.',
                              help="Directory to start discovery ('.' default)")
            parser.add_option('-p', '--pattern', dest='pattern', default=None,
                              help="Pattern to match tests ('test*.py' default)")
            parser.add_option('-t', '--top-level-directory', dest='top', default=None,
                              help='Top level directory of project (defaults to start directory)')

        list_options = []

        if not pluginsDisabled:
            extra_options = []
            if forDiscovery:
                extra_options = _discoveryOptions
            for opt, longopt, help_text, callback in _options + extra_options:
                opts = []
                if opt is not None:
                    opts.append('-' + opt)
                if longopt is not None:
                    opts.append('--' + longopt)
                kwargs = dict(
                    action='callback',
                    help=help_text,
                )
                if isinstance(callback, list):
                    kwargs['action'] = 'append'
                    kwargs['dest'] = longopt
                    list_options.append((longopt, callback))
                else:
                    kwargs['callback'] = _Callback(callback)
                option = optparse.make_option(*opts, **kwargs)
                parser.add_option(option)

        options, args = parser.parse_args(argv)

        for attr, _list in list_options:
            values = getattr(options, attr) or []
            _list.extend(values)

        config = getConfig('unittest')
        if self.verbosity is None:
            try:
                self.verbosity = config.as_int('verbosity', 1)
            except ValueError:
                if ('verbosity' in config and 
                    config['verbosity'].lower() in runner.VERBOSITIES):
                    self.verbosity = runner.VERBOSITIES[config['verbosity']]
                else:
                    raise

        config['discover'] = forDiscovery

        if self.buffer is not None:
            options.buffer = self.buffer
        if self.failfast is not None:
            options.failfast = self.failfast
        if installHandler is None:
            options.catchbreak = False
        elif self.catchbreak is not None:
            options.catchbreak = self.catchbreak

        if options.buffer is None:
            options.buffer = config.as_bool('buffer', default=False)
        if options.failfast is None:
            options.failfast = config.as_bool('failfast', default=False)
        if options.catchbreak is None:
            options.catchbreak = config.as_bool('catch', default=False)

        self.failfast = options.failfast
        self.buffer = options.buffer
        self.catchbreak = options.catchbreak

        if options.verbose:
            self.verbosity = 2
        if options.quiet:
            self.verbosity = 0
        if options.quiet and options.verbose:
            # could raise an exception here I suppose
            self.verbosity = 1

        config['verbosity'] = self.verbosity
        config['buffer'] = self.buffer
        config['catch'] = self.catchbreak
        config['failfast'] = self.failfast

        hooks.pluginsLoaded(PluginsLoadedEvent())
        return options, args
from unittest2.config import getConfig
from unittest2.events import hooks, addOption

import doctest


def getDoctests(event):
    path = event.path
    if not path.lower().endswith('.txt'):
        return
    suite = doctest.DocFileTest(path, module_relative=False)
    event.extraTests.append(suite)

def enable():
    hooks.handleFile += getDoctests

ourOptions = getConfig('doctest')
alwaysOn = ourOptions.as_bool('always-on', default=False)


if alwaysOn:
    enable()
else:
    help_text = 'Load doctests from text files'
    addOption(enable, None, 'doctest', help_text)