base.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. 'use strict';
  2. /**
  3. * @typedef {import('../runner.js')} Runner
  4. * @typedef {import('../test.js')} Test
  5. * @typedef {import('../types.d.ts').FullErrorStack} FullErrorStack
  6. */
  7. /**
  8. * @module Base
  9. */
  10. /**
  11. * Module dependencies.
  12. */
  13. var diff = require('diff');
  14. var milliseconds = require('ms');
  15. var utils = require('../utils');
  16. var supportsColor = require('supports-color');
  17. var symbols = require('log-symbols');
  18. var constants = require('../runner').constants;
  19. var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
  20. var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
  21. const isBrowser = utils.isBrowser();
  22. function getBrowserWindowSize() {
  23. if ('innerHeight' in global) {
  24. return [global.innerHeight, global.innerWidth];
  25. }
  26. // In a Web Worker, the DOM Window is not available.
  27. return [640, 480];
  28. }
  29. /**
  30. * Expose `Base`.
  31. */
  32. exports = module.exports = Base;
  33. /**
  34. * Check if both stdio streams are associated with a tty.
  35. */
  36. var isatty = isBrowser || (process.stdout.isTTY && process.stderr.isTTY);
  37. /**
  38. * Save log references to avoid tests interfering (see GH-3604).
  39. */
  40. var consoleLog = console.log;
  41. /**
  42. * Enable coloring by default, except in the browser interface.
  43. */
  44. exports.useColors =
  45. !isBrowser &&
  46. (supportsColor.stdout || process.env.MOCHA_COLORS !== undefined);
  47. /**
  48. * Inline diffs instead of +/-
  49. */
  50. exports.inlineDiffs = false;
  51. /**
  52. * Truncate diffs longer than this value to avoid slow performance
  53. */
  54. exports.maxDiffSize = 8192;
  55. /**
  56. * Default color map.
  57. */
  58. exports.colors = {
  59. pass: 90,
  60. fail: 31,
  61. 'bright pass': 92,
  62. 'bright fail': 91,
  63. 'bright yellow': 93,
  64. pending: 36,
  65. suite: 0,
  66. 'error title': 0,
  67. 'error message': 31,
  68. 'error stack': 90,
  69. checkmark: 32,
  70. fast: 90,
  71. medium: 33,
  72. slow: 31,
  73. green: 32,
  74. light: 90,
  75. 'diff gutter': 90,
  76. 'diff added': 32,
  77. 'diff removed': 31,
  78. 'diff added inline': '30;42',
  79. 'diff removed inline': '30;41'
  80. };
  81. /**
  82. * Default symbol map.
  83. */
  84. exports.symbols = {
  85. ok: symbols.success,
  86. err: symbols.error,
  87. dot: '.',
  88. comma: ',',
  89. bang: '!'
  90. };
  91. /**
  92. * Color `str` with the given `type`,
  93. * allowing colors to be disabled,
  94. * as well as user-defined color
  95. * schemes.
  96. *
  97. * @private
  98. * @param {string} type
  99. * @param {string} str
  100. * @return {string}
  101. */
  102. var color = (exports.color = function (type, str) {
  103. if (!exports.useColors) {
  104. return String(str);
  105. }
  106. return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
  107. });
  108. /**
  109. * Expose term window size, with some defaults for when stderr is not a tty.
  110. */
  111. exports.window = {
  112. width: 75
  113. };
  114. if (isatty) {
  115. if (isBrowser) {
  116. exports.window.width = getBrowserWindowSize()[1];
  117. } else {
  118. exports.window.width = process.stdout.getWindowSize(1)[0];
  119. }
  120. }
  121. /**
  122. * Expose some basic cursor interactions that are common among reporters.
  123. */
  124. exports.cursor = {
  125. hide: function () {
  126. isatty && process.stdout.write('\u001b[?25l');
  127. },
  128. show: function () {
  129. isatty && process.stdout.write('\u001b[?25h');
  130. },
  131. deleteLine: function () {
  132. isatty && process.stdout.write('\u001b[2K');
  133. },
  134. beginningOfLine: function () {
  135. isatty && process.stdout.write('\u001b[0G');
  136. },
  137. CR: function () {
  138. if (isatty) {
  139. exports.cursor.deleteLine();
  140. exports.cursor.beginningOfLine();
  141. } else {
  142. process.stdout.write('\r');
  143. }
  144. }
  145. };
  146. var showDiff = (exports.showDiff = function (err) {
  147. return (
  148. err &&
  149. err.showDiff !== false &&
  150. sameType(err.actual, err.expected) &&
  151. err.expected !== undefined
  152. );
  153. });
  154. function stringifyDiffObjs(err) {
  155. if (!utils.isString(err.actual) || !utils.isString(err.expected)) {
  156. err.actual = utils.stringify(err.actual);
  157. err.expected = utils.stringify(err.expected);
  158. }
  159. }
  160. /**
  161. * Returns a diff between 2 strings with coloured ANSI output.
  162. *
  163. * @description
  164. * The diff will be either inline or unified dependent on the value
  165. * of `Base.inlineDiff`.
  166. *
  167. * @param {string} actual
  168. * @param {string} expected
  169. * @return {string} Diff
  170. */
  171. var generateDiff = (exports.generateDiff = function (actual, expected) {
  172. try {
  173. var maxLen = exports.maxDiffSize;
  174. var skipped = 0;
  175. if (maxLen > 0) {
  176. skipped = Math.max(actual.length - maxLen, expected.length - maxLen);
  177. actual = actual.slice(0, maxLen);
  178. expected = expected.slice(0, maxLen);
  179. }
  180. let result = exports.inlineDiffs
  181. ? inlineDiff(actual, expected)
  182. : unifiedDiff(actual, expected);
  183. if (skipped > 0) {
  184. result = `${result}\n [mocha] output truncated to ${maxLen} characters, see "maxDiffSize" reporter-option\n`;
  185. }
  186. return result;
  187. } catch (err) {
  188. var msg =
  189. '\n ' +
  190. color('diff added', '+ expected') +
  191. ' ' +
  192. color('diff removed', '- actual: failed to generate Mocha diff') +
  193. '\n';
  194. return msg;
  195. }
  196. });
  197. /**
  198. * Traverses err.cause and returns all stack traces
  199. *
  200. * @private
  201. * @param {Error} err
  202. * @param {Set<Error>} [seen]
  203. * @return {FullErrorStack}
  204. */
  205. var getFullErrorStack = function (err, seen) {
  206. if (seen && seen.has(err)) {
  207. return { message: '', msg: '<circular>', stack: '' };
  208. }
  209. var message;
  210. if (typeof err.inspect === 'function') {
  211. message = err.inspect() + '';
  212. } else if (err.message && typeof err.message.toString === 'function') {
  213. message = err.message + '';
  214. } else {
  215. message = '';
  216. }
  217. var msg;
  218. var stack = err.stack || message;
  219. var index = message ? stack.indexOf(message) : -1;
  220. if (index === -1) {
  221. msg = message;
  222. } else {
  223. index += message.length;
  224. msg = stack.slice(0, index);
  225. // remove msg from stack
  226. stack = stack.slice(index + 1);
  227. if (err.cause) {
  228. seen = seen || new Set();
  229. seen.add(err);
  230. const causeStack = getFullErrorStack(err.cause, seen)
  231. stack += '\n Caused by: ' + causeStack.msg + (causeStack.stack ? '\n' + causeStack.stack : '');
  232. }
  233. }
  234. return {
  235. message,
  236. msg,
  237. stack
  238. };
  239. };
  240. /**
  241. * Outputs the given `failures` as a list.
  242. *
  243. * @public
  244. * @memberof Mocha.reporters.Base
  245. * @variation 1
  246. * @param {Object[]} failures - Each is Test instance with corresponding
  247. * Error property
  248. */
  249. exports.list = function (failures) {
  250. var multipleErr, multipleTest;
  251. Base.consoleLog();
  252. failures.forEach(function (test, i) {
  253. // format
  254. var fmt =
  255. color('error title', ' %s) %s:\n') +
  256. color('error message', ' %s') +
  257. color('error stack', '\n%s\n');
  258. // msg
  259. var err;
  260. if (test.err && test.err.multiple) {
  261. if (multipleTest !== test) {
  262. multipleTest = test;
  263. multipleErr = [test.err].concat(test.err.multiple);
  264. }
  265. err = multipleErr.shift();
  266. } else {
  267. err = test.err;
  268. }
  269. var { message, msg, stack } = getFullErrorStack(err);
  270. // uncaught
  271. if (err.uncaught) {
  272. msg = 'Uncaught ' + msg;
  273. }
  274. // explicitly show diff
  275. if (!exports.hideDiff && showDiff(err)) {
  276. stringifyDiffObjs(err);
  277. fmt =
  278. color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
  279. var match = message.match(/^([^:]+): expected/);
  280. msg = '\n ' + color('error message', match ? match[1] : msg);
  281. msg += generateDiff(err.actual, err.expected);
  282. }
  283. // indent stack trace
  284. stack = stack.replace(/^/gm, ' ');
  285. // indented test title
  286. var testTitle = '';
  287. test.titlePath().forEach(function (str, index) {
  288. if (index !== 0) {
  289. testTitle += '\n ';
  290. }
  291. for (var i = 0; i < index; i++) {
  292. testTitle += ' ';
  293. }
  294. testTitle += str;
  295. });
  296. Base.consoleLog(fmt, i + 1, testTitle, msg, stack);
  297. });
  298. };
  299. /**
  300. * Constructs a new `Base` reporter instance.
  301. *
  302. * @description
  303. * All other reporters generally inherit from this reporter.
  304. *
  305. * @public
  306. * @class
  307. * @memberof Mocha.reporters
  308. * @param {Runner} runner - Instance triggers reporter actions.
  309. * @param {Object} [options] - runner options
  310. */
  311. function Base(runner, options) {
  312. var failures = (this.failures = []);
  313. if (!runner) {
  314. throw new TypeError('Missing runner argument');
  315. }
  316. this.options = options || {};
  317. this.runner = runner;
  318. this.stats = runner.stats; // assigned so Reporters keep a closer reference
  319. var maxDiffSizeOpt =
  320. this.options.reporterOption && this.options.reporterOption.maxDiffSize;
  321. if (maxDiffSizeOpt !== undefined && !isNaN(Number(maxDiffSizeOpt))) {
  322. exports.maxDiffSize = Number(maxDiffSizeOpt);
  323. }
  324. runner.on(EVENT_TEST_PASS, function (test) {
  325. if (test.duration > test.slow()) {
  326. test.speed = 'slow';
  327. } else if (test.duration > test.slow() / 2) {
  328. test.speed = 'medium';
  329. } else {
  330. test.speed = 'fast';
  331. }
  332. });
  333. runner.on(EVENT_TEST_FAIL, function (test, err) {
  334. if (showDiff(err)) {
  335. stringifyDiffObjs(err);
  336. }
  337. // more than one error per test
  338. if (test.err && err instanceof Error) {
  339. test.err.multiple = (test.err.multiple || []).concat(err);
  340. } else {
  341. test.err = err;
  342. }
  343. failures.push(test);
  344. });
  345. }
  346. /**
  347. * Outputs common epilogue used by many of the bundled reporters.
  348. *
  349. * @public
  350. * @memberof Mocha.reporters
  351. */
  352. Base.prototype.epilogue = function () {
  353. var stats = this.stats;
  354. var fmt;
  355. Base.consoleLog();
  356. // passes
  357. fmt =
  358. color('bright pass', ' ') +
  359. color('green', ' %d passing') +
  360. color('light', ' (%s)');
  361. Base.consoleLog(fmt, stats.passes || 0, milliseconds(stats.duration));
  362. // pending
  363. if (stats.pending) {
  364. fmt = color('pending', ' ') + color('pending', ' %d pending');
  365. Base.consoleLog(fmt, stats.pending);
  366. }
  367. // failures
  368. if (stats.failures) {
  369. fmt = color('fail', ' %d failing');
  370. Base.consoleLog(fmt, stats.failures);
  371. Base.list(this.failures);
  372. Base.consoleLog();
  373. }
  374. Base.consoleLog();
  375. };
  376. /**
  377. * Pads the given `str` to `len`.
  378. *
  379. * @private
  380. * @param {string} str
  381. * @param {string} len
  382. * @return {string}
  383. */
  384. function pad(str, len) {
  385. str = String(str);
  386. return Array(len - str.length + 1).join(' ') + str;
  387. }
  388. /**
  389. * Returns inline diff between 2 strings with coloured ANSI output.
  390. *
  391. * @private
  392. * @param {String} actual
  393. * @param {String} expected
  394. * @return {string} Diff
  395. */
  396. function inlineDiff(actual, expected) {
  397. var msg = errorDiff(actual, expected);
  398. // linenos
  399. var lines = msg.split('\n');
  400. if (lines.length > 4) {
  401. var width = String(lines.length).length;
  402. msg = lines
  403. .map(function (str, i) {
  404. return pad(++i, width) + ' |' + ' ' + str;
  405. })
  406. .join('\n');
  407. }
  408. // legend
  409. msg =
  410. '\n' +
  411. color('diff removed inline', 'actual') +
  412. ' ' +
  413. color('diff added inline', 'expected') +
  414. '\n\n' +
  415. msg +
  416. '\n';
  417. // indent
  418. msg = msg.replace(/^/gm, ' ');
  419. return msg;
  420. }
  421. /**
  422. * Returns unified diff between two strings with coloured ANSI output.
  423. *
  424. * @private
  425. * @param {String} actual
  426. * @param {String} expected
  427. * @return {string} The diff.
  428. */
  429. function unifiedDiff(actual, expected) {
  430. var indent = ' ';
  431. function cleanUp(line) {
  432. if (line[0] === '+') {
  433. return indent + colorLines('diff added', line);
  434. }
  435. if (line[0] === '-') {
  436. return indent + colorLines('diff removed', line);
  437. }
  438. if (line.match(/@@/)) {
  439. return '--';
  440. }
  441. if (line.match(/\\ No newline/)) {
  442. return null;
  443. }
  444. return indent + line;
  445. }
  446. function notBlank(line) {
  447. return typeof line !== 'undefined' && line !== null;
  448. }
  449. var msg = diff.createPatch('string', actual, expected);
  450. var lines = msg.split('\n').splice(5);
  451. return (
  452. '\n ' +
  453. colorLines('diff added', '+ expected') +
  454. ' ' +
  455. colorLines('diff removed', '- actual') +
  456. '\n\n' +
  457. lines.map(cleanUp).filter(notBlank).join('\n')
  458. );
  459. }
  460. /**
  461. * Returns character diff for `err`.
  462. *
  463. * @private
  464. * @param {String} actual
  465. * @param {String} expected
  466. * @return {string} the diff
  467. */
  468. function errorDiff(actual, expected) {
  469. return diff
  470. .diffWordsWithSpace(actual, expected)
  471. .map(function (str) {
  472. if (str.added) {
  473. return colorLines('diff added inline', str.value);
  474. }
  475. if (str.removed) {
  476. return colorLines('diff removed inline', str.value);
  477. }
  478. return str.value;
  479. })
  480. .join('');
  481. }
  482. /**
  483. * Colors lines for `str`, using the color `name`.
  484. *
  485. * @private
  486. * @param {string} name
  487. * @param {string} str
  488. * @return {string}
  489. */
  490. function colorLines(name, str) {
  491. return str
  492. .split('\n')
  493. .map(function (str) {
  494. return color(name, str);
  495. })
  496. .join('\n');
  497. }
  498. /**
  499. * Object#toString reference.
  500. */
  501. var objToString = Object.prototype.toString;
  502. /**
  503. * Checks that a / b have the same type.
  504. *
  505. * @private
  506. * @param {Object} a
  507. * @param {Object} b
  508. * @return {boolean}
  509. */
  510. function sameType(a, b) {
  511. return objToString.call(a) === objToString.call(b);
  512. }
  513. Base.consoleLog = consoleLog;
  514. Base.abstract = true;