Debian Codegraph @

closure-library/closure/goog/object/object_test.js

raw
1 // Copyright 2006 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 goog.provide('goog.objectTest');
16 goog.setTestOnly('goog.objectTest');
17
18 goog.require('goog.array');
19 goog.require('goog.functions');
20 goog.require('goog.object');
21 goog.require('goog.testing.jsunit');
22 goog.require('goog.testing.recordFunction');
23
24 function stringifyObject(m) {
25 var keys = goog.object.getKeys(m);
26 var s = '';
27 for (var i = 0; i < keys.length; i++) {
28 s += keys[i] + goog.object.get(m, keys[i]);
29 }
30 return s;
31 }
32
33 function getObject() {
34 return {a: 0, b: 1, c: 2, d: 3};
35 }
36
37 function testKeys() {
38 var m = getObject();
39 assertEquals(
40 'getKeys, The keys should be a,b,c', 'a,b,c,d',
41 goog.object.getKeys(m).join(','));
42 }
43
44 function testValues() {
45 var m = getObject();
46 assertEquals(
47 'getValues, The values should be 0,1,2', '0,1,2,3',
48 goog.object.getValues(m).join(','));
49 }
50
51 function testGetAnyKey() {
52 var m = getObject();
53 assertTrue(
54 'getAnyKey, The key should be a,b,c or d', goog.object.getAnyKey(m) in m);
55 assertUndefined(
56 'getAnyKey, The key should be undefined', goog.object.getAnyKey({}));
57 }
58
59 function testGetAnyValue() {
60 var m = getObject();
61 assertTrue(
62 'getAnyValue, The value should be 0,1,2 or 3',
63 goog.object.containsValue(m, goog.object.getAnyValue(m)));
64 assertUndefined(
65 'getAnyValue, The value should be undefined',
66 goog.object.getAnyValue({}));
67 }
68
69 function testContainsKey() {
70 var m = getObject();
71 assertTrue(
72 "containsKey, Should contain the 'a' key",
73 goog.object.containsKey(m, 'a'));
74 assertFalse(
75 "containsKey, Should not contain the 'e' key",
76 goog.object.containsKey(m, 'e'));
77 }
78
79 function testContainsValue() {
80 var m = getObject();
81 assertTrue(
82 'containsValue, Should contain the value 0',
83 goog.object.containsValue(m, 0));
84 assertFalse(
85 'containsValue, Should not contain the value 4',
86 goog.object.containsValue(m, 4));
87 assertTrue('isEmpty, The map should not be empty', !goog.object.isEmpty(m));
88 }
89
90 function testFindKey() {
91 var dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4};
92 var key = goog.object.findKey(dict, function(v, k, d) {
93 assertEquals('valid 3rd argument', dict, d);
94 assertTrue('valid 1st argument', goog.object.containsValue(d, v));
95 assertTrue('valid 2nd argument', k in d);
96 return v % 3 == 0;
97 });
98 assertEquals('key "c" found', 'c', key);
99
100 var pred = function(value) { return value > 5; };
101 assertUndefined('no match', goog.object.findKey(dict, pred));
102 }
103
104 function testFindValue() {
105 var dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4};
106 var value = goog.object.findValue(dict, function(v, k, d) {
107 assertEquals('valid 3rd argument', dict, d);
108 assertTrue('valid 1st argument', goog.object.containsValue(d, v));
109 assertTrue('valid 2nd argument', k in d);
110 return k.toUpperCase() == 'C';
111 });
112 assertEquals('value 3 found', 3, value);
113
114 var pred = function(value, key) { return key > 'd'; };
115 assertUndefined('no match', goog.object.findValue(dict, pred));
116 }
117
118 function testClear() {
119 var m = getObject();
120 goog.object.clear(m);
121 assertTrue('cleared so it should be empty', goog.object.isEmpty(m));
122 assertFalse(
123 "cleared so it should not contain 'a' key",
124 goog.object.containsKey(m, 'a'));
125 }
126
127 function testClone() {
128 var m = getObject();
129 var m2 = goog.object.clone(m);
130 assertFalse('clone so it should not be empty', goog.object.isEmpty(m2));
131 assertTrue(
132 "clone so it should contain 'c' key", goog.object.containsKey(m2, 'c'));
133 }
134
135 function testUnsafeClonePrimitive() {
136 assertEquals(
137 'cloning a primitive should return an equal primitive', 5,
138 goog.object.unsafeClone(5));
139 }
140
141 function testUnsafeCloneObjectThatHasACloneMethod() {
142 var original = {
143 name: 'original',
144 clone: goog.functions.constant({name: 'clone'})
145 };
146
147 var clone = goog.object.unsafeClone(original);
148 assertEquals('original', original.name);
149 assertEquals('clone', clone.name);
150 }
151
152 function testUnsafeCloneObjectThatHasACloneNonMethod() {
153 var originalIndex = {red: [0, 4], clone: [1, 3, 5, 7], yellow: [2, 6]};
154
155 var clone = goog.object.unsafeClone(originalIndex);
156 assertArrayEquals([1, 3, 5, 7], originalIndex.clone);
157 assertArrayEquals([1, 3, 5, 7], clone.clone);
158 }
159
160 function testUnsafeCloneFlatObject() {
161 var original = {a: 1, b: 2, c: 3};
162 var clone = goog.object.unsafeClone(original);
163 assertNotEquals(original, clone);
164 assertObjectEquals(original, clone);
165 }
166
167 function testUnsafeCloneDeepObject() {
168 var original = {a: 1, b: {c: 2, d: 3}, e: {f: {g: 4, h: 5}}};
169 var clone = goog.object.unsafeClone(original);
170
171 assertNotEquals(original, clone);
172 assertNotEquals(original.b, clone.b);
173 assertNotEquals(original.e, clone.e);
174
175 assertEquals(1, clone.a);
176 assertEquals(2, clone.b.c);
177 assertEquals(3, clone.b.d);
178 assertEquals(4, clone.e.f.g);
179 assertEquals(5, clone.e.f.h);
180 }
181
182 function testUnsafeCloneFunctions() {
183 var original = {f: goog.functions.constant('hi')};
184 var clone = goog.object.unsafeClone(original);
185
186 assertNotEquals(original, clone);
187 assertEquals('hi', clone.f());
188 assertEquals(original.f, clone.f);
189 }
190
191 function testForEach() {
192 var m = getObject();
193 var s = '';
194 goog.object.forEach(m, function(val, key, m2) {
195 assertNotUndefined(key);
196 assertEquals(m, m2);
197 s += key + val;
198 });
199 assertEquals(s, 'a0b1c2d3');
200 }
201
202 function testFilter() {
203 var m = getObject();
204
205 var m2 = goog.object.filter(m, function(val, key, m3) {
206 assertNotUndefined(key);
207 assertEquals(m, m3);
208 return val > 1;
209 });
210 assertEquals(stringifyObject(m2), 'c2d3');
211 }
212
213
214 function testMap() {
215 var m = getObject();
216 var m2 = goog.object.map(m, function(val, key, m3) {
217 assertNotUndefined(key);
218 assertEquals(m, m3);
219 return val * val;
220 });
221 assertEquals(stringifyObject(m2), 'a0b1c4d9');
222 }
223
224 function testSome() {
225 var m = getObject();
226 var b = goog.object.some(m, function(val, key, m2) {
227 assertNotUndefined(key);
228 assertEquals(m, m2);
229 return val > 1;
230 });
231 assertTrue(b);
232 var b = goog.object.some(m, function(val, key, m2) {
233 assertNotUndefined(key);
234 assertEquals(m, m2);
235 return val > 100;
236 });
237 assertFalse(b);
238 }
239
240 function testEvery() {
241 var m = getObject();
242 var b = goog.object.every(m, function(val, key, m2) {
243 assertNotUndefined(key);
244 assertEquals(m, m2);
245 return val >= 0;
246 });
247 assertTrue(b);
248 b = goog.object.every(m, function(val, key, m2) {
249 assertNotUndefined(key);
250 assertEquals(m, m2);
251 return val > 1;
252 });
253 assertFalse(b);
254 }
255
256 function testContains() {
257 var m = getObject();
258 assertTrue(goog.object.contains(m, 3));
259 assertFalse(goog.object.contains(m, 4));
260 }
261
262 function testObjectProperties() {
263 var m = {};
264
265 goog.object.set(m, 'toString', 'once');
266 goog.object.set(m, 'valueOf', 'upon');
267 goog.object.set(m, 'eval', 'a');
268 goog.object.set(m, 'toSource', 'midnight');
269 goog.object.set(m, 'prototype', 'dreary');
270 goog.object.set(m, 'hasOwnProperty', 'dark');
271
272 assertEquals(goog.object.get(m, 'toString'), 'once');
273 assertEquals(goog.object.get(m, 'valueOf'), 'upon');
274 assertEquals(goog.object.get(m, 'eval'), 'a');
275 assertEquals(goog.object.get(m, 'toSource'), 'midnight');
276 assertEquals(goog.object.get(m, 'prototype'), 'dreary');
277 assertEquals(goog.object.get(m, 'hasOwnProperty'), 'dark');
278 }
279
280 function testSetDefault() {
281 var dict = {};
282 assertEquals(1, goog.object.setIfUndefined(dict, 'a', 1));
283 assertEquals(1, dict['a']);
284 assertEquals(1, goog.object.setIfUndefined(dict, 'a', 2));
285 assertEquals(1, dict['a']);
286 }
287
288 function createRecordedGetFoo() {
289 return goog.testing.recordFunction(goog.functions.constant('foo'));
290 }
291
292 function testSetWithReturnValueNotSet_KeyIsSet() {
293 var f = createRecordedGetFoo();
294 var obj = {};
295 obj['key'] = 'bar';
296 assertEquals('bar', goog.object.setWithReturnValueIfNotSet(obj, 'key', f));
297 f.assertCallCount(0);
298 }
299
300 function testSetWithReturnValueNotSet_KeyIsNotSet() {
301 var f = createRecordedGetFoo();
302 var obj = {};
303 assertEquals('foo', goog.object.setWithReturnValueIfNotSet(obj, 'key', f));
304 f.assertCallCount(1);
305 }
306
307 function testSetWithReturnValueNotSet_KeySetValueIsUndefined() {
308 var f = createRecordedGetFoo();
309 var obj = {};
310 obj['key'] = undefined;
311 assertEquals(
312 undefined, goog.object.setWithReturnValueIfNotSet(obj, 'key', f));
313 f.assertCallCount(0);
314 }
315
316 function testTranspose() {
317 var m = getObject();
318 var b = goog.object.transpose(m);
319 assertEquals('a', b[0]);
320 assertEquals('b', b[1]);
321 assertEquals('c', b[2]);
322 assertEquals('d', b[3]);
323 }
324
325 function testExtend() {
326 var o = {};
327 var o2 = {a: 0, b: 1};
328 goog.object.extend(o, o2);
329 assertEquals(0, o.a);
330 assertEquals(1, o.b);
331 assertTrue('a' in o);
332 assertTrue('b' in o);
333
334 o2 = {c: 2};
335 goog.object.extend(o, o2);
336 assertEquals(2, o.c);
337 assertTrue('c' in o);
338
339 o2 = {c: 3};
340 goog.object.extend(o, o2);
341 assertEquals(3, o.c);
342 assertTrue('c' in o);
343
344 o = {};
345 o2 = {c: 2};
346 var o3 = {c: 3};
347 goog.object.extend(o, o2, o3);
348 assertEquals(3, o.c);
349 assertTrue('c' in o);
350
351 o = {};
352 o2 = {a: 0, b: 1};
353 o3 = {c: 2, d: 3};
354 goog.object.extend(o, o2, o3);
355 assertEquals(0, o.a);
356 assertEquals(1, o.b);
357 assertEquals(2, o.c);
358 assertEquals(3, o.d);
359 assertTrue('a' in o);
360 assertTrue('b' in o);
361 assertTrue('c' in o);
362 assertTrue('d' in o);
363
364 o = {};
365 o2 = {
366 'constructor': 0,
367 'hasOwnProperty': 1,
368 'isPrototypeOf': 2,
369 'propertyIsEnumerable': 3,
370 'toLocaleString': 4,
371 'toString': 5,
372 'valueOf': 6
373 };
374 goog.object.extend(o, o2);
375 assertEquals(0, o['constructor']);
376 assertEquals(1, o['hasOwnProperty']);
377 assertEquals(2, o['isPrototypeOf']);
378 assertEquals(3, o['propertyIsEnumerable']);
379 assertEquals(4, o['toLocaleString']);
380 assertEquals(5, o['toString']);
381 assertEquals(6, o['valueOf']);
382 assertTrue('constructor' in o);
383 assertTrue('hasOwnProperty' in o);
384 assertTrue('isPrototypeOf' in o);
385 assertTrue('propertyIsEnumerable' in o);
386 assertTrue('toLocaleString' in o);
387 assertTrue('toString' in o);
388 assertTrue('valueOf' in o);
389 }
390
391 function testCreate() {
392 assertObjectEquals(
393 'With multiple arguments', {a: 0, b: 1},
394 goog.object.create('a', 0, 'b', 1));
395 assertObjectEquals(
396 'With an array argument', {a: 0, b: 1},
397 goog.object.create(['a', 0, 'b', 1]));
398
399 assertObjectEquals('With no arguments', {}, goog.object.create());
400 assertObjectEquals(
401 'With an ampty array argument', {}, goog.object.create([]));
402
403 assertThrows('Should throw due to uneven arguments', function() {
404 goog.object.create('a');
405 });
406 assertThrows('Should throw due to uneven arguments', function() {
407 goog.object.create('a', 0, 'b');
408 });
409 assertThrows('Should throw due to uneven length array', function() {
410 goog.object.create(['a']);
411 });
412 assertThrows('Should throw due to uneven length array', function() {
413 goog.object.create(['a', 0, 'b']);
414 });
415 }
416
417 function testCreateSet() {
418 assertObjectEquals(
419 'With multiple arguments', {a: true, b: true},
420 goog.object.createSet('a', 'b'));
421 assertObjectEquals(
422 'With an array argument', {a: true, b: true},
423 goog.object.createSet(['a', 'b']));
424
425 assertObjectEquals('With no arguments', {}, goog.object.createSet());
426 assertObjectEquals(
427 'With an ampty array argument', {}, goog.object.createSet([]));
428 }
429
430 function createTestDeepObject() {
431 var obj = {};
432 obj.a = {};
433 obj.a.b = {};
434 obj.a.b.c = {};
435 obj.a.b.c.fooArr = [5, 6, 7, 8];
436 obj.a.b.c.knownNull = null;
437 obj.knownEmptyString = '';
438 obj.knownSingleCharacterString = '1';
439
440 return obj;
441 }
442
443 function testGetValueByKeys() {
444 var obj = createTestDeepObject();
445 assertEquals(obj, goog.object.getValueByKeys(obj));
446 assertEquals(obj.a, goog.object.getValueByKeys(obj, 'a'));
447 assertEquals(obj.a.b, goog.object.getValueByKeys(obj, 'a', 'b'));
448 assertEquals(obj.a.b.c, goog.object.getValueByKeys(obj, 'a', 'b', 'c'));
449 assertEquals(
450 obj.a.b.c.d, goog.object.getValueByKeys(obj, 'a', 'b', 'c', 'd'));
451 assertEquals(8, goog.object.getValueByKeys(obj, 'a', 'b', 'c', 'fooArr', 3));
452 assertNull(goog.object.getValueByKeys(obj, 'a', 'b', 'c', 'knownNull'));
453 assertUndefined(
454 goog.object.getValueByKeys(obj, 'a', 'b', 'c', 'knownNull', 'd'));
455 assertUndefined(goog.object.getValueByKeys(obj, 'e', 'f', 'g'));
456 assertEquals(
457 0, goog.object.getValueByKeys(obj, 'knownEmptyString', 'length'));
458 assertEquals(
459 1,
460 goog.object.getValueByKeys(obj, 'knownSingleCharacterString', 'length'));
461 }
462
463 function testGetValueByKeysArraySyntax() {
464 var obj = createTestDeepObject();
465 assertEquals(obj, goog.object.getValueByKeys(obj, []));
466 assertEquals(obj.a, goog.object.getValueByKeys(obj, ['a']));
467
468 assertEquals(obj.a.b, goog.object.getValueByKeys(obj, ['a', 'b']));
469 assertEquals(obj.a.b.c, goog.object.getValueByKeys(obj, ['a', 'b', 'c']));
470 assertEquals(
471 obj.a.b.c.d, goog.object.getValueByKeys(obj, ['a', 'b', 'c', 'd']));
472 assertEquals(
473 8, goog.object.getValueByKeys(obj, ['a', 'b', 'c', 'fooArr', 3]));
474 assertNull(goog.object.getValueByKeys(obj, ['a', 'b', 'c', 'knownNull']));
475 assertUndefined(
476 goog.object.getValueByKeys(obj, ['a', 'b', 'c', 'knownNull', 'd']));
477 assertUndefined(goog.object.getValueByKeys(obj, 'e', 'f', 'g'));
478 }
479
480 function testImmutableView() {
481 if (!Object.isFrozen) {
482 return;
483 }
484 var x = {propA: 3};
485 var y = goog.object.createImmutableView(x);
486 x.propA = 4;
487 x.propB = 6;
488 y.propA = 5;
489 y.propB = 7;
490 assertEquals(4, x.propA);
491 assertEquals(6, x.propB);
492 assertFalse(goog.object.isImmutableView(x));
493
494 assertEquals(4, y.propA);
495 assertEquals(6, y.propB);
496 assertTrue(goog.object.isImmutableView(y));
497
498 assertFalse('x and y should be different references', x == y);
499 assertTrue(
500 'createImmutableView should not create a new view of an immutable object',
501 y == goog.object.createImmutableView(y));
502 }
503
504 function testImmutableViewStrict() {
505 'use strict';
506
507 // IE9 supports isFrozen, but does not support strict mode. Exit early if we
508 // are not actually running in strict mode.
509 var isStrict = (function() { return !this; })();
510
511 if (!Object.isFrozen || !isStrict) {
512 return;
513 }
514 var x = {propA: 3};
515 var y = goog.object.createImmutableView(x);
516 assertThrows(function() { y.propA = 4; });
517 assertThrows(function() { y.propB = 4; });
518 }
519
520 function testEmptyObjectsAreEqual() {
521 assertTrue(goog.object.equals({}, {}));
522 }
523
524 function testObjectsWithDifferentKeysAreUnequal() {
525 assertFalse(goog.object.equals({'a': 1}, {'b': 1}));
526 }
527
528 function testObjectsWithDifferentValuesAreUnequal() {
529 assertFalse(goog.object.equals({'a': 1}, {'a': 2}));
530 }
531
532 function testObjectsWithSameKeysAndValuesAreEqual() {
533 assertTrue(goog.object.equals({'a': 1}, {'a': 1}));
534 }
535
536 function testObjectsWithSameKeysInDifferentOrderAreEqual() {
537 assertTrue(goog.object.equals({'a': 1, 'b': 2}, {'b': 2, 'a': 1}));
538 }
539
540 function testIs() {
541 var object = {};
542 assertTrue(goog.object.is(object, object));
543 assertFalse(goog.object.is(object, {}));
544
545 assertTrue(goog.object.is(NaN, NaN));
546 assertTrue(goog.object.is(0, 0));
547 assertTrue(goog.object.is(1, 1));
548 assertTrue(goog.object.is(-1, -1));
549 assertTrue(goog.object.is(123, 123));
550 assertFalse(goog.object.is(0, -0));
551 assertFalse(goog.object.is(-0, 0));
552 assertFalse(goog.object.is(0, 1));
553
554 assertTrue(goog.object.is(true, true));
555 assertTrue(goog.object.is(false, false));
556 assertFalse(goog.object.is(true, false));
557 assertFalse(goog.object.is(false, true));
558
559 assertTrue(goog.object.is('', ''));
560 assertTrue(goog.object.is('a', 'a'));
561 assertFalse(goog.object.is('', 'a'));
562 assertFalse(goog.object.is('a', ''));
563 assertFalse(goog.object.is('a', 'b'));
564
565 assertFalse(goog.object.is(true, 'true'));
566 assertFalse(goog.object.is('true', true));
567 assertFalse(goog.object.is(false, 'false'));
568 assertFalse(goog.object.is('false', false));
569 assertFalse(goog.object.is(0, '0'));
570 assertFalse(goog.object.is('0', 0));
571 }
572
573 function testGetAllPropertyNames_enumerableProperties() {
574 var obj = {a: function() {}, b: 'b', c: function(x) {}};
575 assertSameElements(['a', 'b', 'c'], goog.object.getAllPropertyNames(obj));
576 }
577
578 function testGetAllPropertyNames_nonEnumerableProperties() {
579 var obj = {};
580 try {
581 Object.defineProperty(obj, 'foo', {value: 'bar', enumerable: false});
582 } catch (ex) {
583 // IE8 doesn't allow Object.defineProperty on non-DOM elements.
584 if (ex.message == 'Object doesn\'t support this action') {
585 return;
586 }
587 }
588
589 var expected = goog.isDef(Object.getOwnPropertyNames) ? ['foo'] : [];
590 assertSameElements(expected, goog.object.getAllPropertyNames(obj));
591 }
592
593 function testGetAllPropertyNames_inheritedProperties() {
594 var parent = function() {};
595 parent.prototype.a = null;
596
597 var child = function() {};
598 goog.inherits(child, parent);
599 child.prototype.b = null;
600
601 var expected = ['a', 'b'];
602 if (goog.isDef(Object.getOwnPropertyNames)) {
603 expected.push('constructor');
604 }
605
606 assertSameElements(
607 expected, goog.object.getAllPropertyNames(child.prototype));
608 }
609
610 function testGetAllPropertyNames_es6ClassProperties() {
611 // Create an ES6 class via eval so we can bail out if it's a syntax error in
612 // browsers that don't support ES6 classes.
613 try {
614 eval(
615 'var Foo = class {' +
616 ' a() {}' +
617 '};' +
618 'Foo.prototype.b = null;' +
619 'var Bar = class extends Foo {' +
620 ' c() {}' +
621 ' static d() {}' +
622 '};');
623 } catch (e) {
624 if (e instanceof SyntaxError) {
625 return;
626 }
627 }
628
629 assertSameElements(
630 ['a', 'b', 'constructor'],
631 goog.object.getAllPropertyNames(Foo.prototype));
632 assertSameElements(
633 ['a', 'b', 'c', 'constructor'],
634 goog.object.getAllPropertyNames(Bar.prototype));
635
636 var expectedBarProperties = ['d', 'prototype', 'length', 'name'];
637
638 // Some versions of Firefox don't find the name property via
639 // getOwnPropertyNames.
640 if (!goog.array.contains(Object.getOwnPropertyNames(Bar), 'name')) {
641 goog.array.remove(expectedBarProperties, 'name');
642 }
643
644 assertSameElements(
645 expectedBarProperties, goog.object.getAllPropertyNames(Bar));
646 }
647
648 function testGetAllPropertyNames_includeObjectPrototype() {
649 var obj = {a: function() {}, b: 'b', c: function(x) {}};
650
651 // There's slightly different behavior depending on what APIs the browser
652 // under test supports.
653 var additionalProps = !!Object.getOwnPropertyNames ?
654 Object.getOwnPropertyNames(Object.prototype) :
655 [];
656 // __proto__ is a bit special and should be excluded from the result set.
657 goog.array.remove(additionalProps, '__proto__');
658
659 assertSameElements(
660 ['a', 'b', 'c'].concat(additionalProps),
661 goog.object.getAllPropertyNames(obj, true));
662 }
663
664 function testGetAllPropertyNames_includeFunctionPrototype() {
665 var obj = function() {};
666 obj.a = function() {};
667
668 // There's slightly different behavior depending on what APIs the browser
669 // under test supports.
670 var additionalProps = !!Object.getOwnPropertyNames ?
671 Object.getOwnPropertyNames(Function.prototype).concat(['prototype']) :
672 [];
673
674 var expectedElements = ['a'].concat(additionalProps);
675 goog.array.removeDuplicates(expectedElements);
676
677 assertSameElements(
678 expectedElements, goog.object.getAllPropertyNames(obj, false, true));
679 }