# not allowed in config files
# Linux users will prefer this "~/.noserc", # Windows users will prefer this "~/nose.cfg" ]
# plaforms on which the exe check defaults to off # Windows and IronPython
module=r'(.*\.)?nose\.config')
Exception.__init__(self, name) self.name = name
""" Handler for options from commandline and config files. """ file_error = lambda msg, **kw: error(msg)
except configparser.Error as exc: raise ConfigError("Error reading config file %r: %s" % (filename, str(exc)))
cfg = configparser.RawConfigParser() try: filename = fh.name except AttributeError: filename = '<???>' try: cfg.readfp(fh) except configparser.Error as exc: raise ConfigError("Error reading config file %r: %s" % (filename, str(exc))) return self._configTuples(cfg, filename)
filenames = [filename_or_filenames] else: else: fh = config_files config = self._readFromFileObject(fh)
raise NoSuchOptionError(name) else:
continue except NoSuchOptionError as exc: self._file_error( "Error reading config file %r: " "no such option %r" % (filename, exc.name), name=name, filename=filename) except optparse.OptionValueError as exc: msg = str(exc).replace('--' + name, repr(name), 1) self._file_error("Error reading config file %r: " "%s" % (filename, msg), name=name, filename=filename)
except ConfigError as exc: self._error(str(exc)) else: except ConfigError as exc: self._error(str(exc))
"""nose configuration.
Instances of Config are used throughout nose to configure behavior, including plugin lists. Here are the default values for all config keys::
self.env = env = kw.pop('env', {}) self.args = () self.testMatch = re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep) self.addPaths = not env.get('NOSE_NOPATH', False) self.configSection = 'nosetests' self.debug = env.get('NOSE_DEBUG') self.debugLog = env.get('NOSE_DEBUG_LOG') self.exclude = None self.getTestCaseNamesCompat = False self.includeExe = env.get('NOSE_INCLUDE_EXE', sys.platform in exe_allowed_platforms) self.ignoreFiles = (re.compile(r'^\.'), re.compile(r'^_'), re.compile(r'^setup\.py$') ) self.include = None self.loggingConfig = None self.logStream = sys.stderr self.options = NoOptions() self.parser = None self.plugins = NoPlugins() self.srcDirs = ('lib', 'src') self.runOnInit = True self.stopOnError = env.get('NOSE_STOP', False) self.stream = sys.stderr self.testNames = () self.verbosity = int(env.get('NOSE_VERBOSE', 1)) self.where = () self.py3where = () self.workingDir = None """
r'(?:^|[\b_\.%s-])[Tt]est' % os.sep) sys.platform in exe_allowed_platforms) r'^_', r'^setup\.py$', ]
state = self.__dict__.copy() del state['stream'] del state['_orig'] del state['_default'] del state['env'] del state['logStream'] # FIXME remove plugins, have only plugin manager class state['plugins'] = self.plugins.__class__ return state
plugincls = state.pop('plugins') self.update(state) self.worker = True # FIXME won't work for static plugin lists self.plugins = plugincls() self.plugins.loadPlugins() # needed so .can_configure gets set appropriately dummy_parser = self.parserClass() self.plugins.addOptions(dummy_parser, {}) self.plugins.configure(self.options, self)
def __repr__(self): d = self.__dict__.copy() # don't expose env, could include sensitive info d['env'] = {} keys = [ k for k in list(d.keys()) if not k.startswith('_') ] keys.sort() return "Config(%s)" % ', '.join([ '%s=%r' % (k, d[k]) for k in keys ])
if (hasattr(self.plugins, 'excludedOption') and self.plugins.excludedOption(name)): msg = ("Option %r in config file %r ignored: " "excluded by runtime environment" % (name, filename)) warn(msg, RuntimeWarning) else: raise ConfigError(msg) self.getParser(), self.configSection, file_error=warn_sometimes)
"""Configure the nose running environment. Execute configure before collecting tests with nose.TestCollector to enable output capture and other features. """ argv = sys.argv
# If -c --config has been specified on command line, # load those config files and reparse options, args = self._parseArgs(argv, options.files)
self.testNames.extend(tolist(options.testNames))
if sys.version_info >= (3,): options.where = options.py3where
# `where` is an append action, so it can't have a default value # in the parser, or that default will always be in the list
# include and exclude also
sys.dont_write_bytecode = True
self.configureWhere(options.where)
self.ignoreFiles = list(map(re.compile, tolist(options.ignoreFiles))) log.info("Ignoring files matching %s", options.ignoreFiles) else:
self.include = list(map(re.compile, tolist(options.include))) log.info("Including tests matching %s", options.include)
self.exclude = list(map(re.compile, tolist(options.exclude))) log.info("Excluding tests matching %s", options.exclude)
# When listing plugins we don't want to run them
"""Configure logging for nose, or optionally other packages. Any logger name may be set with the debug option, and that logger will be set to debug level and be assigned the same handler as the nose loggers, unless it already has a handler. """ from logging.config import fileConfig fileConfig(self.loggingConfig) return
handler = logging.FileHandler(self.debugLog) else:
# only add our default handler if there isn't already one there # this avoids annoying duplicate log messages. debugLogAbsPath = os.path.abspath(self.debugLog) for h in logger.handlers: if type(h) == logging.FileHandler and \ h.baseFilename == debugLogAbsPath: found = True else: if type(h) == logging.StreamHandler and \ h.stream == self.logStream: found = True
# default level lvl = 0 lvl = logging.DEBUG lvl = logging.INFO
# individual overrides # no blanks debug_loggers = [ name for name in self.debug.split(',') if name ] for logger_name in debug_loggers: l = logging.getLogger(logger_name) l.setLevel(logging.DEBUG) if not l.handlers and not logger_name.startswith('nose'): l.addHandler(handler)
"""Configure the working directory or directories for the test run. """ from nose.importer import add_path self.workingDir = None where = tolist(where) warned = False for path in where: if not self.workingDir: abs_path = absdir(path) if abs_path is None: raise ValueError("Working directory '%s' not found, or " "not a directory" % path) log.info("Set working dir to %s", abs_path) self.workingDir = abs_path if self.addPaths and \ os.path.exists(os.path.join(abs_path, '__init__.py')): log.info("Working directory %s is a package; " "adding to sys.path" % abs_path) add_path(abs_path) continue if not warned: warn("Use of multiple -w arguments is deprecated and " "support may be removed in a future release. You can " "get the same behavior by passing directories without " "the -w argument on the command line, or by using the " "--tests argument in a configuration file.", DeprecationWarning) warned = True self.testNames.append(path)
"""Reset all config values to defaults. """ self.__dict__.update(self._default)
"""Get the command line option parser. """ return self.parser "-V","--version", action="store_true", dest="version", default=False, help="Output nose version and exit") "-p", "--plugins", action="store_true", dest="showPlugins", default=False, help="Output list of available plugins and exit. Combine with " "higher verbosity for greater detail") "-v", "--verbose", action="count", dest="verbosity", default=self.verbosity, help="Be more verbose. [NOSE_VERBOSE]") "--verbosity", action="store", dest="verbosity", metavar='VERBOSITY', type="int", help="Set verbosity; --verbosity=2 is " "the same as -v") "-q", "--quiet", action="store_const", const=0, dest="verbosity", help="Be less verbose") "-c", "--config", action="append", dest="files", metavar="FILES", help="Load configuration from config file(s). May be specified " "multiple times; in that case, all config files will be " "loaded and combined") "-w", "--where", action="append", dest="where", metavar="WHERE", help="Look for tests in this directory. " "May be specified multiple times. The first directory passed " "will be used as the working directory, in place of the current " "working directory, which is the default. Others will be added " "to the list of tests to execute. [NOSE_WHERE]" ) "--py3where", action="append", dest="py3where", metavar="PY3WHERE", help="Look for tests in this directory under Python 3.x. " "Functions the same as 'where', but only applies if running under " "Python 3.x or above. Note that, if present under 3.x, this " "option completely replaces any directories specified with " "'where', so the 'where' option becomes ineffective. " "[NOSE_PY3WHERE]" ) "-m", "--match", "--testmatch", action="store", dest="testMatch", metavar="REGEX", help="Files, directories, function names, and class names " "that match this regular expression are considered tests. " "Default: %s [NOSE_TESTMATCH]" % self.testMatchPat, default=self.testMatchPat) "--tests", action="store", dest="testNames", default=None, metavar='NAMES', help="Run these tests (comma-separated list). This argument is " "useful mainly from configuration files; on the command line, " "just pass the tests to run as additional arguments with no " "switch.") "-l", "--debug", action="store", dest="debug", default=self.debug, help="Activate debug logging for one or more systems. " "Available debug loggers: nose, nose.importer, " "nose.inspector, nose.plugins, nose.result and " "nose.selector. Separate multiple names with a comma.") "--debug-log", dest="debugLog", action="store", default=self.debugLog, metavar="FILE", help="Log debug messages to this file " "(default: sys.stderr)") "--logging-config", "--log-config", dest="loggingConfig", action="store", default=self.loggingConfig, metavar="FILE", help="Load logging config from this file -- bypasses all other" " logging config settings.") "-I", "--ignore-files", action="append", dest="ignoreFiles", metavar="REGEX", help="Completely ignore any file that matches this regular " "expression. Takes precedence over any other settings or " "plugins. " "Specifying this option will replace the default setting. " "Specify this option multiple times " "to add more regular expressions [NOSE_IGNORE_FILES]") "-e", "--exclude", action="append", dest="exclude", metavar="REGEX", help="Don't run tests that match regular " "expression [NOSE_EXCLUDE]") "-i", "--include", action="append", dest="include", metavar="REGEX", help="This regular expression will be applied to files, " "directories, function names, and class names for a chance " "to include additional tests that do not match TESTMATCH. " "Specify this option multiple times " "to add more regular expressions [NOSE_INCLUDE]") "-x", "--stop", action="store_true", dest="stopOnError", default=self.stopOnError, help="Stop running tests after the first error or failure") "-P", "--no-path-adjustment", action="store_false", dest="addPaths", default=self.addPaths, help="Don't make any changes to sys.path when " "loading tests [NOSE_NOPATH]") "--exe", action="store_true", dest="includeExe", default=self.includeExe, help="Look for tests in python modules that are " "executable. Normal behavior is to exclude executable " "modules, since they may not be import-safe " "[NOSE_INCLUDE_EXE]") "--noexe", action="store_false", dest="includeExe", help="DO NOT look for tests in python modules that are " "executable. (The default on the windows platform is to " "do so.)") "--traverse-namespace", action="store_true", default=self.traverseNamespace, dest="traverseNamespace", help="Traverse through all path entries of a namespace package") "--first-package-wins", "--first-pkg-wins", "--1st-pkg-wins", action="store_true", default=False, dest="firstPackageWins", help="nose's importer will normally evict a package from sys." "modules if it sees a package with the same name in a different " "location. Set this option to disable that behavior.") "--no-byte-compile", action="store_false", default=True, dest="byteCompile", help="Prevent nose from byte-compiling the source into .pyc files " "while nose is scanning for and running tests.")
"""Return the generated help message """ return self.getParser(doc).format_help()
self.__dict__.update(self._orig)
return self.__dict__.copy()
"""Options container that returns None for all options. """ return {}
pass
return ()
return False
"""Return path to any existing user config files """ list(map(os.path.expanduser, config_files))))
"""Return path to any existing user config files, plus any setup.cfg in the current working directory. """ return user
# used when parsing config files """Does the value look like an on/off flag?""" if val == 1: return True elif val == 0: return False val = str(val) if len(val) > 5: return False return val.upper() in ('1', '0', 'F', 'T', 'TRUE', 'FALSE', 'ON', 'OFF')
return str(val).upper() in ('1', 'T', 'TRUE', 'ON') |