Пример #1
0
def main(args):
    # Auto set arguments if none were provided

    # If no sourcefile was provided, find the test-coverage.info file.
    #  This assumes that the first file found is the desired one, so if multiple
    #  exist then the sourceFile must be specified on the command line.
    if not args.sourceFile:
        f = glob.glob('**/test-coverage.info', recursive=True)
        if f:
            sourceFile = f[0]
        else:
            sys.exit("No lcov output file found below current directory.")
    else:
        sourceFile = args.sourceFile

    # If no output file was provided, then place it in the same directory as
    #  the source file.
    if not args.outFile:
        outFile = os.path.dirname(sourceFile) + '/test-coverage.xml'
    else:
        outFile = args.outFile

    # Read all the data from the lcov output file
    with open(sourceFile) as fr:
        data = fr.read()

    # Create a converter and convert coverage data
    converter = LcovCobertura(data)
    res = converter.convert()

    # Write all output data to the destination file.
    with open(outFile, 'w') as fw:
        fw.write(res)
Пример #2
0
    def main(argv):
        """
        Converts LCOV coverage data to Cobertura-compatible XML for reporting.

        Usage:
            lcov_cobertura.py lcov-file.dat
            lcov_cobertura.py lcov-file.dat -b src/dir -e test.lib -o path/out.xml

        By default, XML output will be written to ./coverage.xml
        """

        parser = OptionParser()
        parser.usage = 'lcov_cobertura.py lcov-file.dat [-b source/dir] [-e <exclude packages regex>] [-o output.xml]'
        parser.description = 'Converts lcov output to cobertura-compatible XML'
        parser.add_option('-b',
                          '--base-dir',
                          action='store',
                          help='Directory where source files are located',
                          dest='base_dir',
                          default='.')
        parser.add_option(
            '-e',
            '--excludes',
            help='Comma-separated list of regexes of packages to exclude',
            action='append',
            dest='excludes',
            default=[])
        parser.add_option('-o',
                          '--output',
                          help='Path to store cobertura xml file',
                          action='store',
                          dest='output',
                          default='coverage.xml')
        (options, args) = parser.parse_args(args=argv)

        if len(args) != 2:
            print((main.__doc__))
            sys.exit(1)

        try:
            with open(args[1], 'r') as lcov_file:
                lcov_data = lcov_file.read()
                lcov_cobertura = LcovCobertura(lcov_data, options.base_dir,
                                               options.excludes)
                cobertura_xml = lcov_cobertura.convert()
            with open(options.output, mode='wt') as output_file:
                output_file.write(cobertura_xml)
        except IOError:
            sys.stderr.write("Unable to convert %s to Cobertura XML" % args[1])
Пример #3
0
    def main(argv):
        """
        Converts LCOV coverage data to Cobertura-compatible XML for reporting.

        Usage:
            lcov_cobertura.py lcov-file.dat
            lcov_cobertura.py lcov-file.dat -b src/dir -e test.lib -o path/out.xml

        By default, XML output will be written to ./coverage.xml
        """

        parser = OptionParser()
        parser.usage = 'lcov_cobertura.py lcov-file.dat [-b source/dir] [-e <exclude packages regex>] [-o output.xml]'
        parser.description = 'Converts lcov output to cobertura-compatible XML'
        parser.add_option('-b', '--base-dir', action='store',
                          help='Directory where source files are located',
                          dest='base_dir', default='.')
        parser.add_option('-e', '--excludes',
                          help='Comma-separated list of regexes of packages to exclude',
                          action='append', dest='excludes', default=[])
        parser.add_option('-o', '--output',
                          help='Path to store cobertura xml file',
                          action='store', dest='output', default='coverage.xml')
        (options, args) = parser.parse_args(args=argv)

        if len(args) != 2:
            print((main.__doc__))
            sys.exit(1)

        try:
            with open(args[1], 'r') as lcov_file:
                lcov_data = lcov_file.read()
                lcov_cobertura = LcovCobertura(lcov_data, options.base_dir, options.excludes)
                cobertura_xml = lcov_cobertura.convert()
            with open(options.output, mode='wt') as output_file:
                output_file.write(cobertura_xml)
        except IOError:
            sys.stderr.write("Unable to convert %s to Cobertura XML" % args[1])
