runnable.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. 'use strict';
  2. var EventEmitter = require('events').EventEmitter;
  3. var Pending = require('./pending');
  4. var debug = require('debug')('mocha:runnable');
  5. var milliseconds = require('ms');
  6. var utils = require('./utils');
  7. var createInvalidExceptionError = require('./errors')
  8. .createInvalidExceptionError;
  9. /**
  10. * Save timer references to avoid Sinon interfering (see GH-237).
  11. */
  12. var Date = global.Date;
  13. var setTimeout = global.setTimeout;
  14. var clearTimeout = global.clearTimeout;
  15. var toString = Object.prototype.toString;
  16. module.exports = Runnable;
  17. /**
  18. * Initialize a new `Runnable` with the given `title` and callback `fn`.
  19. *
  20. * @class
  21. * @extends external:EventEmitter
  22. * @public
  23. * @param {String} title
  24. * @param {Function} fn
  25. */
  26. function Runnable(title, fn) {
  27. this.title = title;
  28. this.fn = fn;
  29. this.body = (fn || '').toString();
  30. this.async = fn && fn.length;
  31. this.sync = !this.async;
  32. this._timeout = 2000;
  33. this._slow = 75;
  34. this._enableTimeouts = true;
  35. this.timedOut = false;
  36. this._retries = -1;
  37. this._currentRetry = 0;
  38. this.pending = false;
  39. }
  40. /**
  41. * Inherit from `EventEmitter.prototype`.
  42. */
  43. utils.inherits(Runnable, EventEmitter);
  44. /**
  45. * Get current timeout value in msecs.
  46. *
  47. * @private
  48. * @returns {number} current timeout threshold value
  49. */
  50. /**
  51. * @summary
  52. * Set timeout threshold value (msecs).
  53. *
  54. * @description
  55. * A string argument can use shorthand (e.g., "2s") and will be converted.
  56. * The value will be clamped to range [<code>0</code>, <code>2^<sup>31</sup>-1</code>].
  57. * If clamped value matches either range endpoint, timeouts will be disabled.
  58. *
  59. * @private
  60. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value}
  61. * @param {number|string} ms - Timeout threshold value.
  62. * @returns {Runnable} this
  63. * @chainable
  64. */
  65. Runnable.prototype.timeout = function(ms) {
  66. if (!arguments.length) {
  67. return this._timeout;
  68. }
  69. if (typeof ms === 'string') {
  70. ms = milliseconds(ms);
  71. }
  72. // Clamp to range
  73. var INT_MAX = Math.pow(2, 31) - 1;
  74. var range = [0, INT_MAX];
  75. ms = utils.clamp(ms, range);
  76. // see #1652 for reasoning
  77. if (ms === range[0] || ms === range[1]) {
  78. this._enableTimeouts = false;
  79. }
  80. debug('timeout %d', ms);
  81. this._timeout = ms;
  82. if (this.timer) {
  83. this.resetTimeout();
  84. }
  85. return this;
  86. };
  87. /**
  88. * Set or get slow `ms`.
  89. *
  90. * @private
  91. * @param {number|string} ms
  92. * @return {Runnable|number} ms or Runnable instance.
  93. */
  94. Runnable.prototype.slow = function(ms) {
  95. if (!arguments.length || typeof ms === 'undefined') {
  96. return this._slow;
  97. }
  98. if (typeof ms === 'string') {
  99. ms = milliseconds(ms);
  100. }
  101. debug('slow %d', ms);
  102. this._slow = ms;
  103. return this;
  104. };
  105. /**
  106. * Set and get whether timeout is `enabled`.
  107. *
  108. * @private
  109. * @param {boolean} enabled
  110. * @return {Runnable|boolean} enabled or Runnable instance.
  111. */
  112. Runnable.prototype.enableTimeouts = function(enabled) {
  113. if (!arguments.length) {
  114. return this._enableTimeouts;
  115. }
  116. debug('enableTimeouts %s', enabled);
  117. this._enableTimeouts = enabled;
  118. return this;
  119. };
  120. /**
  121. * Halt and mark as pending.
  122. *
  123. * @memberof Mocha.Runnable
  124. * @public
  125. */
  126. Runnable.prototype.skip = function() {
  127. throw new Pending('sync skip');
  128. };
  129. /**
  130. * Check if this runnable or its parent suite is marked as pending.
  131. *
  132. * @private
  133. */
  134. Runnable.prototype.isPending = function() {
  135. return this.pending || (this.parent && this.parent.isPending());
  136. };
  137. /**
  138. * Return `true` if this Runnable has failed.
  139. * @return {boolean}
  140. * @private
  141. */
  142. Runnable.prototype.isFailed = function() {
  143. return !this.isPending() && this.state === constants.STATE_FAILED;
  144. };
  145. /**
  146. * Return `true` if this Runnable has passed.
  147. * @return {boolean}
  148. * @private
  149. */
  150. Runnable.prototype.isPassed = function() {
  151. return !this.isPending() && this.state === constants.STATE_PASSED;
  152. };
  153. /**
  154. * Set or get number of retries.
  155. *
  156. * @private
  157. */
  158. Runnable.prototype.retries = function(n) {
  159. if (!arguments.length) {
  160. return this._retries;
  161. }
  162. this._retries = n;
  163. };
  164. /**
  165. * Set or get current retry
  166. *
  167. * @private
  168. */
  169. Runnable.prototype.currentRetry = function(n) {
  170. if (!arguments.length) {
  171. return this._currentRetry;
  172. }
  173. this._currentRetry = n;
  174. };
  175. /**
  176. * Return the full title generated by recursively concatenating the parent's
  177. * full title.
  178. *
  179. * @memberof Mocha.Runnable
  180. * @public
  181. * @return {string}
  182. */
  183. Runnable.prototype.fullTitle = function() {
  184. return this.titlePath().join(' ');
  185. };
  186. /**
  187. * Return the title path generated by concatenating the parent's title path with the title.
  188. *
  189. * @memberof Mocha.Runnable
  190. * @public
  191. * @return {string}
  192. */
  193. Runnable.prototype.titlePath = function() {
  194. return this.parent.titlePath().concat([this.title]);
  195. };
  196. /**
  197. * Clear the timeout.
  198. *
  199. * @private
  200. */
  201. Runnable.prototype.clearTimeout = function() {
  202. clearTimeout(this.timer);
  203. };
  204. /**
  205. * Inspect the runnable void of private properties.
  206. *
  207. * @private
  208. * @return {string}
  209. */
  210. Runnable.prototype.inspect = function() {
  211. return JSON.stringify(
  212. this,
  213. function(key, val) {
  214. if (key[0] === '_') {
  215. return;
  216. }
  217. if (key === 'parent') {
  218. return '#<Suite>';
  219. }
  220. if (key === 'ctx') {
  221. return '#<Context>';
  222. }
  223. return val;
  224. },
  225. 2
  226. );
  227. };
  228. /**
  229. * Reset the timeout.
  230. *
  231. * @private
  232. */
  233. Runnable.prototype.resetTimeout = function() {
  234. var self = this;
  235. var ms = this.timeout() || 1e9;
  236. if (!this._enableTimeouts) {
  237. return;
  238. }
  239. this.clearTimeout();
  240. this.timer = setTimeout(function() {
  241. if (!self._enableTimeouts) {
  242. return;
  243. }
  244. self.callback(self._timeoutError(ms));
  245. self.timedOut = true;
  246. }, ms);
  247. };
  248. /**
  249. * Set or get a list of whitelisted globals for this test run.
  250. *
  251. * @private
  252. * @param {string[]} globals
  253. */
  254. Runnable.prototype.globals = function(globals) {
  255. if (!arguments.length) {
  256. return this._allowedGlobals;
  257. }
  258. this._allowedGlobals = globals;
  259. };
  260. /**
  261. * Run the test and invoke `fn(err)`.
  262. *
  263. * @param {Function} fn
  264. * @private
  265. */
  266. Runnable.prototype.run = function(fn) {
  267. var self = this;
  268. var start = new Date();
  269. var ctx = this.ctx;
  270. var finished;
  271. var emitted;
  272. // Sometimes the ctx exists, but it is not runnable
  273. if (ctx && ctx.runnable) {
  274. ctx.runnable(this);
  275. }
  276. // called multiple times
  277. function multiple(err) {
  278. if (emitted) {
  279. return;
  280. }
  281. emitted = true;
  282. var msg = 'done() called multiple times';
  283. if (err && err.message) {
  284. err.message += " (and Mocha's " + msg + ')';
  285. self.emit('error', err);
  286. } else {
  287. self.emit('error', new Error(msg));
  288. }
  289. }
  290. // finished
  291. function done(err) {
  292. var ms = self.timeout();
  293. if (self.timedOut) {
  294. return;
  295. }
  296. if (finished) {
  297. return multiple(err);
  298. }
  299. self.clearTimeout();
  300. self.duration = new Date() - start;
  301. finished = true;
  302. if (!err && self.duration > ms && self._enableTimeouts) {
  303. err = self._timeoutError(ms);
  304. }
  305. fn(err);
  306. }
  307. // for .resetTimeout()
  308. this.callback = done;
  309. // explicit async with `done` argument
  310. if (this.async) {
  311. this.resetTimeout();
  312. // allows skip() to be used in an explicit async context
  313. this.skip = function asyncSkip() {
  314. done(new Pending('async skip call'));
  315. // halt execution. the Runnable will be marked pending
  316. // by the previous call, and the uncaught handler will ignore
  317. // the failure.
  318. throw new Pending('async skip; aborting execution');
  319. };
  320. if (this.allowUncaught) {
  321. return callFnAsync(this.fn);
  322. }
  323. try {
  324. callFnAsync(this.fn);
  325. } catch (err) {
  326. emitted = true;
  327. done(Runnable.toValueOrError(err));
  328. }
  329. return;
  330. }
  331. if (this.allowUncaught) {
  332. if (this.isPending()) {
  333. done();
  334. } else {
  335. callFn(this.fn);
  336. }
  337. return;
  338. }
  339. // sync or promise-returning
  340. try {
  341. if (this.isPending()) {
  342. done();
  343. } else {
  344. callFn(this.fn);
  345. }
  346. } catch (err) {
  347. emitted = true;
  348. done(Runnable.toValueOrError(err));
  349. }
  350. function callFn(fn) {
  351. var result = fn.call(ctx);
  352. if (result && typeof result.then === 'function') {
  353. self.resetTimeout();
  354. result.then(
  355. function() {
  356. done();
  357. // Return null so libraries like bluebird do not warn about
  358. // subsequently constructed Promises.
  359. return null;
  360. },
  361. function(reason) {
  362. done(reason || new Error('Promise rejected with no or falsy reason'));
  363. }
  364. );
  365. } else {
  366. if (self.asyncOnly) {
  367. return done(
  368. new Error(
  369. '--async-only option in use without declaring `done()` or returning a promise'
  370. )
  371. );
  372. }
  373. done();
  374. }
  375. }
  376. function callFnAsync(fn) {
  377. var result = fn.call(ctx, function(err) {
  378. if (err instanceof Error || toString.call(err) === '[object Error]') {
  379. return done(err);
  380. }
  381. if (err) {
  382. if (Object.prototype.toString.call(err) === '[object Object]') {
  383. return done(
  384. new Error('done() invoked with non-Error: ' + JSON.stringify(err))
  385. );
  386. }
  387. return done(new Error('done() invoked with non-Error: ' + err));
  388. }
  389. if (result && utils.isPromise(result)) {
  390. return done(
  391. new Error(
  392. 'Resolution method is overspecified. Specify a callback *or* return a Promise; not both.'
  393. )
  394. );
  395. }
  396. done();
  397. });
  398. }
  399. };
  400. /**
  401. * Instantiates a "timeout" error
  402. *
  403. * @param {number} ms - Timeout (in milliseconds)
  404. * @returns {Error} a "timeout" error
  405. * @private
  406. */
  407. Runnable.prototype._timeoutError = function(ms) {
  408. var msg =
  409. 'Timeout of ' +
  410. ms +
  411. 'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.';
  412. if (this.file) {
  413. msg += ' (' + this.file + ')';
  414. }
  415. return new Error(msg);
  416. };
  417. var constants = utils.defineConstants(
  418. /**
  419. * {@link Runnable}-related constants.
  420. * @public
  421. * @memberof Runnable
  422. * @readonly
  423. * @static
  424. * @alias constants
  425. * @enum {string}
  426. */
  427. {
  428. /**
  429. * Value of `state` prop when a `Runnable` has failed
  430. */
  431. STATE_FAILED: 'failed',
  432. /**
  433. * Value of `state` prop when a `Runnable` has passed
  434. */
  435. STATE_PASSED: 'passed'
  436. }
  437. );
  438. /**
  439. * Given `value`, return identity if truthy, otherwise create an "invalid exception" error and return that.
  440. * @param {*} [value] - Value to return, if present
  441. * @returns {*|Error} `value`, otherwise an `Error`
  442. * @private
  443. */
  444. Runnable.toValueOrError = function(value) {
  445. return (
  446. value ||
  447. createInvalidExceptionError(
  448. 'Runnable failed with falsy or undefined exception. Please throw an Error instead.',
  449. value
  450. )
  451. );
  452. };
  453. Runnable.constants = constants;