Parse the test results from the specified directory and load them under the name
        of 'module.executable ' that they were created with. E.g. parse classes.polya/
432080
def do_parse(self, arg, fullparse=False):
        
        from os import path
        fullpath = path.abspath(path.expanduser(arg))
        if path.isdir(fullpath):
            if fullpath[-1] == "/":
                end = -2
            else:
                end = -1
            case = fullpath.split("/")[end]
            self.tests[case] = Analysis(fullpath, fullparse)
            self.do_set(case)
        else:
            msg.err("The folder {} does not exist.".format(fullpath))
537432
def load_jamfile(self, dir, jamfile_module):
        """"""
        assert isinstance(dir, basestring)
        assert isinstance(jamfile_module, basestring)

        # See if the Jamfile is where it should be.
        is_jamroot = False
        jamfile_to_load = b2.util.path.glob([dir], self.JAMROOT)
        if jamfile_to_load:
            if len(jamfile_to_load) > 1:
                get_manager().errors()(
                    "Multiple Jamfiles found at '{}'\n"
                    "Filenames are: {}"
                    .format(dir, ' '.join(os.path.basename(j) for j in jamfile_to_load))
                )
            is_jamroot = True
            jamfile_to_load = jamfile_to_load[0]
        else:
            jamfile_to_load = self.find_jamfile(dir)

        dir = os.path.dirname(jamfile_to_load)
        if not dir:
            dir = "."

        self.used_projects[jamfile_module] = []

        # Now load the Jamfile in it's own context.
        # The call to 'initialize' may load parent Jamfile, which might have
        # 'use-project' statement that causes a second attempt to load the
        # same project we're loading now.  Checking inside .jamfile-modules
        # prevents that second attempt from messing up.
        if not jamfile_module in self.jamfile_modules:
            previous_project = self.current_project
            # Initialize the jamfile module before loading.
            self.initialize(jamfile_module, dir, os.path.basename(jamfile_to_load))

            if not jamfile_module in self.jamfile_modules:
                saved_project = self.current_project
                self.jamfile_modules[jamfile_module] = True

                bjam.call("load", jamfile_module, jamfile_to_load)

                if is_jamroot:
                    jamfile = self.find_jamfile(dir, no_errors=True)
                    if jamfile:
                        bjam.call("load", jamfile_module, jamfile)

                # Now do some checks
                if self.current_project != saved_project:
                    from textwrap import dedent
                    self.manager.errors()(dedent(
                        """
                        The value of the .current-project variable has magically changed
                        after loading a Jamfile. This means some of the targets might be
                        defined a the wrong project.
                        after loading %s
                        expected value %s
                        actual value %s
                        """
                        % (jamfile_module, saved_project, self.current_project)
                    ))

                self.end_load(previous_project)

                if self.global_build_dir:
                    id = self.attributeDefault(jamfile_module, "id", None)
                    project_root = self.attribute(jamfile_module, "project-root")
                    location = self.attribute(jamfile_module, "location")

                    if location and project_root == dir:
                        # This is Jamroot
                        if not id:
                            # FIXME: go via errors module, so that contexts are
                            # shown?
                            print "warning: the --build-dir option was specified"
                            print "warning: but Jamroot at '%s'" % dir
                            print "warning: specified no project id"
                            print "warning: the --build-dir option will be ignored"
