file.js 9.8 KB

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