jstdasyncwrapper.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. // Copyright 2016 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview A utility for wrapping a JSTD test object so that any test
  16. * methods are receive a queue that is compatible with JSTD but supports the
  17. * JsUnit async API of returning a promise in the test method.
  18. *
  19. * To convert a JSTD object call convertToAsyncTestObj on it and run with the
  20. * JsUnit test runner.
  21. */
  22. goog.provide('goog.testing.JsTdAsyncWrapper');
  23. goog.require('goog.Promise');
  24. /**
  25. * @param {Function|string} callback
  26. * @param {number=} opt_delay
  27. * @param {...*} var_args
  28. * @return {number}
  29. * @private
  30. */
  31. goog.testing.JsTdAsyncWrapper.REAL_SET_TIMEOUT_FN_ = goog.global.setTimeout;
  32. /**
  33. * Calls a function after a specified timeout. This uses the original setTimeout
  34. * to be resilient to tests that override it.
  35. * @param {Function} fn The function to call.
  36. * @param {number} timeout Timeout time in ms.
  37. * @private
  38. */
  39. goog.testing.JsTdAsyncWrapper.REAL_SET_TIMEOUT_ = function(fn, timeout) {
  40. // Setting timeout into a variable is necessary to invoke the function in the
  41. // default global context. Inlining breaks chrome since it requires setTimeout
  42. // to be called with the global context, and IE8 doesn't support the call
  43. // method on setTimeout.
  44. var setTimeoutFn = goog.testing.JsTdAsyncWrapper.REAL_SET_TIMEOUT_FN_;
  45. setTimeoutFn(fn, timeout);
  46. };
  47. /**
  48. * Wraps an object's methods by passing in a Queue that is based on the JSTD
  49. * async API. The queue exposes a promise that resolves when the queue
  50. * completes. This promise can be used in JsUnit tests.
  51. * @param {!Object} original The original JSTD test object. The object should
  52. * contain methods such as testXyz or setUp.
  53. * @return {!Object} A object that has all test methods wrapped in a fake
  54. * testing queue.
  55. */
  56. goog.testing.JsTdAsyncWrapper.convertToAsyncTestObj = function(original) {
  57. // Wraps a call to a test function and passes an instance of a fake queue
  58. // into the test function.
  59. var queueWrapperFn = function(fn) {
  60. return function() {
  61. var queue = new goog.testing.JsTdAsyncWrapper.Queue(this);
  62. fn.call(this, queue);
  63. return queue.startExecuting();
  64. };
  65. };
  66. var newTestObj = {};
  67. for (var prop in original) {
  68. // If this is a test or tearDown/setUp method wrap the method with a queue
  69. if (prop.indexOf('test') == 0 || prop == 'setUp' || prop == 'tearDown') {
  70. newTestObj[prop] = queueWrapperFn(original[prop]);
  71. } else {
  72. newTestObj[prop] = original[prop];
  73. }
  74. }
  75. return newTestObj;
  76. };
  77. /**
  78. * A queue that mirrors the JSTD Async Queue api but exposes a promise that
  79. * resolves once the queue is complete for compatibility with JsUnit.
  80. * @param {!Object} testObj The test object containing all test methods. This
  81. * object is passed into queue callbacks as the "this" object.
  82. * @constructor
  83. * @final
  84. */
  85. goog.testing.JsTdAsyncWrapper.Queue = function(testObj) {
  86. /**
  87. * The queue steps.
  88. * @private {!Array<!goog.testing.JsTdAsyncWrapper.Step_>}
  89. */
  90. this.steps_ = [];
  91. /**
  92. * A delegate that is used within a defer call.
  93. * @private {?goog.testing.JsTdAsyncWrapper.Queue}
  94. */
  95. this.delegate_ = null;
  96. /**
  97. * thisArg that should be used by default for addCallback function calls.
  98. * @private {!Object}
  99. */
  100. this.testObj_ = testObj;
  101. };
  102. /**
  103. * @param {string|function(!goog.testing.JsTdAsyncWrapper.Pool_=)} stepName
  104. * The name of the current testing step, or the fn parameter if
  105. * no stepName is desired.
  106. * @param {function(!goog.testing.JsTdAsyncWrapper.Pool_=)=} opt_fn A function
  107. * that will be called.
  108. */
  109. goog.testing.JsTdAsyncWrapper.Queue.prototype.defer = function(
  110. stepName, opt_fn) {
  111. var fn = opt_fn;
  112. if (!opt_fn && typeof stepName == 'function') {
  113. fn = stepName;
  114. stepName = '(Not named)';
  115. }
  116. // If another queue.defer is called within a pool callback it should be
  117. // executed after the current one. Any defer that is called within a defer
  118. // will be passed to a delegate and the current defer waits till all delegate
  119. // defer are resolved.
  120. if (this.delegate_) {
  121. this.delegate_.defer(stepName, fn);
  122. return;
  123. }
  124. this.steps_.push(new goog.testing.JsTdAsyncWrapper.Step_(
  125. /** @type {string} */ (stepName),
  126. /** @type {function(!goog.testing.JsTdAsyncWrapper.Pool_=)} */ (fn)));
  127. };
  128. /**
  129. * Starts the execution.
  130. * @return {!goog.Promise<void>}
  131. */
  132. goog.testing.JsTdAsyncWrapper.Queue.prototype.startExecuting = function() {
  133. return new goog.Promise(goog.bind(function(resolve, reject) {
  134. this.executeNextStep_(resolve, reject);
  135. }, this));
  136. };
  137. /**
  138. * Executes the next step on the queue waiting for all pool callbacks and then
  139. * starts executing any delegate queues before it finishes.
  140. * @param {function()} callback
  141. * @param {function(*)} errback
  142. * @private
  143. */
  144. goog.testing.JsTdAsyncWrapper.Queue.prototype.executeNextStep_ = function(
  145. callback, errback) {
  146. // Note: From this point on, we can no longer use goog.Promise (which uses
  147. // the goog.async.run queue) because it conflicts with MockClock, and we can't
  148. // use the native Promise because it is not supported on IE. So we revert to
  149. // using callbacks and setTimeout.
  150. if (!this.steps_.length) {
  151. callback();
  152. return;
  153. }
  154. var step = this.steps_.shift();
  155. this.delegate_ = new goog.testing.JsTdAsyncWrapper.Queue(this.testObj_);
  156. var pool = new goog.testing.JsTdAsyncWrapper.Pool_(
  157. this.testObj_, goog.bind(function() {
  158. goog.testing.JsTdAsyncWrapper.REAL_SET_TIMEOUT_(goog.bind(function() {
  159. this.executeDelegate_(callback, errback);
  160. }, this), 0);
  161. }, this), goog.bind(function(reason) {
  162. this.handleError_(errback, reason, step.name);
  163. }, this));
  164. try {
  165. step.fn.call(this.testObj_, pool);
  166. } catch (e) {
  167. this.handleError_(errback, e, step.name);
  168. }
  169. pool.maybeComplete();
  170. };
  171. /**
  172. * Execute the delegate queue.
  173. * @param {function()} callback
  174. * @param {function(*)} errback
  175. * @private
  176. */
  177. goog.testing.JsTdAsyncWrapper.Queue.prototype.executeDelegate_ = function(
  178. callback, errback) {
  179. // Wait till the delegate queue completes before moving on to the
  180. // next step.
  181. if (!this.delegate_) {
  182. this.executeNextStep_(callback, errback);
  183. return;
  184. }
  185. this.delegate_.executeNextStep_(goog.bind(function() {
  186. this.delegate_ = null;
  187. goog.testing.JsTdAsyncWrapper.REAL_SET_TIMEOUT_(goog.bind(function() {
  188. this.executeNextStep_(callback, errback);
  189. }, this), 0);
  190. }, this), errback);
  191. };
  192. /**
  193. * @param {function(*)} errback
  194. * @param {*} reason
  195. * @param {string} stepName
  196. * @private
  197. */
  198. goog.testing.JsTdAsyncWrapper.Queue.prototype.handleError_ = function(
  199. errback, reason, stepName) {
  200. var error = reason instanceof Error ? reason : Error(reason);
  201. error.message = 'In step ' + stepName + ', error: ' + error.message;
  202. errback(reason);
  203. };
  204. /**
  205. * A step to be executed.
  206. * @param {string} name
  207. * @param {function(!goog.testing.JsTdAsyncWrapper.Pool_=)} fn
  208. * @constructor
  209. * @private
  210. */
  211. goog.testing.JsTdAsyncWrapper.Step_ = function(name, fn) {
  212. /** @final {string} */
  213. this.name = name;
  214. /** @final {function(!goog.testing.JsTdAsyncWrapper.Pool_=)} */
  215. this.fn = fn;
  216. };
  217. /**
  218. * A fake pool that mimics the JSTD AsyncTestCase's pool object.
  219. * @param {!Object} testObj The test object containing all test methods. This
  220. * object is passed into queue callbacks as the "this" object.
  221. * @param {function()} callback
  222. * @param {function(*)} errback
  223. * @constructor
  224. * @private
  225. * @final
  226. */
  227. goog.testing.JsTdAsyncWrapper.Pool_ = function(testObj, callback, errback) {
  228. /** @private {number} */
  229. this.outstandingCallbacks_ = 0;
  230. /** @private {function()} */
  231. this.callback_ = callback;
  232. /** @private {function(*)} */
  233. this.errback_ = errback;
  234. /**
  235. * thisArg that should be used by default for defer function calls.
  236. * @private {!Object}
  237. */
  238. this.testObj_ = testObj;
  239. /** @private {boolean} */
  240. this.callbackCalled_ = false;
  241. };
  242. /**
  243. * @return {function()}
  244. */
  245. goog.testing.JsTdAsyncWrapper.Pool_.prototype.noop = function() {
  246. return this.addCallback(function() {});
  247. };
  248. /**
  249. * @param {function(...*):*} fn The function to add to the pool.
  250. * @param {?number=} opt_n The number of permitted uses of the given callback;
  251. * defaults to one.
  252. * @param {?number=} opt_timeout The timeout in milliseconds.
  253. * This is not supported in the adapter for now. Specifying this argument
  254. * will result in a test failure.
  255. * @param {?string=} opt_description The callback description.
  256. * @return {function()}
  257. */
  258. goog.testing.JsTdAsyncWrapper.Pool_.prototype.addCallback = function(
  259. fn, opt_n, opt_timeout, opt_description) {
  260. // TODO(mtragut): This could be fixed if required by test cases.
  261. if (opt_timeout || opt_description) {
  262. throw Error(
  263. 'Setting timeout or description in a pool callback is not supported.');
  264. }
  265. var numCallbacks = opt_n || 1;
  266. this.outstandingCallbacks_ = this.outstandingCallbacks_ + numCallbacks;
  267. return goog.bind(function() {
  268. try {
  269. fn.apply(this.testObj_, arguments);
  270. } catch (e) {
  271. if (opt_description) {
  272. e.message = opt_description + e.message;
  273. }
  274. this.errback_(e);
  275. }
  276. this.outstandingCallbacks_ = this.outstandingCallbacks_ - 1;
  277. this.maybeComplete();
  278. }, this);
  279. };
  280. /**
  281. * @param {function(...*):*} fn The function to add to the pool.
  282. * @param {?number=} opt_n The number of permitted uses of the given callback;
  283. * defaults to one.
  284. * @param {?number=} opt_timeout The timeout in milliseconds.
  285. * This is not supported in the adapter for now. Specifying this argument
  286. * will result in a test failure.
  287. * @param {?string=} opt_description The callback description.
  288. * @return {function()}
  289. */
  290. goog.testing.JsTdAsyncWrapper.Pool_.prototype.add =
  291. goog.testing.JsTdAsyncWrapper.Pool_.prototype.addCallback;
  292. /**
  293. * @param {string} msg The message to print if the error callback gets called.
  294. * @return {function()}
  295. */
  296. goog.testing.JsTdAsyncWrapper.Pool_.prototype.addErrback = function(msg) {
  297. return goog.bind(function() {
  298. var errorMsg = msg;
  299. if (arguments.length) {
  300. errorMsg += ' - Error callback called with params: ( ';
  301. for (var i = 0; i < arguments.length; i++) {
  302. var arg = arguments[i];
  303. errorMsg += arg + ' ';
  304. if (arg instanceof Error) {
  305. errorMsg += '\n' + arg.stack + '\n';
  306. }
  307. }
  308. errorMsg += ')';
  309. }
  310. this.errback_(errorMsg);
  311. }, this);
  312. };
  313. /**
  314. * Completes the pool if there are no outstanding callbacks.
  315. */
  316. goog.testing.JsTdAsyncWrapper.Pool_.prototype.maybeComplete = function() {
  317. if (this.outstandingCallbacks_ == 0 && !this.callbackCalled_) {
  318. this.callbackCalled_ = true;
  319. this.callback_();
  320. }
  321. };