Debian Codegraph @

closure-library/closure/goog/functions/functions_test.js

raw
1 // Copyright 2008 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 Unit tests for goog.functions.
17 */
18
19 goog.provide('goog.functionsTest');
20 goog.setTestOnly('goog.functionsTest');
21
22 goog.require('goog.array');
23 goog.require('goog.functions');
24 goog.require('goog.testing.MockClock');
25 goog.require('goog.testing.PropertyReplacer');
26 goog.require('goog.testing.jsunit');
27 goog.require('goog.testing.recordFunction');
28
29
30 var fTrue = makeCallOrderLogger('fTrue', true);
31 var gFalse = makeCallOrderLogger('gFalse', false);
32 var hTrue = makeCallOrderLogger('hTrue', true);
33
34 var stubs = new goog.testing.PropertyReplacer();
35
36 function setUp() {
37 callOrder = [];
38 }
39
40 function tearDown() {
41 stubs.reset();
42 }
43
44 var foo = 'global';
45 var obj = {foo: 'obj'};
46
47 function getFoo(arg1, arg2) {
48 return {foo: this.foo, arg1: arg1, arg2: arg2};
49 }
50
51 function testTrue() {
52 assertTrue(goog.functions.TRUE());
53 }
54
55 function testFalse() {
56 assertFalse(goog.functions.FALSE());
57 }
58
59 function testLock() {
60 function add(var_args) {
61 var result = 0;
62 for (var i = 0; i < arguments.length; i++) {
63 result += arguments[i];
64 }
65 return result;
66 }
67
68 assertEquals(6, add(1, 2, 3));
69 assertEquals(0, goog.functions.lock(add)(1, 2, 3));
70 assertEquals(3, goog.functions.lock(add, 2)(1, 2, 3));
71 assertEquals(6, goog.partial(add, 1, 2)(3));
72 assertEquals(3, goog.functions.lock(goog.partial(add, 1, 2))(3));
73 }
74
75 function testNth() {
76 assertEquals(1, goog.functions.nth(0)(1));
77 assertEquals(2, goog.functions.nth(1)(1, 2));
78 assertEquals('a', goog.functions.nth(0)('a', 'b'));
79 assertEquals(undefined, goog.functions.nth(0)());
80 assertEquals(undefined, goog.functions.nth(1)(true));
81 assertEquals(undefined, goog.functions.nth(-1)());
82 }
83
84 function testPartialRight() {
85 var f = function(x, y) { return x / y; };
86 var g = goog.functions.partialRight(f, 2);
87 assertEquals(2, g(4));
88
89 var h = goog.functions.partialRight(f, 4, 2);
90 assertEquals(2, h());
91
92 var i = goog.functions.partialRight(f);
93 assertEquals(2, i(4, 2));
94 }
95
96 function testPartialRightUsesGlobal() {
97 var f = function(x, y) {
98 assertEquals(goog.global, this);
99 return x / y;
100 };
101 var g = goog.functions.partialRight(f, 2);
102 var h = goog.functions.partialRight(g, 4);
103 assertEquals(2, h());
104 }
105
106 function testPartialRightWithCall() {
107 var obj = {};
108 var f = function(x, y) {
109 assertEquals(obj, this);
110 return x / y;
111 };
112 var g = goog.functions.partialRight(f, 2);
113 var h = goog.functions.partialRight(g, 4);
114 assertEquals(2, h.call(obj));
115 }
116
117 function testPartialRightAndBind() {
118 // This ensures that this "survives" through a partialRight.
119 var p = goog.functions.partialRight(getFoo, 'dog');
120 var b = goog.bind(p, obj, 'hot');
121
122 var res = b();
123 assertEquals(obj.foo, res.foo);
124 assertEquals('hot', res.arg1);
125 assertEquals('dog', res.arg2);
126 }
127
128 function testBindAndPartialRight() {
129 // This ensures that this "survives" through a partialRight.
130 var b = goog.bind(getFoo, obj, 'hot');
131 var p = goog.functions.partialRight(b, 'dog');
132
133 var res = p();
134 assertEquals(obj.foo, res.foo);
135 assertEquals('hot', res.arg1);
136 assertEquals('dog', res.arg2);
137 }
138
139 function testPartialRightMultipleCalls() {
140 var f = goog.testing.recordFunction();
141
142 var a = goog.functions.partialRight(f, 'foo');
143 var b = goog.functions.partialRight(a, 'bar');
144
145 a();
146 a();
147 b();
148 b();
149
150 assertEquals(4, f.getCallCount());
151
152 var calls = f.getCalls();
153 assertArrayEquals(['foo'], calls[0].getArguments());
154 assertArrayEquals(['foo'], calls[1].getArguments());
155 assertArrayEquals(['bar', 'foo'], calls[2].getArguments());
156 assertArrayEquals(['bar', 'foo'], calls[3].getArguments());
157 }
158
159 function testIdentity() {
160 assertEquals(3, goog.functions.identity(3));
161 assertEquals(3, goog.functions.identity(3, 4, 5, 6));
162 assertEquals('Hi there', goog.functions.identity('Hi there'));
163 assertEquals(null, goog.functions.identity(null));
164 assertEquals(undefined, goog.functions.identity());
165
166 var arr = [1, 'b', null];
167 assertEquals(arr, goog.functions.identity(arr));
168 var obj = {a: 'ay', b: 'bee', c: 'see'};
169 assertEquals(obj, goog.functions.identity(obj));
170 }
171
172 function testConstant() {
173 assertEquals(3, goog.functions.constant(3)());
174 assertEquals(undefined, goog.functions.constant()());
175 }
176
177 function testError() {
178 var f = goog.functions.error('x');
179 var e = assertThrows(
180 'A function created by goog.functions.error must throw an error', f);
181 assertEquals('x', e.message);
182 }
183
184 function testFail() {
185 var obj = {};
186 var f = goog.functions.fail(obj);
187 var e = assertThrows(
188 'A function created by goog.functions.raise must throw its input', f);
189 assertEquals(obj, e);
190 }
191
192 function testCompose() {
193 var add2 = function(x) { return x + 2; };
194
195 var doubleValue = function(x) { return x * 2; };
196
197 assertEquals(6, goog.functions.compose(doubleValue, add2)(1));
198 assertEquals(4, goog.functions.compose(add2, doubleValue)(1));
199 assertEquals(6, goog.functions.compose(add2, add2, doubleValue)(1));
200 assertEquals(
201 12, goog.functions.compose(doubleValue, add2, add2, doubleValue)(1));
202 assertUndefined(goog.functions.compose()(1));
203 assertEquals(3, goog.functions.compose(add2)(1));
204
205 var add2Numbers = function(x, y) { return x + y; };
206 assertEquals(17, goog.functions.compose(add2Numbers)(10, 7));
207 assertEquals(34, goog.functions.compose(doubleValue, add2Numbers)(10, 7));
208 }
209
210 function testAdd() {
211 assertUndefined(goog.functions.sequence()());
212 assertCallOrderAndReset([]);
213
214 assert(goog.functions.sequence(fTrue)());
215 assertCallOrderAndReset(['fTrue']);
216
217 assertFalse(goog.functions.sequence(fTrue, gFalse)());
218 assertCallOrderAndReset(['fTrue', 'gFalse']);
219
220 assert(goog.functions.sequence(fTrue, gFalse, hTrue)());
221 assertCallOrderAndReset(['fTrue', 'gFalse', 'hTrue']);
222
223 assert(goog.functions.sequence(goog.functions.identity)(true));
224 assertFalse(goog.functions.sequence(goog.functions.identity)(false));
225 }
226
227 function testAnd() {
228 // the return value is unspecified for an empty and
229 goog.functions.and()();
230 assertCallOrderAndReset([]);
231
232 assert(goog.functions.and(fTrue)());
233 assertCallOrderAndReset(['fTrue']);
234
235 assertFalse(goog.functions.and(fTrue, gFalse)());
236 assertCallOrderAndReset(['fTrue', 'gFalse']);
237
238 assertFalse(goog.functions.and(fTrue, gFalse, hTrue)());
239 assertCallOrderAndReset(['fTrue', 'gFalse']);
240
241 assert(goog.functions.and(goog.functions.identity)(true));
242 assertFalse(goog.functions.and(goog.functions.identity)(false));
243 }
244
245 function testOr() {
246 // the return value is unspecified for an empty or
247 goog.functions.or()();
248 assertCallOrderAndReset([]);
249
250 assert(goog.functions.or(fTrue)());
251 assertCallOrderAndReset(['fTrue']);
252
253 assert(goog.functions.or(fTrue, gFalse)());
254 assertCallOrderAndReset(['fTrue']);
255
256 assert(goog.functions.or(fTrue, gFalse, hTrue)());
257 assertCallOrderAndReset(['fTrue']);
258
259 assert(goog.functions.or(goog.functions.identity)(true));
260 assertFalse(goog.functions.or(goog.functions.identity)(false));
261 }
262
263 function testNot() {
264 assertTrue(goog.functions.not(gFalse)());
265 assertCallOrderAndReset(['gFalse']);
266
267 assertTrue(goog.functions.not(goog.functions.identity)(false));
268 assertFalse(goog.functions.not(goog.functions.identity)(true));
269
270 var f = function(a, b) {
271 assertEquals(1, a);
272 assertEquals(2, b);
273 return false;
274 };
275
276 assertTrue(goog.functions.not(f)(1, 2));
277 }
278
279 function testCreate(expectedArray) {
280 var tempConstructor = function(a, b) {
281 this.foo = a;
282 this.bar = b;
283 };
284
285 var factory = goog.partial(goog.functions.create, tempConstructor, 'baz');
286 var instance = factory('qux');
287
288 assert(instance instanceof tempConstructor);
289 assertEquals(instance.foo, 'baz');
290 assertEquals(instance.bar, 'qux');
291 }
292
293 function testWithReturnValue() {
294 var obj = {};
295 var f = function(a, b) {
296 assertEquals(obj, this);
297 assertEquals(1, a);
298 assertEquals(2, b);
299 };
300 assertTrue(goog.functions.withReturnValue(f, true).call(obj, 1, 2));
301 assertFalse(goog.functions.withReturnValue(f, false).call(obj, 1, 2));
302 }
303
304 function testEqualTo() {
305 assertTrue(goog.functions.equalTo(42)(42));
306 assertFalse(goog.functions.equalTo(42)(13));
307 assertFalse(goog.functions.equalTo(42)('a string'));
308
309 assertFalse(goog.functions.equalTo(42)('42'));
310 assertTrue(goog.functions.equalTo(42, true)('42'));
311
312 assertTrue(goog.functions.equalTo(0)(0));
313 assertFalse(goog.functions.equalTo(0)(''));
314 assertFalse(goog.functions.equalTo(0)(1));
315
316 assertTrue(goog.functions.equalTo(0, true)(0));
317 assertTrue(goog.functions.equalTo(0, true)(''));
318 assertFalse(goog.functions.equalTo(0, true)(1));
319 }
320
321 function makeCallOrderLogger(name, returnValue) {
322 return function() {
323 callOrder.push(name);
324 return returnValue;
325 };
326 }
327
328 function assertCallOrderAndReset(expectedArray) {
329 assertArrayEquals(expectedArray, callOrder);
330 callOrder = [];
331 }
332
333 function testCacheReturnValue() {
334 var returnFive = function() { return 5; };
335
336 var recordedReturnFive = goog.testing.recordFunction(returnFive);
337 var cachedRecordedReturnFive =
338 goog.functions.cacheReturnValue(recordedReturnFive);
339
340 assertEquals(0, recordedReturnFive.getCallCount());
341 assertEquals(5, cachedRecordedReturnFive());
342 assertEquals(1, recordedReturnFive.getCallCount());
343 assertEquals(5, cachedRecordedReturnFive());
344 assertEquals(1, recordedReturnFive.getCallCount());
345 }
346
347
348 function testCacheReturnValueFlagEnabled() {
349 var count = 0;
350 var returnIncrementingInteger = function() {
351 count++;
352 return count;
353 };
354
355 var recordedFunction = goog.testing.recordFunction(returnIncrementingInteger);
356 var cachedRecordedFunction =
357 goog.functions.cacheReturnValue(recordedFunction);
358
359 assertEquals(0, recordedFunction.getCallCount());
360 assertEquals(1, cachedRecordedFunction());
361 assertEquals(1, recordedFunction.getCallCount());
362 assertEquals(1, cachedRecordedFunction());
363 assertEquals(1, recordedFunction.getCallCount());
364 assertEquals(1, cachedRecordedFunction());
365 }
366
367
368 function testCacheReturnValueFlagDisabled() {
369 stubs.set(goog.functions, 'CACHE_RETURN_VALUE', false);
370
371 var count = 0;
372 var returnIncrementingInteger = function() {
373 count++;
374 return count;
375 };
376
377 var recordedFunction = goog.testing.recordFunction(returnIncrementingInteger);
378 var cachedRecordedFunction =
379 goog.functions.cacheReturnValue(recordedFunction);
380
381 assertEquals(0, recordedFunction.getCallCount());
382 assertEquals(1, cachedRecordedFunction());
383 assertEquals(1, recordedFunction.getCallCount());
384 assertEquals(2, cachedRecordedFunction());
385 assertEquals(2, recordedFunction.getCallCount());
386 assertEquals(3, cachedRecordedFunction());
387 }
388
389
390 function testOnce() {
391 var recordedFunction = goog.testing.recordFunction();
392 var f = goog.functions.once(recordedFunction);
393
394 assertEquals(0, recordedFunction.getCallCount());
395 f();
396 assertEquals(1, recordedFunction.getCallCount());
397 f();
398 assertEquals(1, recordedFunction.getCallCount());
399 }
400
401
402 function testDebounce() {
403 // Encoded sequences of commands to perform mapped to expected # of calls.
404 // f: fire
405 // w: wait (for the timer to elapse)
406 assertAsyncDecoratorCommandSequenceCalls(goog.functions.debounce, {
407 'f': 0,
408 'ff': 0,
409 'fff': 0,
410 'fw': 1,
411 'ffw': 1,
412 'fffw': 1,
413 'fwffwf': 2,
414 'ffwwwffwwfwf': 3
415 });
416 }
417
418
419 function testDebounceScopeBinding() {
420 var interval = 500;
421 var mockClock = new goog.testing.MockClock(true);
422
423 var x = {'y': 0};
424 goog.functions.debounce(function() { ++this['y']; }, interval, x)();
425 assertEquals(0, x['y']);
426
427 mockClock.tick(interval);
428 assertEquals(1, x['y']);
429
430 mockClock.uninstall();
431 }
432
433
434 function testDebounceArgumentBinding() {
435 var interval = 500;
436 var mockClock = new goog.testing.MockClock(true);
437
438 var calls = 0;
439 var debouncedFn = goog.functions.debounce(function(a, b, c) {
440 ++calls;
441 assertEquals(3, a);
442 assertEquals('string', b);
443 assertEquals(false, c);
444 }, interval);
445
446 debouncedFn(3, 'string', false);
447 mockClock.tick(interval);
448 assertEquals(1, calls);
449
450 // goog.functions.debounce should always pass the last arguments passed to the
451 // decorator into the decorated function, even if called multiple times.
452 debouncedFn();
453 mockClock.tick(interval / 2);
454 debouncedFn(8, null, true);
455 debouncedFn(3, 'string', false);
456 mockClock.tick(interval);
457 assertEquals(2, calls);
458
459 mockClock.uninstall();
460 }
461
462
463 function testDebounceArgumentAndScopeBinding() {
464 var interval = 500;
465 var mockClock = new goog.testing.MockClock(true);
466
467 var x = {'calls': 0};
468 var debouncedFn = goog.functions.debounce(function(a, b, c) {
469 ++this['calls'];
470 assertEquals(3, a);
471 assertEquals('string', b);
472 assertEquals(false, c);
473 }, interval, x);
474
475 debouncedFn(3, 'string', false);
476 mockClock.tick(interval);
477 assertEquals(1, x['calls']);
478
479 // goog.functions.debounce should always pass the last arguments passed to the
480 // decorator into the decorated function, even if called multiple times.
481 debouncedFn();
482 mockClock.tick(interval / 2);
483 debouncedFn(8, null, true);
484 debouncedFn(3, 'string', false);
485 mockClock.tick(interval);
486 assertEquals(2, x['calls']);
487
488 mockClock.uninstall();
489 }
490
491
492 function testThrottle() {
493 // Encoded sequences of commands to perform mapped to expected # of calls.
494 // f: fire
495 // w: wait (for the timer to elapse)
496 assertAsyncDecoratorCommandSequenceCalls(goog.functions.throttle, {
497 'f': 1,
498 'ff': 1,
499 'fff': 1,
500 'fw': 1,
501 'ffw': 2,
502 'fwf': 2,
503 'fffw': 2,
504 'fwfff': 2,
505 'fwfffw': 3,
506 'fwffwf': 3,
507 'ffwf': 2,
508 'ffwff': 2,
509 'ffwfw': 3,
510 'ffwffwf': 3,
511 'ffwffwff': 3,
512 'ffwffwffw': 4,
513 'ffwwwffwwfw': 5,
514 'ffwwwffwwfwf': 6
515 });
516 }
517
518
519 function testThrottleScopeBinding() {
520 var interval = 500;
521 var mockClock = new goog.testing.MockClock(true);
522
523 var x = {'y': 0};
524 goog.functions.throttle(function() { ++this['y']; }, interval, x)();
525 assertEquals(1, x['y']);
526
527 mockClock.uninstall();
528 }
529
530
531 function testThrottleArgumentBinding() {
532 var interval = 500;
533 var mockClock = new goog.testing.MockClock(true);
534
535 var calls = 0;
536 var throttledFn = goog.functions.throttle(function(a, b, c) {
537 ++calls;
538 assertEquals(3, a);
539 assertEquals('string', b);
540 assertEquals(false, c);
541 }, interval);
542
543 throttledFn(3, 'string', false);
544 assertEquals(1, calls);
545
546 // goog.functions.throttle should always pass the last arguments passed to the
547 // decorator into the decorated function, even if called multiple times.
548 throttledFn();
549 mockClock.tick(interval / 2);
550 throttledFn(8, null, true);
551 throttledFn(3, 'string', false);
552 mockClock.tick(interval);
553 assertEquals(2, calls);
554
555 mockClock.uninstall();
556 }
557
558
559 function testThrottleArgumentAndScopeBinding() {
560 var interval = 500;
561 var mockClock = new goog.testing.MockClock(true);
562
563 var x = {'calls': 0};
564 var throttledFn = goog.functions.throttle(function(a, b, c) {
565 ++this['calls'];
566 assertEquals(3, a);
567 assertEquals('string', b);
568 assertEquals(false, c);
569 }, interval, x);
570
571 throttledFn(3, 'string', false);
572 assertEquals(1, x['calls']);
573
574 // goog.functions.throttle should always pass the last arguments passed to the
575 // decorator into the decorated function, even if called multiple times.
576 throttledFn();
577 mockClock.tick(interval / 2);
578 throttledFn(8, null, true);
579 throttledFn(3, 'string', false);
580 mockClock.tick(interval);
581 assertEquals(2, x['calls']);
582
583 mockClock.uninstall();
584 }
585
586
587 function testRateLimit() {
588 // Encoded sequences of commands to perform mapped to expected # of calls.
589 // f: fire
590 // w: wait (for the timer to elapse)
591 assertAsyncDecoratorCommandSequenceCalls(goog.functions.rateLimit, {
592 'f': 1,
593 'ff': 1,
594 'fff': 1,
595 'fw': 1,
596 'ffw': 1,
597 'fwf': 2,
598 'fffw': 1,
599 'fwfff': 2,
600 'fwfffw': 2,
601 'fwffwf': 3,
602 'ffwf': 2,
603 'ffwff': 2,
604 'ffwfw': 2,
605 'ffwffwf': 3,
606 'ffwffwff': 3,
607 'ffwffwffw': 3,
608 'ffwwwffwwfw': 3,
609 'ffwwwffwwfwf': 4
610 });
611 }
612
613
614 function testRateLimitScopeBinding() {
615 var interval = 500;
616 var mockClock = new goog.testing.MockClock(true);
617
618 var x = {'y': 0};
619 goog.functions.rateLimit(function() {
620 ++this['y'];
621 }, interval, x)();
622 assertEquals(1, x['y']);
623
624 mockClock.uninstall();
625 }
626
627
628 function testRateLimitArgumentBinding() {
629 var interval = 500;
630 var mockClock = new goog.testing.MockClock(true);
631
632 var calls = 0;
633 var rateLimitedFn = goog.functions.rateLimit(function(a, b, c) {
634 ++calls;
635 assertEquals(3, a);
636 assertEquals('string', b);
637 assertEquals(false, c);
638 }, interval);
639
640 rateLimitedFn(3, 'string', false);
641 assertEquals(1, calls);
642
643 // goog.functions.rateLimit should always pass the first arguments passed to
644 // the
645 // decorator into the decorated function, even if called multiple times.
646 rateLimitedFn();
647 mockClock.tick(interval / 2);
648 rateLimitedFn(8, null, true);
649 mockClock.tick(interval);
650 rateLimitedFn(3, 'string', false);
651 assertEquals(2, calls);
652
653 mockClock.uninstall();
654 }
655
656
657 function testRateLimitArgumentAndScopeBinding() {
658 var interval = 500;
659 var mockClock = new goog.testing.MockClock(true);
660
661 var x = {'calls': 0};
662 var rateLimitedFn = goog.functions.rateLimit(function(a, b, c) {
663 ++this['calls'];
664 assertEquals(3, a);
665 assertEquals('string', b);
666 assertEquals(false, c);
667 }, interval, x);
668
669 rateLimitedFn(3, 'string', false);
670 assertEquals(1, x['calls']);
671
672 // goog.functions.rateLimit should always pass the last arguments passed to
673 // the
674 // decorator into the decorated function, even if called multiple times.
675 rateLimitedFn();
676 mockClock.tick(interval / 2);
677 rateLimitedFn(8, null, true);
678 mockClock.tick(interval);
679 rateLimitedFn(3, 'string', false);
680 assertEquals(2, x['calls']);
681
682 mockClock.uninstall();
683 }
684
685
686 /**
687 * Wraps a {@code goog.testing.recordFunction} with the specified decorator and
688 * executes a list of command sequences, asserting that in each case the
689 * decorated function is called the expected number of times.
690 * @param {function():*} decorator The async decorator to test.
691 * @param {!Object.<string, number>} expectedCommandSequenceCalls An object
692 * mapping string command sequences (where 'f' is 'fire' and 'w' is 'wait')
693 * to the number times we expect a decorated function to be called during
694 * the execution of those commands.
695 */
696 function assertAsyncDecoratorCommandSequenceCalls(
697 decorator, expectedCommandSequenceCalls) {
698 var interval = 500;
699
700 var mockClock = new goog.testing.MockClock(true);
701 for (var commandSequence in expectedCommandSequenceCalls) {
702 var recordedFunction = goog.testing.recordFunction();
703 var f = decorator(recordedFunction, interval);
704
705 for (var i = 0; i < commandSequence.length; ++i) {
706 switch (commandSequence[i]) {
707 case 'f':
708 f();
709 break;
710 case 'w':
711 mockClock.tick(interval);
712 break;
713 }
714 }
715
716 var expectedCalls = expectedCommandSequenceCalls[commandSequence];
717 assertEquals(
718 'Expected ' + expectedCalls + ' calls for command sequence "' +
719 commandSequence + '" (' +
720 goog.array
721 .map(
722 commandSequence,
723 function(command) {
724 switch (command) {
725 case 'f':
726 return 'fire';
727 case 'w':
728 return 'wait';
729 }
730 })
731 .join(' -> ') +
732 ')',
733 expectedCalls, recordedFunction.getCallCount());
734 }
735 mockClock.uninstall();
736 }