Пример #4
0
def parse_lcov_coverage_data(cov_data: str,
                             toc: List[str]) -> types.CoverageData:
    converter = LcovCobertura(cov_data)
    cobertura_xml = converter.convert()
    return parse_xml_coverage_data(cobertura_xml, toc)
Пример #5
0
    def collect(self):
        from lcov_cobertura import LcovCobertura

        # Check if file exists
        source = Path(self.config.source.value)
        if not source.exists():
            raise FileNotFoundError(
                'No such file or directory {}'.format(source)
            )
        source = source.resolve()

        # Check if lcov is available
        lcov = which('lcov')
        if lcov is None:
            raise FileNotFoundError('lcov executable not found.')

        # Transform from list to something like
        #   --rc setting1=value1 --rc setting2=value2
        rc_overrides = ''
        if self.config.rc_overrides.value:
            rc_overrides = '--rc {}'.format(
                ' --rc '.join(self.config.rc_overrides.value)
            )

        # Load remove patterns
        remove = self.config.remove.value
        for remove_file in self.config.remove_files.value:
            for pattern in load_filter_file(remove_file):
                if pattern not in remove:
                    remove.append(pattern)

        # Load extract patterns
        extract = self.config.extract.value
        for extract_file in self.config.extract_files.value:
            for pattern in load_filter_file(extract_file):
                if pattern not in extract:
                    extract.append(pattern)

        # Check if --derive-func-data is needed
        derive_func_data = '--derive-func-data' \
            if self.config.derive_func_data.value else ''

        if source.is_dir():
            # Create a temporary file. Close it, we just need the name.
            tmp_file = NamedTemporaryFile(suffix='.info')
            tmp_file.close()

            tracefile = Path(tmp_file.name)

            cmd = (
                '{lcov} '
                '{rc_overrides} '
                '{derive_func_data} '
                '--directory {directory} --capture '
                '--output-file {tracefile}'.format(
                    lcov=lcov,
                    rc_overrides=rc_overrides,
                    derive_func_data=derive_func_data,
                    directory=source,
                    tracefile=tracefile
                )
            )
            log.info('Gathering coverage info: "{}"'.format(cmd))
            status = run(cmd)

            if status.returncode != 0:
                raise RuntimeError(
                    'Lcov failed capturing data:\n{}'.format(status.stderr)
                )
        else:
            # Check file extension
            if source.suffix != '.info':
                raise ValueError(
                    'Unknown file extension "{}" '
                    'for a tracefile. Must be ".info"'.format(source.suffix)
                )
            tracefile = source

        result = {
            'tracefile': str(tracefile),
        }

        # Remove files from patterns
        if remove:
            cmd = (
                '{lcov} '
                '{rc_overrides} '
                '{derive_func_data} '
                '--remove {tracefile} {remove} '
                '--output-file {tracefile}'.format(
                    lcov=lcov,
                    rc_overrides=rc_overrides,
                    derive_func_data=derive_func_data,
                    tracefile=tracefile,
                    remove=' '.join(
                        '"{}"'.format(e) for e in remove
                    )
                )
            )
            log.info('Removing files: "{}"'.format(cmd))
            status = run(cmd)

            if status.returncode != 0:
                raise RuntimeError(
                    'Lcov failed removing files from coverage:\n{}'.format(
                        status.stderr
                    )
                )

        # Extract files from patterns
        if extract:
            cmd = (
                '{lcov} '
                '{rc_overrides} '
                '{derive_func_data} '
                '--extract {tracefile} {extract} '
                '--output-file {tracefile}'.format(
                    lcov=lcov,
                    rc_overrides=rc_overrides,
                    derive_func_data=derive_func_data,
                    tracefile=tracefile,
                    extract=' '.join(
                        '"{}"'.format(e) for e in extract
                    )
                )
            )
            log.info('Extracting files: "{}"'.format(cmd))
            status = run(cmd)

            if status.returncode != 0:
                raise RuntimeError(
                    'Lcov failed extracting files from coverage:\n{}'.format(
                        status.stderr
                    )
                )

        # Create cobertura xml file and parse it
        converter = LcovCobertura(tracefile.open().read())
        cobertura_xml = converter.convert()

        with NamedTemporaryFile(delete=False, suffix='.xml') as xml:
            xml.write(cobertura_xml.encode('utf-8'))

        cobertura_src = CoberturaSource(
            self._index, 'cobertura', self._id,
            config={
                'xmlpath': str(xml.name)
            }
        )

        result.update(cobertura_src.collect())

        return result