Debian Codegraph @

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

raw
1 // Copyright 2007 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 Mock Clock implementation for working with setTimeout,
17 * setInterval, clearTimeout and clearInterval within unit tests.
18 *
19 * Derived from jsUnitMockTimeout.js, contributed to JsUnit by
20 * Pivotal Computer Systems, www.pivotalsf.com
21 *
22 */
23
24 goog.setTestOnly('goog.testing.MockClock');
25 goog.provide('goog.testing.MockClock');
26
27 goog.require('goog.Disposable');
28 /** @suppress {extraRequire} */
29 goog.require('goog.Promise');
30 goog.require('goog.Thenable');
31 goog.require('goog.async.run');
32 goog.require('goog.testing.PropertyReplacer');
33 goog.require('goog.testing.events');
34 goog.require('goog.testing.events.Event');
35
36
37
38 /**
39 * Class for unit testing code that uses setTimeout and clearTimeout.
40 *
41 * NOTE: If you are using MockClock to test code that makes use of
42 * goog.fx.Animation, then you must either:
43 *
44 * 1. Install and dispose of the MockClock in setUpPage() and tearDownPage()
45 * respectively (rather than setUp()/tearDown()).
46 *
47 * or
48 *
49 * 2. Ensure that every test clears the animation queue by calling
50 * mockClock.tick(x) at the end of each test function (where `x` is large
51 * enough to complete all animations).
52 *
53 * Otherwise, if any animation is left pending at the time that
54 * MockClock.dispose() is called, that will permanently prevent any future
55 * animations from playing on the page.
56 *
57 * @param {boolean=} opt_autoInstall Install the MockClock at construction time.
58 * @constructor
59 * @extends {goog.Disposable}
60 * @final
61 */
62 goog.testing.MockClock = function(opt_autoInstall) {
63 goog.Disposable.call(this);
64
65 /**
66 * Reverse-order queue of timers to fire.
67 *
68 * The last item of the queue is popped off. Insertion happens from the
69 * right. For example, the expiration times for each element of the queue
70 * might be in the order 300, 200, 200.
71 *
72 * @type {Array<Object>}
73 * @private
74 */
75 this.queue_ = [];
76
77 /**
78 * Set of timeouts that should be treated as cancelled.
79 *
80 * Rather than removing cancelled timers directly from the queue, this set
81 * simply marks them as deleted so that they can be ignored when their
82 * turn comes up. The keys are the timeout keys that are cancelled, each
83 * mapping to true.
84 *
85 * @private {Object<number, boolean>}
86 */
87 this.deletedKeys_ = {};
88
89 if (opt_autoInstall) {
90 this.install();
91 }
92 };
93 goog.inherits(goog.testing.MockClock, goog.Disposable);
94
95
96 /**
97 * Default wait timeout for mocking requestAnimationFrame (in milliseconds).
98 *
99 * @type {number}
100 * @const
101 */
102 goog.testing.MockClock.REQUEST_ANIMATION_FRAME_TIMEOUT = 20;
103
104
105 /**
106 * ID to use for next timeout. Timeout IDs must never be reused, even across
107 * MockClock instances.
108 * @public {number}
109 */
110 goog.testing.MockClock.nextId = Math.round(Math.random() * 10000);
111
112
113 /**
114 * Count of the number of setTimeout/setInterval/etc. calls received by this
115 * instance.
116 * @type {number}
117 * @private
118 */
119 goog.testing.MockClock.prototype.timeoutsMade_ = 0;
120
121
122 /**
123 * Count of the number of timeout/interval/etc. callbacks triggered by this
124 * instance.
125 * @type {number}
126 * @private
127 */
128 goog.testing.MockClock.prototype.callbacksTriggered_ = 0;
129
130
131 /**
132 * PropertyReplacer instance which overwrites and resets setTimeout,
133 * setInterval, etc. or null if the MockClock is not installed.
134 * @type {goog.testing.PropertyReplacer}
135 * @private
136 */
137 goog.testing.MockClock.prototype.replacer_ = null;
138
139
140 /**
141 * The current simulated time in milliseconds.
142 * @type {number}
143 * @private
144 */
145 goog.testing.MockClock.prototype.nowMillis_ = 0;
146
147
148 /**
149 * Additional delay between the time a timeout was set to fire, and the time
150 * it actually fires. Useful for testing workarounds for this Firefox 2 bug:
151 * https://bugzilla.mozilla.org/show_bug.cgi?id=291386
152 * May be negative.
153 * @type {number}
154 * @private
155 */
156 goog.testing.MockClock.prototype.timeoutDelay_ = 0;
157
158
159 /**
160 * The real set timeout for reference.
161 * @const @private {!Function}
162 */
163 goog.testing.MockClock.REAL_SETTIMEOUT_ = goog.global.setTimeout;
164
165
166 /**
167 * Installs the MockClock by overriding the global object's implementation of
168 * setTimeout, setInterval, clearTimeout and clearInterval.
169 */
170 goog.testing.MockClock.prototype.install = function() {
171 if (!this.replacer_) {
172 if (goog.testing.MockClock.REAL_SETTIMEOUT_ !== goog.global.setTimeout) {
173 if (typeof console !== 'undefined' && console.warn) {
174 console.warn(
175 'Non default setTimeout detected. ' +
176 'Use of multiple MockClock instances or other clock mocking ' +
177 'should be avoided due to unspecified behavior and ' +
178 'the resulting fragility.');
179 }
180 }
181
182 var r = this.replacer_ = new goog.testing.PropertyReplacer();
183 r.set(goog.global, 'setTimeout', goog.bind(this.setTimeout_, this));
184 r.set(goog.global, 'setInterval', goog.bind(this.setInterval_, this));
185 r.set(goog.global, 'setImmediate', goog.bind(this.setImmediate_, this));
186 r.set(goog.global, 'clearTimeout', goog.bind(this.clearTimeout_, this));
187 r.set(goog.global, 'clearInterval', goog.bind(this.clearInterval_, this));
188 // goog.Promise uses goog.async.run. In order to be able to test
189 // Promise-based code, we need to make sure that goog.async.run uses
190 // nextTick instead of native browser Promises. This means that it will
191 // default to setImmediate, which is replaced above. Note that we test for
192 // the presence of goog.async.run.forceNextTick to be resilient to the case
193 // where tests replace goog.async.run directly.
194 goog.async.run.forceNextTick &&
195 goog.async.run.forceNextTick(goog.testing.MockClock.REAL_SETTIMEOUT_);
196
197 // Replace the requestAnimationFrame functions.
198 this.replaceRequestAnimationFrame_();
199
200 // PropertyReplacer#set can't be called with renameable functions.
201 this.oldGoogNow_ = goog.now;
202 goog.now = goog.bind(this.getCurrentTime, this);
203 }
204 };
205
206
207 /**
208 * Installs the mocks for requestAnimationFrame and cancelRequestAnimationFrame.
209 * @private
210 */
211 goog.testing.MockClock.prototype.replaceRequestAnimationFrame_ = function() {
212 var r = this.replacer_;
213 var requestFuncs = [
214 'requestAnimationFrame', 'webkitRequestAnimationFrame',
215 'mozRequestAnimationFrame', 'oRequestAnimationFrame',
216 'msRequestAnimationFrame'
217 ];
218
219 var cancelFuncs = [
220 'cancelAnimationFrame', 'cancelRequestAnimationFrame',
221 'webkitCancelRequestAnimationFrame', 'mozCancelRequestAnimationFrame',
222 'oCancelRequestAnimationFrame', 'msCancelRequestAnimationFrame'
223 ];
224
225 for (var i = 0; i < requestFuncs.length; ++i) {
226 if (goog.global && goog.global[requestFuncs[i]]) {
227 r.set(
228 goog.global, requestFuncs[i],
229 goog.bind(this.requestAnimationFrame_, this));
230 }
231 }
232
233 for (var i = 0; i < cancelFuncs.length; ++i) {
234 if (goog.global && goog.global[cancelFuncs[i]]) {
235 r.set(
236 goog.global, cancelFuncs[i],
237 goog.bind(this.cancelRequestAnimationFrame_, this));
238 }
239 }
240 };
241
242
243 /**
244 * Removes the MockClock's hooks into the global object's functions and revert
245 * to their original values.
246 */
247 goog.testing.MockClock.prototype.uninstall = function() {
248 if (this.replacer_) {
249 this.replacer_.reset();
250 this.replacer_ = null;
251 goog.now = this.oldGoogNow_;
252 }
253
254 this.resetAsyncQueue_();
255 };
256
257
258 /** @override */
259 goog.testing.MockClock.prototype.disposeInternal = function() {
260 this.uninstall();
261 this.queue_ = null;
262 this.deletedKeys_ = null;
263 goog.testing.MockClock.superClass_.disposeInternal.call(this);
264 };
265
266
267 /**
268 * Resets the MockClock, removing all timeouts that are scheduled and resets
269 * the fake timer count.
270 */
271 goog.testing.MockClock.prototype.reset = function() {
272 this.queue_ = [];
273 this.deletedKeys_ = {};
274 this.nowMillis_ = 0;
275 this.timeoutsMade_ = 0;
276 this.callbacksTriggered_ = 0;
277 this.timeoutDelay_ = 0;
278
279 this.resetAsyncQueue_();
280 };
281
282
283 /**
284 * Resets the async queue when this clock resets.
285 * @private
286 */
287 goog.testing.MockClock.prototype.resetAsyncQueue_ = function() {
288 goog.async.run.resetQueue();
289 };
290
291
292 /**
293 * Sets the amount of time between when a timeout is scheduled to fire and when
294 * it actually fires.
295 * @param {number} delay The delay in milliseconds. May be negative.
296 */
297 goog.testing.MockClock.prototype.setTimeoutDelay = function(delay) {
298 this.timeoutDelay_ = delay;
299 };
300
301
302 /**
303 * @return {number} delay The amount of time between when a timeout is
304 * scheduled to fire and when it actually fires, in milliseconds. May
305 * be negative.
306 */
307 goog.testing.MockClock.prototype.getTimeoutDelay = function() {
308 return this.timeoutDelay_;
309 };
310
311
312 /**
313 * Increments the MockClock's time by a given number of milliseconds, running
314 * any functions that are now overdue.
315 * @param {number=} opt_millis Number of milliseconds to increment the counter.
316 * If not specified, clock ticks 1 millisecond.
317 * @return {number} Current mock time in milliseconds.
318 */
319 goog.testing.MockClock.prototype.tick = function(opt_millis) {
320 if (typeof opt_millis != 'number') {
321 opt_millis = 1;
322 }
323 var endTime = this.nowMillis_ + opt_millis;
324 this.runFunctionsWithinRange_(endTime);
325 this.nowMillis_ = endTime;
326 return endTime;
327 };
328
329
330 /**
331 * Takes a promise and then ticks the mock clock. If the promise successfully
332 * resolves, returns the value produced by the promise. If the promise is
333 * rejected, it throws the rejection as an exception. If the promise is not
334 * resolved at all, throws an exception.
335 * Also ticks the general clock by the specified amount.
336 * Only works with goog.Thenable, hence goog.Promise. Does NOT work with native
337 * browser promises.
338 *
339 * @param {!goog.Thenable<T>} promise A promise that should be resolved after
340 * the mockClock is ticked for the given opt_millis.
341 * @param {number=} opt_millis Number of milliseconds to increment the counter.
342 * If not specified, clock ticks 1 millisecond.
343 * @return {T}
344 * @template T
345 */
346 goog.testing.MockClock.prototype.tickPromise = function(promise, opt_millis) {
347 var value;
348 var error;
349 var resolved = false;
350 promise.then(
351 function(v) {
352 value = v;
353 resolved = true;
354 },
355 function(e) {
356 error = e;
357 resolved = true;
358 });
359 this.tick(opt_millis);
360 if (!resolved) {
361 throw new Error(
362 'Promise was expected to be resolved after mock clock tick.');
363 }
364 if (error) {
365 throw error;
366 }
367 return value;
368 };
369
370
371 /**
372 * @return {number} The number of timeouts or intervals that have been
373 * scheduled. A setInterval call is only counted once.
374 */
375 goog.testing.MockClock.prototype.getTimeoutsMade = function() {
376 return this.timeoutsMade_;
377 };
378
379
380 /**
381 * @return {number} The number of timeout or interval callbacks that have been
382 * triggered. For setInterval, each callback is counted separately.
383 */
384 goog.testing.MockClock.prototype.getCallbacksTriggered = function() {
385 return this.callbacksTriggered_;
386 };
387
388
389 /**
390 * @return {number} The MockClock's current time in milliseconds.
391 */
392 goog.testing.MockClock.prototype.getCurrentTime = function() {
393 return this.nowMillis_;
394 };
395
396
397 /**
398 * @param {number} timeoutKey The timeout key.
399 * @return {boolean} Whether the timer has been set and not cleared,
400 * independent of the timeout's expiration. In other words, the timeout
401 * could have passed or could be scheduled for the future. Either way,
402 * this function returns true or false depending only on whether the
403 * provided timeoutKey represents a timeout that has been set and not
404 * cleared.
405 */
406 goog.testing.MockClock.prototype.isTimeoutSet = function(timeoutKey) {
407 return timeoutKey < goog.testing.MockClock.nextId &&
408 timeoutKey >= goog.testing.MockClock.nextId - this.timeoutsMade_ &&
409 !this.deletedKeys_[timeoutKey];
410 };
411
412
413 /**
414 * Runs any function that is scheduled before a certain time. Timeouts can
415 * be made to fire early or late if timeoutDelay_ is non-0.
416 * @param {number} endTime The latest time in the range, in milliseconds.
417 * @private
418 */
419 goog.testing.MockClock.prototype.runFunctionsWithinRange_ = function(endTime) {
420 var adjustedEndTime = endTime - this.timeoutDelay_;
421
422 // Repeatedly pop off the last item since the queue is always sorted.
423 while (this.queue_ && this.queue_.length &&
424 this.queue_[this.queue_.length - 1].runAtMillis <= adjustedEndTime) {
425 var timeout = this.queue_.pop();
426
427 if (!(timeout.timeoutKey in this.deletedKeys_)) {
428 // Only move time forwards.
429 this.nowMillis_ =
430 Math.max(this.nowMillis_, timeout.runAtMillis + this.timeoutDelay_);
431 // Call timeout in global scope and pass the timeout key as the argument.
432 this.callbacksTriggered_++;
433 timeout.funcToCall.call(goog.global, timeout.timeoutKey);
434 // In case the interval was cleared in the funcToCall
435 if (timeout.recurring) {
436 this.scheduleFunction_(
437 timeout.timeoutKey, timeout.funcToCall, timeout.millis, true);
438 }
439 }
440 }
441 };
442
443
444 /**
445 * Schedules a function to be run at a certain time.
446 * @param {number} timeoutKey The timeout key.
447 * @param {Function} funcToCall The function to call.
448 * @param {number} millis The number of milliseconds to call it in.
449 * @param {boolean} recurring Whether to function call should recur.
450 * @private
451 */
452 goog.testing.MockClock.prototype.scheduleFunction_ = function(
453 timeoutKey, funcToCall, millis, recurring) {
454 if (!goog.isFunction(funcToCall)) {
455 // Early error for debuggability rather than dying in the next .tick()
456 throw new TypeError(
457 'The provided callback must be a function, not a ' + typeof funcToCall);
458 }
459
460 var timeout = {
461 runAtMillis: this.nowMillis_ + millis,
462 funcToCall: funcToCall,
463 recurring: recurring,
464 timeoutKey: timeoutKey,
465 millis: millis
466 };
467
468 goog.testing.MockClock.insert_(timeout, this.queue_);
469 };
470
471
472 /**
473 * Inserts a timer descriptor into a descending-order queue.
474 *
475 * Later-inserted duplicates appear at lower indices. For example, the
476 * asterisk in (5,4,*,3,2,1) would be the insertion point for 3.
477 *
478 * @param {Object} timeout The timeout to insert, with numerical runAtMillis
479 * property.
480 * @param {Array<Object>} queue The queue to insert into, with each element
481 * having a numerical runAtMillis property.
482 * @private
483 */
484 goog.testing.MockClock.insert_ = function(timeout, queue) {
485 // Although insertion of N items is quadratic, requiring goog.structs.Heap
486 // from a unit test will make tests more prone to breakage. Since unit
487 // tests are normally small, scalability is not a primary issue.
488
489 // Find an insertion point. Since the queue is in reverse order (so we
490 // can pop rather than unshift), and later timers with the same time stamp
491 // should be executed later, we look for the element strictly greater than
492 // the one we are inserting.
493
494 for (var i = queue.length; i != 0; i--) {
495 if (queue[i - 1].runAtMillis > timeout.runAtMillis) {
496 break;
497 }
498 queue[i] = queue[i - 1];
499 }
500
501 queue[i] = timeout;
502 };
503
504
505 /**
506 * Maximum 32-bit signed integer.
507 *
508 * Timeouts over this time return immediately in many browsers, due to integer
509 * overflow. Such known browsers include Firefox, Chrome, and Safari, but not
510 * IE.
511 *
512 * @type {number}
513 * @private
514 */
515 goog.testing.MockClock.MAX_INT_ = 2147483647;
516
517
518 /**
519 * Schedules a function to be called after {@code millis} milliseconds.
520 * Mock implementation for setTimeout.
521 * @param {Function} funcToCall The function to call.
522 * @param {number=} opt_millis The number of milliseconds to call it after.
523 * @return {number} The number of timeouts created.
524 * @private
525 */
526 goog.testing.MockClock.prototype.setTimeout_ = function(
527 funcToCall, opt_millis) {
528 var millis = opt_millis || 0;
529 if (millis > goog.testing.MockClock.MAX_INT_) {
530 throw new Error(
531 'Bad timeout value: ' + millis + '. Timeouts over MAX_INT ' +
532 '(24.8 days) cause timeouts to be fired ' +
533 'immediately in most browsers, except for IE.');
534 }
535 this.timeoutsMade_++;
536 this.scheduleFunction_(
537 goog.testing.MockClock.nextId, funcToCall, millis, false);
538 return goog.testing.MockClock.nextId++;
539 };
540
541
542 /**
543 * Schedules a function to be called every {@code millis} milliseconds.
544 * Mock implementation for setInterval.
545 * @param {Function} funcToCall The function to call.
546 * @param {number=} opt_millis The number of milliseconds between calls.
547 * @return {number} The number of timeouts created.
548 * @private
549 */
550 goog.testing.MockClock.prototype.setInterval_ = function(
551 funcToCall, opt_millis) {
552 var millis = opt_millis || 0;
553 this.timeoutsMade_++;
554 this.scheduleFunction_(
555 goog.testing.MockClock.nextId, funcToCall, millis, true);
556 return goog.testing.MockClock.nextId++;
557 };
558
559
560 /**
561 * Schedules a function to be called when an animation frame is triggered.
562 * Mock implementation for requestAnimationFrame.
563 * @param {Function} funcToCall The function to call.
564 * @return {number} The number of timeouts created.
565 * @private
566 */
567 goog.testing.MockClock.prototype.requestAnimationFrame_ = function(funcToCall) {
568 return this.setTimeout_(goog.bind(function() {
569 if (funcToCall) {
570 funcToCall(this.getCurrentTime());
571 } else if (goog.global.mozRequestAnimationFrame) {
572 var event = new goog.testing.events.Event('MozBeforePaint', goog.global);
573 event['timeStamp'] = this.getCurrentTime();
574 goog.testing.events.fireBrowserEvent(event);
575 }
576 }, this), goog.testing.MockClock.REQUEST_ANIMATION_FRAME_TIMEOUT);
577 };
578
579
580 /**
581 * Schedules a function to be called immediately after the current JS
582 * execution.
583 * Mock implementation for setImmediate.
584 * @param {Function} funcToCall The function to call.
585 * @return {number} The number of timeouts created.
586 * @private
587 */
588 goog.testing.MockClock.prototype.setImmediate_ = function(funcToCall) {
589 return this.setTimeout_(funcToCall, 0);
590 };
591
592
593 /**
594 * Clears a timeout.
595 * Mock implementation for clearTimeout.
596 * @param {number} timeoutKey The timeout key to clear.
597 * @private
598 */
599 goog.testing.MockClock.prototype.clearTimeout_ = function(timeoutKey) {
600 // Some common libraries register static state with timers.
601 // This is bad. It leads to all sorts of crazy test problems where
602 // 1) Test A sets up a new mock clock and a static timer.
603 // 2) Test B sets up a new mock clock, but re-uses the static timer
604 // from Test A.
605 // 3) A timeout key from test A gets cleared, breaking a timeout in
606 // Test B.
607 //
608 // For now, we just hackily fail silently if someone tries to clear a timeout
609 // key before we've allocated it.
610 // Ideally, we should throw an exception if we see this happening.
611 if (this.isTimeoutSet(timeoutKey)) {
612 this.deletedKeys_[timeoutKey] = true;
613 }
614 };
615
616
617 /**
618 * Clears an interval.
619 * Mock implementation for clearInterval.
620 * @param {number} timeoutKey The interval key to clear.
621 * @private
622 */
623 goog.testing.MockClock.prototype.clearInterval_ = function(timeoutKey) {
624 this.clearTimeout_(timeoutKey);
625 };
626
627
628 /**
629 * Clears a requestAnimationFrame.
630 * Mock implementation for cancelRequestAnimationFrame.
631 * @param {number} timeoutKey The requestAnimationFrame key to clear.
632 * @private
633 */
634 goog.testing.MockClock.prototype.cancelRequestAnimationFrame_ = function(
635 timeoutKey) {
636 this.clearTimeout_(timeoutKey);
637 };