base.js.orig 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. 'use strict';
  2. /**
  3. * Module dependencies.
  4. */
  5. var tty = require('tty');
  6. var diff = require('diff');
  7. var ms = require('../ms');
  8. var utils = require('../utils');
  9. var supportsColor = process.browser ? null : require('supports-color');
  10. /**
  11. * Expose `Base`.
  12. */
  13. exports = module.exports = Base;
  14. /**
  15. * Save timer references to avoid Sinon interfering.
  16. * See: https://github.com/mochajs/mocha/issues/237
  17. */
  18. /* eslint-disable no-unused-vars, no-native-reassign */
  19. var Date = global.Date;
  20. var setTimeout = global.setTimeout;
  21. var setInterval = global.setInterval;
  22. var clearTimeout = global.clearTimeout;
  23. var clearInterval = global.clearInterval;
  24. /* eslint-enable no-unused-vars, no-native-reassign */
  25. /**
  26. * Check if both stdio streams are associated with a tty.
  27. */
  28. var isatty = tty.isatty(1) && tty.isatty(2);
  29. /**
  30. * Enable coloring by default, except in the browser interface.
  31. */
  32. exports.useColors = !process.browser && (supportsColor || (process.env.MOCHA_COLORS !== undefined));
  33. /**
  34. * Inline diffs instead of +/-
  35. */
  36. exports.inlineDiffs = false;
  37. /**
  38. * Default color map.
  39. */
  40. exports.colors = {
  41. pass: 90,
  42. fail: 31,
  43. 'bright pass': 92,
  44. 'bright fail': 91,
  45. 'bright yellow': 93,
  46. pending: 36,
  47. suite: 0,
  48. 'error title': 0,
  49. 'error message': 31,
  50. 'error stack': 90,
  51. checkmark: 32,
  52. fast: 90,
  53. medium: 33,
  54. slow: 31,
  55. green: 32,
  56. light: 90,
  57. 'diff gutter': 90,
  58. 'diff added': 32,
  59. 'diff removed': 31
  60. };
  61. /**
  62. * Default symbol map.
  63. */
  64. exports.symbols = {
  65. ok: '✓',
  66. err: '✖',
  67. dot: '․',
  68. comma: ',',
  69. bang: '!'
  70. };
  71. // With node.js on Windows: use symbols available in terminal default fonts
  72. if (process.platform === 'win32') {
  73. exports.symbols.ok = '\u221A';
  74. exports.symbols.err = '\u00D7';
  75. exports.symbols.dot = '.';
  76. }
  77. /**
  78. * Color `str` with the given `type`,
  79. * allowing colors to be disabled,
  80. * as well as user-defined color
  81. * schemes.
  82. *
  83. * @param {string} type
  84. * @param {string} str
  85. * @return {string}
  86. * @api private
  87. */
  88. var color = exports.color = function (type, str) {
  89. if (!exports.useColors) {
  90. return String(str);
  91. }
  92. return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
  93. };
  94. /**
  95. * Expose term window size, with some defaults for when stderr is not a tty.
  96. */
  97. exports.window = {
  98. width: 75
  99. };
  100. if (isatty) {
  101. exports.window.width = process.stdout.getWindowSize
  102. ? process.stdout.getWindowSize(1)[0]
  103. : tty.getWindowSize()[1];
  104. }
  105. /**
  106. * Expose some basic cursor interactions that are common among reporters.
  107. */
  108. exports.cursor = {
  109. hide: function () {
  110. isatty && process.stdout.write('\u001b[?25l');
  111. },
  112. show: function () {
  113. isatty && process.stdout.write('\u001b[?25h');
  114. },
  115. deleteLine: function () {
  116. isatty && process.stdout.write('\u001b[2K');
  117. },
  118. beginningOfLine: function () {
  119. isatty && process.stdout.write('\u001b[0G');
  120. },
  121. CR: function () {
  122. if (isatty) {
  123. exports.cursor.deleteLine();
  124. exports.cursor.beginningOfLine();
  125. } else {
  126. process.stdout.write('\r');
  127. }
  128. }
  129. };
  130. function showDiff (err) {
  131. return err && err.showDiff !== false && sameType(err.actual, err.expected) && err.expected !== undefined;
  132. }
  133. function stringifyDiffObjs (err) {
  134. if (!utils.isString(err.actual) || !utils.isString(err.expected)) {
  135. err.actual = utils.stringify(err.actual);
  136. err.expected = utils.stringify(err.expected);
  137. }
  138. }
  139. /**
  140. * Output the given `failures` as a list.
  141. *
  142. * @param {Array} failures
  143. * @api public
  144. */
  145. exports.list = function (failures) {
  146. console.log();
  147. failures.forEach(function (test, i) {
  148. // format
  149. var fmt = color('error title', ' %s) %s:\n') +
  150. color('error message', ' %s') +
  151. color('error stack', '\n%s\n');
  152. // msg
  153. var msg;
  154. var err = test.err;
  155. var message;
  156. if (err.message && typeof err.message.toString === 'function') {
  157. message = err.message + '';
  158. } else if (typeof err.inspect === 'function') {
  159. message = err.inspect() + '';
  160. } else {
  161. message = '';
  162. }
  163. var stack = err.stack || message;
  164. var index = message ? stack.indexOf(message) : -1;
  165. if (index === -1) {
  166. msg = message;
  167. } else {
  168. index += message.length;
  169. msg = stack.slice(0, index);
  170. // remove msg from stack
  171. stack = stack.slice(index + 1);
  172. }
  173. // uncaught
  174. if (err.uncaught) {
  175. msg = 'Uncaught ' + msg;
  176. }
  177. // explicitly show diff
  178. <<<<<<< HEAD
  179. if (showDiff(err)) {
  180. stringifyDiffObjs(err);
  181. =======
  182. if (exports.hideDiff !== true && err.showDiff !== false && sameType(actual, expected) && expected !== undefined) {
  183. escape = false;
  184. if (!(utils.isString(actual) && utils.isString(expected))) {
  185. err.actual = actual = utils.stringify(actual);
  186. err.expected = expected = utils.stringify(expected);
  187. }
  188. >>>>>>> Add --no-diff option (fixes mochajs/mocha#2514)
  189. fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
  190. var match = message.match(/^([^:]+): expected/);
  191. msg = '\n ' + color('error message', match ? match[1] : msg);
  192. if (exports.inlineDiffs) {
  193. msg += inlineDiff(err);
  194. } else {
  195. msg += unifiedDiff(err);
  196. }
  197. }
  198. // indent stack trace
  199. stack = stack.replace(/^/gm, ' ');
  200. // indented test title
  201. var testTitle = '';
  202. test.titlePath().forEach(function (str, index) {
  203. if (index !== 0) {
  204. testTitle += '\n ';
  205. }
  206. for (var i = 0; i < index; i++) {
  207. testTitle += ' ';
  208. }
  209. testTitle += str;
  210. });
  211. console.log(fmt, (i + 1), testTitle, msg, stack);
  212. });
  213. };
  214. /**
  215. * Initialize a new `Base` reporter.
  216. *
  217. * All other reporters generally
  218. * inherit from this reporter, providing
  219. * stats such as test duration, number
  220. * of tests passed / failed etc.
  221. *
  222. * @param {Runner} runner
  223. * @api public
  224. */
  225. function Base (runner) {
  226. var stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 };
  227. var failures = this.failures = [];
  228. if (!runner) {
  229. return;
  230. }
  231. this.runner = runner;
  232. runner.stats = stats;
  233. runner.on('start', function () {
  234. stats.start = new Date();
  235. });
  236. runner.on('suite', function (suite) {
  237. stats.suites = stats.suites || 0;
  238. suite.root || stats.suites++;
  239. });
  240. runner.on('test end', function () {
  241. stats.tests = stats.tests || 0;
  242. stats.tests++;
  243. });
  244. runner.on('pass', function (test) {
  245. stats.passes = stats.passes || 0;
  246. if (test.duration > test.slow()) {
  247. test.speed = 'slow';
  248. } else if (test.duration > test.slow() / 2) {
  249. test.speed = 'medium';
  250. } else {
  251. test.speed = 'fast';
  252. }
  253. stats.passes++;
  254. });
  255. runner.on('fail', function (test, err) {
  256. stats.failures = stats.failures || 0;
  257. stats.failures++;
  258. if (showDiff(err)) {
  259. stringifyDiffObjs(err);
  260. }
  261. test.err = err;
  262. failures.push(test);
  263. });
  264. runner.on('end', function () {
  265. stats.end = new Date();
  266. stats.duration = new Date() - stats.start;
  267. });
  268. runner.on('pending', function () {
  269. stats.pending++;
  270. });
  271. }
  272. /**
  273. * Output common epilogue used by many of
  274. * the bundled reporters.
  275. *
  276. * @api public
  277. */
  278. Base.prototype.epilogue = function () {
  279. var stats = this.stats;
  280. var fmt;
  281. console.log();
  282. // passes
  283. fmt = color('bright pass', ' ') +
  284. color('green', ' %d passing') +
  285. color('light', ' (%s)');
  286. console.log(fmt,
  287. stats.passes || 0,
  288. ms(stats.duration));
  289. // pending
  290. if (stats.pending) {
  291. fmt = color('pending', ' ') +
  292. color('pending', ' %d pending');
  293. console.log(fmt, stats.pending);
  294. }
  295. // failures
  296. if (stats.failures) {
  297. fmt = color('fail', ' %d failing');
  298. console.log(fmt, stats.failures);
  299. Base.list(this.failures);
  300. console.log();
  301. }
  302. console.log();
  303. };
  304. /**
  305. * Pad the given `str` to `len`.
  306. *
  307. * @api private
  308. * @param {string} str
  309. * @param {string} len
  310. * @return {string}
  311. */
  312. function pad (str, len) {
  313. str = String(str);
  314. return Array(len - str.length + 1).join(' ') + str;
  315. }
  316. /**
  317. * Returns an inline diff between 2 strings with coloured ANSI output
  318. *
  319. * @api private
  320. * @param {Error} err with actual/expected
  321. * @return {string} Diff
  322. */
  323. function inlineDiff (err) {
  324. var msg = errorDiff(err);
  325. // linenos
  326. var lines = msg.split('\n');
  327. if (lines.length > 4) {
  328. var width = String(lines.length).length;
  329. msg = lines.map(function (str, i) {
  330. return pad(++i, width) + ' |' + ' ' + str;
  331. }).join('\n');
  332. }
  333. // legend
  334. msg = '\n' +
  335. color('diff removed', 'actual') +
  336. ' ' +
  337. color('diff added', 'expected') +
  338. '\n\n' +
  339. msg +
  340. '\n';
  341. // indent
  342. msg = msg.replace(/^/gm, ' ');
  343. return msg;
  344. }
  345. /**
  346. * Returns a unified diff between two strings.
  347. *
  348. * @api private
  349. * @param {Error} err with actual/expected
  350. * @return {string} The diff.
  351. */
  352. function unifiedDiff (err) {
  353. var indent = ' ';
  354. function cleanUp (line) {
  355. if (line[0] === '+') {
  356. return indent + colorLines('diff added', line);
  357. }
  358. if (line[0] === '-') {
  359. return indent + colorLines('diff removed', line);
  360. }
  361. if (line.match(/@@/)) {
  362. return '--';
  363. }
  364. if (line.match(/\\ No newline/)) {
  365. return null;
  366. }
  367. return indent + line;
  368. }
  369. function notBlank (line) {
  370. return typeof line !== 'undefined' && line !== null;
  371. }
  372. var msg = diff.createPatch('string', err.actual, err.expected);
  373. var lines = msg.split('\n').splice(5);
  374. return '\n ' +
  375. colorLines('diff added', '+ expected') + ' ' +
  376. colorLines('diff removed', '- actual') +
  377. '\n\n' +
  378. lines.map(cleanUp).filter(notBlank).join('\n');
  379. }
  380. /**
  381. * Return a character diff for `err`.
  382. *
  383. * @api private
  384. * @param {Error} err
  385. * @return {string}
  386. */
  387. function errorDiff (err) {
  388. return diff.diffWordsWithSpace(err.actual, err.expected).map(function (str) {
  389. if (str.added) {
  390. return colorLines('diff added', str.value);
  391. }
  392. if (str.removed) {
  393. return colorLines('diff removed', str.value);
  394. }
  395. return str.value;
  396. }).join('');
  397. }
  398. /**
  399. * Color lines for `str`, using the color `name`.
  400. *
  401. * @api private
  402. * @param {string} name
  403. * @param {string} str
  404. * @return {string}
  405. */
  406. function colorLines (name, str) {
  407. return str.split('\n').map(function (str) {
  408. return color(name, str);
  409. }).join('\n');
  410. }
  411. /**
  412. * Object#toString reference.
  413. */
  414. var objToString = Object.prototype.toString;
  415. /**
  416. * Check that a / b have the same type.
  417. *
  418. * @api private
  419. * @param {Object} a
  420. * @param {Object} b
  421. * @return {boolean}
  422. */
  423. function sameType (a, b) {
  424. return objToString.call(a) === objToString.call(b);
  425. }