443586
def from_raw(self, file_names=None, **kwargs):
        
        # This function only loads one test at a time (but could contain several
        # files). The function from_res() also implements loading several
        # datasets (using list of lists as input).

        if file_names:
            self.file_names = file_names

        if not isinstance(file_names, (list, tuple)):
            self.file_names = [file_names, ]

        # file_type = self.tester
        raw_file_loader = self.loader
        set_number = 0
        test = None
        counter = 0
        self.logger.debug("start iterating through file(s)")
        for f in self.file_names:
            self.logger.debug("loading raw file:")
            self.logger.debug(f"{f}")
            new_tests = raw_file_loader(f, **kwargs)
            if new_tests:
                if test is not None:
                    self.logger.debug("continuing reading files...")
                    _test = self._append(test[set_number], new_tests[set_number])
                    if not _test:
                        self.logger.warning(f"EMPTY TEST: {f}")
                        continue
                    test[set_number] = _test
                    self.logger.debug("added this test - started merging")
                    for j in range(len(new_tests[set_number].raw_data_files)):
                        raw_data_file = new_tests[set_number].raw_data_files[j]
                        file_size = new_tests[set_number].raw_data_files_length[j]
                        test[set_number].raw_data_files.append(raw_data_file)
                        test[set_number].raw_data_files_length.append(file_size)
                        counter += 1
                        if counter > 10:
                            self.logger.debug("ERROR? Too many files to merge")
                            raise ValueError("Too many files to merge - "
                                             "could be a p2-p3 zip thing")
                else:
                    self.logger.debug("getting data from first file")
                    if new_tests[set_number].no_data:
                        self.logger.debug("NO DATA")
                    else:
                        test = new_tests
            else:
                self.logger.debug("NOTHING LOADED")

        self.logger.debug("finished loading the raw-files")

        test_exists = False
        if test:
            if test[0].no_data:
                self.logging.debug("the first dataset (or only dataset) loaded from the raw data file is empty")
            else:
                test_exists = True

        if test_exists:
            if not prms.Reader.sorted_data:
                self.logger.debug("sorting data")
                test[set_number] = self._sort_data(test[set_number])

            self.datasets.append(test[set_number])
        else:
            self.logger.warning("No new datasets added!")
        self.number_of_datasets = len(self.datasets)
        self.status_datasets = self._validate_datasets()
        self._invent_a_name()
        return self
151965
def load(cls, filename, dir=None, main=False, **kwargs):
        
        name = main and "__main__" or Path(filename).stem
        loader = cls(name, str(filename), **kwargs)
        module = module_from_spec(FileModuleSpec(name, loader, origin=loader.path))
        cwd = str(Path(loader.path).parent)
        try:
            with ExitStack() as stack:
                sys.path.append(cwd)
                loader.name != "__main__" and stack.enter_context(_installed_safely(module))
                loader.exec_module(module)
        finally:
            sys.path.pop()

        return module
72319
function (options, iterationInfo, modules) {
        // filename filter
        if (options.fileNameFilter) {
            var match = iterationInfo.fileName.match(options.fileNameFilter);
            if (!match) {
                return;
            }
        }

        // Filter spec.js files
        var match = iterationInfo.fileName.match(/.spec.js/i);
        if (match) {
            return;
        }

        // relative path filter
        if (options.relativePathFilter) {
            var pathMatch = iterationInfo.relativeFullPath.match(options.relativePathFilter);
            if (!pathMatch)
                return;
        }

        //load module
        loadModule(modules, options, iterationInfo);
    }
480565
def load(self):
        
        # If we are given a string, open it up else assume it's something we
        # can call read on.
        if isinstance(self.specfile, str):
            f = open(self.specfile, 'r')
        else:
            f = self.specfile

        for line in f:
            if self.v_regex.match(line):
                self._pkg_version = self.v_regex.match(line).group(1)
            if self.n_regex.match(line):
                self._pkg_name = self.n_regex.match(line).group(1)
        f.close()
        self._loaded = True
