def configure(self, argv=None, doc=None): """Configure the nose running environment. Execute configure before collecting tests with nose.TestCollector to enable output capture and other features. """ env = self.env if argv is None: argv = sys.argv cfg_files = getattr(self, 'files', []) options, args = self._parseArgs(argv, cfg_files) # If -c --config has been specified on command line, # load those config files and reparse if getattr(options, 'files', []): options, args = self._parseArgs(argv, options.files) self.options = options if args: self.testNames = args if options.testNames is not None: self.testNames.extend(tolist(options.testNames)) # `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 if not options.where: options.where = env.get('NOSE_WHERE', None) # include and exclude also if not options.include: options.include = env.get('NOSE_INCLUDE', []) if not options.exclude: options.exclude = env.get('NOSE_EXCLUDE', []) self.addPaths = options.addPaths self.stopOnError = options.stopOnError self.verbosity = options.verbosity self.includeExe = options.includeExe self.debug = options.debug self.debugLog = options.debugLog self.loggingConfig = options.loggingConfig self.configureLogging() if options.where is not None: self.configureWhere(options.where) if options.testMatch: self.testMatch = re.compile(options.testMatch) if options.include: self.include = map(re.compile, tolist(options.include)) log.info("Including tests matching %s", options.include) if options.exclude: self.exclude = map(re.compile, tolist(options.exclude)) log.info("Excluding tests matching %s", options.exclude) # When listing plugins we don't want to run them if not options.showPlugins: self.plugins.configure(options, self) self.plugins.begin()
def configure(self, options, config): """Configure the plugin and system, based on selected options. attr and eval_attr may each be lists. self.attribs will be a list of lists of tuples. In that list, each list is a group of attributes, all of which must match for the rule to match. """ self.attribs = [] # handle python eval-expression parameter if compat_24 and options.eval_attr: eval_attr = tolist(options.eval_attr) # multiple attribute rule expressions are conjugated attr = " and ".join(map(lambda s: "(%s)" % (s), eval_attr)) # "<python expression>" # -> eval(expr) in attribute context must be True def eval_in_context(expr, obj, cls): return eval(expr, None, ContextHelper(obj, cls)) self.attribs.append([(attr, eval_in_context)]) # attribute requirements are a comma separated list of # 'key=value' pairs if options.attr: std_attr = tolist(options.attr) for attr in std_attr: # all attributes within an attribute group must match attr_group = [] for attrib in attr.strip().split(","): # don't die on trailing comma if not attrib: continue items = attrib.split("=", 1) if len(items) > 1: # "name=value" # -> 'str(obj.name) == value' must be True key, value = items else: key = items[0] if key[0] == "!": # "!name" # 'bool(obj.name)' must be False key = key[1:] value = False else: # "name" # -> 'bool(obj.name)' must be True value = True attr_group.append((key, value)) self.attribs.append(attr_group) if self.attribs: self.enabled = True
def configure(self, options, config): """Configure the plugin and system, based on selected options. attr and eval_attr may each be lists. self.attribs will be a list of lists of tuples. In that list, each list is a group of attributes, all of which must match for the rule to match. """ self.attribs = [] # handle python eval-expression parameter if compat_24 and options.eval_attr: eval_attr = tolist(options.eval_attr) for attr in eval_attr: # "<python expression>" # -> eval(expr) in attribute context must be True def eval_in_context(expr, obj, cls): return eval(expr, None, ContextHelper(obj, cls)) self.attribs.append([(attr, eval_in_context)]) # attribute requirements are a comma separated list of # 'key=value' pairs if options.attr: std_attr = tolist(options.attr) for attr in std_attr: # all attributes within an attribute group must match attr_group = [] for attrib in attr.strip().split(","): # don't die on trailing comma if not attrib: continue items = attrib.split("=", 1) if len(items) > 1: # "name=value" # -> 'str(obj.name) == value' must be True key, value = items else: key = items[0] if key[0] == "!": # "!name" # 'bool(obj.name)' must be False key = key[1:] value = False else: # "name" # -> 'bool(obj.name)' must be True value = True attr_group.append((key, value)) self.attribs.append(attr_group) if self.attribs: self.enabled = True
def configure(self, options, config): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass Plugin.configure(self, options, config) if self.enabled: try: import coverage except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = config self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverPackages = [] if options.cover_packages: for pkgs in [tolist(x) for x in options.cover_packages]: self.coverPackages.extend(pkgs) self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages) self.coverHtmlDir = None if options.cover_html: self.coverHtmlDir = options.cover_html_dir log.debug('Will put HTML coverage report in %s', self.coverHtmlDir) if self.enabled: self.status['active'] = True
def configure(self, options, conf): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass super(DuvetCover, self).configure(options, conf) if conf.worker: return self.enabled = bool(coverage) and bool(git) self.conf = conf self.options = options self.coverPackages = [] if options.cover_packages: if isinstance(options.cover_packages, (list, tuple)): cover_packages = options.cover_packages else: cover_packages = [options.cover_packages] for pkgs in [tolist(x) for x in cover_packages]: self.coverPackages.extend(pkgs) if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages) if self.enabled: self.status['active'] = True
def configureWhere(self, where): """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) self.testNames.append(path)
def configure(self, options, config): plugins.Plugin.configure(self, options, config) self.conf = config self.tissue_packages = [] self.tissue_statistics = options.tissue_statistics self.tissue_fail_on_error = options.tissue_fail_on_error if options.tissue_packages: for pkgs in [util.tolist(x) for x in options.tissue_packages]: self.tissue_packages.extend(pkgs) self.tissue_inclusive = options.tissue_inclusive if self.tissue_packages: log.info('PEP8 report will include only packages: %s', self.tissue_packages) arglist = [] if options.tissue_repeat: arglist.append('--repeat') if options.tissue_select: arglist.append('--select') arglist.append(options.tissue_select) if options.tissue_ignore: arglist.append('--ignore') arglist.append(options.tissue_ignore) if options.tissue_show_source: arglist.append('--show-source') if options.tissue_show_pep8: arglist.append('--show-pep8') options, paths = pep8.process_options(arglist) self.pep8 = pep8.StyleGuide(**options.__dict__) self.pep8.init_report(TissueReport)
def configure(self, options, config): """Configure plugin. """ Plugin.configure(self, options, config) self.doctest_result_var = options.doctest_result_var self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.fixtures = options.doctestFixtures self.finder = doctest.DocTestFinder() self.optionflags = 0 if options.doctestOptions: flags = ",".join(options.doctestOptions).split(',') for flag in flags: if not flag or flag[0] not in '+-': raise ValueError( "Must specify doctest options with starting " + "'+' or '-'. Got %s" % (flag,)) mode, option_name = flag[0], flag[1:] option_flag = doctest.OPTIONFLAGS_BY_NAME.get(option_name) if not option_flag: raise ValueError("Unknown doctest option %s" % (option_name,)) if mode == '+': self.optionflags |= option_flag elif mode == '-': self.optionflags &= ~option_flag
def configure(self, options, noseconfig): """ Call the super and then validate and call the relevant parser for the configuration file passed in """ if not options.testconfig: return Plugin.configure(self, options, noseconfig) self.config = noseconfig if not options.capture: self.enabled = False if options.testconfigformat: self.format = options.testconfigformat if self.format not in self.valid_loaders.keys(): raise Exception('%s is not a valid configuration file format' \ % self.format) # Load the configuration file: self.valid_loaders[self.format](options.testconfig) if options.overrides: self.overrides = [] overrides = tolist(options.overrides) for override in overrides: keys, val = override.split(":") if options.exact: config[keys] = val else: ns = ''.join(['["%s"]' % i for i in keys.split(".") ]) # BUG: Breaks if the config value you're overriding is not # defined in the configuration file already. TBD exec('config%s = "%s"' % (ns, val))
def configureWhere(self, where): """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)
def wantModuleCoverage(self, name, module): if not hasattr(module, '__file__'): log.debug("no coverage of %s: no __file__", name) return False root, ext = os.path.splitext(module.__file__) if not ext in ('.py', '.pyc', '.pyo'): log.debug("no coverage of %s: not a python file", name) return False if tolist(self.options.cover_packages): for package in self.options.cover_packages: if (name.startswith(package) and (self.options.cover_tests or not self.conf.testMatch.search(name))): log.debug("coverage for %s", name) return True if name in self.skipModules: log.debug("no coverage for %s: loaded before coverage start", name) return False if self.conf.testMatch.search(name) and not self.options.cover_tests: log.debug("no coverage for %s: is a test", name) return False # accept any package that passed the previous tests, unless # coverPackages is on -- in that case, if we wanted this # module, we would have already returned True return not self.options.cover_packages
def options(self, parser, env=os.environ): # print "Options for nose plugin:", self.name # dbg Plugin.options(self, parser, env) parser.add_option( "--ipdoctest-tests", action="store_true", dest="ipdoctest_tests", default=env.get("NOSE_IPDOCTEST_TESTS", True), help="Also look for doctests in test modules. " "Note that classes, methods and functions should " "have either doctests or non-doctest tests, " "not both. [NOSE_IPDOCTEST_TESTS]", ) parser.add_option( "--ipdoctest-extension", action="append", dest="ipdoctest_extension", help="Also look for doctests in files with " "this extension [NOSE_IPDOCTEST_EXTENSION]", ) # Set the default as a list, if given in env; otherwise # an additional value set on the command line will cause # an error. env_setting = env.get("NOSE_IPDOCTEST_EXTENSION") if env_setting is not None: parser.set_defaults(ipdoctest_extension=tolist(env_setting))
def configure(self, options, config): """Configure plugin. """ Plugin.configure(self, options, config) self.doctest_result_var = options.doctest_result_var self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.fixtures = options.doctestFixtures self.finder = doctest.DocTestFinder() self.optionflags = 0 if options.doctestOptions: flags = ",".join(options.doctestOptions).split(',') for flag in flags: if not flag or flag[0] not in '+-': raise ValueError( "Must specify doctest options with starting " + "'+' or '-'. Got %s" % (flag, )) mode, option_name = flag[0], flag[1:] option_flag = doctest.OPTIONFLAGS_BY_NAME.get(option_name) if not option_flag: raise ValueError("Unknown doctest option %s" % (option_name, )) if mode == '+': self.optionflags |= option_flag elif mode == '-': self.optionflags &= ~option_flag
def configure(self, options, config): """Configure plugin. """ Plugin.configure(self, options, config) self.doctest_result_var = options.doctest_result_var self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.fixtures = options.doctestFixtures self.finder = doctest.DocTestFinder() self.optionflags = 0 if options.doctestOptions: flags = ",".join(options.doctestOptions).split(',') for flag in flags: try: if flag.startswith('+'): self.optionflags |= getattr(doctest, flag[1:]) elif flag.startswith('-'): self.optionflags &= ~getattr(doctest, flag[1:]) else: raise ValueError( "Must specify doctest options with starting " + "'+' or '-'. Got %s" % (flag,)) except AttributeError: raise ValueError("Unknown doctest option %s" % (flag[1:],))
def configure(self, options, config): # it is overriden in order to fix doctest options discovery Plugin.configure(self, options, config) self.doctest_result_var = options.doctest_result_var self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.fixtures = options.doctestFixtures self.finder = doctest.DocTestFinder() #super(DoctestPluginHelper, self).configure(options, config) self.optionflags = 0 if options.doctestOptions: flags = ",".join(options.doctestOptions).split(',') for flag in flags: try: if flag.startswith('+'): self.optionflags |= doctest.OPTIONFLAGS_BY_NAME[ flag[1:]] elif flag.startswith('-'): self.optionflags &= ~doctest.OPTIONFLAGS_BY_NAME[ flag[1:]] else: raise ValueError( "Must specify doctest options with starting " + "'+' or '-'. Got %s" % (flag, )) except (AttributeError, KeyError): raise ValueError("Unknown doctest option %s" % (flag[1:], ))
def configure(self, options, config): sw_lst = [] if options.switch: sw_lst = tolist(options.switch) if sw_lst: self.enabled = True NoseSwitch.switches += sw_lst
def configure(self, options, config): Plugin.configure(self, options, config) self.doctest_tests = options.doctest_tests try: self.extension = tolist(options.doctestExtension) except AttributeError: # 2.3, no other-file option self.extension = None
def configure(self, options, conf): Plugin.configure(self, options, conf) conf.exclude = map(re.compile, tolist(r'^(manage\.py|.*settings\.py|apps)$')) if options.django_settings and self.env is not None: self.env['DJANGO_SETTINGS_MODULE'] = options.django_settings self.verbosity = conf.verbosity
def configure(self, options, config): """Configure plugin. """ Plugin.configure(self, options, config) self.doctest_result_var = options.doctest_result_var self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.fixtures = options.doctestFixtures self.finder = doctest.DocTestFinder()
def val_ratio(self, Position_ratio, Position): Position_ = pd.DataFrame(Position, columns=["code", "amount"]) his_amount = sum(tolist(Position_["amount"].values)) / Position_ratio my_amount = self.portfolio_value() print("我的总市值:", my_amount) print("他的总市值:", his_amount) print("我的总市值/他的总市值:", my_amount / his_amount) return my_amount / his_amount
def configure(self, options, conf): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass super(Coverage, self).configure(options, conf) if conf.worker: return if self.enabled: try: import coverage if not hasattr(coverage, 'coverage'): raise ImportError("Unable to import coverage module") except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = conf self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverPackages = [] if options.cover_packages: if isinstance(options.cover_packages, (list, tuple)): cover_packages = options.cover_packages else: cover_packages = [options.cover_packages] for pkgs in [tolist(x) for x in cover_packages]: self.coverPackages.extend(pkgs) if options.cover_omit: cover_omit = [] for pattern in options.cover_omit: cover_omit.extend(pattern.split('\n')) options.cover_omit = cover_omit self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages) self.coverHtmlDir = None if options.cover_html: self.coverHtmlDir = options.cover_html_dir log.debug('Will put HTML coverage report in %s', self.coverHtmlDir) self.coverBranches = options.cover_branches self.coverXmlFile = None if options.cover_min_percentage: self.coverMinPercentage = int(options.cover_min_percentage.rstrip('%')) if options.cover_xml: self.coverXmlFile = options.cover_xml_file log.debug('Will put XML coverage report in %s', self.coverXmlFile) if self.enabled: self.status['active'] = True self.coverInstance = coverage.coverage(auto_data=False, branch=self.coverBranches, data_suffix=None, omit=options.cover_omit)
def configure(self, options, config): plugins.Plugin.configure(self, options, config) self.conf = config self.tissue_packages = [] self.tissue_statistics = options.tissue_statistics if options.tissue_packages: for pkgs in [util.tolist(x) for x in options.tissue_packages]: self.tissue_packages.extend(pkgs) self.tissue_inclusive = options.tissue_inclusive if self.tissue_packages: log.info("PEP8 report will include only packages: %s", self.coverPackages) # NOTE(jkoelker) Monkey-patch pep8 to not print directly def message(text): # if the output has a filename, then it should be colored if # the tissue_color option is used if ':' in text and os.path.exists(text.split(':')[0]): if options.tissue_color: if 'E' in text.split(':')[-1]: text = in_color('red', text) else: text = in_color('yellow', text) # if using the tissue_show_source or tissue_show_pep8, it # should separate the filename from the information if options.tissue_show_pep8 or options.tissue_show_source: text = "\n%s\n" % text self.messages.append(text) pep8.message = message # NOTE(jkoelker) Urgh! Really? Global options? At least there is a # function that takes the arglist ;( arglist = [] if options.tissue_repeat: arglist.append("--repeat") if options.tissue_select: arglist.append("--select") arglist.append(options.tissue_select) if options.tissue_ignore: arglist.append("--ignore") arglist.append(options.tissue_ignore) if options.tissue_show_source: arglist.append("--show-source") if options.tissue_show_pep8: arglist.append("--show-pep8") # NOTE(jkoelker) PEP8 requires something to be left over in args arglist.append("hozer") tissue_options, tissue_args = pep8.process_options(arglist)
def configure(self, options, config): Plugin.configure(self, options, config) self.doctest_tests = options.doctest_tests try: self.extension = tolist(options.doctestExtension) except AttributeError: # 2.3, no other-file option self.extension = None self.finder = doctest.DocTestFinder()
def configure(self, options, config): Plugin.configure(self, options, config) self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.parser = doctest.DocTestParser() self.finder = DocTestFinder() self.checker = IPDoctestOutputChecker() self.globs = None self.extraglobs = None
def configure(self, options, conf): """Configure plugin. """ super(ExtendedTestsCases, self).configure(options, conf) self.conf = conf if options.tests_cases: self.cases = tolist(options.tests_cases) self.enabled = True try: self.cases_conf = ConfigParser() self.cases_conf.read(options.cases_conf) all_tests = [] for case in self.cases: tests = tolist(self.cases_conf.get(case, "tests")) all_tests += tests self.conf.testNames += all_tests except IOError: raise IOError( "configuration file %s is not found" % options.cases_conf)
def configure(self, options, conf): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass super(Coverage, self).configure(options, conf) if conf.worker: return if self.enabled: try: import coverage if not hasattr(coverage, 'coverage'): raise ImportError("Unable to import coverage module") except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = conf self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverPackages = [] if options.cover_packages: if isinstance(options.cover_packages, (list, tuple)): cover_packages = options.cover_packages else: cover_packages = [options.cover_packages] for pkgs in [tolist(x) for x in cover_packages]: self.coverPackages.extend(pkgs) self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages) self.coverHtmlDir = None if options.cover_html: self.coverHtmlDir = options.cover_html_dir log.debug('Will put HTML coverage report in %s', self.coverHtmlDir) self.coverBranches = options.cover_branches self.coverXmlFile = None if options.cover_min_percentage: self.coverMinPercentage = int( options.cover_min_percentage.rstrip('%')) if options.cover_xml: self.coverXmlFile = options.cover_xml_file log.debug('Will put XML coverage report in %s', self.coverXmlFile) if self.enabled: self.status['active'] = True self.coverInstance = coverage.coverage(auto_data=False, branch=self.coverBranches, data_suffix=None, source=self.coverPackages)
def options(self, parser, env): """Register commmandline options. """ Plugin.options(self, parser, env) parser.add_option( "--doctest-tests", action="store_true", dest="doctest_tests", default=env.get("NOSE_DOCTEST_TESTS"), help="Also look for doctests in test modules. " "Note that classes, methods and functions should " "have either doctests or non-doctest tests, " "not both. [NOSE_DOCTEST_TESTS]", ) parser.add_option( "--doctest-extension", action="append", dest="doctestExtension", metavar="EXT", help="Also look for doctests in files with " "this extension [NOSE_DOCTEST_EXTENSION]", ) parser.add_option( "--doctest-result-variable", dest="doctest_result_var", default=env.get("NOSE_DOCTEST_RESULT_VAR"), metavar="VAR", help="Change the variable name set to the result of " "the last interpreter command from the default '_'. " "Can be used to avoid conflicts with the _() " "function used for text translation. " "[NOSE_DOCTEST_RESULT_VAR]", ) parser.add_option( "--doctest-fixtures", action="store", dest="doctestFixtures", metavar="SUFFIX", help="Find fixtures for a doctest file in module " "with this name appended to the base name " "of the doctest file", ) parser.add_option( "--doctest-options", action="append", dest="doctestOptions", metavar="OPTIONS", help="Specify options to pass to doctest. " + "Eg. '+ELLIPSIS,+NORMALIZE_WHITESPACE'", ) # Set the default as a list, if given in env; otherwise # an additional value set on the command line will cause # an error. env_setting = env.get("NOSE_DOCTEST_EXTENSION") if env_setting is not None: parser.set_defaults(doctestExtension=tolist(env_setting))
def configure(self, options, config): #print "Configuring nose plugin:", self.name # dbg Plugin.configure(self, options, config) self.doctest_tests = options.ipdoctest_tests self.extension = tolist(options.ipdoctest_extension) self.parser = IPDocTestParser() self.finder = DocTestFinder(parser=self.parser) self.checker = IPDoctestOutputChecker() self.globs = None self.extraglobs = None
def configure(self, options, config): Plugin.configure(self, options, config) # Pull standard doctest plugin out of config; we will do doctesting config.plugins.plugins = [p for p in config.plugins.plugins if p.name != "doctest"] self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.parser = doctest.DocTestParser() self.finder = DocTestFinder() self.checker = IPDoctestOutputChecker() self.globs = None self.extraglobs = None
def configure(self, options, config): Plugin.configure(self, options, config) # Pull standard doctest plugin out of config; we will do doctesting config.plugins.plugins = [p for p in config.plugins.plugins if p.name != 'doctest'] self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.parser = doctest.DocTestParser() self.finder = DocTestFinder() self.checker = IPDoctestOutputChecker() self.globs = None self.extraglobs = None
def configure(self, options, conf): Plugin.configure(self, options, conf) self.options = options self.conf = conf if options.profile_stats_file: self.pfile = options.profile_stats_file self.clean_stats_file = False else: self.pfile = None self.clean_stats_file = True self.fileno = None self.sort = options.profile_sort self.restrict = tolist(options.profile_restrict)
def configure(self, options, config): #print "Configuring nose plugin:", self.name # dbg Plugin.configure(self, options, config) # Pull standard doctest plugin out of config; we will do doctesting config.plugins.plugins = [p for p in config.plugins.plugins if p.name != 'doctest'] self.doctest_tests = options.ipdoctest_tests self.extension = tolist(options.ipdoctest_extension) self.parser = IPDocTestParser() self.finder = DocTestFinder(parser=self.parser) self.checker = IPDoctestOutputChecker() self.globs = None self.extraglobs = None
def configure(self, options, conf): if not self.available(): self.enabled = False return Plugin.configure(self, options, conf) self.conf = conf if options.profile_stats_file: self.pfile = options.profile_stats_file self.clean_stats_file = False else: self.pfile = None self.clean_stats_file = True self.fileno = None self.sort = options.profile_sort self.restrict = tolist(options.profile_restrict)
def configure(self, options, config): # print "Configuring nose plugin:", self.name # dbg Plugin.configure(self, options, config) # Pull standard doctest plugin out of config; we will do doctesting config.plugins.plugins = [ p for p in config.plugins.plugins if p.name != "doctest" ] self.doctest_tests = options.ipdoctest_tests self.extension = tolist(options.ipdoctest_extension) self.parser = IPDocTestParser() self.finder = DocTestFinder(parser=self.parser) self.checker = IPDoctestOutputChecker() self.globs = None self.extraglobs = None
def options(self, parser, env): """Register commmandline options. """ Plugin.options(self, parser, env) parser.add_option('--doctest-tests', action='store_true', dest='doctest_tests', default=env.get('NOSE_DOCTEST_TESTS'), help="Also look for doctests in test modules. " "Note that classes, methods and functions should " "have either doctests or non-doctest tests, " "not both. [NOSE_DOCTEST_TESTS]") parser.add_option('--doctest-extension', action="append", dest="doctestExtension", metavar="EXT", help="Also look for doctests in files with " "this extension [NOSE_DOCTEST_EXTENSION]") parser.add_option('--doctest-result-variable', dest='doctest_result_var', default=env.get('NOSE_DOCTEST_RESULT_VAR'), metavar="VAR", help="Change the variable name set to the result of " "the last interpreter command from the default '_'. " "Can be used to avoid conflicts with the _() " "function used for text translation. " "[NOSE_DOCTEST_RESULT_VAR]") parser.add_option('--doctest-fixtures', action="store", dest="doctestFixtures", metavar="SUFFIX", help="Find fixtures for a doctest file in module " "with this name appended to the base name " "of the doctest file") parser.add_option('--doctest-options', action="append", dest="doctestOptions", metavar="OPTIONS", help="Specify options to pass to doctest. " + "Eg. '+ELLIPSIS,+NORMALIZE_WHITESPACE'") # Set the default as a list, if given in env; otherwise # an additional value set on the command line will cause # an error. env_setting = env.get('NOSE_DOCTEST_EXTENSION') if env_setting is not None: parser.set_defaults(doctestExtension=tolist(env_setting))
def configure(self, options, conf): """Configure plugin. """ if not self.available(): self.enabled = False return Plugin.configure(self, options, conf) self.conf = conf if options.calltree_stats_file: self.pfile = os.path.abspath(options.calltree_stats_file) self.clean_stats_file = False else: self.pfile = None self.clean_stats_file = True self.fileno = None self.sort = options.calltree_sort self.restrict = tolist(options.calltree_restrict)
def configure(self, options, config): Plugin.configure(self, options, config) if self.enabled: try: import coverage except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = config self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverPackages = tolist(options.cover_packages) self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages)
def __init__(self, options): self.trace_paths = [] if isinstance(options.trace_paths, (list, tuple)): trace_paths = options.trace_paths else: trace_paths = [options.trace_paths] for pkgs in [tolist(os.path.expanduser(x)) for x in trace_paths]: self.trace_paths.extend(pkgs) if self.trace_paths: log.info("Tracing will only be done for paths: %s", self.trace_paths) self.output = options.callgraph_output self.seppel_callgraph = SeppelCallGraphController( log, self.trace_paths) _settrace(self.seppel_callgraph.trace_calls)
def configure(self, options, noseconfig): """ Call the super and then validate and call the relevant parser for the configuration file passed in """ if not options.tc_file: return self.enabled = True Plugin.configure(self, options, noseconfig) loader = ConfigLoader(options.tc_file, options.tc_format) with Signals.on_before_extend.connected_to(self.callbacks['on_before_extend']), \ Signals.on_after_extend.connected_to(self.callbacks['on_after_extend']): cfgifc = ConfigInterface(loader=loader) cfgifc.set_global_config() config = cfgifc.get_config() if options.tc_debug_open_contexts: atexit.register(print_open_contexts) if options.overrides: self.overrides = [] overrides = set(tolist(options.overrides)) for override in overrides: keys, val = override.split(":", 1) # Attempt to convert the string into int/bool/float or default # to string if val == '': val = None else: needquotes = False try: val = ast.literal_eval(val) except ValueError: needquotes = True if needquotes or isinstance(val, basestring): val = '"%s"' % val if options.tc_exact: config[keys] = val else: ns = ''.join(['["%s"]' % i for i in keys.split(".")]) # BUG: Breaks if the config value you're overriding is not # defined in the configuration file already. TBD exec('config%s = %s' % (ns, val))
def options(self, parser, env=os.environ): Plugin.options(self, parser, env) parser.add_option('--doctest-tests', action='store_true', dest='doctest_tests', default=env.get('NOSE_DOCTEST_TESTS',True), help="Also look for doctests in test modules. " "Note that classes, methods and functions should " "have either doctests or non-doctest tests, " "not both. [NOSE_DOCTEST_TESTS]") parser.add_option('--doctest-extension', action="append", dest="doctestExtension", help="Also look for doctests in files with " "this extension [NOSE_DOCTEST_EXTENSION]") # Set the default as a list, if given in env; otherwise # an additional value set on the command line will cause # an error. env_setting = env.get('NOSE_DOCTEST_EXTENSION') if env_setting is not None: parser.set_defaults(doctestExtension=tolist(env_setting))
def configure(self, options, conf): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass super(Coverage, self).configure(options, conf) if conf.worker: return if self.enabled: try: import coverage except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = conf self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverPackages = [] if options.cover_packages: for pkgs in [tolist(x) for x in options.cover_packages]: self.coverPackages.extend(pkgs) self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages) self.coverHtmlDir = None if options.cover_html: self.coverHtmlDir = options.cover_html_dir log.debug('Will put HTML coverage report in %s', self.coverHtmlDir) self.coverBranches = options.cover_branches self.coverXmlFile = None if options.cover_xml: self.coverXmlFile = options.cover_xml_file log.debug('Will put XML coverage report in %s', self.coverXmlFile) if self.enabled: self.status['active'] = True self.coverInstance = coverage.coverage(auto_data=False, branch=self.coverBranches, data_suffix=None)
def configure(self, options, config): # it is overriden in order to fix doctest options discovery Plugin.configure(self, options, config) self.doctest_result_var = options.doctest_result_var self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.fixtures = options.doctestFixtures self.finder = doctest.DocTestFinder() #super(DoctestPluginHelper, self).configure(options, config) self.optionflags = 0 self.options = {} if options.doctestOptions: stroptions = ",".join(options.doctestOptions).split(',') for stroption in stroptions: try: if stroption.startswith('+'): self.optionflags |= doctest.OPTIONFLAGS_BY_NAME[ stroption[1:]] continue elif stroption.startswith('-'): self.optionflags &= ~doctest.OPTIONFLAGS_BY_NAME[ stroption[1:]] continue try: key, value = stroption.split('=') except ValueError: pass else: if not key in self.OPTION_BY_NAME: raise ValueError() self.options[key] = value continue except (AttributeError, ValueError, KeyError): raise ValueError( "Unknown doctest option {}".format(stroption)) else: raise ValueError( "Doctest option is not a flag or a key/value pair: {} " .format(stroption))
def configure(self, options, config): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass Plugin.configure(self, options, config) if getattr(config, "worker", None) and config.worker: return if self.enabled: try: import coverage except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = config self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverBranch = options.cover_branch self.coverExclude = options.cover_exclude or [] if isinstance(self.coverExclude, str): self.coverExclude = RE_LIST.split(self.coverExclude) self.coverXml = options.cover_xml self.coverXmlFile = options.cover_xml_file self.coverPackages = [] if options.cover_packages: for pkgs in [tolist(x) for x in options.cover_packages]: self.coverPackages.extend(pkgs) self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages) self.coverHtmlDir = None if options.cover_html: self.coverHtmlDir = options.cover_html_dir log.debug('Will put HTML coverage report in %s', self.coverHtmlDir) if self.enabled: self.status['active'] = True
def configure(self, options, config): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass Plugin.configure(self, options, config) if getattr(config, "worker", None) and config.worker: return if self.enabled: try: import coverage except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = config self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverBranch = options.cover_branch self.coverExclude = options.cover_exclude or [] if isinstance(self.coverExclude, basestring): self.coverExclude = RE_LIST.split(self.coverExclude) self.coverXml = options.cover_xml self.coverXmlFile = options.cover_xml_file self.coverPackages = [] if options.cover_packages: for pkgs in [tolist(x) for x in options.cover_packages]: self.coverPackages.extend(pkgs) self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages) self.coverHtmlDir = None if options.cover_html: self.coverHtmlDir = options.cover_html_dir log.debug('Will put HTML coverage report in %s', self.coverHtmlDir) if self.enabled: self.status['active'] = True
def configure(self, options, conf): Plugin.configure(self, options, conf) self._nose_uploader_url = options.nose_uploader_url self._nose_uploader_user = options.nose_uploader_user self._nose_uploader_pass = options.nose_uploader_pass self._nose_uploader_vars = {} if options.nose_uploader_vars: std_vars = tolist(options.nose_uploader_vars) for var in std_vars: for pair in var.strip().split(","): if not pair: continue items = pair.split("=", 1) if len(items) > 1: # "name=value" key, value = items self._nose_uploader_vars[key] = value # Include env variables that start wit 'NOSE_UPLOADER' self._nose_uploader_vars.update(env_vars(self.env_prefix))
def configure(self, options, noseconfig): """ Call the super and then validate and call the relevant parser for the configuration file passed in """ if options.testconfig == [None]: raise FrameworkException("No test-config specified (--tc-file)") if not options.testconfig and not options.overrides: return Plugin.configure(self, options, noseconfig) self.config = noseconfig if not options.capture: self.enabled = False if options.testconfigformat: self.format = options.testconfigformat if self.format not in self.valid_loaders.keys(): raise Exception('%s is not a valid configuration file format' \ % self.format) # Load the configuration file: for configfile in options.testconfig: if configfile: self.valid_loaders[self.format](configfile, options.testconfigencoding) overrides = tolist(options.overrides) or [] for override in overrides: keys, val = override.split(":", 1) if options.exact: config[keys] = val else: # Create all *parent* keys that may not exist in the config section = config keys = keys.split('.') for key in keys[:-1]: if key not in section: section[key] = {} section = section[key] # Finally assign the value to the last key key = keys[-1] section[key] = val
def configure(self, options, config): # it is overriden in order to fix doctest options discovery Plugin.configure(self, options, config) self.doctest_result_var = options.doctest_result_var self.doctest_tests = options.doctest_tests self.extension = tolist(options.doctestExtension) self.fixtures = options.doctestFixtures self.finder = doctest.DocTestFinder() # super(DoctestPluginHelper, self).configure(options, config) self.optionflags = 0 self.options = {} if options.doctestOptions: stroptions = ",".join(options.doctestOptions).split(',') for stroption in stroptions: try: if stroption.startswith('+'): self.optionflags |= doctest.OPTIONFLAGS_BY_NAME[stroption[1:]] continue elif stroption.startswith('-'): self.optionflags &= ~doctest.OPTIONFLAGS_BY_NAME[stroption[1:]] continue try: key, value = stroption.split('=') except ValueError: pass else: if not key in self.OPTION_BY_NAME: raise ValueError() self.options[key] = value continue except (AttributeError, ValueError, KeyError): raise ValueError("Unknown doctest option {}".format(stroption)) else: raise ValueError( "Doctest option is not a flag or a key/value pair: {} ".format( stroption ) )
def configure(self, options, config): Plugin.configure(self, options, config) if self.enabled: try: import coverage except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = config self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverPackages = [] if options.cover_packages: for pkgs in [tolist(x) for x in options.cover_packages]: self.coverPackages.extend(pkgs) self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages)
def parseArgs(self, argv): """Parse argv and env and configure running environment. """ self.config.configure(argv, doc=self.usage()) log.debug("configured %s", self.config) # quick outs: version, plugins (optparse would have already # caught and exited on help) if self.config.options.version: from nose import __version__ sys.stdout = sys.__stdout__ print("%s version %s" % (os.path.basename(sys.argv[0]), __version__)) sys.exit(0) if self.config.options.showPlugins: self.showPlugins() sys.exit(0) if self.testLoader is None: self.testLoader = defaultTestLoader(config=self.config) elif isclass(self.testLoader): self.testLoader = self.testLoader(config=self.config) plug_loader = self.config.plugins.prepareTestLoader(self.testLoader) if plug_loader is not None: self.testLoader = plug_loader log.debug("test loader is %s", self.testLoader) # FIXME if self.module is a string, add it to self.testNames? not sure if self.config.testNames: self.testNames = self.config.testNames else: self.testNames = tolist(self.defaultTest) log.debug('defaultTest %s', self.defaultTest) log.debug('Test names are %s', self.testNames) if self.config.workingDir is not None: os.chdir(self.config.workingDir) self.createTests()