Exemple #1
0
    def get_coverage(args: list, root_path: str, module_use=False) -> Dict[str, Line]:
        """
        Returns Dict of covered line's Line object.
         :param args: list of module name and target testcase want to get coverage
         :param root_path: target src root want to get coverage
         :return: {
             Line1_hash: {file_path, line_no, line_text},
             Line2_hash: {file_path, line_no, line_text}
         }
        1. cover 한 라인 (file path, line no, line text)
        2. file path 가 root 에 포함되는가.
        2. Line(line text, line no, file path)
        3. res_dict[Line.getHash()] = Line
        4. return res_dict
        """

        regular_path = os.path.abspath(root_path)
        covered = defaultdict(Line)
        # path 에 해당하는 .py file run.
        # report 에 covered line 정보 담겨있음.
        cov = Coverage()
        # args = args[:1] + [root_path] + args[1:]
        runner = PyRunner(args, as_module=module_use)
        runner.prepare()

        cov.start()
        code_ran = True
        try:
            runner.run()
        except NoSource:
            code_ran = False
            raise
        finally:
            cov.stop()
            if code_ran:
                cov.save()

            # testcase.py args 없다고 가정.
            report = get_analysis_to_report(cov, [])
            try:
                for fr, analysis in report:
                    # report : [(file1, [line1, line2, ...]), (), ...]
                    fn = fr.filename
                    if regular_path not in fn:
                        continue

                    if os.path.splitext(fn)[-1] != ".py":
                        continue

                    with open(fn, 'r', encoding="UTF8") as f:
                        lines = f.readlines()
                        if lines:
                            for line_no in analysis.executed:
                                lo = Line(fr.filename, line_no, lines[line_no-1])
                                covered[lo.getHash()] = lo
                        f.close()
            except CoverageException:
                print("There is no Test ran")

            return covered
Exemple #2
0
    def do_run(self, options, args):
        """Implementation of 'coverage run'."""

        if not args:
            if options.module:
                # Specified -m with nothing else.
                show_help("No module specified for -m")
                return ERR
            command_line = self.coverage.get_option("run:command_line")
            if command_line is not None:
                args = shlex.split(command_line)
                if args and args[0] in {"-m", "--module"}:
                    options.module = True
                    args = args[1:]
        if not args:
            show_help("Nothing to do.")
            return ERR

        if options.append and self.coverage.get_option("run:parallel"):
            show_help("Can't append to data files in parallel mode.")
            return ERR

        if options.concurrency == "multiprocessing":
            # Can't set other run-affecting command line options with
            # multiprocessing.
            for opt_name in [
                    'branch', 'include', 'omit', 'pylib', 'source', 'timid'
            ]:
                # As it happens, all of these options have no default, meaning
                # they will be None if they have not been specified.
                if getattr(options, opt_name) is not None:
                    show_help(
                        "Options affecting multiprocessing must only be specified "
                        + "in a configuration file.\n" +
                        f"Remove --{opt_name} from the command line.")
                    return ERR

        os.environ["COVERAGE_RUN"] = "true"

        runner = PyRunner(args, as_module=bool(options.module))
        runner.prepare()

        if options.append:
            self.coverage.load()

        # Run the script.
        self.coverage.start()
        code_ran = True
        try:
            runner.run()
        except NoSource:
            code_ran = False
            raise
        finally:
            self.coverage.stop()
            if code_ran:
                self.coverage.save()

        return OK
Exemple #3
0
    def do_run(self, options, args):
        """Implementation of 'coverage run'."""

        if not args:
            if options.module:
                # Specified -m with nothing else.
                show_help("No module specified for -m")
                return ERR
            command_line = self.coverage.get_option("run:command_line")
            if command_line is not None:
                args = shlex.split(command_line)
                if args and args[0] == "-m":
                    options.module = True
                    args = args[1:]
        if not args:
            show_help("Nothing to do.")
            return ERR

        if options.append and self.coverage.get_option("run:parallel"):
            show_help("Can't append to data files in parallel mode.")
            return ERR

        if options.concurrency == "multiprocessing":
            # Can't set other run-affecting command line options with
            # multiprocessing.
            for opt_name in ['branch', 'include', 'omit', 'pylib', 'source', 'timid']:
                # As it happens, all of these options have no default, meaning
                # they will be None if they have not been specified.
                if getattr(options, opt_name) is not None:
                    show_help(
                        "Options affecting multiprocessing must only be specified "
                        "in a configuration file.\n"
                        "Remove --{} from the command line.".format(opt_name)
                    )
                    return ERR

        runner = PyRunner(args, as_module=bool(options.module))
        runner.prepare()

        if options.append:
            self.coverage.load()

        # Run the script.
        self.coverage.start()
        code_ran = True
        try:
            runner.run()
        except NoSource:
            code_ran = False
            raise
        finally:
            self.coverage.stop()
            if code_ran:
                self.coverage.save()

        return OK
Exemple #4
0
    from _coverage_util import save_normalized_coverage, patch_coverage

    del sys.path[-1]

    # Patch coverage
    patch_coverage()

    from coverage import coverage as coverage_factory
    from coverage.execfile import PyRunner

    coverage = coverage_factory(*(config.get("cov_args", ())),
                                **(config.get("cov_kwargs", {})))
    source_path = config["cov_source_path"]
    omit_patterns = config["cov_omit_patterns"]

    args = sys.argv
    module = False
    if args and args[0] == "-m":
        module = True
        args = args[1:]

    runner = PyRunner(args, as_module=module)
    runner.prepare()

    coverage.start()
    try:
        runner.run()
    finally:
        coverage.stop()
        save_normalized_coverage(coverage, source_path, omit_patterns)