1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
|
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for Closure's base.js.
*/
goog.provide('goog.baseTest');
goog.setTestOnly('goog.baseTest');
goog.require('goog.Promise');
// Used to test dynamic loading works, see testRequire*
goog.require('goog.Timer');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.object');
goog.require('goog.test_module');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.recordFunction');
goog.require('goog.userAgent');
var earlyTestModuleGet = goog.module.get('goog.test_module');
/**
* @param {?} name
* @return {?}
*/
function getFramedVars(name) {
var w = window.frames[name];
var doc = w.document;
doc.open();
doc.write(
'<script>' +
'var a = [0, 1, 2];' +
'var o = {a: 0, b: 1};' +
'var n = 42;' +
'var b = true;' +
'var s = "string";' +
'var nv = null;' +
'var u = undefined;' +
'var fv = function(){};' +
'</' +
'script>');
doc.close();
return {
'array': w.a,
'object': w.o,
'number': w.n,
'boolean': w.b,
'string': w.s,
'functionVar': w.fv,
'nullVar': w.nv,
'undefinedVar': w.u
};
}
var framedVars;
var framedVars2;
var stubs = new goog.testing.PropertyReplacer();
var originalGoogBind = goog.bind;
function setUpPage() {
framedVars = getFramedVars('f1');
framedVars2 = getFramedVars('f2');
// remove iframe
var iframeElement = document.getElementById('f2');
iframeElement.parentNode.removeChild(iframeElement);
}
function tearDown() {
goog.setCssNameMapping(undefined);
stubs.reset();
goog.bind = originalGoogBind;
}
function testLibrary() {
assertNotUndefined('\'goog\' not loaded', goog);
}
function testDefine() {
goog.define('SOME_DEFINE', 123); // overridden by 456
assertEquals(SOME_DEFINE, 456);
goog.define('SOME_OTHER_DEFINE', 123); // not overridden
assertEquals(SOME_OTHER_DEFINE, 123);
// alias to avoid the being picked up by the deps scanner.
var provide = goog.provide;
provide('ns');
goog.define('ns.SOME_DEFINE', 123); // overridden by 456
assertEquals(SOME_DEFINE, 456);
goog.define('ns.SOME_OTHER_DEFINE', 123); // not overridden
assertEquals(SOME_OTHER_DEFINE, 123);
}
function testProvide() {
// alias to avoid the being picked up by the deps scanner.
var provide = goog.provide;
provide('goog.test.name.space');
assertNotUndefined('provide failed: goog.test', goog.test);
assertNotUndefined('provide failed: goog.test.name', goog.test.name);
assertNotUndefined(
'provide failed: goog.test.name.space', goog.test.name.space);
// ensure that providing 'goog.test.name' doesn't throw an exception
provide('goog.test');
provide('goog.test.name');
delete goog.test;
}
// "watch" is a native member of Object.prototype on Firefox
// Ensure it can still be added as a namespace
function testProvideWatch() {
// alias to avoid the being picked up by the deps scanner.
var provide = goog.provide;
provide('goog.yoddle.watch');
assertNotUndefined('provide failed: goog.yoddle.watch', goog.yoddle.watch);
delete goog.yoddle;
}
// Namespaces should not conflict with elements added to the window based on
// their id
function testConflictingSymbolAndId() {
// Create a div with a given id
var divElement = document.createElement('div');
divElement.id = 'clashingname';
document.body.appendChild(divElement);
// The object at window.clashingname is the element with that id
assertEquals(window.clashingname, divElement);
// Export a symbol to a sub-namespace of that id
var symbolObject = {};
goog.exportSymbol('clashingname.symbolname', symbolObject);
// The symbol has been added...
assertEquals(window.clashingname.symbolname, symbolObject);
// ...and has not affected the original div
assertEquals(window.clashingname, divElement);
}
function testProvideStrictness() {
// alias to avoid the being picked up by the deps scanner.
var provide = goog.provide;
provide('goog.xy');
assertProvideFails('goog.xy');
provide('goog.xy.z');
assertProvideFails('goog.xy');
window['goog']['xyz'] = 'Bob';
assertProvideFails('goog.xyz');
delete goog.xy;
delete goog.xyz;
}
/** @param {?} namespace */
function assertProvideFails(namespace) {
assertThrows(
'goog.provide(' + namespace + ') should have failed',
goog.partial(goog.provide, namespace));
}
function testIsProvided() {
// alias to avoid the being picked up by the deps scanner.
var provide = goog.provide;
provide('goog.explicit');
assertTrue(goog.isProvided_('goog.explicit'));
provide('goog.implicit.explicit');
assertFalse(goog.isProvided_('goog.implicit'));
assertTrue(goog.isProvided_('goog.implicit.explicit'));
}
function testGlobalize() {
var a = {a: 1, b: 2, c: 3};
var b = {};
goog.globalize(a, b);
assertNotUndefined('Globalize to arbitrary object', b.a);
assertNotUndefined('Globalize to arbitrary object', b.b);
assertNotUndefined('Globalize to arbitrary object', b.c);
}
function testExportSymbol() {
var date = new Date();
// alias to avoid the being picked up by the deps scanner.
var provide = goog.provide;
assertTrue(typeof nodots == 'undefined');
goog.exportSymbol('nodots', date);
assertEquals(date, nodots);
nodots = undefined;
assertTrue(typeof gotcher == 'undefined');
goog.exportSymbol('gotcher.dots.right.Here', date);
assertEquals(date, gotcher.dots.right.Here);
gotcher = undefined;
provide('an.existing.path');
assertNotNull(an.existing.path);
goog.exportSymbol('an.existing.path', date);
assertEquals(date, an.existing.path);
an = undefined;
var foo = {foo: 'foo'};
var bar = {bar: 'bar'};
var baz = {baz: 'baz'};
goog.exportSymbol('one.two.three.Four', foo);
goog.exportSymbol('one.two.three.five', bar);
goog.exportSymbol('one.two.six', baz);
assertEquals(foo, one.two.three.Four);
assertEquals(bar, one.two.three.five);
assertEquals(baz, one.two.six);
var win = {};
var fooBar = {foo: 'foo', bar: 'bar'};
goog.exportSymbol('one.two.four', fooBar, win);
assertEquals(fooBar, win.one.two.four);
assertTrue('four' in win.one.two);
assertFalse('four' in one.two);
one = undefined;
}
goog.exportSymbol('exceptionTest', function() {
throw new Error('ERROR');
});
function testExportSymbolExceptions() {
var inner = function() {
// If exceptionTest wasn't exported using execScript, IE8 will throw "Object
// doesn't support this property or method" instead.
exceptionTest();
};
var e = assertThrows('Exception wasn\'t thrown by exported function', inner);
assertEquals('Unexpected error thrown', 'ERROR', e.message);
}
//=== tests for Require logic ===
function testRequireClosure() {
assertNotUndefined('goog.Timer should be available', goog.Timer);
/** @suppress {missingRequire} */
assertNotUndefined(
'goog.events.EventTarget should be available', goog.events.EventTarget);
}
function testRequireWithExternalDuplicate() {
// alias to avoid the being picked up by the deps scanner.
var provide = goog.provide;
// Do a provide without going via goog.require. Then goog.require it
// indirectly and ensure it doesn't cause a duplicate script.
goog.addDependency('dup.js', ['dup.base'], []);
goog.addDependency('dup-child.js', ['dup.base.child'], ['dup.base']);
provide('dup.base');
stubs.set(goog, 'isDocumentFinishedLoading_', false);
stubs.set(goog.global, 'CLOSURE_IMPORT_SCRIPT', function(src) {
if (src == goog.basePath + 'dup.js') {
fail('Duplicate script written!');
} else if (src == goog.basePath + 'dup-child.js') {
// Allow expected script.
return true;
} else {
// Avoid affecting other state.
return false;
}
});
// To differentiate this call from the real one.
var require = goog.require;
require('dup.base.child');
}
//=== tests for language enhancements ===
function testTypeOf() {
assertEquals('array', goog.typeOf([]));
assertEquals('string', goog.typeOf('string'));
assertEquals('number', goog.typeOf(123));
assertEquals('null', goog.typeOf(null));
assertEquals('undefined', goog.typeOf(undefined));
assertEquals('object', goog.typeOf({}));
assertEquals('function', goog.typeOf(function() {}));
// Make sure that NodeList is not treated as an array... NodeLists should
// be of type object but Safari incorrectly reports it as function so a not
// equals test will have to suffice here.
assertNotEquals('array', goog.typeOf(document.getElementsByName('*')));
assertNotEquals('function', goog.typeOf(document.getElementsByName('*')));
assertEquals('object', goog.typeOf(document.getElementsByName('*')));
}
function testTypeOfFramed() {
assertEquals('array', goog.typeOf(framedVars.array));
assertEquals('string', goog.typeOf(framedVars.string));
assertEquals('number', goog.typeOf(framedVars.number));
assertEquals('null', goog.typeOf(framedVars.nullVar));
assertEquals('undefined', goog.typeOf(framedVars.undefinedVar));
assertEquals('object', goog.typeOf(framedVars.object));
assertEquals('function', goog.typeOf(framedVars.functionVar));
// Opera throws when trying to do cross frame typeof on node lists.
// IE behaves very strange when it comes to DOM nodes on disconnected frames.
}
function testTypeOfFramed2() {
assertEquals('array', goog.typeOf(framedVars2.array));
assertEquals('string', goog.typeOf(framedVars2.string));
assertEquals('number', goog.typeOf(framedVars2.number));
assertEquals('null', goog.typeOf(framedVars2.nullVar));
assertEquals('undefined', goog.typeOf(framedVars2.undefinedVar));
assertEquals('object', goog.typeOf(framedVars2.object));
assertEquals('function', goog.typeOf(framedVars2.functionVar));
// Opera throws when trying to do cross frame typeof on node lists.
// IE behaves very strange when it comes to DOM nodes on disconnected frames.
}
function testIsDef() {
var defined = 'foo';
var nullVar = null;
var notDefined;
assertTrue('defined should be defined', goog.isDef(defined));
assertTrue('null should be defined', goog.isDef(nullVar));
assertFalse('undefined should not be defined', goog.isDef(notDefined));
}
function testIsDefAndNotNull() {
assertTrue('string is defined and non-null', goog.isDefAndNotNull(''));
assertTrue('object is defined and non-null', goog.isDefAndNotNull({}));
assertTrue(
'function is defined and non-null',
goog.isDefAndNotNull(goog.nullFunction));
assertTrue('zero is defined and non-null', goog.isDefAndNotNull(0));
assertFalse('null', goog.isDefAndNotNull(null));
assertFalse('undefined', goog.isDefAndNotNull(undefined));
}
function testIsNull() {
var notNull = 'foo';
var nullVar = null;
var notDefined;
assertFalse('defined should not be null', goog.isNull(notNull));
assertTrue('null should be null', goog.isNull(nullVar));
assertFalse('undefined should not be null', goog.isNull(notDefined));
}
function testIsArray() {
var array = [1, 2, 3];
var arrayWithLengthSet = [1, 2, 3];
arrayWithLengthSet.length = 2;
var objWithArrayFunctions = {slice: function() {}, length: 0};
var object = {a: 1, b: 2, c: 3};
var nullVar = null;
var notDefined;
var elem = document.getElementById('elem');
var text = document.getElementById('text').firstChild;
var impostor = document.body.getElementsByTagName('BOGUS');
impostor.push = Array.prototype.push;
impostor.pop = Array.prototype.pop;
impostor.slice = Array.prototype.slice;
impostor.splice = Array.prototype.splice;
assertTrue('array should be an array', goog.isArray(array));
assertTrue(
'arrayWithLengthSet should be an array',
goog.isArray(arrayWithLengthSet));
assertFalse(
'object with array functions should not be an array unless ' +
'length is not enumerable',
goog.isArray(objWithArrayFunctions));
assertFalse('object should not be an array', goog.isArray(object));
assertFalse('null should not be an array', goog.isArray(nullVar));
assertFalse('undefined should not be an array', goog.isArray(notDefined));
assertFalse('NodeList should not be an array', goog.isArray(elem.childNodes));
assertFalse('TextNode should not be an array', goog.isArray(text));
assertTrue(
'Array of nodes should be an array',
goog.isArray([elem.firstChild, elem.lastChild]));
assertFalse('An impostor should not be an array', goog.isArray(impostor));
}
function testTypeOfAcrossWindow() {
if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('10') &&
!goog.userAgent.isVersionOrHigher('11')) {
// TODO(johnlenz): This test is flaky on IE10 (passing 90+% of the time).
// When it flakes the values are undefined which appears to indicate the
// script did not run in the opened window and not a failure of the logic
// we are trying to test.
return;
}
var w = window.open('', 'blank');
if (w) {
try {
var d = w.document;
d.open();
d.write(
'<script>function fun(){};' +
'var arr = [];' +
'var x = 42;' +
'var s = "";' +
'var b = true;' +
'var obj = {length: 0, splice: {}, call: {}};' +
'</' +
'script>');
d.close();
assertEquals('function', goog.typeOf(w.fun));
assertEquals('array', goog.typeOf(w.arr));
assertEquals('number', goog.typeOf(w.x));
assertEquals('string', goog.typeOf(w.s));
assertEquals('boolean', goog.typeOf(w.b));
assertEquals('object', goog.typeOf(w.obj));
} finally {
w.close();
}
}
}
function testIsArrayLike() {
var array = [1, 2, 3];
var objectWithNumericLength = {length: 2};
var objectWithNonNumericLength = {length: 'a'};
var object = {a: 1, b: 2};
var nullVar = null;
var notDefined;
var elem = document.getElementById('elem');
var text = document.getElementById('text').firstChild;
assertTrue('array should be array-like', goog.isArrayLike(array));
assertTrue(
'obj w/numeric length should be array-like',
goog.isArrayLike(objectWithNumericLength));
assertFalse(
'obj w/non-numeric length should not be array-like',
goog.isArrayLike(objectWithNonNumericLength));
assertFalse('object should not be array-like', goog.isArrayLike(object));
assertFalse('null should not be array-like', goog.isArrayLike(nullVar));
assertFalse(
'undefined should not be array-like', goog.isArrayLike(notDefined));
assertTrue(
'NodeList should be array-like', goog.isArrayLike(elem.childNodes));
// TODO(attila): Fix isArrayLike to return false for text nodes!
// assertFalse('TextNode should not be array-like', goog.isArrayLike(text));
assertTrue(
'Array of nodes should be array-like',
goog.isArrayLike([elem.firstChild, elem.lastChild]));
}
/**
* Use mock date in testIsDateLike() rather than a real goog.date.Date to
* minimize dependencies in this unit test.
*/
function MockGoogDate() {}
/** @return {number} */
MockGoogDate.prototype.getFullYear = function() {
return 2007;
};
function testIsDateLike() {
var jsDate = new Date();
var googDate = new MockGoogDate();
var string = 'foo';
var number = 1;
var nullVar = null;
var notDefined;
assertTrue('js Date should be date-like', goog.isDateLike(jsDate));
assertTrue('goog Date should be date-like', goog.isDateLike(googDate));
assertFalse('string should not be date-like', goog.isDateLike(string));
assertFalse('number should not be date-like', goog.isDateLike(number));
assertFalse('nullVar should not be date-like', goog.isDateLike(nullVar));
assertFalse('undefined should not be date-like', goog.isDateLike(notDefined));
}
function testIsString() {
var string = 'foo';
var number = 2;
var nullVar = null;
var notDefined;
assertTrue('string should be a string', goog.isString(string));
assertFalse('number should not be a string', goog.isString(number));
assertFalse('null should not be a string', goog.isString(nullVar));
assertFalse('undefined should not be a string', goog.isString(notDefined));
}
function testIsBoolean() {
var b = true;
var s = 'true';
var num = 1;
var nullVar = null;
var notDefined;
assertTrue('boolean should be a boolean', goog.isBoolean(b));
assertFalse('string should not be a boolean', goog.isBoolean(s));
assertFalse('number should not be a boolean', goog.isBoolean(num));
assertFalse('null should not be a boolean', goog.isBoolean(nullVar));
assertFalse('undefined should not be a boolean', goog.isBoolean(notDefined));
}
function testIsNumber() {
var number = 1;
var string = '1';
var nullVar = null;
var notDefined;
assertTrue('number should be a number', goog.isNumber(number));
assertFalse('string should not be a number', goog.isNumber(string));
assertFalse('null should not be a number', goog.isNumber(nullVar));
assertFalse('undefined should not be a number', goog.isNumber(notDefined));
}
function testIsFunction() {
var func = function() {
return 1;
};
var object = {a: 1, b: 2};
var nullVar = null;
var notDefined;
assertTrue('function should be a function', goog.isFunction(func));
assertFalse('object should not be a function', goog.isFunction(object));
assertFalse('null should not be a function', goog.isFunction(nullVar));
assertFalse(
'undefined should not be a function', goog.isFunction(notDefined));
}
function testIsObject() {
var object = {a: 1, b: 2};
var string = 'b';
var nullVar = null;
var notDefined;
var array = [0, 1, 2];
var fun = function() {};
assertTrue('object should be an object', goog.isObject(object));
assertTrue('array should be an object', goog.isObject(array));
assertTrue('function should be an object', goog.isObject(fun));
assertFalse('string should not be an object', goog.isObject(string));
assertFalse('null should not be an object', goog.isObject(nullVar));
assertFalse('undefined should not be an object', goog.isObject(notDefined));
}
//=== tests for unique ID methods ===
function testGetUid() {
var a = {};
var b = {};
var c = {};
var uid1 = goog.getUid(a);
var uid2 = goog.getUid(b);
var uid3 = goog.getUid(c);
assertNotEquals('Unique IDs must be unique', uid1, uid2);
assertNotEquals('Unique IDs must be unique', uid1, uid3);
assertNotEquals('Unique IDs must be unique', uid2, uid3);
}
function testHasUid() {
var a = {};
assertFalse(goog.hasUid(a));
assertFalse(goog.UID_PROPERTY_ in a);
var uid = goog.getUid(a);
assertTrue(goog.hasUid(a));
assertEquals(uid, goog.getUid(a));
}
function testRemoveUidFromPlainObject() {
var a = {};
var uid = goog.getUid(a);
goog.removeUid(a);
assertNotEquals(
'An object\'s old and new unique IDs should be different', uid,
goog.getUid(a));
}
function testRemoveUidFromObjectWithoutUid() {
var a = {};
// Removing a unique ID should not fail even if it did not exist
goog.removeUid(a);
}
function testRemoveUidFromNode() {
var node = goog.dom.createElement(goog.dom.TagName.DIV);
var nodeUid = goog.getUid(node);
goog.removeUid(node);
assertNotEquals(
'A node\'s old and new unique IDs should be different', nodeUid,
goog.getUid(node));
}
function testConstructorUid() {
function BaseClass() {}
function SubClass() {}
goog.inherits(SubClass, BaseClass);
var baseClassUid = goog.getUid(BaseClass);
var subClassUid = goog.getUid(SubClass);
assertTrue(
'Unique ID of BaseClass must be a number',
typeof baseClassUid == 'number');
assertTrue(
'Unique ID of SubClass must be a number', typeof subClassUid == 'number');
assertNotEquals(
'Unique IDs of BaseClass and SubClass must differ', baseClassUid,
subClassUid);
assertNotEquals(
'Unique IDs of BaseClass and SubClass instances must differ',
goog.getUid(new BaseClass), goog.getUid(new SubClass));
assertEquals(
'Unique IDs of BaseClass.prototype and SubClass.prototype ' +
'should differ, but to keep the implementation simple, we do not ' +
'handle this edge case.',
goog.getUid(BaseClass.prototype), goog.getUid(SubClass.prototype));
}
/**
* Tests against Chrome bug where the re-created element will have the uid
* property set but undefined. See bug 1252508.
*/
function testUidNotUndefinedOnReusedElement() {
var div = goog.dom.createElement(goog.dom.TagName.DIV);
document.body.appendChild(div);
div.innerHTML = '<form id="form"></form>';
var span = goog.dom.getElementsByTagName(goog.dom.TagName.FORM, div)[0];
goog.getUid(span);
div.innerHTML = '<form id="form"></form>';
var span2 = goog.dom.getElementsByTagName(goog.dom.TagName.FORM, div)[0];
assertNotUndefined(goog.getUid(span2));
}
function testWindowUid() {
var uid = goog.getUid(window);
assertTrue('window unique id is a number', goog.isNumber(uid));
assertEquals('returns the same id second time', uid, goog.getUid(window));
goog.removeUid(window);
assertNotEquals(
'generates new id after the old one is removed', goog.getUid(window));
}
//=== tests for clone method ===
function testClonePrimitive() {
assertEquals(
'cloning a primitive should return an equal primitive', 5,
goog.cloneObject(5));
}
function testCloneObjectThatHasACloneMethod() {
var original = {
name: 'original',
clone: function() {
return {name: 'clone'};
}
};
var clone = goog.cloneObject(original);
assertEquals('original', original.name);
assertEquals('clone', clone.name);
}
function testCloneFlatObject() {
var original = {a: 1, b: 2, c: 3};
var clone = goog.cloneObject(original);
assertNotEquals(original, clone);
assertEquals(1, clone.a);
assertEquals(2, clone.b);
assertEquals(3, clone.c);
}
function testCloneDeepObject() {
var original = {a: 1, b: {c: 2, d: 3}, e: {f: {g: 4, h: 5}}};
var clone = goog.cloneObject(original);
assertNotEquals(original, clone);
assertNotEquals(original.b, clone.b);
assertNotEquals(original.e, clone.e);
assertEquals(1, clone.a);
assertEquals(2, clone.b.c);
assertEquals(3, clone.b.d);
assertEquals(4, clone.e.f.g);
assertEquals(5, clone.e.f.h);
}
function testCloneFunctions() {
var original = {
f: function() {
return 'hi';
}
};
var clone = goog.cloneObject(original);
assertNotEquals(original, clone);
assertEquals('hi', clone.f());
assertEquals(original.f, clone.f);
}
//=== tests for bind() and friends ===
// Function.prototype.bind and Function.prototype.partial are purposefullly
// not defined in open sourced Closure. These functions sniff for their
// presence.
var foo = 'global';
var obj = {foo: 'obj'};
/**
* @param {?} arg1
* @param {?} arg2
* @return {?}
*/
function getFoo(arg1, arg2) {
return {foo: this.foo, arg1: arg1, arg2: arg2};
}
function testBindWithoutObj() {
if (Function.prototype.bind) {
assertEquals(foo, getFoo.bind()().foo);
}
}
function testBindWithObj() {
if (Function.prototype.bind) {
assertEquals(obj.foo, getFoo.bind(obj)().foo);
}
}
function testBindWithNullObj() {
if (Function.prototype.bind) {
assertEquals(foo, getFoo.bind()().foo);
}
}
function testBindStaticArgs() {
if (Function.prototype.bind) {
var fooprime = getFoo.bind(obj, 'hot', 'dog');
var res = fooprime();
assertEquals(obj.foo, res.foo);
assertEquals('hot', res.arg1);
assertEquals('dog', res.arg2);
}
}
function testBindDynArgs() {
if (Function.prototype.bind) {
var res = getFoo.bind(obj)('hot', 'dog');
assertEquals(obj.foo, res.foo);
assertEquals('hot', res.arg1);
assertEquals('dog', res.arg2);
}
}
function testBindCurriedArgs() {
if (Function.prototype.bind) {
var res = getFoo.bind(obj, 'hot')('dog');
assertEquals(obj.foo, res.foo);
assertEquals('hot', res.arg1);
assertEquals('dog', res.arg2);
}
}
function testBindDoubleBind() {
var getFooP = goog.bind(getFoo, obj, 'hot');
var getFooP2 = goog.bind(getFooP, null, 'dog');
var res = getFooP2();
assertEquals('res.arg1 should be \'hot\'', 'hot', res.arg1);
assertEquals('res.arg2 should be \'dog\'', 'dog', res.arg2);
}
function testBindWithCall() {
var obj = {};
var obj2 = {};
var f = function() {
assertEquals('this should be bound to obj', obj, this);
};
var b = goog.bind(f, obj);
b.call(null);
b.call(obj2);
}
function testBindJs() {
assertEquals(1, goog.bindJs_(add, {
valueOf: function() {
return 1;
}
})());
assertEquals(3, goog.bindJs_(add, null, 1, 2)());
}
function testBindNative() {
if (Function.prototype.bind &&
Function.prototype.bind.toString().indexOf('native code') != -1) {
assertEquals(1, goog.bindNative_(add, {
valueOf: function() {
return 1;
}
})());
assertEquals(3, goog.bindNative_(add, null, 1, 2)());
assertThrows(function() {
goog.bindNative_(null, null);
});
}
}
function testBindDefault() {
assertEquals(1, goog.bind(add, {
valueOf: function() {
return 1;
}
})());
assertEquals(3, goog.bind(add, null, 1, 2)());
}
/**
* @param {...?} var_args
* @return {?}
*/
function add(var_args) {
var sum = Number(this) || 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
function testPartial() {
var f = function(x, y) {
return x + y;
};
var g = goog.partial(f, 1);
assertEquals(3, g(2));
var h = goog.partial(f, 1, 2);
assertEquals(3, h());
var i = goog.partial(f);
assertEquals(3, i(1, 2));
}
function testPartialUsesGlobal() {
var f = function(x, y) {
assertEquals(goog.global, this);
return x + y;
};
var g = goog.partial(f, 1);
var h = goog.partial(g, 2);
assertEquals(3, h());
}
function testPartialWithCall() {
var obj = {};
var f = function(x, y) {
assertEquals(obj, this);
return x + y;
};
var g = goog.partial(f, 1);
var h = goog.partial(g, 2);
assertEquals(3, h.call(obj));
}
function testPartialAndBind() {
// This ensures that this "survives" through a partial.
var p = goog.partial(getFoo, 'hot');
var b = goog.bind(p, obj, 'dog');
var res = b();
assertEquals(obj.foo, res.foo);
assertEquals('hot', res.arg1);
assertEquals('dog', res.arg2);
}
function testBindAndPartial() {
// This ensures that this "survives" through a partial.
var b = goog.bind(getFoo, obj, 'hot');
var p = goog.partial(b, 'dog');
var res = p();
assertEquals(obj.foo, res.foo);
assertEquals('hot', res.arg1);
assertEquals('dog', res.arg2);
}
function testPartialMultipleCalls() {
var f = goog.testing.recordFunction();
var a = goog.partial(f, 'foo');
var b = goog.partial(a, 'bar');
a();
a();
b();
b();
assertEquals(4, f.getCallCount());
var calls = f.getCalls();
assertArrayEquals(['foo'], calls[0].getArguments());
assertArrayEquals(['foo'], calls[1].getArguments());
assertArrayEquals(['foo', 'bar'], calls[2].getArguments());
assertArrayEquals(['foo', 'bar'], calls[3].getArguments());
}
function testGlobalEval() {
goog.globalEval('var foofoofoo = 125;');
assertEquals('Var should be globally assigned', 125, goog.global.foofoofoo);
var foofoofoo = 128;
assertEquals('Global should not have changed', 125, goog.global.foofoofoo);
// NOTE(user): foofoofoo would normally be available in the function scope,
// via the scope chain, but the JsUnit framework seems to do something weird
// which makes it not work.
}
function testGlobalEvalWithHtml() {
// Make sure we don't trip on HTML markup in the code
goog.global.evalTestResult = 'failed';
goog.global.evalTest = function(arg) {
goog.global.evalTestResult = arg;
};
goog.globalEval('evalTest("<test>")');
assertEquals(
'Should be able to evaluate strings with HTML in', '<test>',
goog.global.evalTestResult);
}
//=== tests for inherits ===
function testInherits() {
function Foo() {}
function Bar() {}
goog.inherits(Bar, Foo);
var bar = new Bar();
assert('object should be instance of constructor', bar instanceof Bar);
assert('object should be instance of base constructor', bar instanceof Foo);
}
function testInherits_constructor() {
function Foo() {}
function Bar() {}
goog.inherits(Bar, Foo);
var bar = new Bar();
assertEquals(
'constructor property should match constructor function', Bar,
bar.constructor);
assertEquals(
'Superclass constructor should match constructor function', Foo,
Bar.superClass_.constructor);
}
//=== tests for makeSingleton ===
function testMakeSingleton() {
function Foo() {}
goog.addSingletonGetter(Foo);
assertNotNull('Should add get instance function', Foo.getInstance);
var x = Foo.getInstance();
assertNotNull('Should successfully create an object', x);
var y = Foo.getInstance();
assertEquals('Should return the same object', x, y);
delete Foo.instance_;
var z = Foo.getInstance();
assertNotNull('Should work after clearing for testing', z);
assertNotEquals(
'Should return a different object after clearing for testing', x, z);
}
//=== tests for now ===
function testNow() {
var toleranceMilliseconds = 20; // 10 ms was not enough for IE7.
var now1 = new Date().getTime();
var now2 = goog.now();
assertTrue(Math.abs(now1 - now2) < toleranceMilliseconds);
}
//=== tests for getmsg ===
function testGetMsgWithDollarSigns() {
var msg = goog.getMsg('{$amount} per minute', {amount: '$0.15'});
assertEquals('$0.15 per minute', msg);
msg = goog.getMsg('{$amount} per minute', {amount: '$0.$1$5'});
assertEquals('$0.$1$5 per minute', msg);
msg = goog.getMsg('This is a {$rate} sale!', {rate: '$$$$$$$$$$10'});
assertEquals('This is a $$$$$$$$$$10 sale!', msg);
msg = goog.getMsg(
'{$name}! Hamburgers: {$hCost}, Hotdogs: {$dCost}.',
{name: 'Burger Bob', hCost: '$0.50', dCost: '$100'});
assertEquals('Burger Bob! Hamburgers: $0.50, Hotdogs: $100.', msg);
}
function testGetMsgWithPlaceholders() {
var msg = goog.getMsg('{$a} has {$b}', {a: '{$b}', b: 1});
assertEquals('{$b} has 1', msg);
msg = goog.getMsg('{$a}{$b}', {b: ''});
assertEquals('{$a}', msg);
}
//=== miscellaneous tests ===
function testGetObjectByName() {
var m = {
'undefined': undefined,
'null': null,
emptyString: '',
'false': false,
'true': true,
zero: 0,
one: 1,
two: {three: 3, four: {five: 5}},
'six|seven': '6|7',
'eight.nine': 8.9,
'': {b: 42},
};
goog.global.m = m;
assertNull(goog.getObjectByName('m.undefined'));
assertNull(goog.getObjectByName('m.null'));
assertEquals(goog.getObjectByName('m.emptyString'), '');
assertEquals(goog.getObjectByName('m.false'), false);
assertEquals(goog.getObjectByName('m.true'), true);
assertEquals(goog.getObjectByName('m.zero'), 0);
assertEquals(goog.getObjectByName('m.one'), 1);
assertEquals(goog.getObjectByName('m.two.three'), 3);
assertEquals(goog.getObjectByName('m.two.four.five'), 5);
assertEquals(goog.getObjectByName('m.six|seven'), '6|7');
assertNull(goog.getObjectByName('m.eight.nine'));
assertNull(goog.getObjectByName('m.notThere'));
assertEquals(goog.getObjectByName('one', m), 1);
assertEquals(goog.getObjectByName('two.three', m), 3);
assertEquals(goog.getObjectByName('two.four.five', m), 5);
assertEquals(goog.getObjectByName('six|seven', m), '6|7');
assertNull(goog.getObjectByName('eight.nine', m));
assertNull(goog.getObjectByName('notThere', m));
assertNull(goog.getObjectByName('./invalid', m));
assertEquals(goog.getObjectByName('.b', m), 42);
}
function testGetCssName() {
assertEquals('classname', goog.getCssName('classname'));
assertEquals('random-classname', goog.getCssName('random-classname'));
assertEquals('control-modifier', goog.getCssName('control', 'modifier'));
goog.setCssNameMapping({'goog': 'a', 'disabled': 'b'}, 'BY_PART');
var g = goog.getCssName('goog');
assertEquals('a', g);
assertEquals('a-b', goog.getCssName(g, 'disabled'));
assertEquals('a-b', goog.getCssName('goog-disabled'));
assertEquals('a-button', goog.getCssName('goog-button'));
goog.setCssNameMapping({'goog-button': 'a', 'active': 'b'}, 'BY_WHOLE');
g = goog.getCssName('goog-button');
assertEquals('a', g);
assertEquals('a-b', goog.getCssName(g, 'active'));
assertEquals('goog-disabled', goog.getCssName('goog-disabled'));
e = assertThrows(function() {
goog.getCssName('.name');
});
assertEquals(
'className passed in goog.getCssName must not start with ".".' +
' You passed: .name',
e.message);
assertNull(goog.getCssName(null));
}
function testGetCssName_nameMapFn() {
assertEquals('classname', goog.getCssName('classname'));
goog.global.CLOSURE_CSS_NAME_MAP_FN = function(classname) {
return classname + '!';
};
assertEquals('classname!', goog.getCssName('classname'));
}
function testBaseMethod() {
function A() {}
A.prototype.foo = function(x, y) {
return x + y;
};
function B() {}
goog.inherits(B, A);
B.prototype.foo = function(x, y) {
return 2 + goog.base(this, 'foo', x, y);
};
function C() {}
goog.inherits(C, B);
C.prototype.foo = function(x, y) {
return 4 + goog.base(this, 'foo', x, y);
};
var d = new C();
d.foo = function(x, y) {
return 8 + goog.base(this, 'foo', x, y);
};
assertEquals(15, d.foo(1, 0));
assertEquals(16, d.foo(1, 1));
assertEquals(16, d.foo(2, 0));
assertEquals(7, (new C()).foo(1, 0));
assertEquals(3, (new B()).foo(1, 0));
assertThrows(function() {
goog.base(d, 'foo', 1, 0);
});
delete B.prototype.foo;
assertEquals(13, d.foo(1, 0));
delete C.prototype.foo;
assertEquals(9, d.foo(1, 0));
}
function testBaseMethodAndBaseCtor() {
// This will fail on FF4.0 if the following bug is not fixed:
// https://bugzilla.mozilla.org/show_bug.cgi?id=586482
function A(x, y) {
this.foo(x, y);
}
A.prototype.foo = function(x, y) {
this.bar = x + y;
};
function B(x, y) {
goog.base(this, x, y);
}
goog.inherits(B, A);
B.prototype.foo = function(x, y) {
goog.base(this, 'foo', x, y);
this.bar = this.bar * 2;
};
assertEquals(14, new B(3, 4).bar);
}
function testBaseClass() {
function A(x, y) {
this.foo = x + y;
}
function B(x, y) {
goog.base(this, x, y);
this.foo += 2;
}
goog.inherits(B, A);
function C(x, y) {
goog.base(this, x, y);
this.foo += 4;
}
goog.inherits(C, B);
function D(x, y) {
goog.base(this, x, y);
this.foo += 8;
}
goog.inherits(D, C);
assertEquals(15, (new D(1, 0)).foo);
assertEquals(16, (new D(1, 1)).foo);
assertEquals(16, (new D(2, 0)).foo);
assertEquals(7, (new C(1, 0)).foo);
assertEquals(3, (new B(1, 0)).foo);
}
function testClassBaseOnMethod() {
function A() {}
A.prototype.foo = function(x, y) {
return x + y;
};
function B() {}
goog.inherits(B, A);
B.prototype.foo = function(x, y) {
return 2 + B.base(this, 'foo', x, y);
};
function C() {}
goog.inherits(C, B);
C.prototype.foo = function(x, y) {
return 4 + C.base(this, 'foo', x, y);
};
var d = new C();
assertEquals(7, d.foo(1, 0));
assertEquals(8, d.foo(1, 1));
assertEquals(8, d.foo(2, 0));
assertEquals(3, (new B()).foo(1, 0));
delete B.prototype.foo;
assertEquals(5, d.foo(1, 0));
delete C.prototype.foo;
assertEquals(1, d.foo(1, 0));
}
function testClassBaseOnConstructor() {
function A(x, y) {
this.foo = x + y;
}
function B(x, y) {
B.base(this, 'constructor', x, y);
this.foo += 2;
}
goog.inherits(B, A);
function C(x, y) {
C.base(this, 'constructor', x, y);
this.foo += 4;
}
goog.inherits(C, B);
function D(x, y) {
D.base(this, 'constructor', x, y);
this.foo += 8;
}
goog.inherits(D, C);
assertEquals(15, (new D(1, 0)).foo);
assertEquals(16, (new D(1, 1)).foo);
assertEquals(16, (new D(2, 0)).foo);
assertEquals(7, (new C(1, 0)).foo);
assertEquals(3, (new B(1, 0)).foo);
}
function testClassBaseOnMethodAndBaseCtor() {
function A(x, y) {
this.foo(x, y);
}
A.prototype.foo = function(x, y) {
this.bar = x + y;
};
function B(x, y) {
B.base(this, 'constructor', x, y);
}
goog.inherits(B, A);
B.prototype.foo = function(x, y) {
B.base(this, 'foo', x, y);
this.bar = this.bar * 2;
};
assertEquals(14, new B(3, 4).bar);
}
function testGoogRequireCheck() {
// alias to avoid the being picked up by the deps scanner.
var provide = goog.provide;
stubs.set(goog, 'ENABLE_DEBUG_LOADER', true);
stubs.set(goog, 'useStrictRequires', true);
stubs.set(goog, 'implicitNamespaces_', {});
// Aliased so that build tools do not mistake this for an actual call.
var require = goog.require;
assertThrows('Requiring non-required namespace should fail', function() {
require('far.outnotprovided');
});
assertUndefined(goog.global.far);
assertEvaluatesToFalse(goog.getObjectByName('far.out'));
assertObjectEquals({}, goog.implicitNamespaces_);
assertFalse(goog.isProvided_('far.out'));
provide('far.out');
assertNotUndefined(far.out);
assertEvaluatesToTrue(goog.getObjectByName('far.out'));
assertObjectEquals({'far': true}, goog.implicitNamespaces_);
assertTrue(goog.isProvided_('far.out'));
goog.global.far.out = 42;
assertEquals(42, goog.getObjectByName('far.out'));
assertTrue(goog.isProvided_('far.out'));
// Empty string should be allowed.
goog.global.far.out = '';
assertEquals('', goog.getObjectByName('far.out'));
assertTrue(goog.isProvided_('far.out'));
// Null or undefined are not allowed.
goog.global.far.out = null;
assertNull(goog.getObjectByName('far.out'));
assertFalse(goog.isProvided_('far.out'));
goog.global.far.out = undefined;
assertNull(goog.getObjectByName('far.out'));
assertFalse(goog.isProvided_('far.out'));
stubs.reset();
delete far;
}
/**
* @return {?}
*/
function diables_testCspSafeGoogRequire() {
if (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('10')) {
return;
}
stubs.set(goog, 'ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', true);
// Aliased so that build tools do not mistake this for an actual call.
var require = goog.require;
require('goog.Uri');
// Set a timeout to allow the user agent to finish parsing this script block,
// thus allowing the appended script (via goog.require) to execute.
var ASYNC_TIMEOUT_MS = 1000;
var resolver = goog.Promise.withResolver();
window.setTimeout(function() {
assertNotUndefined(goog.Uri);
resolver.resolve();
stubs.reset();
}, ASYNC_TIMEOUT_MS);
return resolver.promise;
}
function testDefineClass() {
var Base = goog.defineClass(null, {
constructor: function(foo) {
this.foo = foo;
},
statics: {x: 42},
frobnicate: function() {
return this.foo + this.foo;
}
});
var Derived = goog.defineClass(Base, {
constructor: function() {
Derived.base(this, 'constructor', 'bar');
},
frozzle: function(foo) {
this.foo = foo;
}
});
assertEquals(42, Base.x);
var der = new Derived();
assertEquals('barbar', der.frobnicate());
der.frozzle('qux');
assertEquals('quxqux', der.frobnicate());
}
function testDefineClass_interface() {
/** @interface */
var Interface =
goog.defineClass(null, {statics: {foo: 'bar'}, qux: function() {}});
assertEquals('bar', Interface.foo);
assertThrows(function() {
new Interface();
});
}
function testDefineClass_seals() {
if (!(Object.seal instanceof Function)) return; // IE<9 doesn't have seal
var A = goog.defineClass(null, {constructor: function() {}});
var a = new A();
try {
a.foo = 'bar';
} catch (expectedInStrictModeOnly) { /* ignored */
}
assertEquals(undefined, a.foo);
}
function testDefineClass_unsealable() {
var LegacyBase = function() {};
LegacyBase.prototype.foo = null;
LegacyBase.prototype.setFoo = function(foo) {
this.foo = foo;
};
goog.tagUnsealableClass(LegacyBase);
var Derived = goog.defineClass(LegacyBase, {constructor: function() {}});
var der = new Derived();
der.setFoo('bar');
assertEquals('bar', der.foo);
}
function testDefineClass_constructorIsNotWrappedWhenSealingIsDisabled() {
var org = goog.defineClass;
var ctr = null;
var replacement = function(superClass, def) {
ctr = def.constructor;
return org(superClass, def);
};
// copy all the properties
goog.object.extend(replacement, org);
replacement.SEAL_CLASS_INSTANCES = false;
stubs.replace(goog, 'defineClass', replacement);
var MyClass = goog.defineClass(null, {constructor: function() {}});
assertEquals('The constructor should not be wrapped.', ctr, MyClass);
}
function testDefineClass_unsealableConstructorIsWrapped() {
var LegacyBase = function() {};
LegacyBase.prototype.foo = null;
LegacyBase.prototype.setFoo = function(foo) {
this.foo = foo;
};
goog.tagUnsealableClass(LegacyBase);
var org = goog.defineClass;
var ctr = null;
var replacement = function(superClass, def) {
ctr = def.constructor;
return org(superClass, def);
};
// copy all the properties
goog.object.extend(replacement, org);
stubs.replace(goog, 'defineClass', replacement);
var Derived = goog.defineClass(LegacyBase, {constructor: function() {}});
assertNotEquals('The constructor should be wrapped.', ctr, Derived);
}
// Validate the behavior of goog.module when used from traditional files.
function testGoogModuleGet() {
// assert that goog.module doesn't modify the global namespace
assertUndefined(
'module failed to protect global namespace: ' +
'goog.test_module_dep',
goog.test_module_dep);
// assert that goog.module with goog.module.declareLegacyNamespace is present.
assertNotUndefined(
'module failed to declare global namespace: ' +
'goog.test_module',
goog.test_module);
// assert that a require'd goog.module is available immediately after the
// goog.require call.
assertNotUndefined(
'module failed to protect global namespace: ' +
'goog.test_module_dep',
earlyTestModuleGet);
// assert that an non-existent module request doesn't throw and returns null.
assertEquals(null, goog.module.get('unrequired.module.id'));
// Validate the module exports
var testModuleExports = goog.module.get('goog.test_module');
assertTrue(goog.isFunction(testModuleExports));
// Test that any escaping of </script> in test files is correct. Escape the
// / in </script> here so that any such code does not affect it here.
assertEquals('<\/script>', testModuleExports.CLOSING_SCRIPT_TAG);
// Validate that the module exports object has not changed
assertEquals(earlyTestModuleGet, testModuleExports);
}
function testModuleExportSealed() {
if (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9')) {
// IE before 9 don't support sealing objects
return;
}
goog.loadModule('goog.module("a.b.supplied"); exports.foo = {};');
var exports0 = goog.module.get('a.b.supplied');
assertTrue(Object.isSealed(exports0));
goog.loadModule('goog.module("a.b.object"); exports = {};');
var exports1 = goog.module.get('a.b.object');
assertTrue(Object.isSealed(exports1));
goog.loadModule('goog.module("a.b.fn"); exports = function() {};');
var exports2 = goog.module.get('a.b.fn');
assertFalse(Object.isSealed(exports2));
}
function testWorkaroundSafari10EvalBug0() {
// Validate the safari module loading workaround isn't triggered for
// browsers we know it isn't needed.
if (goog.userAgent.SAFARI) {
return;
}
assertFalse(goog.useSafari10Workaround());
}
function testWorkaroundSafari10EvalBug1() {
assertEquals(
'(function(){' + // no \n
'goog.module(\'foo\');\n' +
'\n;})();\n',
goog.workaroundSafari10EvalBug(
'goog.module(\'foo\');\n'));
}
function testWorkaroundSafari10EvalBug2() {
assertEquals(
'(function(){' + // no \n
'goog.module(\'foo\');\n' +
'alert("//# sourceMappingURL a.b.c.map")\n' +
'alert("//# sourceURL a.b.c.js")\n' +
'\n;})();\n',
goog.workaroundSafari10EvalBug(
'goog.module(\'foo\');\n' +
'alert("//# sourceMappingURL a.b.c.map")\n' +
'alert("//# sourceURL a.b.c.js")\n'));
}
function testGoogLoadModuleInSafari10() {
try {
eval('let es6 = 1');
} catch (e) {
// If ES6 block scope syntax isn't supported, don't run the rest of the
// test.
return;
}
goog.loadModule(
'goog.module("a.safari.test");' +
'let x = true;' +
'function fn() { return x }' +
'exports.fn = fn;');
var exports = goog.module.get('a.safari.test');
// Safari 10 will throw an exception if the module being loaded is eval'd
// without a containing function.
assertNotThrows(exports.fn);
}
function testLoadFileSync() {
var fileContents = goog.loadFileSync_('base.js');
assertTrue(
'goog.loadFileSync_ returns string', typeof fileContents === 'string');
assertTrue('goog.loadFileSync_ string length > 0', fileContents.length > 0);
stubs.set(goog.global, 'CLOSURE_LOAD_FILE_SYNC', function(src) {
return 'closure load file sync: ' + src;
});
assertEquals(
'goog.CLOSURE_LOAD_FILE_SYNC override', goog.loadFileSync_('test url'),
'closure load file sync: test url');
}
function testNormalizePath1() {
assertEquals('foo/path.js', goog.normalizePath_('./foo/./path.js'));
assertEquals('foo/path.js', goog.normalizePath_('bar/../foo/path.js'));
assertEquals('bar/path.js', goog.normalizePath_('bar/foo/../path.js'));
assertEquals('path.js', goog.normalizePath_('bar/foo/../../path.js'));
assertEquals('../foo/path.js', goog.normalizePath_('../foo/path.js'));
assertEquals('../../foo/path.js', goog.normalizePath_('../../foo/path.js'));
assertEquals('../path.js', goog.normalizePath_('../foo/../path.js'));
assertEquals('../../path.js', goog.normalizePath_('../foo/../../path.js'));
assertEquals('/../foo/path.js', goog.normalizePath_('/../foo/path.js'));
assertEquals('/path.js', goog.normalizePath_('/foo/../path.js'));
assertEquals('/foo/path.js', goog.normalizePath_('/./foo/path.js'));
assertEquals('//../foo/path.js', goog.normalizePath_('//../foo/path.js'));
assertEquals('//path.js', goog.normalizePath_('//foo/../path.js'));
assertEquals('//foo/path.js', goog.normalizePath_('//./foo/path.js'));
assertEquals('http://../x/y.js', goog.normalizePath_('http://../x/y.js'));
assertEquals('http://path.js', goog.normalizePath_('http://foo/../path.js'));
assertEquals('http://x/path.js', goog.normalizePath_('http://./x/path.js'));
}
function testGoogModuleNames() {
// avoid usage checks
var module = goog.module;
function assertInvalidId(id) {
var err = assertThrows(function() {
module(id);
});
assertEquals('Invalid module identifier', err.message);
}
function assertValidId(id) {
// This is a cheesy check, but we validate that we don't get an invalid
// namespace warning, but instead get a module isn't loaded correctly
// error.
var err = assertThrows(function() {
module(id);
});
assertTrue(err.message.indexOf('has been loaded incorrectly') != -1);
}
assertInvalidId('/somepath/module.js');
assertInvalidId('./module.js');
assertInvalidId('1');
assertValidId('a');
assertValidId('a.b');
assertValidId('a.b.c');
assertValidId('aB.Cd.eF');
assertValidId('a1.0E.Fg');
assertValidId('_');
assertValidId('$');
assertValidId('_$');
assertValidId('$_');
}
|