file-coverage.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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 isObj = o => !!o && typeof o === 'object';
  44. const isLineCol = o =>
  45. isObj(o) && typeof o.line === 'number' && typeof o.column === 'number';
  46. const isLoc = o => isObj(o) && isLineCol(o.start) && isLineCol(o.end);
  47. const getLoc = o => (isLoc(o) ? o : isLoc(o.loc) ? o.loc : null);
  48. // When merging, we can have a case where two ranges cover
  49. // the same block of code with `hits=1`, and each carve out a
  50. // different range with `hits=0` to indicate it's uncovered.
  51. // Find the nearest container so that we can properly indicate
  52. // that both sections are hit.
  53. // Returns null if no containing item is found.
  54. const findNearestContainer = (item, map) => {
  55. const itemLoc = getLoc(item);
  56. if (!itemLoc) return null;
  57. // the B item is not an identified range in the A set, BUT
  58. // it may be contained by an identified A range. If so, then
  59. // any hit of that containing A range counts as a hit of this
  60. // B range as well. We have to find the *narrowest* containing
  61. // range to be accurate, since ranges can be hit and un-hit
  62. // in a nested fashion.
  63. let nearestContainingItem = null;
  64. let containerDistance = null;
  65. let containerKey = null;
  66. for (const [i, mapItem] of Object.entries(map)) {
  67. const mapLoc = getLoc(mapItem);
  68. if (!mapLoc) continue;
  69. // contained if all of line distances are > 0
  70. // or line distance is 0 and col dist is >= 0
  71. const distance = [
  72. itemLoc.start.line - mapLoc.start.line,
  73. itemLoc.start.column - mapLoc.start.column,
  74. mapLoc.end.line - itemLoc.end.line,
  75. mapLoc.end.column - itemLoc.end.column
  76. ];
  77. if (
  78. distance[0] < 0 ||
  79. distance[2] < 0 ||
  80. (distance[0] === 0 && distance[1] < 0) ||
  81. (distance[2] === 0 && distance[3] < 0)
  82. ) {
  83. continue;
  84. }
  85. if (nearestContainingItem === null) {
  86. containerDistance = distance;
  87. nearestContainingItem = mapItem;
  88. containerKey = i;
  89. continue;
  90. }
  91. // closer line more relevant than closer column
  92. const closerBefore =
  93. distance[0] < containerDistance[0] ||
  94. (distance[0] === 0 && distance[1] < containerDistance[1]);
  95. const closerAfter =
  96. distance[2] < containerDistance[2] ||
  97. (distance[2] === 0 && distance[3] < containerDistance[3]);
  98. if (closerBefore || closerAfter) {
  99. // closer
  100. containerDistance = distance;
  101. nearestContainingItem = mapItem;
  102. containerKey = i;
  103. }
  104. }
  105. return containerKey;
  106. };
  107. // either add two numbers, or all matching entries in a number[]
  108. const addHits = (aHits, bHits) => {
  109. if (typeof aHits === 'number' && typeof bHits === 'number') {
  110. return aHits + bHits;
  111. } else if (Array.isArray(aHits) && Array.isArray(bHits)) {
  112. return aHits.map((a, i) => (a || 0) + (bHits[i] || 0));
  113. }
  114. return null;
  115. };
  116. const addNearestContainerHits = (item, itemHits, map, mapHits) => {
  117. const container = findNearestContainer(item, map);
  118. if (container) {
  119. return addHits(itemHits, mapHits[container]);
  120. } else {
  121. return itemHits;
  122. }
  123. };
  124. const mergeProp = (aHits, aMap, bHits, bMap, itemKey = keyFromLoc) => {
  125. const aItems = {};
  126. for (const [key, itemHits] of Object.entries(aHits)) {
  127. const item = aMap[key];
  128. aItems[itemKey(item)] = [itemHits, item];
  129. }
  130. const bItems = {};
  131. for (const [key, itemHits] of Object.entries(bHits)) {
  132. const item = bMap[key];
  133. bItems[itemKey(item)] = [itemHits, item];
  134. }
  135. const mergedItems = {};
  136. for (const [key, aValue] of Object.entries(aItems)) {
  137. let aItemHits = aValue[0];
  138. const aItem = aValue[1];
  139. const bValue = bItems[key];
  140. if (!bValue) {
  141. // not an identified range in b, but might be contained by one
  142. aItemHits = addNearestContainerHits(aItem, aItemHits, bMap, bHits);
  143. } else {
  144. // is an identified range in b, so add the hits together
  145. aItemHits = addHits(aItemHits, bValue[0]);
  146. }
  147. mergedItems[key] = [aItemHits, aItem];
  148. }
  149. // now find the items in b that are not in a. already added matches.
  150. for (const [key, bValue] of Object.entries(bItems)) {
  151. let bItemHits = bValue[0];
  152. const bItem = bValue[1];
  153. if (mergedItems[key]) continue;
  154. // not an identified range in b, but might be contained by one
  155. bItemHits = addNearestContainerHits(bItem, bItemHits, aMap, aHits);
  156. mergedItems[key] = [bItemHits, bItem];
  157. }
  158. const hits = {};
  159. const map = {};
  160. Object.values(mergedItems).forEach(([itemHits, item], i) => {
  161. hits[i] = itemHits;
  162. map[i] = item;
  163. });
  164. return [hits, map];
  165. };
  166. /**
  167. * provides a read-only view of coverage for a single file.
  168. * The deep structure of this object is documented elsewhere. It has the following
  169. * properties:
  170. *
  171. * * `path` - the file path for which coverage is being tracked
  172. * * `statementMap` - map of statement locations keyed by statement index
  173. * * `fnMap` - map of function metadata keyed by function index
  174. * * `branchMap` - map of branch metadata keyed by branch index
  175. * * `s` - hit counts for statements
  176. * * `f` - hit count for functions
  177. * * `b` - hit count for branches
  178. */
  179. class FileCoverage {
  180. /**
  181. * @constructor
  182. * @param {Object|FileCoverage|String} pathOrObj is a string that initializes
  183. * and empty coverage object with the specified file path or a data object that
  184. * has all the required properties for a file coverage object.
  185. */
  186. constructor(pathOrObj, reportLogic = false) {
  187. if (!pathOrObj) {
  188. throw new Error(
  189. 'Coverage must be initialized with a path or an object'
  190. );
  191. }
  192. if (typeof pathOrObj === 'string') {
  193. this.data = emptyCoverage(pathOrObj, reportLogic);
  194. } else if (pathOrObj instanceof FileCoverage) {
  195. this.data = pathOrObj.data;
  196. } else if (typeof pathOrObj === 'object') {
  197. this.data = pathOrObj;
  198. } else {
  199. throw new Error('Invalid argument to coverage constructor');
  200. }
  201. assertValidObject(this.data);
  202. }
  203. /**
  204. * returns computed line coverage from statement coverage.
  205. * This is a map of hits keyed by line number in the source.
  206. */
  207. getLineCoverage() {
  208. const statementMap = this.data.statementMap;
  209. const statements = this.data.s;
  210. const lineMap = Object.create(null);
  211. Object.entries(statements).forEach(([st, count]) => {
  212. /* istanbul ignore if: is this even possible? */
  213. if (!statementMap[st]) {
  214. return;
  215. }
  216. const { line } = statementMap[st].start;
  217. const prevVal = lineMap[line];
  218. if (prevVal === undefined || prevVal < count) {
  219. lineMap[line] = count;
  220. }
  221. });
  222. return lineMap;
  223. }
  224. /**
  225. * returns an array of uncovered line numbers.
  226. * @returns {Array} an array of line numbers for which no hits have been
  227. * collected.
  228. */
  229. getUncoveredLines() {
  230. const lc = this.getLineCoverage();
  231. const ret = [];
  232. Object.entries(lc).forEach(([l, hits]) => {
  233. if (hits === 0) {
  234. ret.push(l);
  235. }
  236. });
  237. return ret;
  238. }
  239. /**
  240. * returns a map of branch coverage by source line number.
  241. * @returns {Object} an object keyed by line number. Each object
  242. * has a `covered`, `total` and `coverage` (percentage) property.
  243. */
  244. getBranchCoverageByLine() {
  245. const branchMap = this.branchMap;
  246. const branches = this.b;
  247. const ret = {};
  248. Object.entries(branchMap).forEach(([k, map]) => {
  249. const line = map.line || map.loc.start.line;
  250. const branchData = branches[k];
  251. ret[line] = ret[line] || [];
  252. ret[line].push(...branchData);
  253. });
  254. Object.entries(ret).forEach(([k, dataArray]) => {
  255. const covered = dataArray.filter(item => item > 0);
  256. const coverage = (covered.length / dataArray.length) * 100;
  257. ret[k] = {
  258. covered: covered.length,
  259. total: dataArray.length,
  260. coverage
  261. };
  262. });
  263. return ret;
  264. }
  265. /**
  266. * return a JSON-serializable POJO for this file coverage object
  267. */
  268. toJSON() {
  269. return this.data;
  270. }
  271. /**
  272. * merges a second coverage object into this one, updating hit counts
  273. * @param {FileCoverage} other - the coverage object to be merged into this one.
  274. * Note that the other object should have the same structure as this one (same file).
  275. */
  276. merge(other) {
  277. if (other.all === true) {
  278. return;
  279. }
  280. if (this.all === true) {
  281. this.data = other.data;
  282. return;
  283. }
  284. let [hits, map] = mergeProp(
  285. this.s,
  286. this.statementMap,
  287. other.s,
  288. other.statementMap
  289. );
  290. this.data.s = hits;
  291. this.data.statementMap = map;
  292. const keyFromLocProp = x => keyFromLoc(x.loc);
  293. const keyFromLocationsProp = x => keyFromLoc(x.locations[0]);
  294. [hits, map] = mergeProp(
  295. this.f,
  296. this.fnMap,
  297. other.f,
  298. other.fnMap,
  299. keyFromLocProp
  300. );
  301. this.data.f = hits;
  302. this.data.fnMap = map;
  303. [hits, map] = mergeProp(
  304. this.b,
  305. this.branchMap,
  306. other.b,
  307. other.branchMap,
  308. keyFromLocationsProp
  309. );
  310. this.data.b = hits;
  311. this.data.branchMap = map;
  312. // Tracking additional information about branch truthiness
  313. // can be optionally enabled:
  314. if (this.bT && other.bT) {
  315. [hits, map] = mergeProp(
  316. this.bT,
  317. this.branchMap,
  318. other.bT,
  319. other.branchMap,
  320. keyFromLocationsProp
  321. );
  322. this.data.bT = hits;
  323. }
  324. }
  325. computeSimpleTotals(property) {
  326. let stats = this[property];
  327. if (typeof stats === 'function') {
  328. stats = stats.call(this);
  329. }
  330. const ret = {
  331. total: Object.keys(stats).length,
  332. covered: Object.values(stats).filter(v => !!v).length,
  333. skipped: 0
  334. };
  335. ret.pct = percent(ret.covered, ret.total);
  336. return ret;
  337. }
  338. computeBranchTotals(property) {
  339. const stats = this[property];
  340. const ret = { total: 0, covered: 0, skipped: 0 };
  341. Object.values(stats).forEach(branches => {
  342. ret.covered += branches.filter(hits => hits > 0).length;
  343. ret.total += branches.length;
  344. });
  345. ret.pct = percent(ret.covered, ret.total);
  346. return ret;
  347. }
  348. /**
  349. * resets hit counts for all statements, functions and branches
  350. * in this coverage object resulting in zero coverage.
  351. */
  352. resetHits() {
  353. const statements = this.s;
  354. const functions = this.f;
  355. const branches = this.b;
  356. const branchesTrue = this.bT;
  357. Object.keys(statements).forEach(s => {
  358. statements[s] = 0;
  359. });
  360. Object.keys(functions).forEach(f => {
  361. functions[f] = 0;
  362. });
  363. Object.keys(branches).forEach(b => {
  364. branches[b].fill(0);
  365. });
  366. // Tracking additional information about branch truthiness
  367. // can be optionally enabled:
  368. if (branchesTrue) {
  369. Object.keys(branchesTrue).forEach(bT => {
  370. branchesTrue[bT].fill(0);
  371. });
  372. }
  373. }
  374. /**
  375. * returns a CoverageSummary for this file coverage object
  376. * @returns {CoverageSummary}
  377. */
  378. toSummary() {
  379. const ret = {};
  380. ret.lines = this.computeSimpleTotals('getLineCoverage');
  381. ret.functions = this.computeSimpleTotals('f', 'fnMap');
  382. ret.statements = this.computeSimpleTotals('s', 'statementMap');
  383. ret.branches = this.computeBranchTotals('b');
  384. // Tracking additional information about branch truthiness
  385. // can be optionally enabled:
  386. if (this.bT) {
  387. ret.branchesTrue = this.computeBranchTotals('bT');
  388. }
  389. return new CoverageSummary(ret);
  390. }
  391. }
  392. // expose coverage data attributes
  393. dataProperties(FileCoverage, [
  394. 'path',
  395. 'statementMap',
  396. 'fnMap',
  397. 'branchMap',
  398. 's',
  399. 'f',
  400. 'b',
  401. 'bT',
  402. 'all'
  403. ]);
  404. module.exports = {
  405. FileCoverage,
  406. // exported for testing
  407. findNearestContainer,
  408. addHits,
  409. addNearestContainerHits
  410. };