All files / istanbul-lib-report/src/reports/cobertura index.ts

95.23% Statements 80/84
88.46% Branches 23/26
100% Functions 14/14
95.23% Lines 80/84

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208                                                74x 74x                     11x   11x   11x 11x 11x 11x 11x       11x 11x 11x       11x 11x       11x 11x 11x     11x                     11x 11x 11x 11x       15x 15x 2x   13x         15x       15x 15x 2x   13x 13x       13x 13x 13x   13x             13x 13x 13x 13x 37x     37x 37x           37x   37x       37x 37x   13x   13x 13x 13x 223x         223x   223x 55x 55x     223x     13x 13x         4x       13x     9x       13x 13x 37x 37x 35x 35x     2x 2x 1x 1x 1x       1x 1x     1x 1x 1x       1x 1x          
/*
 Copyright 2012-2015, Yahoo Inc.
 Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */
import path from "node:path";
 
import type { Totals } from "@vitest/istanbul-lib-coverage";
 
import { escape } from "../../html-escape";
import type { ContentWriter, Context, ReportNode, XmlAttributes, XMLWriter } from "../../index";
import ReportBase from "../../report-base";
 
/** options accepted by {@link CoberturaReport} */
export interface CoberturaOptions {
  /** the file to write the report to, defaults to `cobertura-coverage.xml` */
  file?: string;
  /** timestamp to embed in the report, defaults to `Date.now()` */
  timestamp?: string;
  /** the project root used to relativize file paths, defaults to `process.cwd()` */
  projectRoot?: string;
}
 
/** narrows a possibly-`"Unknown"` pct into the 0-1 rate the report emits */
function rate(metrics: Totals): number {
  const { pct } = metrics;
  return typeof pct === "number" ? pct / 100.0 : NaN;
}
 
class CoberturaReport extends ReportBase {
  declare cw: ContentWriter | null;
  declare xml: XMLWriter | null;
  declare timestamp: string;
  declare projectRoot: string;
  declare file: string;
 
  constructor(opts?: CoberturaOptions) {
    super();
 
    opts = opts || {};
 
    this.cw = null;
    this.xml = null;
    this.timestamp = opts.timestamp || Date.now().toString();
    this.projectRoot = opts.projectRoot || process.cwd();
    this.file = opts.file || "cobertura-coverage.xml";
  }
 
  onStart(root: ReportNode, context: Context): void {
    this.cw = context.writer.writeFile(this.file);
    this.xml = context.getXMLWriter(this.cw);
    this.writeRootStats(root);
  }
 
  onEnd(): void {
    this.xml!.closeAll();
    this.cw!.close();
  }
 
  writeRootStats(node: ReportNode): void {
    const metrics = node.getCoverageSummary()!;
    this.cw!.println('<?xml version="1.0" ?>');
    this.cw!.println(
      '<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">',
    );
    this.xml!.openTag("coverage", {
      "lines-valid": metrics.lines.total,
      "lines-covered": metrics.lines.covered,
      "line-rate": rate(metrics.lines),
      "branches-valid": metrics.branches.total,
      "branches-covered": metrics.branches.covered,
      "branch-rate": rate(metrics.branches),
      timestamp: this.timestamp,
      complexity: "0",
      version: "0.1",
    });
    this.xml!.openTag("sources");
    this.xml!.inlineTag("source", undefined, this.projectRoot);
    this.xml!.closeTag("sources");
    this.xml!.openTag("packages");
  }
 
  onSummary(node: ReportNode): void {
    const metrics = node.getCoverageSummary(true);
    if (!metrics) {
      return;
    }
    this.xml!.openTag("package", {
      name: node.isRoot() ? "main" : escape(asJavaPackage(node)),
      "line-rate": rate(metrics.lines),
      "branch-rate": rate(metrics.branches),
    });
    this.xml!.openTag("classes");
  }
 
  onSummaryEnd(node: ReportNode): void {
    const metrics = node.getCoverageSummary(true);
    if (!metrics) {
      return;
    }
    this.xml!.closeTag("classes");
    this.xml!.closeTag("package");
  }
 
  onDetail(node: ReportNode): void {
    const fileCoverage = node.getFileCoverage();
    const metrics = node.getCoverageSummary()!;
    const branchByLine = fileCoverage.getBranchCoverageByLine();
 
    this.xml!.openTag("class", {
      name: escape(asClassName(node)),
      filename: path.relative(this.projectRoot, fileCoverage.path),
      "line-rate": rate(metrics.lines),
      "branch-rate": rate(metrics.branches),
    });
 
    this.xml!.openTag("methods");
    const fnMap = fileCoverage.fnMap;
    const uniqueMethodName = createUniqueNamer();
    Object.entries(fnMap).forEach(([k, { name, decl, loc }]) => {
      const hits = fileCoverage.f[k];
      // Some versions of the instrumenter in the wild populate 'loc'
      // but not 'decl':
      const start = (decl || loc).start;
      this.xml!.openTag("method", {
        // Jenkins rejects two <method> tags with the same name in one class.
        name: escape(uniqueMethodName(name)),
        hits,
        signature: "()V", //fake out a no-args void return
      });
      this.xml!.openTag("lines");
      //Add the function definition line and hits so that jenkins cobertura plugin records method hits
      this.xml!.inlineTag("line", {
        number: start.line,
        hits,
      });
      this.xml!.closeTag("lines");
      this.xml!.closeTag("method");
    });
    this.xml!.closeTag("methods");
 
    this.xml!.openTag("lines");
    const lines = fileCoverage.getLineCoverage();
    Object.entries(lines).forEach(([k, hits]) => {
      const attrs: XmlAttributes = {
        number: k,
        hits,
        branch: "false",
      };
      const branchDetail = branchByLine[k];
 
      if (branchDetail) {
        attrs.branch = "true";
        attrs["condition-coverage"] =
          branchDetail.coverage + "% (" + branchDetail.covered + "/" + branchDetail.total + ")";
      }
      this.xml!.inlineTag("line", attrs);
    });
 
    this.xml!.closeTag("lines");
    this.xml!.closeTag("class");
  }
}
 
function asJavaPackage(node: ReportNode): string {
  return node.getRelativeName().replace(/\//g, ".").replace(/\\/g, ".").replace(/\.$/, "");
}
 
function asClassName(node: ReportNode): string {
  return node.getRelativeName().replace(/.*[\\/]/, "");
}
 
const ANONYMOUS_NAME = /^\(anonymous_(\d+)\)$/;
 
/** Returns a namer that deduplicates method names within one class. */
function createUniqueNamer() {
  const used = new Set<string>();
  return (name: string | undefined): string => {
    const base = name || "(anonymous)";
    if (!used.has(base)) {
      used.add(base);
      return base;
    }
 
    const anonMatch = ANONYMOUS_NAME.exec(base);
    if (anonMatch) {
      let i = Number(anonMatch[1]) + 1;
      let next = `(anonymous_${i})`;
      while (used.has(next)) {
        i += 1;
        next = `(anonymous_${i})`;
      }
      used.add(next);
      return next;
    }
 
    let i = 2;
    let next = `${base}_${i}`;
    while (used.has(next)) {
      i += 1;
      next = `${base}_${i}`;
    }
    used.add(next);
    return next;
  };
}
 
export default CoberturaReport;