793609
def main(*args):
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument("action",
                        help="create, check, run, make-nb, or run-nb")
    parser.add_argument("--directory", "-dir", default=os.getcwd(),
                        help="path to directory with a .sciunit file")
    parser.add_argument("--stop", "-s", default=True,
                        help="stop and raise errors, halting the program")
    parser.add_argument("--tests", "-t", default=False,
                        help="runs tests instead of suites")
    if args:
        args = parser.parse_args(args)
    else:
        args = parser.parse_args()
    file_path = os.path.join(args.directory, '.sciunit')
    config = None
    if args.action == 'create':
        create(file_path)
    elif args.action == 'check':
        config = parse(file_path, show=True)
        print("\nNo configuration errors reported.")
    elif args.action == 'run':
        config = parse(file_path)
        run(config, path=args.directory,
            stop_on_error=args.stop, just_tests=args.tests)
    elif args.action == 'make-nb':
        config = parse(file_path)
        make_nb(config, path=args.directory,
                stop_on_error=args.stop, just_tests=args.tests)
    elif args.action == 'run-nb':
        config = parse(file_path)
        run_nb(config, path=args.directory)
    else:
        raise NameError('No such action %s' % args.action)
    if config:
        cleanup(config, path=args.directory)
1150549
def load(cls, filename=None):
        """"""
        if filename is None:
            LOGGER.debug("Loading default configuration.")
            with open_text(templates, "test_config.yml",
                           encoding="utf-8") as file_handle:
                content = yaml.load(file_handle)
        else:
            LOGGER.debug("Loading custom configuration '%s'.", filename)
            try:
                with open(filename, encoding="utf-8") as file_handle:
                    content = yaml.load(file_handle)
            except IOError as err:
                LOGGER.error(
                    "Failed to load the custom configuration '%s'. Skipping.",
                    filename)
                LOGGER.debug(str(err))
                content = dict()
        return cls(content)
902188
def load_module(self, name):
        
        # Implementation inspired from pytest.rewrite and importlib

        # If there is an existing module object named 'name' in
        # sys.modules, the loader must use that existing module. (Otherwise,
        # the reload() builtin will not work correctly.)
        if name in sys.modules:
            return sys.modules[name]
        try:
            # we have already done the search, an gone through package layers
            # so we directly feed the latest module and correct path
            # to reuse the logic for choosing the proper loading behavior

            # TODO : double check maybe we do not need the loop here, already handled by finders in dir hierarchy
            # TODO : use exec_module (recent, more tested API) from here
            for name_idx, name_part in enumerate(name.split('.')):
                pkgname = ".".join(name.split('.')[:name_idx+1])
                if pkgname not in sys.modules:
                    if '.' in pkgname:
                        # parent has to be in sys.modules. make sure it is a package, else fails
                        if '__path__' in vars(sys.modules[pkgname.rpartition('.')[0]]):
                            path = sys.modules[pkgname.rpartition('.')[0]].__path__
                        else:
                            raise ImportError("{0} is not a package (no __path__ detected)".format(pkgname.rpartition('.')[0]))
                    else:  # using __file__ instead. should always be there.
                        path = os.path.dirname(sys.modules[pkgname].__file__)if pkgname in sys.modules else None
                    try:
                        file, pathname, description = imp.find_module(pkgname.rpartition('.')[-1], path)
                        sys.modules[pkgname] = imp.load_module(pkgname, file, pathname, description)
                    finally:
                        if file:
                            file.close()
        except:
            # dont pollute the interpreter environment if we dont know what we are doing
            if name in sys.modules:
                del sys.modules[name]
            raise
        return sys.modules[name]
160756
def main():
  
  parser = argparse.ArgumentParser(description='A distributed test framework')
  parser.add_argument('testfile',
      help='The file that is used to determine the test suite run')
  parser.add_argument('--test-only',
      nargs='*',
      dest='test_list',
      help='run only the named tests to help debug broken tests')
  parser.add_argument('--machine-list',
      nargs='*',
      dest='machine_list',
      help='''mapping of logical host names to physical names allowing the same
              test suite to run on different hardware, each argument is a pair
              of logical name and physical name separated by a =''')
  parser.add_argument('--config-overrides',
      nargs='*',
      dest='config_overrides',
      help='''config overrides at execution time, each argument is a config with
              its value separated by a =. This has the highest priority of all
              configs''')
  parser.add_argument('-d', '--output-dir',
      dest='output_dir',
      help='''Directory to write output files and logs. Defaults to the current
              directory.''')
  parser.add_argument("--log-level", dest="log_level", help="Log level (default INFO)", default="INFO")
  parser.add_argument("--console-log-level", dest="console_level", help="Console Log level (default ERROR)",
                      default="ERROR")
  parser.add_argument("--nopassword", action='store_true', dest="nopassword", help="Disable password prompt")
  parser.add_argument("--user", dest="user", help="user to run the test as (defaults to current user)")
  args = parser.parse_args()
  try:
    call_main(args)
  except ValueError:
    #We only sys.exit here, as call_main is used as part of a unit test
    #and should not exit the system
    sys.exit(1)
