file-coverage.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /*
  2. Copyright 2012-2015, Yahoo Inc.
  3. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
  4. */
  5. 'use strict';
  6. const percent = require('./percent');
  7. const dataProperties = require('./data-properties');
  8. const { CoverageSummary } = require('./coverage-summary');
  9. // returns a data object that represents empty coverage
  10. function emptyCoverage(filePath, reportLogic) {
  11. const cov = {
  12. path: filePath,
  13. statementMap: {},
  14. fnMap: {},
  15. branchMap: {},
  16. s: {},
  17. f: {},
  18. b: {}
  19. };
  20. if (reportLogic) cov.bT = {};
  21. return cov;
  22. }
  23. // asserts that a data object "looks like" a coverage object
  24. function assertValidObject(obj) {
  25. const valid =
  26. obj &&
  27. obj.path &&
  28. obj.statementMap &&
  29. obj.fnMap &&
  30. obj.branchMap &&
  31. obj.s &&
  32. obj.f &&
  33. obj.b;
  34. if (!valid) {
  35. throw new Error(
  36. 'Invalid file coverage object, missing keys, found:' +
  37. Object.keys(obj).join(',')
  38. );
  39. }
  40. }
  41. const keyFromLoc = ({ start, end }) =>
  42. `${start.line}|${start.column}|${end.line}|${end.column}`;
  43. const mergeProp = (aHits, aMap, bHits, bMap, itemKey = keyFromLoc) => {
  44. const aItems = {};
  45. for (const [key, itemHits] of Object.entries(aHits)) {
  46. const item = aMap[key];
  47. aItems[itemKey(item)] = [itemHits, item];
  48. }
  49. for (const [key, bItemHits] of Object.entries(bHits)) {
  50. const bItem = bMap[key];
  51. const k = itemKey(bItem);
  52. if (aItems[k]) {
  53. const aPair = aItems[k];
  54. if (bItemHits.forEach) {
  55. // should this throw an exception if aPair[0] is not an array?
  56. bItemHits.forEach((hits, h) => {
  57. if (aPair[0][h] !== undefined) aPair[0][h] += hits;
  58. else aPair[0][h] = hits;
  59. });
  60. } else {
  61. aPair[0] += bItemHits;
  62. }
  63. } else {
  64. aItems[k] = [bItemHits, bItem];
  65. }
  66. }
  67. const hits = {};
  68. const map = {};
  69. Object.values(aItems).forEach(([itemHits, item], i) => {
  70. hits[i] = itemHits;
  71. map[i] = item;
  72. });
  73. return [hits, map];
  74. };
  75. /**
  76. * provides a read-only view of coverage for a single file.
  77. * The deep structure of this object is documented elsewhere. It has the following
  78. * properties:
  79. *
  80. * * `path` - the file path for which coverage is being tracked
  81. * * `statementMap` - map of statement locations keyed by statement index
  82. * * `fnMap` - map of function metadata keyed by function index
  83. * * `branchMap` - map of branch metadata keyed by branch index
  84. * * `s` - hit counts for statements
  85. * * `f` - hit count for functions
  86. * * `b` - hit count for branches
  87. */
  88. class FileCoverage {
  89. /**
  90. * @constructor
  91. * @param {Object|FileCoverage|String} pathOrObj is a string that initializes
  92. * and empty coverage object with the specified file path or a data object that
  93. * has all the required properties for a file coverage object.
  94. */
  95. constructor(pathOrObj, reportLogic = false) {
  96. if (!pathOrObj) {
  97. throw new Error(
  98. 'Coverage must be initialized with a path or an object'
  99. );
  100. }
  101. if (typeof pathOrObj === 'string') {
  102. this.data = emptyCoverage(pathOrObj, reportLogic);
  103. } else if (pathOrObj instanceof FileCoverage) {
  104. this.data = pathOrObj.data;
  105. } else if (typeof pathOrObj === 'object') {
  106. this.data = pathOrObj;
  107. } else {
  108. throw new Error('Invalid argument to coverage constructor');
  109. }
  110. assertValidObject(this.data);
  111. }
  112. /**
  113. * returns computed line coverage from statement coverage.
  114. * This is a map of hits keyed by line number in the source.
  115. */
  116. getLineCoverage() {
  117. const statementMap = this.data.statementMap;
  118. const statements = this.data.s;
  119. const lineMap = Object.create(null);
  120. Object.entries(statements).forEach(([st, count]) => {
  121. /* istanbul ignore if: is this even possible? */
  122. if (!statementMap[st]) {
  123. return;
  124. }
  125. const { line } = statementMap[st].start;
  126. const prevVal = lineMap[line];
  127. if (prevVal === undefined || prevVal < count) {
  128. lineMap[line] = count;
  129. }
  130. });
  131. return lineMap;
  132. }
  133. /**
  134. * returns an array of uncovered line numbers.
  135. * @returns {Array} an array of line numbers for which no hits have been
  136. * collected.
  137. */
  138. getUncoveredLines() {
  139. const lc = this.getLineCoverage();
  140. const ret = [];
  141. Object.entries(lc).forEach(([l, hits]) => {
  142. if (hits === 0) {
  143. ret.push(l);
  144. }
  145. });
  146. return ret;
  147. }
  148. /**
  149. * returns a map of branch coverage by source line number.
  150. * @returns {Object} an object keyed by line number. Each object
  151. * has a `covered`, `total` and `coverage` (percentage) property.
  152. */
  153. getBranchCoverageByLine() {
  154. const branchMap = this.branchMap;
  155. const branches = this.b;
  156. const ret = {};
  157. Object.entries(branchMap).forEach(([k, map]) => {
  158. const line = map.line || map.loc.start.line;
  159. const branchData = branches[k];
  160. ret[line] = ret[line] || [];
  161. ret[line].push(...branchData);
  162. });
  163. Object.entries(ret).forEach(([k, dataArray]) => {
  164. const covered = dataArray.filter(item => item > 0);
  165. const coverage = (covered.length / dataArray.length) * 100;
  166. ret[k] = {
  167. covered: covered.length,
  168. total: dataArray.length,
  169. coverage
  170. };
  171. });
  172. return ret;
  173. }
  174. /**
  175. * return a JSON-serializable POJO for this file coverage object
  176. */
  177. toJSON() {
  178. return this.data;
  179. }
  180. /**
  181. * merges a second coverage object into this one, updating hit counts
  182. * @param {FileCoverage} other - the coverage object to be merged into this one.
  183. * Note that the other object should have the same structure as this one (same file).
  184. */
  185. merge(other) {
  186. if (other.all === true) {
  187. return;
  188. }
  189. if (this.all === true) {
  190. this.data = other.data;
  191. return;
  192. }
  193. let [hits, map] = mergeProp(
  194. this.s,
  195. this.statementMap,
  196. other.s,
  197. other.statementMap
  198. );
  199. this.data.s = hits;
  200. this.data.statementMap = map;
  201. const keyFromLocProp = x => keyFromLoc(x.loc);
  202. const keyFromLocationsProp = x => keyFromLoc(x.locations[0]);
  203. [hits, map] = mergeProp(
  204. this.f,
  205. this.fnMap,
  206. other.f,
  207. other.fnMap,
  208. keyFromLocProp
  209. );
  210. this.data.f = hits;
  211. this.data.fnMap = map;
  212. [hits, map] = mergeProp(
  213. this.b,
  214. this.branchMap,
  215. other.b,
  216. other.branchMap,
  217. keyFromLocationsProp
  218. );
  219. this.data.b = hits;
  220. this.data.branchMap = map;
  221. // Tracking additional information about branch truthiness
  222. // can be optionally enabled:
  223. if (this.bT && other.bT) {
  224. [hits, map] = mergeProp(
  225. this.bT,
  226. this.branchMap,
  227. other.bT,
  228. other.branchMap,
  229. keyFromLocationsProp
  230. );
  231. this.data.bT = hits;
  232. }
  233. }
  234. computeSimpleTotals(property) {
  235. let stats = this[property];
  236. if (typeof stats === 'function') {
  237. stats = stats.call(this);
  238. }
  239. const ret = {
  240. total: Object.keys(stats).length,
  241. covered: Object.values(stats).filter(v => !!v).length,
  242. skipped: 0
  243. };
  244. ret.pct = percent(ret.covered, ret.total);
  245. return ret;
  246. }
  247. computeBranchTotals(property) {
  248. const stats = this[property];
  249. const ret = { total: 0, covered: 0, skipped: 0 };
  250. Object.values(stats).forEach(branches => {
  251. ret.covered += branches.filter(hits => hits > 0).length;
  252. ret.total += branches.length;
  253. });
  254. ret.pct = percent(ret.covered, ret.total);
  255. return ret;
  256. }
  257. /**
  258. * resets hit counts for all statements, functions and branches
  259. * in this coverage object resulting in zero coverage.
  260. */
  261. resetHits() {
  262. const statements = this.s;
  263. const functions = this.f;
  264. const branches = this.b;
  265. const branchesTrue = this.bT;
  266. Object.keys(statements).forEach(s => {
  267. statements[s] = 0;
  268. });
  269. Object.keys(functions).forEach(f => {
  270. functions[f] = 0;
  271. });
  272. Object.keys(branches).forEach(b => {
  273. branches[b].fill(0);
  274. });
  275. // Tracking additional information about branch truthiness
  276. // can be optionally enabled:
  277. if (branchesTrue) {
  278. Object.keys(branchesTrue).forEach(bT => {
  279. branchesTrue[bT].fill(0);
  280. });
  281. }
  282. }
  283. /**
  284. * returns a CoverageSummary for this file coverage object
  285. * @returns {CoverageSummary}
  286. */
  287. toSummary() {
  288. const ret = {};
  289. ret.lines = this.computeSimpleTotals('getLineCoverage');
  290. ret.functions = this.computeSimpleTotals('f', 'fnMap');
  291. ret.statements = this.computeSimpleTotals('s', 'statementMap');
  292. ret.branches = this.computeBranchTotals('b');
  293. // Tracking additional information about branch truthiness
  294. // can be optionally enabled:
  295. if (this['bt']) {
  296. ret.branchesTrue = this.computeBranchTotals('bT');
  297. }
  298. return new CoverageSummary(ret);
  299. }
  300. }
  301. // expose coverage data attributes
  302. dataProperties(FileCoverage, [
  303. 'path',
  304. 'statementMap',
  305. 'fnMap',
  306. 'branchMap',
  307. 's',
  308. 'f',
  309. 'b',
  310. 'bT',
  311. 'all'
  312. ]);
  313. module.exports = {
  314. FileCoverage
  315. };