Debian Codegraph @

closure-library/closure/goog/testing/jstdasyncwrapper.js

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