436848
def parse(self, limit=None):
        
        if limit is not None:
            LOG.info("Only parsing first %s rows fo each file", str(limit))

        LOG.info("Parsing files...")

        if self.test_only:
            self.test_mode = True

        # for f in ['impc', 'euro', 'mgd', '3i']:
        for f in ['all']:
            file = '/'.join((self.rawdir, self.files[f]['file']))
            self._process_data(file, limit)

        LOG.info("Finished parsing")

        return
79343
def _parse_programs(self, string, parent, filepath=None):
        """"""
        #First, get hold of the docstrings  for all the modules so that we can
        #attach them as we parse them.
        moddocs = self.docparser.parse_docs(string)
        #Now look for modules in the file and then match them to their decorators.
        matches = self.RE_PROGRAM.finditer(string)
        result = []
        for rmodule in matches:
            name = rmodule.group("name").lower()
            contents = re.sub("&[ ]*\n", "", rmodule.group("contents"))
            module = self._process_module(name, contents, parent, rmodule, filepath)
            #Check whether the docparser found docstrings for the module.
            if name in moddocs:                
                module.docstring = self.docparser.to_doc(moddocs[name][0], name)
                module.docstart, module.docend = module.absolute_charindex(string, moddocs[name][1],
                                                                           moddocs[name][2])
            result.append(module)
        return result
225161
def load(settings=None, namespace=None, prefix=None):
    

    parent = pyaas.util.getParent()
    script_name = os.path.basename(parent)
    script_name = script_name.rsplit('.', 1)[0]

    if prefix is None:
        # get the filename of the caller
        # get the directory name of the file
        prefix = os.path.dirname(parent)

        if prefix.endswith(os.path.sep + 'bin'):
            prefix = os.path.join(prefix, '..')
            prefix = os.path.abspath(prefix)

    prefix = os.path.abspath(prefix)
    if pyaas.prefix != prefix:
        pyaas.prefix = prefix
        logging.debug('Setting prefix to "%s"', pyaas.prefix)

    if namespace is None:
        namespace = script_name

    if namespace != pyaas.namespace:
        pyaas.namespace = namespace
        logging.debug('Setting namespace to "%s"', pyaas.namespace)

    # if settings is not passed in use the supplied or derived namespace
    settings = settings or namespace

    pyaas.args = pyaas.argparser.parse_args()

    pyaas.config = configparser.SafeConfigParser(dict_type=collections.OrderedDict)
    pyaas.config.optionxform = str

    ini_files = [
        pyaas.paths('etc', settings + '.ini'),
        pyaas.paths('etc', settings + '.ini.local')
    ]

    if pyaas.args.ini:
        ini_files.append(pyaas.args.ini)

    try:
        ok = pyaas.config.read(ini_files)
    except configparser.ParsingError as e:
        raise pyaas.error('Unable to parse file: %s', e)

    if not ok:
        raise pyaas.error('Unable to read config file(s): %s', ini_files)

    # setup file log
    file_name = '%s_%s.log' % (script_name, time.strftime('%Y%m%d_%H%M%S'))

    # hack back in single log file option without breaking existing code
    if pyaas.config.has_section('logging'):
        if pyaas.config.has_option('logging', 'append'):
            append = pyaas.config.getboolean('logging', 'append')
            if append:
                file_name = script_name + '.log'

    full_path = pyaas.paths('var', file_name)
    logfile = logging.FileHandler(full_path)
    logfile.setLevel(logging.INFO)

    logfile.setFormatter(
        logging.Formatter(
            fmt = '%(asctime)s %(levelname)-8s %(message)s',
            datefmt = '%Y-%m-%d %H:%M:%S',
            )
        )

    # add the handlers to the logger
    root = logging.getLogger()
    root.addHandler(logfile)

    if pyaas.args.debug:
        root.setLevel(logging.DEBUG)
        logfile.setLevel(logging.DEBUG)

    # call this here if there is no daemon option
    if not hasattr(pyaas.args, 'daemon'):
        pyaas.module.load()

    return
