Report test coverage.

@param  {Object} cov
173485
function reportCoverage(cov) {
    // Stats
    print('\n   [bold]{Test Coverage}\n');
    var sep = '   +------------------------------------------+----------+------+------+--------+',
        lastSep = '                                              +----------+------+------+--------+';
	result = sep+'\n';
    result += '   | filename                                 | coverage | LOC  | SLOC | missed |\n';
    result += sep+'\n';
    for (var name in cov) {
        var file = cov[name];
        if (Array.isArray(file)) {
            result += '   | ' + rpad(name, 40);
            result += ' | ' + lpad(file.coverage.toFixed(2), 8);
            result += ' | ' + lpad(file.LOC, 4);
            result += ' | ' + lpad(file.SLOC, 4);
            result += ' | ' + lpad(file.totalMisses, 6);
            result += ' |\n';
        }
    }
    result += sep+'\n';
    result += '     ' + rpad('', 40);
    result += ' | ' + lpad(cov.coverage.toFixed(2), 8);
    result += ' | ' + lpad(cov.LOC, 4);
    result += ' | ' + lpad(cov.SLOC, 4);
    result += ' | ' + lpad(cov.totalMisses, 6);
    result += ' |\n';
    result += lastSep;
	console.log(result);

	for (var name in cov) {
		if (name.match(file_matcher)) {
			var file = cov[name];
			var annotated = '';
			annotated += colorize('\n  [bold]{' + name + '}:');
			annotated += colorize(file.source);
			annotated += '\n';
			fs.writeFileSync('annotated/'+name, annotated);
		}
	}
}
1278159
def combine_coverage_reports(self, omit, parallel):
        
        tmp_cov = coverage.coverage(omit=omit, data_suffix=parallel)
        tmp_cov.load()
        tmp_cov.combine()
        tmp_cov.save()
549141
function reportResult(test, indent) {
		assertTest(test);

		if (test.result.valid) {
			if (test.failOnMissing && test.result.missing && test.result.missing.length > 0) {
				reportFailed(test, indent);
			}
			else {
				reportSuccess(test);
			}
		}
		else {
			reportFailed(test, indent);
		}
		reportMissing(test, indent);
	}
691794
def sanitize(cov)
      ncov = {}
      cov.each do |path, runs|
        if runs.is_a?(Array)
          ncov[path] = runs
          next
        end

        ncov[path] = {}
        ncov[path][:lines] = runs[:lines] if runs[:lines]
        ncov[path][:branches] = runs[:branches] if runs[:branches]

        if runs[:methods]
          ncov[path][:methods] = methods = {}
          runs[:methods].each do |mthd, run|
            klass =
              begin
                Marshal.dump(mthd[0])
                mthd[0]
              rescue
                mthd[0].to_s
              end
            methods[[klass] + mthd.drop(1)] = run
          end
        end
      end
      ncov
    end
250185
function JSONCov(runner, output) {
  var self = this
    , output = 1 == arguments.length ? true : output;

  Base.call(this, runner);

  var tests = []
    , failures = []
    , passes = [];

  runner.on('test end', function(test){
    tests.push(test);
  });

  runner.on('pass', function(test){
    passes.push(test);
  });

  runner.on('fail', function(test){
    failures.push(test);
  });

  runner.on('end', function(){
    var cov = global._$jscoverage || {};
    var result = self.cov = map(cov);
    result.stats = self.stats;
    result.tests = tests.map(clean);
    result.failures = failures.map(clean);
    result.passes = passes.map(clean);
    if (!output) return;
    process.stdout.write(JSON.stringify(result, null, 2 ));
  });
}
195317
def generate_coverage_report(coverage_xml, compare_branch,
                             html_report=None, css_file=None,
                             ignore_staged=False, ignore_unstaged=False,
                             exclude=None, src_roots=None):
    
    diff = GitDiffReporter(
        compare_branch, git_diff=GitDiffTool(), ignore_staged=ignore_staged,
        ignore_unstaged=ignore_unstaged, exclude=exclude)

    xml_roots = [cElementTree.parse(xml_root) for xml_root in coverage_xml]
    coverage = XmlCoverageReporter(xml_roots, src_roots)

    # Build a report generator
    if html_report is not None:
        css_url = css_file
        if css_url is not None:
            css_url = os.path.relpath(css_file, os.path.dirname(html_report))
        reporter = HtmlReportGenerator(coverage, diff, css_url=css_url)
        with open(html_report, "wb") as output_file:
            reporter.generate_report(output_file)
        if css_file is not None:
            with open(css_file, "wb") as output_file:
                reporter.generate_css(output_file)

    reporter = StringReportGenerator(coverage, diff)
    output_file = sys.stdout if six.PY2 else sys.stdout.buffer

    # Generate the report
    reporter.generate_report(output_file)
    return reporter.total_percent_covered()
