runnable.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. 'use strict';
  2. /**
  3. * Module dependencies.
  4. */
  5. var EventEmitter = require('events').EventEmitter;
  6. var JSON = require('json3');
  7. var Pending = require('./pending');
  8. var debug = require('debug')('mocha:runnable');
  9. var milliseconds = require('./ms');
  10. var utils = require('./utils');
  11. var create = require('lodash.create');
  12. /**
  13. * Save timer references to avoid Sinon interfering (see GH-237).
  14. */
  15. /* eslint-disable no-unused-vars, no-native-reassign */
  16. var Date = global.Date;
  17. var setTimeout = global.setTimeout;
  18. var setInterval = global.setInterval;
  19. var clearTimeout = global.clearTimeout;
  20. var clearInterval = global.clearInterval;
  21. /* eslint-enable no-unused-vars, no-native-reassign */
  22. /**
  23. * Object#toString().
  24. */
  25. var toString = Object.prototype.toString;
  26. /**
  27. * Expose `Runnable`.
  28. */
  29. module.exports = Runnable;
  30. /**
  31. * Initialize a new `Runnable` with the given `title` and callback `fn`.
  32. *
  33. * @param {String} title
  34. * @param {Function} fn
  35. * @api private
  36. * @param {string} title
  37. * @param {Function} fn
  38. */
  39. function Runnable (title, fn) {
  40. this.title = title;
  41. this.fn = fn;
  42. this.body = (fn || '').toString();
  43. this.async = fn && fn.length;
  44. this.sync = !this.async;
  45. this._timeout = 2000;
  46. this._slow = 75;
  47. this._enableTimeouts = true;
  48. this.timedOut = false;
  49. this._trace = new Error('done() called multiple times');
  50. this._retries = -1;
  51. this._currentRetry = 0;
  52. this.pending = false;
  53. }
  54. /**
  55. * Inherit from `EventEmitter.prototype`.
  56. */
  57. Runnable.prototype = create(EventEmitter.prototype, {
  58. constructor: Runnable
  59. });
  60. /**
  61. * Set & get timeout `ms`.
  62. *
  63. * @api private
  64. * @param {number|string} ms
  65. * @return {Runnable|number} ms or Runnable instance.
  66. */
  67. Runnable.prototype.timeout = function (ms) {
  68. if (!arguments.length) {
  69. return this._timeout;
  70. }
  71. // see #1652 for reasoning
  72. if (ms === 0 || ms > Math.pow(2, 31)) {
  73. this._enableTimeouts = false;
  74. }
  75. if (typeof ms === 'string') {
  76. ms = milliseconds(ms);
  77. }
  78. debug('timeout %d', ms);
  79. this._timeout = ms;
  80. if (this.timer) {
  81. this.resetTimeout();
  82. }
  83. return this;
  84. };
  85. /**
  86. * Set & get slow `ms`.
  87. *
  88. * @api private
  89. * @param {number|string} ms
  90. * @return {Runnable|number} ms or Runnable instance.
  91. */
  92. Runnable.prototype.slow = function (ms) {
  93. if (typeof ms === 'undefined') {
  94. return this._slow;
  95. }
  96. if (typeof ms === 'string') {
  97. ms = milliseconds(ms);
  98. }
  99. debug('timeout %d', ms);
  100. this._slow = ms;
  101. return this;
  102. };
  103. /**
  104. * Set and get whether timeout is `enabled`.
  105. *
  106. * @api private
  107. * @param {boolean} enabled
  108. * @return {Runnable|boolean} enabled or Runnable instance.
  109. */
  110. Runnable.prototype.enableTimeouts = function (enabled) {
  111. if (!arguments.length) {
  112. return this._enableTimeouts;
  113. }
  114. debug('enableTimeouts %s', enabled);
  115. this._enableTimeouts = enabled;
  116. return this;
  117. };
  118. /**
  119. * Halt and mark as pending.
  120. *
  121. * @api public
  122. */
  123. Runnable.prototype.skip = function () {
  124. throw new Pending('sync skip');
  125. };
  126. /**
  127. * Check if this runnable or its parent suite is marked as pending.
  128. *
  129. * @api private
  130. */
  131. Runnable.prototype.isPending = function () {
  132. return this.pending || (this.parent && this.parent.isPending());
  133. };
  134. /**
  135. * Set number of retries.
  136. *
  137. * @api private
  138. */
  139. Runnable.prototype.retries = function (n) {
  140. if (!arguments.length) {
  141. return this._retries;
  142. }
  143. this._retries = n;
  144. };
  145. /**
  146. * Get current retry
  147. *
  148. * @api private
  149. */
  150. Runnable.prototype.currentRetry = function (n) {
  151. if (!arguments.length) {
  152. return this._currentRetry;
  153. }
  154. this._currentRetry = n;
  155. };
  156. /**
  157. * Return the full title generated by recursively concatenating the parent's
  158. * full title.
  159. *
  160. * @api public
  161. * @return {string}
  162. */
  163. Runnable.prototype.fullTitle = function () {
  164. return this.parent.fullTitle() + ' ' + this.title;
  165. };
  166. /**
  167. * Clear the timeout.
  168. *
  169. * @api private
  170. */
  171. Runnable.prototype.clearTimeout = function () {
  172. clearTimeout(this.timer);
  173. };
  174. /**
  175. * Inspect the runnable void of private properties.
  176. *
  177. * @api private
  178. * @return {string}
  179. */
  180. Runnable.prototype.inspect = function () {
  181. return JSON.stringify(this, function (key, val) {
  182. if (key[0] === '_') {
  183. return;
  184. }
  185. if (key === 'parent') {
  186. return '#<Suite>';
  187. }
  188. if (key === 'ctx') {
  189. return '#<Context>';
  190. }
  191. return val;
  192. }, 2);
  193. };
  194. /**
  195. * Reset the timeout.
  196. *
  197. * @api private
  198. */
  199. Runnable.prototype.resetTimeout = function () {
  200. var self = this;
  201. var ms = this.timeout() || 1e9;
  202. if (!this._enableTimeouts) {
  203. return;
  204. }
  205. this.clearTimeout();
  206. this.timer = setTimeout(function () {
  207. if (!self._enableTimeouts) {
  208. return;
  209. }
  210. self.callback(new Error('Timeout of ' + ms +
  211. 'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.'));
  212. self.timedOut = true;
  213. }, ms);
  214. };
  215. /**
  216. * Whitelist a list of globals for this test run.
  217. *
  218. * @api private
  219. * @param {string[]} globals
  220. */
  221. Runnable.prototype.globals = function (globals) {
  222. if (!arguments.length) {
  223. return this._allowedGlobals;
  224. }
  225. this._allowedGlobals = globals;
  226. };
  227. /**
  228. * Run the test and invoke `fn(err)`.
  229. *
  230. * @param {Function} fn
  231. * @api private
  232. */
  233. Runnable.prototype.run = function (fn) {
  234. var self = this;
  235. var start = new Date();
  236. var ctx = this.ctx;
  237. var finished;
  238. var emitted;
  239. // Sometimes the ctx exists, but it is not runnable
  240. if (ctx && ctx.runnable) {
  241. ctx.runnable(this);
  242. }
  243. // called multiple times
  244. function multiple (err) {
  245. if (emitted) {
  246. return;
  247. }
  248. emitted = true;
  249. self.emit('error', err || new Error('done() called multiple times; stacktrace may be inaccurate'));
  250. }
  251. // finished
  252. function done (err) {
  253. var ms = self.timeout();
  254. if (self.timedOut) {
  255. return;
  256. }
  257. if (finished) {
  258. return multiple(err || self._trace);
  259. }
  260. self.clearTimeout();
  261. self.duration = new Date() - start;
  262. finished = true;
  263. if (!err && self.duration > ms && self._enableTimeouts) {
  264. err = new Error('Timeout of ' + ms +
  265. 'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.');
  266. }
  267. fn(err);
  268. }
  269. // for .resetTimeout()
  270. this.callback = done;
  271. // explicit async with `done` argument
  272. if (this.async) {
  273. this.resetTimeout();
  274. // allows skip() to be used in an explicit async context
  275. this.skip = function asyncSkip () {
  276. done(new Pending('async skip call'));
  277. // halt execution. the Runnable will be marked pending
  278. // by the previous call, and the uncaught handler will ignore
  279. // the failure.
  280. throw new Pending('async skip; aborting execution');
  281. };
  282. if (this.allowUncaught) {
  283. return callFnAsync(this.fn);
  284. }
  285. try {
  286. callFnAsync(this.fn);
  287. } catch (err) {
  288. emitted = true;
  289. done(utils.getError(err));
  290. }
  291. return;
  292. }
  293. if (this.allowUncaught) {
  294. callFn(this.fn);
  295. done();
  296. return;
  297. }
  298. // sync or promise-returning
  299. try {
  300. if (this.isPending()) {
  301. done();
  302. } else {
  303. callFn(this.fn);
  304. }
  305. } catch (err) {
  306. emitted = true;
  307. done(utils.getError(err));
  308. }
  309. function callFn (fn) {
  310. var result = fn.call(ctx);
  311. if (result && typeof result.then === 'function') {
  312. self.resetTimeout();
  313. result
  314. .then(function () {
  315. done();
  316. // Return null so libraries like bluebird do not warn about
  317. // subsequently constructed Promises.
  318. return null;
  319. },
  320. function (reason) {
  321. done(reason || new Error('Promise rejected with no or falsy reason'));
  322. });
  323. } else {
  324. if (self.asyncOnly) {
  325. return done(new Error('--async-only option in use without declaring `done()` or returning a promise'));
  326. }
  327. done();
  328. }
  329. }
  330. function callFnAsync (fn) {
  331. var result = fn.call(ctx, function (err) {
  332. if (err instanceof Error || toString.call(err) === '[object Error]') {
  333. return done(err);
  334. }
  335. if (err) {
  336. if (Object.prototype.toString.call(err) === '[object Object]') {
  337. return done(new Error('done() invoked with non-Error: ' +
  338. JSON.stringify(err)));
  339. }
  340. return done(new Error('done() invoked with non-Error: ' + err));
  341. }
  342. if (result && utils.isPromise(result)) {
  343. return done(new Error('Resolution method is overspecified. Specify a callback *or* return a Promise; not both.'));
  344. }
  345. done();
  346. });
  347. }
  348. };