389750
def load_and_parse(self):
        """"""

        archives = []
        to_return = {}

        for name, project in self.all_projects.items():
            archives = archives + self.parse_archives_from_project(project)

        # We're going to have a similar issue with parsed nodes, if we want to
        # make parse_node return those.
        for a in archives:
            # archives have a config, but that would make for an invalid
            # UnparsedNode, so remove it and pass it along to parse_node as an
            # argument.
            archive_config = a.pop('config')
            archive = UnparsedNode(**a)
            node_path = self.get_path(archive.resource_type,
                                      archive.package_name,
                                      archive.name)

            to_return[node_path] = self.parse_node(
                archive,
                node_path,
                self.all_projects.get(archive.package_name),
                archive_config=archive_config)

        return to_return
326413
def evaluate(module_name: str, fname: str, verbose: bool):
    
    if verbose:
        print("Testing {}".format(fname))
    spec = importlib.util.spec_from_file_location(module_name, fname)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
862186
def parse_files(*files)
      require 'ox'
      @tests = []
      failed_tests = []

      Array(files).flatten.each do |file|
        raise "No JUnit file was found at #{file}" unless File.exist? file

        xml_string = File.read(file)
        doc = Ox.parse(xml_string)

        suite_root = doc.nodes.first.value == 'testsuites' ? doc.nodes.first : doc
        @tests += suite_root.nodes.map(&:nodes).flatten.select { |node| node.kind_of?(Ox::Element) && node.value == 'testcase' }

        failed_suites = suite_root.nodes.select { |suite| suite[:failures].to_i > 0 || suite[:errors].to_i > 0 }
        failed_tests += failed_suites.map(&:nodes).flatten.select { |node| node.kind_of?(Ox::Element) && node.value == 'testcase' }
      end

      @failures = failed_tests.select do |test| 
        test.nodes.count > 0
      end.select do |test|
        node = test.nodes.first
        node.kind_of?(Ox::Element) && node.value == 'failure'
      end

      @errors = failed_tests.select do |test| 
        test.nodes.count > 0
      end.select do |test| 
        node = test.nodes.first
        node.kind_of?(Ox::Element) && node.value == 'error'
      end

      @skipped = tests.select do |test| 
        test.nodes.count > 0
      end.select do |test| 
        node = test.nodes.first
        node.kind_of?(Ox::Element) && node.value == 'skipped'
      end

      @passes = tests - @failures - @errors - @skipped
    end
1195353
def _parse_app_spec(src_dir):
    
    if not os.path.isdir(src_dir):
        parser.error("%s is not a directory" % src_dir)
    if not os.path.exists(os.path.join(src_dir, "dxapp.json")):
        raise dxpy.app_builder.AppBuilderException("Directory %s does not contain dxapp.json: not a valid DNAnexus app source directory" % src_dir)
    with open(os.path.join(src_dir, "dxapp.json")) as app_desc:
        try:
            return json_load_raise_on_duplicates(app_desc)
        except Exception as e:
            raise dxpy.app_builder.AppBuilderException("Could not parse dxapp.json file as JSON: " + str(e.args))