177840
def covlen(args):
    
    import numpy as np
    import pandas as pd
    import seaborn as sns
    from jcvi.formats.base import DictFile

    p = OptionParser(covlen.__doc__)
    p.add_option("--maxsize", default=1000000, type="int", help="Max contig size")
    p.add_option("--maxcov", default=100, type="int", help="Max contig size")
    p.add_option("--color", default='m', help="Color of the data points")
    p.add_option("--kind", default="scatter",
                 choices=("scatter", "reg", "resid", "kde", "hex"),
                 help="Kind of plot to draw")
    opts, args, iopts = p.set_image_options(args, figsize="8x8")

    if len(args) != 2:
        sys.exit(not p.print_help())

    covfile, fastafile = args
    cov = DictFile(covfile, cast=float)
    s = Sizes(fastafile)
    data = []
    maxsize, maxcov = opts.maxsize, opts.maxcov
    for ctg, size in s.iter_sizes():
        c = cov.get(ctg, 0)
        if size > maxsize:
            continue
        if c > maxcov:
            continue
        data.append((size, c))

    x, y = zip(*data)
    x = np.array(x)
    y = np.array(y)
    logging.debug("X size {0}, Y size {1}".format(x.size, y.size))

    df = pd.DataFrame()
    xlab, ylab = "Length", "Coverage of depth (X)"
    df[xlab] = x
    df[ylab] = y
    sns.jointplot(xlab, ylab, kind=opts.kind, data=df,
                  xlim=(0, maxsize), ylim=(0, maxcov),
                  stat_func=None, edgecolor="w", color=opts.color)

    figname = covfile + ".pdf"
    savefig(figname, dpi=iopts.dpi, iopts=iopts)
1190900
def to_lcov_info(cov, out: "", test_name: nil)
      out << "TN:#{ test_name }\n"
      cov.each do |path, runs|
        out << "SF:#{ path }\n"

        # function coverage
        if runs.is_a?(Hash) && runs[:methods]
          total = covered = 0
          runs[:methods].each do |(klass, name, lineno), run|
            out << "FN:#{ lineno },#{ klass }##{ name }\n"
            total += 1
            covered += 1 if run > 0
          end
          out << "FNF:#{ total }\n"
          out << "FNF:#{ covered }\n"
          runs[:methods].each do |(klass, name, _), run|
            out << "FNDA:#{ run },#{ klass }##{ name }\n"
          end
        end

        # line coverage
        if runs.is_a?(Array) || (runs.is_a?(Hash) && runs[:lines])
          total = covered = 0
          lines = runs.is_a?(Array) ? runs : runs[:lines]
          lines.each_with_index do |run, lineno|
            next unless run
            out << "DA:#{ lineno + 1 },#{ run }\n"
            total += 1
            covered += 1 if run > 0
          end
          out << "LF:#{ total }\n"
          out << "LH:#{ covered }\n"
        end

        # branch coverage
        if runs.is_a?(Hash) && runs[:branches]
          total = covered = 0
          id = 0
          runs[:branches].each do |(_base_type, _, base_lineno), targets|
            i = 0
            targets.each do |(_target_type, _target_lineno), run|
              out << "BRDA:#{ base_lineno },#{ id },#{ i },#{ run }\n"
              total += 1
              covered += 1 if run > 0
              i += 1
            end
            id += 1
          end
          out << "BRF:#{ total }\n"
          out << "BRH:#{ covered }\n"
        end

        out << "end_of_record\n"
      end

      out
    end
1133215
def cover(session):
    
    session.interpreter = 'python3.6'
    session.install('coverage', 'pytest-cov')
    session.run('coverage', 'report', '--show-missing', '--fail-under=100')
    session.run('coverage', 'erase')
1362848
def main(argv=None, directory=None):
    
    logging.basicConfig(format='%(message)s')

    argv = argv or sys.argv
    arg_dict = parse_coverage_args(argv[1:])
    GitPathTool.set_cwd(directory)
    fail_under = arg_dict.get('fail_under')
    percent_covered = generate_coverage_report(
        arg_dict['coverage_xml'],
        arg_dict['compare_branch'],
        html_report=arg_dict['html_report'],
        css_file=arg_dict['external_css_file'],
        ignore_staged=arg_dict['ignore_staged'],
        ignore_unstaged=arg_dict['ignore_unstaged'],
        exclude=arg_dict['exclude'],
        src_roots=arg_dict['src_roots'],
    )

    if percent_covered >= fail_under:
        return 0
    else:
        LOGGER.error("Failure. Coverage is below {}%.".format(fail_under))
        return 1
909258
def coverage():
    """"""
    try:
        import pytest_cov  # NOQA
    except ImportError:
        print_failure_message(
            'Install the pytest coverage plugin to use this task, '
            "i.e., `pip install pytest-cov'.")
        raise SystemExit(1)
    import pytest
    pytest.main(PYTEST_FLAGS + [
        '--cov', CODE_DIRECTORY,
        '--cov-report', 'term-missing',
        '--junit-xml', 'test-report.xml',
        TESTS_DIRECTORY])
674933
protected function logCoverage()
    {
        if (!$this->hasCoverage()) {
            return;
        }

        $filteredOptions = $this->options->filtered;

        $reporter = $this->getCoverage()->getReporter();

        if (isset($filteredOptions['coverage-clover'])) {
            $reporter->clover($filteredOptions['coverage-clover']);
        }

        if (isset($filteredOptions['coverage-html'])) {
            $reporter->html($filteredOptions['coverage-html']);
        }
        if (isset($filteredOptions['coverage-text'])) {
            $reporter->text();
        }

        if (isset($filteredOptions['coverage-xml'])) {
            $reporter->xml($filteredOptions['coverage-xml']);
        }

        $reporter->php($filteredOptions['coverage-php']);
    }
825670
def coverage(c, html=True):
    
    # NOTE: this MUST use coverage itself, and not pytest-cov, because the
    # latter is apparently unable to prevent pytest plugins from being loaded
    # before pytest-cov itself is able to start up coverage.py! The result is
    # that coverage _always_ skips over all module level code, i.e. constants,
    # 'def' lines, etc. Running coverage as the "outer" layer avoids this
    # problem, thus no need for pytest-cov.
    # NOTE: this does NOT hold true for NON-PYTEST code, so
    # pytest-relaxed-USING modules can happily use pytest-cov.
    c.run("coverage run --source=pytest_relaxed -m pytest")
    if html:
        c.run("coverage html")
        c.run("open htmlcov/index.html")
620387
function coverage(filename, data) {
  var ret = {
    filename: filename,
    coverage: 0,
    hits: 0,
    misses: 0,
    sloc: 0,
    source: {}
  };

  data.source.forEach(function(line, num){
    num++;

    if (data[num] === 0) {
      ret.misses++;
      ret.sloc++;
    } else if (data[num] !== undefined) {
      ret.hits++;
      ret.sloc++;
    }

    ret.source[num] = {
        source: line
      , coverage: data[num] === undefined
        ? ''
        : data[num]
    };
  });

  ret.coverage = ret.hits / ret.sloc * 100;

  return ret;
}
932309
def _merge_nbval_coverage_data(cov):
    """"""
    if not cov:
        return

    suffix = _make_suffix(cov)
    if suffix is True:
        # Note: If suffix is true, we are running in parallel, so several
        # files will be generated. This will cause some warnings about "no coverage"
        # but is otherwise OK. Do nothing.
        return

    # Get the filename of the nbval coverage:
    filename = cov.data_files.filename + '.' + suffix

    # Read coverage generated by nbval in this run:
    nbval_data = coverage.CoverageData(debug=cov.debug)
    try:
        nbval_data.read_file(os.path.abspath(filename))
    except coverage.CoverageException:
        return

    # Set up aliases (following internal coverage.py code here)
    aliases = None
    if cov.config.paths:
        aliases = coverage.files.PathAliases()
        for paths in cov.config.paths.values():
            result = paths[0]
            for pattern in paths[1:]:
                aliases.add(pattern, result)

    # Merge nbval data into pytest-cov data:
    cov.data.update(nbval_data, aliases=aliases)
    # Delete our nbval coverage data
    coverage.misc.file_be_gone(filename)
839247
def guard(ctx, opts=""):
    
    # TODO if coverage was run via pytest-cov, we could add coverage here too
    return test(ctx, include_slow=True, loop_on_fail=True, opts=opts)
976347
def record_coverage(self, rule):
        """"""
        log(DEBUG, u'Rule ({}): {}'.format(*rule).encode('utf-8'))
        self.coverage_lines.append('DA:{},1'.format(rule[0]))