Debian Codegraph @

closure-library/closure/goog/string/string_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 /**
16 * @fileoverview Unit tests for goog.string.
17 */
18
19 /** @suppress {extraProvide} */
20 goog.provide('goog.stringTest');
21
22 goog.require('goog.dom');
23 goog.require('goog.dom.TagName');
24 goog.require('goog.functions');
25 goog.require('goog.object');
26 goog.require('goog.string');
27 goog.require('goog.string.Unicode');
28 goog.require('goog.testing.MockControl');
29 goog.require('goog.testing.PropertyReplacer');
30 goog.require('goog.testing.jsunit');
31
32 goog.setTestOnly('goog.stringTest');
33
34 var stubs;
35 var mockControl;
36
37 function setUp() {
38 stubs = new goog.testing.PropertyReplacer();
39 mockControl = new goog.testing.MockControl();
40 }
41
42 function tearDown() {
43 stubs.reset();
44 mockControl.$tearDown();
45 }
46
47
48 //=== tests for goog.string.collapseWhitespace ===
49
50 function testCollapseWhiteSpace() {
51 var f = goog.string.collapseWhitespace;
52
53 assertEquals('Leading spaces not stripped', f(' abc'), 'abc');
54 assertEquals('Trailing spaces not stripped', f('abc '), 'abc');
55 assertEquals('Wrapping spaces not stripped', f(' abc '), 'abc');
56
57 assertEquals(
58 'All white space chars not stripped', f('\xa0\n\t abc\xa0\n\t '), 'abc');
59
60 assertEquals('Spaces not collapsed', f('a b c'), 'a b c');
61
62 assertEquals('Tabs not collapsed', f('a\t\t\tb\tc'), 'a b c');
63
64 assertEquals(
65 'All check failed', f(' \ta \t \t\tb\t\n\xa0 c \t\n'), 'a b c');
66 }
67
68
69 function testIsEmpty() {
70 assertTrue(goog.string.isEmpty(''));
71 assertTrue(goog.string.isEmpty(' '));
72 assertTrue(goog.string.isEmpty(' '));
73 assertTrue(goog.string.isEmpty(' \t\t\n\xa0 '));
74
75 assertFalse(goog.string.isEmpty(' abc \t\xa0'));
76 assertFalse(goog.string.isEmpty(' a b c \t'));
77 assertFalse(goog.string.isEmpty(';'));
78
79 assertFalse(goog.string.isEmpty(undefined));
80 assertFalse(goog.string.isEmpty(null));
81 assertFalse(goog.string.isEmpty({a: 1, b: 2}));
82 }
83
84
85 function testIsEmptyOrWhitespace() {
86 assertTrue(goog.string.isEmptyOrWhitespace(''));
87 assertTrue(goog.string.isEmptyOrWhitespace(' '));
88 assertTrue(goog.string.isEmptyOrWhitespace(' '));
89 assertTrue(goog.string.isEmptyOrWhitespace(' \t\t\n\xa0 '));
90
91 assertFalse(goog.string.isEmptyOrWhitespace(' abc \t\xa0'));
92 assertFalse(goog.string.isEmptyOrWhitespace(' a b c \t'));
93 assertFalse(goog.string.isEmptyOrWhitespace(';'));
94
95 assertFalse(goog.string.isEmptyOrWhitespace(undefined));
96 assertFalse(goog.string.isEmptyOrWhitespace(null));
97 assertFalse(goog.string.isEmptyOrWhitespace({a: 1, b: 2}));
98 }
99
100
101 function testIsEmptyString() {
102 assertTrue(goog.string.isEmptyString(''));
103
104 assertFalse(goog.string.isEmptyString(' '));
105 assertFalse(goog.string.isEmptyString(' '));
106 assertFalse(goog.string.isEmptyString(' \t\t\n\xa0 '));
107 assertFalse(goog.string.isEmptyString(' abc \t\xa0'));
108 assertFalse(goog.string.isEmptyString(' a b c \t'));
109 assertFalse(goog.string.isEmptyString(';'));
110
111 assertFalse(goog.string.isEmptyString({a: 1, b: 2}));
112 }
113
114
115 function testIsEmptySafe() {
116 assertTrue(goog.string.isEmptySafe(''));
117 assertTrue(goog.string.isEmptySafe(' '));
118 assertTrue(goog.string.isEmptySafe(' '));
119 assertTrue(goog.string.isEmptySafe(' \t\t\n\xa0 '));
120
121 assertFalse(goog.string.isEmptySafe(' abc \t\xa0'));
122 assertFalse(goog.string.isEmptySafe(' a b c \t'));
123 assertFalse(goog.string.isEmptySafe(';'));
124
125 assertTrue(goog.string.isEmptySafe(undefined));
126 assertTrue(goog.string.isEmptySafe(null));
127 assertFalse(goog.string.isEmptySafe({a: 1, b: 2}));
128 }
129
130
131 function testIsEmptyOrWhitespaceSafe() {
132 assertTrue(goog.string.isEmptyOrWhitespaceSafe(''));
133 assertTrue(goog.string.isEmptyOrWhitespaceSafe(' '));
134 assertTrue(goog.string.isEmptyOrWhitespaceSafe(' '));
135 assertTrue(goog.string.isEmptyOrWhitespaceSafe(' \t\t\n\xa0 '));
136
137 assertFalse(goog.string.isEmptyOrWhitespaceSafe(' abc \t\xa0'));
138 assertFalse(goog.string.isEmptyOrWhitespaceSafe(' a b c \t'));
139 assertFalse(goog.string.isEmptyOrWhitespaceSafe(';'));
140
141 assertTrue(goog.string.isEmptyOrWhitespaceSafe(undefined));
142 assertTrue(goog.string.isEmptyOrWhitespaceSafe(null));
143 assertFalse(goog.string.isEmptyOrWhitespaceSafe({a: 1, b: 2}));
144 }
145
146
147 //=== tests for goog.string.isAlpha ===
148 function testIsAlpha() {
149 assertTrue('"a" should be alpha', goog.string.isAlpha('a'));
150 assertTrue('"n" should be alpha', goog.string.isAlpha('n'));
151 assertTrue('"z" should be alpha', goog.string.isAlpha('z'));
152 assertTrue('"A" should be alpha', goog.string.isAlpha('A'));
153 assertTrue('"N" should be alpha', goog.string.isAlpha('N'));
154 assertTrue('"Z" should be alpha', goog.string.isAlpha('Z'));
155 assertTrue('"aa" should be alpha', goog.string.isAlpha('aa'));
156 assertTrue('null is alpha', goog.string.isAlpha(null));
157 assertTrue('undefined is alpha', goog.string.isAlpha(undefined));
158
159 assertFalse('"aa!" is not alpha', goog.string.isAlpha('aa!s'));
160 assertFalse('"!" is not alpha', goog.string.isAlpha('!'));
161 assertFalse('"0" is not alpha', goog.string.isAlpha('0'));
162 assertFalse('"5" is not alpha', goog.string.isAlpha('5'));
163 }
164
165
166
167 //=== tests for goog.string.isNumeric ===
168 function testIsNumeric() {
169 assertTrue('"8" is a numeric string', goog.string.isNumeric('8'));
170 assertTrue('"5" is a numeric string', goog.string.isNumeric('5'));
171 assertTrue('"34" is a numeric string', goog.string.isNumeric('34'));
172 assertTrue('34 is a number', goog.string.isNumeric(34));
173
174 assertFalse('"3.14" has a period', goog.string.isNumeric('3.14'));
175 assertFalse('"A" is a letter', goog.string.isNumeric('A'));
176 assertFalse('"!" is punctuation', goog.string.isNumeric('!'));
177 assertFalse('null is not numeric', goog.string.isNumeric(null));
178 assertFalse('undefined is not numeric', goog.string.isNumeric(undefined));
179 }
180
181
182 //=== tests for tests for goog.string.isAlphaNumeric ===
183 function testIsAlphaNumeric() {
184 assertTrue(
185 '"ABCabc" should be alphanumeric', goog.string.isAlphaNumeric('ABCabc'));
186 assertTrue('"123" should be alphanumeric', goog.string.isAlphaNumeric('123'));
187 assertTrue(
188 '"ABCabc123" should be alphanumeric',
189 goog.string.isAlphaNumeric('ABCabc123'));
190 assertTrue('null is alphanumeric', goog.string.isAlphaNumeric(null));
191 assertTrue(
192 'undefined is alphanumeric', goog.string.isAlphaNumeric(undefined));
193
194 assertFalse(
195 '"123!" should not be alphanumeric', goog.string.isAlphaNumeric('123!'));
196 assertFalse(
197 '" " should not be alphanumeric', goog.string.isAlphaNumeric(' '));
198 }
199
200
201 //== tests for goog.string.isBreakingWhitespace ===
202
203 function testIsBreakingWhitespace() {
204 assertTrue('" " is breaking', goog.string.isBreakingWhitespace(' '));
205 assertTrue('"\\n" is breaking', goog.string.isBreakingWhitespace('\n'));
206 assertTrue('"\\t" is breaking', goog.string.isBreakingWhitespace('\t'));
207 assertTrue('"\\r" is breaking', goog.string.isBreakingWhitespace('\r'));
208 assertTrue(
209 '"\\r\\n\\t " is breaking', goog.string.isBreakingWhitespace('\r\n\t '));
210
211 assertFalse('nbsp is non-breaking', goog.string.isBreakingWhitespace('\xa0'));
212 assertFalse('"a" is non-breaking', goog.string.isBreakingWhitespace('a'));
213 assertFalse(
214 '"a\\r" is non-breaking', goog.string.isBreakingWhitespace('a\r'));
215 }
216
217
218 //=== tests for goog.string.isSpace ===
219 function testIsSpace() {
220 assertTrue('" " is a space', goog.string.isSpace(' '));
221
222 assertFalse('"\\n" is not a space', goog.string.isSpace('\n'));
223 assertFalse('"\\t" is not a space', goog.string.isSpace('\t'));
224 assertFalse(
225 '" " is not a space, it\'s two spaces', goog.string.isSpace(' '));
226 assertFalse('"a" is not a space', goog.string.isSpace('a'));
227 assertFalse('"3" is not a space', goog.string.isSpace('3'));
228 assertFalse('"#" is not a space', goog.string.isSpace('#'));
229 assertFalse('null is not a space', goog.string.isSpace(null));
230 assertFalse('nbsp is not a space', goog.string.isSpace('\xa0'));
231 }
232
233
234 // === tests for goog.string.stripNewlines ===
235 function testStripNewLines() {
236 assertEquals(
237 'Should replace new lines with spaces',
238 goog.string.stripNewlines('some\nlines\rthat\r\nare\n\nsplit'),
239 'some lines that are split');
240 }
241
242
243 // === tests for goog.string.canonicalizeNewlines ===
244 function testCanonicalizeNewlines() {
245 assertEquals(
246 'Should replace all types of new line with \\n',
247 goog.string.canonicalizeNewlines('some\nlines\rthat\r\nare\n\nsplit'),
248 'some\nlines\nthat\nare\n\nsplit');
249 }
250
251
252 // === tests for goog.string.normalizeWhitespace ===
253 function testNormalizeWhitespace() {
254 assertEquals(
255 'All whitespace chars should be replaced with a normal space',
256 goog.string.normalizeWhitespace('\xa0 \n\t \xa0 \n\t'), ' ');
257 }
258
259
260 // === tests for goog.string.normalizeSpaces ===
261 function testNormalizeSpaces() {
262 assertEquals(
263 'All whitespace chars should be replaced with a normal space',
264 goog.string.normalizeSpaces('\xa0 \t \xa0 \t'), ' ');
265 }
266
267 function testCollapseBreakingSpaces() {
268 assertEquals(
269 'breaking spaces are collapsed', 'a b',
270 goog.string.collapseBreakingSpaces(' \t\r\n a \t\r\n b \t\r\n '));
271 assertEquals(
272 'non-breaking spaces are kept', 'a \u00a0\u2000 b',
273 goog.string.collapseBreakingSpaces('a \u00a0\u2000 b'));
274 }
275
276 /// === tests for goog.string.trim ===
277 function testTrim() {
278 assertEquals(
279 'Should be the same', goog.string.trim('nothing 2 trim'),
280 'nothing 2 trim');
281 assertEquals(
282 'Remove spaces', goog.string.trim(' hello goodbye '),
283 'hello goodbye');
284 assertEquals(
285 'Trim other stuff', goog.string.trim('\n\r\xa0 hi \r\n\xa0'), 'hi');
286 }
287
288
289 /// === tests for goog.string.trimLeft ===
290 function testTrimLeft() {
291 var f = goog.string.trimLeft;
292 assertEquals('Should be the same', f('nothing to trim'), 'nothing to trim');
293 assertEquals('Remove spaces', f(' hello goodbye '), 'hello goodbye ');
294 assertEquals('Trim other stuff', f('\xa0\n\r hi \r\n\xa0'), 'hi \r\n\xa0');
295 }
296
297
298 /// === tests for goog.string.trimRight ===
299 function testTrimRight() {
300 var f = goog.string.trimRight;
301 assertEquals('Should be the same', f('nothing to trim'), 'nothing to trim');
302 assertEquals('Remove spaces', f(' hello goodbye '), ' hello goodbye');
303 assertEquals('Trim other stuff', f('\n\r\xa0 hi \r\n\xa0'), '\n\r\xa0 hi');
304 }
305
306
307 // === tests for goog.string.startsWith ===
308 function testStartsWith() {
309 assertTrue('Should start with \'\'', goog.string.startsWith('abcd', ''));
310 assertTrue('Should start with \'ab\'', goog.string.startsWith('abcd', 'ab'));
311 assertTrue(
312 'Should start with \'abcd\'', goog.string.startsWith('abcd', 'abcd'));
313 assertFalse(
314 'Should not start with \'bcd\'', goog.string.startsWith('abcd', 'bcd'));
315 }
316
317 function testEndsWith() {
318 assertTrue('Should end with \'\'', goog.string.endsWith('abcd', ''));
319 assertTrue('Should end with \'ab\'', goog.string.endsWith('abcd', 'cd'));
320 assertTrue('Should end with \'abcd\'', goog.string.endsWith('abcd', 'abcd'));
321 assertFalse('Should not end \'abc\'', goog.string.endsWith('abcd', 'abc'));
322 assertFalse(
323 'Should not end \'abcde\'', goog.string.endsWith('abcd', 'abcde'));
324 }
325
326
327 // === tests for goog.string.caseInsensitiveStartsWith ===
328 function testCaseInsensitiveStartsWith() {
329 assertTrue(
330 'Should start with \'\'',
331 goog.string.caseInsensitiveStartsWith('abcd', ''));
332 assertTrue(
333 'Should start with \'ab\'',
334 goog.string.caseInsensitiveStartsWith('abcd', 'Ab'));
335 assertTrue(
336 'Should start with \'abcd\'',
337 goog.string.caseInsensitiveStartsWith('AbCd', 'abCd'));
338 assertFalse(
339 'Should not start with \'bcd\'',
340 goog.string.caseInsensitiveStartsWith('ABCD', 'bcd'));
341 }
342
343 // === tests for goog.string.caseInsensitiveEndsWith ===
344 function testCaseInsensitiveEndsWith() {
345 assertTrue(
346 'Should end with \'\'', goog.string.caseInsensitiveEndsWith('abcd', ''));
347 assertTrue(
348 'Should end with \'cd\'',
349 goog.string.caseInsensitiveEndsWith('abCD', 'cd'));
350 assertTrue(
351 'Should end with \'abcd\'',
352 goog.string.caseInsensitiveEndsWith('abcd', 'abCd'));
353 assertFalse(
354 'Should not end \'abc\'',
355 goog.string.caseInsensitiveEndsWith('aBCd', 'ABc'));
356 assertFalse(
357 'Should not end \'abcde\'',
358 goog.string.caseInsensitiveEndsWith('ABCD', 'abcde'));
359 }
360
361 // === tests for goog.string.caseInsensitiveEquals ===
362 function testCaseInsensitiveEquals() {
363 function assertCaseInsensitiveEquals(str1, str2) {
364 assertTrue(goog.string.caseInsensitiveEquals(str1, str2));
365 }
366
367 function assertCaseInsensitiveNotEquals(str1, str2) {
368 assertFalse(goog.string.caseInsensitiveEquals(str1, str2));
369 }
370
371 assertCaseInsensitiveEquals('abc', 'abc');
372 assertCaseInsensitiveEquals('abc', 'abC');
373 assertCaseInsensitiveEquals('d,e,F,G', 'd,e,F,G');
374 assertCaseInsensitiveEquals('ABCD EFGH 1234', 'abcd efgh 1234');
375 assertCaseInsensitiveEquals('FooBarBaz', 'fOObARbAZ');
376
377 assertCaseInsensitiveNotEquals('ABCD EFGH', 'abcd efg');
378 assertCaseInsensitiveNotEquals('ABC DEFGH', 'ABCD EFGH');
379 assertCaseInsensitiveNotEquals('FooBarBaz', 'fOObARbAZ ');
380 }
381
382
383 // === tests for goog.string.subs ===
384 function testSubs() {
385 assertEquals(
386 'Should be the same', 'nothing to subs',
387 goog.string.subs('nothing to subs'));
388 assertEquals('Should be the same', '1', goog.string.subs('%s', '1'));
389 assertEquals(
390 'Should be the same', '12true', goog.string.subs('%s%s%s', '1', 2, true));
391 function f() { fail('This should not be called'); }
392 f.toString = function() { return 'f'; };
393 assertEquals('Should not call function', 'f', goog.string.subs('%s', f));
394
395 // If the string that is to be substituted in contains $& then it will be
396 // usually be replaced with %s, we need to check goog.string.subs, handles
397 // this case.
398 assertEquals(
399 '$& should not be substituted with %s', 'Foo Bar $&',
400 goog.string.subs('Foo %s', 'Bar $&'));
401
402 assertEquals(
403 '$$ should not be substituted', '_$$_', goog.string.subs('%s', '_$$_'));
404 assertEquals(
405 '$` should not be substituted', '_$`_', goog.string.subs('%s', '_$`_'));
406 assertEquals(
407 '$\' should not be substituted', '_$\'_',
408 goog.string.subs('%s', '_$\'_'));
409 for (var i = 0; i < 99; i += 9) {
410 assertEquals(
411 '$' + i + ' should not be substituted', '_$' + i + '_',
412 goog.string.subs('%s', '_$' + i + '_'));
413 }
414
415 assertEquals(
416 'Only the first three "%s" strings should be replaced.',
417 'test foo test bar test baz test %s test %s test',
418 goog.string.subs(
419 'test %s test %s test %s test %s test %s test', 'foo', 'bar', 'baz'));
420 }
421
422
423 /**
424 * Verifies that if too many arguments are given, they are ignored.
425 * Logic test for bug documented here: http://go/eusxz
426 */
427 function testSubsTooManyArguments() {
428 assertEquals('one', goog.string.subs('one', 'two', 'three'));
429 assertEquals('onetwo', goog.string.subs('one%s', 'two', 'three'));
430 }
431
432
433 // === tests for goog.string.caseInsensitiveCompare ===
434 function testCaseInsensitiveCompare() {
435 var f = goog.string.caseInsensitiveCompare;
436
437 assert('"ABC" should be less than "def"', f('ABC', 'def') == -1);
438 assert('"abc" should be less than "DEF"', f('abc', 'DEF') == -1);
439
440 assert('"XYZ" should equal "xyz"', f('XYZ', 'xyz') == 0);
441
442 assert('"XYZ" should be greater than "UVW"', f('xyz', 'UVW') == 1);
443 assert('"XYZ" should be greater than "uvw"', f('XYZ', 'uvw') == 1);
444 }
445
446
447 /**
448 * Test cases for goog.string.floatAwareCompare and goog.string.intAwareCompare.
449 * Each comparison in this list is tested to assure that terms[0] < terms[1],
450 * terms[1] > terms[0], and identity tests terms[0] == terms[0] and
451 * terms[1] == terms[1].
452 * @const {!Array<!Array<string>>}
453 */
454 var NUMERIC_COMPARISON_TEST_CASES = [
455 ['', '0'], ['2', '10'], ['05', '9'], ['sub', 'substring'],
456 ['photo 7', 'Photo 8'], // Case insensitive for most sorts.
457 ['Mango', 'mango'], // Case sensitive if strings are otherwise identical.
458 ['album 2 photo 20', 'album 10 photo 20'],
459 ['album 7 photo 20', 'album 7 photo 100']
460 ];
461
462
463 function testFloatAwareCompare() {
464 var comparisons = NUMERIC_COMPARISON_TEST_CASES.concat([['3.14', '3.2']]);
465 for (var i = 0; i < comparisons.length; i++) {
466 var terms = comparisons[i];
467 assert(
468 terms[0] + ' should be less than ' + terms[1],
469 goog.string.floatAwareCompare(terms[0], terms[1]) < 0);
470 assert(
471 terms[1] + ' should be greater than ' + terms[0],
472 goog.string.floatAwareCompare(terms[1], terms[0]) > 0);
473 assert(
474 terms[0] + ' should be equal to ' + terms[0],
475 goog.string.floatAwareCompare(terms[0], terms[0]) == 0);
476 assert(
477 terms[1] + ' should be equal to ' + terms[1],
478 goog.string.floatAwareCompare(terms[1], terms[1]) == 0);
479 }
480 }
481
482
483 function testIntAwareCompare() {
484 var comparisons = NUMERIC_COMPARISON_TEST_CASES.concat([['3.2', '3.14']]);
485 for (var i = 0; i < comparisons.length; i++) {
486 var terms = comparisons[i];
487 assert(
488 terms[0] + ' should be less than ' + terms[1],
489 goog.string.intAwareCompare(terms[0], terms[1]) < 0);
490 assert(
491 terms[1] + ' should be greater than ' + terms[0],
492 goog.string.intAwareCompare(terms[1], terms[0]) > 0);
493 assert(
494 terms[0] + ' should be equal to ' + terms[0],
495 goog.string.intAwareCompare(terms[0], terms[0]) == 0);
496 assert(
497 terms[1] + ' should be equal to ' + terms[1],
498 goog.string.intAwareCompare(terms[1], terms[1]) == 0);
499 }
500 }
501
502
503 // === tests for goog.string.urlEncode && .urlDecode ===
504 // NOTE: When test was written it was simply an alias for the built in
505 // 'encodeURICompoent', therefore this test is simply used to make sure that in
506 // the future it doesn't get broken.
507 function testUrlEncodeAndDecode() {
508 var input = '<p>"hello there," she said, "what is going on here?</p>';
509 var output = '%3Cp%3E%22hello%20there%2C%22%20she%20said%2C%20%22what%20is' +
510 '%20going%20on%20here%3F%3C%2Fp%3E';
511
512 assertEquals(
513 'urlEncode vs encodeURIComponent', encodeURIComponent(input),
514 goog.string.urlEncode(input));
515
516 assertEquals('urlEncode vs model', goog.string.urlEncode(input), output);
517
518 assertEquals('urlDecode vs model', goog.string.urlDecode(output), input);
519
520 assertEquals(
521 'urlDecode vs urlEncode',
522 goog.string.urlDecode(goog.string.urlEncode(input)), input);
523
524 assertEquals(
525 'urlDecode with +s instead of %20s',
526 goog.string.urlDecode(output.replace(/%20/g, '+')), input);
527 }
528
529
530 // === tests for goog.string.newLineToBr ===
531 function testNewLineToBr() {
532 var str = 'some\nlines\rthat\r\nare\n\nsplit';
533 var html = 'some<br>lines<br>that<br>are<br><br>split';
534 var xhtml = 'some<br />lines<br />that<br />are<br /><br />split';
535
536 assertEquals('Should be html', goog.string.newLineToBr(str), html);
537 assertEquals('Should be html', goog.string.newLineToBr(str, false), html);
538 assertEquals('Should be xhtml', goog.string.newLineToBr(str, true), xhtml);
539 }
540
541
542 // === tests for goog.string.htmlEscape and .unescapeEntities ===
543 function testHtmlEscapeAndUnescapeEntities() {
544 var text = '\'"x1 < x2 && y2 > y1"\'';
545 var html = '&#39;&quot;x1 &lt; x2 &amp;&amp; y2 &gt; y1&quot;&#39;';
546
547 assertEquals('Testing htmlEscape', html, goog.string.htmlEscape(text));
548 assertEquals('Testing htmlEscape', html, goog.string.htmlEscape(text, false));
549 assertEquals('Testing htmlEscape', html, goog.string.htmlEscape(text, true));
550 assertEquals(
551 'Testing unescapeEntities', text, goog.string.unescapeEntities(html));
552
553 assertEquals(
554 'escape -> unescape', text,
555 goog.string.unescapeEntities(goog.string.htmlEscape(text)));
556 assertEquals(
557 'unescape -> escape', html,
558 goog.string.htmlEscape(goog.string.unescapeEntities(html)));
559 }
560
561 function testHtmlUnescapeEntitiesWithDocument() {
562 var documentMock = {
563 createElement: mockControl.createFunctionMock('createElement')
564 };
565 var divMock = goog.dom.createElement(goog.dom.TagName.DIV);
566 documentMock.createElement('div').$returns(divMock);
567 mockControl.$replayAll();
568
569 var html = '&lt;a&b&gt;';
570 var text = '<a&b>';
571
572 assertEquals(
573 'wrong unescaped value', text,
574 goog.string.unescapeEntitiesWithDocument(html, documentMock));
575 assertNotEquals(
576 'divMock.innerHTML should have been used', '', divMock.innerHTML);
577 mockControl.$verifyAll();
578 }
579
580 function testHtmlEscapeAndUnescapeEntitiesUsingDom() {
581 var text = '"x1 < x2 && y2 > y1"';
582 var html = '&quot;x1 &lt; x2 &amp;&amp; y2 &gt; y1&quot;';
583
584 assertEquals(
585 'Testing unescapeEntities', goog.string.unescapeEntitiesUsingDom_(html),
586 text);
587 assertEquals(
588 'escape -> unescape',
589 goog.string.unescapeEntitiesUsingDom_(goog.string.htmlEscape(text)),
590 text);
591 assertEquals(
592 'unescape -> escape',
593 goog.string.htmlEscape(goog.string.unescapeEntitiesUsingDom_(html)),
594 html);
595 }
596
597 function testHtmlUnescapeEntitiesUsingDom_withAmpersands() {
598 var html = '&lt;a&b&gt;';
599 var text = '<a&b>';
600
601 assertEquals(
602 'wrong unescaped value', text,
603 goog.string.unescapeEntitiesUsingDom_(html));
604 }
605
606 function testHtmlEscapeAndUnescapePureXmlEntities_() {
607 var text = '"x1 < x2 && y2 > y1"';
608 var html = '&quot;x1 &lt; x2 &amp;&amp; y2 &gt; y1&quot;';
609
610 assertEquals(
611 'Testing unescapePureXmlEntities_',
612 goog.string.unescapePureXmlEntities_(html), text);
613 assertEquals(
614 'escape -> unescape',
615 goog.string.unescapePureXmlEntities_(goog.string.htmlEscape(text)), text);
616 assertEquals(
617 'unescape -> escape',
618 goog.string.htmlEscape(goog.string.unescapePureXmlEntities_(html)), html);
619 }
620
621
622 function testForceNonDomHtmlUnescaping() {
623 stubs.set(goog.string, 'FORCE_NON_DOM_HTML_UNESCAPING', true);
624 // Set document.createElement to empty object so that the call to
625 // unescapeEntities will blow up if html unescaping is carried out with DOM.
626 // Notice that we can't directly set document to empty object since IE8 won't
627 // let us do so.
628 stubs.set(goog.global.document, 'createElement', {});
629 goog.string.unescapeEntities('&quot;x1 &lt; x2 &amp;&amp; y2 &gt; y1&quot;');
630 }
631
632
633 function testHtmlEscapeDetectDoubleEscaping() {
634 stubs.set(goog.string, 'DETECT_DOUBLE_ESCAPING', true);
635 assertEquals('&#101; &lt; pi', goog.string.htmlEscape('e < pi'));
636 assertEquals('&#101; &lt; pi', goog.string.htmlEscape('e < pi', true));
637 }
638
639 function testHtmlEscapeNullByte() {
640 assertEquals('&#0;', goog.string.htmlEscape('\x00'));
641 assertEquals('&#0;', goog.string.htmlEscape('\x00', true));
642 assertEquals('\\x00', goog.string.htmlEscape('\\x00'));
643 assertEquals('\\x00', goog.string.htmlEscape('\\x00', true));
644 }
645
646 var globalXssVar = 0;
647
648 function testXssUnescapeEntities() {
649 // This tests that we don't have any XSS exploits in unescapeEntities
650 var test = '&amp;<script defer>globalXssVar=1;</' +
651 'script>';
652 var expected = '&<script defer>globalXssVar=1;</' +
653 'script>';
654
655 assertEquals(
656 'Testing unescapeEntities', expected, goog.string.unescapeEntities(test));
657 assertEquals('unescapeEntities is vulnarable to XSS', 0, globalXssVar);
658
659 test = '&amp;<script>globalXssVar=1;</' +
660 'script>';
661 expected = '&<script>globalXssVar=1;</' +
662 'script>';
663
664 assertEquals(
665 'Testing unescapeEntities', expected, goog.string.unescapeEntities(test));
666 assertEquals('unescapeEntities is vulnarable to XSS', 0, globalXssVar);
667 }
668
669
670 function testXssUnescapeEntitiesUsingDom() {
671 // This tests that we don't have any XSS exploits in unescapeEntitiesUsingDom
672 var test = '&amp;<script defer>globalXssVar=1;</' +
673 'script>';
674 var expected = '&<script defer>globalXssVar=1;</' +
675 'script>';
676
677 assertEquals(
678 'Testing unescapeEntitiesUsingDom_', expected,
679 goog.string.unescapeEntitiesUsingDom_(test));
680 assertEquals(
681 'unescapeEntitiesUsingDom_ is vulnerable to XSS', 0, globalXssVar);
682
683 test = '&amp;<script>globalXssVar=1;</' +
684 'script>';
685 expected = '&<script>globalXssVar=1;</' +
686 'script>';
687
688 assertEquals(
689 'Testing unescapeEntitiesUsingDom_', expected,
690 goog.string.unescapeEntitiesUsingDom_(test));
691 assertEquals(
692 'unescapeEntitiesUsingDom_ is vulnerable to XSS', 0, globalXssVar);
693 }
694
695
696 function testXssUnescapePureXmlEntities() {
697 // This tests that we don't have any XSS exploits in unescapePureXmlEntities
698 var test = '&amp;<script defer>globalXssVar=1;</' +
699 'script>';
700 var expected = '&<script defer>globalXssVar=1;</' +
701 'script>';
702
703 assertEquals(
704 'Testing unescapePureXmlEntities_', expected,
705 goog.string.unescapePureXmlEntities_(test));
706 assertEquals(
707 'unescapePureXmlEntities_ is vulnarable to XSS', 0, globalXssVar);
708
709 test = '&amp;<script>globalXssVar=1;</' +
710 'script>';
711 expected = '&<script>globalXssVar=1;</' +
712 'script>';
713
714 assertEquals(
715 'Testing unescapePureXmlEntities_', expected,
716 goog.string.unescapePureXmlEntities_(test));
717 assertEquals(
718 'unescapePureXmlEntities_ is vulnarable to XSS', 0, globalXssVar);
719 }
720
721
722 function testUnescapeEntitiesPreservesWhitespace() {
723 // This tests that whitespace is preserved (primarily for IE)
724 // Also make sure leading and trailing whitespace are preserved.
725 var test = '\nTesting\n\twhitespace\n preservation\n';
726 var expected = test;
727
728 assertEquals(
729 'Testing unescapeEntities', expected, goog.string.unescapeEntities(test));
730
731 // Now with entities
732 test += ' &amp;&nbsp;\n';
733 expected += ' &\u00A0\n';
734 assertEquals(
735 'Testing unescapeEntities', expected, goog.string.unescapeEntities(test));
736 }
737
738
739 // === tests for goog.string.whitespaceEscape ===
740 function testWhitespaceEscape() {
741 assertEquals(
742 'Should be the same',
743 goog.string.whitespaceEscape('one two three four five '),
744 'one two &#160;three &#160; four &#160; &#160;five &#160; &#160; ');
745 }
746
747
748 // === tests for goog.string.preserveSpaces ===
749 function testPreserveSpaces() {
750 var nbsp = goog.string.Unicode.NBSP;
751 assertEquals('', goog.string.preserveSpaces(''));
752 assertEquals(nbsp + 'a', goog.string.preserveSpaces(' a'));
753 assertEquals(nbsp + ' a', goog.string.preserveSpaces(' a'));
754 assertEquals(nbsp + ' ' + nbsp + 'a', goog.string.preserveSpaces(' a'));
755 assertEquals('a ' + nbsp + 'b', goog.string.preserveSpaces('a b'));
756 assertEquals('a\n' + nbsp + 'b', goog.string.preserveSpaces('a\n b'));
757
758 // We don't care about trailing spaces.
759 assertEquals('a ', goog.string.preserveSpaces('a '));
760 assertEquals('a \n' + nbsp + 'b', goog.string.preserveSpaces('a \n b'));
761 }
762
763
764 // === tests for goog.string.stripQuotes ===
765 function testStripQuotes() {
766 assertEquals(
767 'Quotes should be stripped', goog.string.stripQuotes('"hello"', '"'),
768 'hello');
769
770 assertEquals(
771 'Quotes should be stripped', goog.string.stripQuotes('\'hello\'', '\''),
772 'hello');
773
774 assertEquals(
775 'Quotes should not be stripped', goog.string.stripQuotes('-"hello"', '"'),
776 '-"hello"');
777 }
778
779 function testStripQuotesMultiple() {
780 assertEquals(
781 'Quotes should be stripped', goog.string.stripQuotes('"hello"', '"\''),
782 'hello');
783 assertEquals(
784 'Quotes should be stripped', goog.string.stripQuotes('\'hello\'', '"\''),
785 'hello');
786
787 assertEquals(
788 'Quotes should be stripped', goog.string.stripQuotes('\'hello\'', ''),
789 '\'hello\'');
790 }
791
792 function testStripQuotesMultiple2() {
793 // Makes sure we do not strip twice
794 assertEquals(
795 'Quotes should be stripped',
796 goog.string.stripQuotes('"\'hello\'"', '"\''), '\'hello\'');
797 assertEquals(
798 'Quotes should be stripped',
799 goog.string.stripQuotes('"\'hello\'"', '\'"'), '\'hello\'');
800 }
801
802 // === tests for goog.string.truncate ===
803 function testTruncate() {
804 var str = 'abcdefghijklmnopqrstuvwxyz';
805 assertEquals('Should be equal', goog.string.truncate(str, 8), 'abcde...');
806 assertEquals('Should be equal', goog.string.truncate(str, 11), 'abcdefgh...');
807
808 var html = 'true &amp;&amp; false == false';
809 assertEquals(
810 'Should clip html char', goog.string.truncate(html, 11), 'true &am...');
811 assertEquals(
812 'Should not clip html char', goog.string.truncate(html, 12, true),
813 'true &amp;&amp; f...');
814 }
815
816
817 // === tests for goog.string.truncateMiddle ===
818 function testTruncateMiddle() {
819 var str = 'abcdefghijklmnopqrstuvwxyz';
820 assertEquals('abc...xyz', goog.string.truncateMiddle(str, 6));
821 assertEquals('abc...yz', goog.string.truncateMiddle(str, 5));
822 assertEquals(str, goog.string.truncateMiddle(str, str.length));
823
824 var html = 'true &amp;&amp; false == false';
825 assertEquals(
826 'Should clip html char', 'true &a...= false',
827 goog.string.truncateMiddle(html, 14));
828 assertEquals(
829 'Should not clip html char', 'true &amp;&amp;...= false',
830 goog.string.truncateMiddle(html, 14, true));
831
832 assertEquals('ab...xyz', goog.string.truncateMiddle(str, 5, null, 3));
833 assertEquals('abcdefg...xyz', goog.string.truncateMiddle(str, 10, null, 3));
834 assertEquals('abcdef...wxyz', goog.string.truncateMiddle(str, 10, null, 4));
835 assertEquals('...yz', goog.string.truncateMiddle(str, 2, null, 3));
836 assertEquals(str, goog.string.truncateMiddle(str, 50, null, 3));
837
838 assertEquals(
839 'Should clip html char', 'true &amp;&...lse',
840 goog.string.truncateMiddle(html, 14, null, 3));
841 assertEquals(
842 'Should not clip html char', 'true &amp;&amp; fal...lse',
843 goog.string.truncateMiddle(html, 14, true, 3));
844 }
845
846
847 // === goog.string.quote ===
848 function testQuote() {
849 var str = allChars();
850 assertEquals(str, eval(goog.string.quote(str)));
851
852 // empty string
853 assertEquals('', eval(goog.string.quote('')));
854
855 // unicode
856 str = allChars(0, 10000);
857 assertEquals(str, eval(goog.string.quote(str)));
858 }
859
860 function testQuoteSpecialChars() {
861 assertEquals('"\\""', goog.string.quote('"'));
862 assertEquals('"\'"', goog.string.quote("'"));
863 assertEquals('"\\\\"', goog.string.quote('\\'));
864 assertEquals('"\x3c"', goog.string.quote('<'));
865
866 var zeroQuoted = goog.string.quote('\0');
867 assertTrue(
868 'goog.string.quote mangles the 0 char: ',
869 '"\\0"' == zeroQuoted || '"\\x00"' == zeroQuoted);
870 }
871
872 function testCrossBrowserQuote() {
873 // The vertical space char has weird semantics on jscript, so we don't test
874 // that one.
875 var vertChar = '\x0B'.charCodeAt(0);
876
877 // The zero char has two alternate encodings (\0 and \x00) both are ok,
878 // and tested above.
879 var zeroChar = 0;
880
881 var str = allChars(zeroChar + 1, vertChar) + allChars(vertChar + 1, 10000);
882 var nativeQuote = goog.string.quote(str);
883
884 stubs.set(String.prototype, 'quote', null);
885 assertNull(''.quote);
886
887 assertEquals(nativeQuote, goog.string.quote(str));
888 }
889
890 function allChars(opt_start, opt_end) {
891 opt_start = opt_start || 0;
892 opt_end = opt_end || 256;
893 var rv = '';
894 for (var i = opt_start; i < opt_end; i++) {
895 rv += String.fromCharCode(i);
896 }
897 return rv;
898 }
899
900 function testEscapeString() {
901 var expected = allChars(0, 10000);
902 try {
903 var actual = eval('"' + goog.string.escapeString(expected) + '"');
904 } catch (e) {
905 fail('Quote failed: err ' + e.message);
906 }
907 assertEquals(expected, actual);
908 }
909
910 function testCountOf() {
911 assertEquals(goog.string.countOf('REDSOXROX', undefined), 0);
912 assertEquals(goog.string.countOf('REDSOXROX', null), 0);
913 assertEquals(goog.string.countOf('REDSOXROX', ''), 0);
914 assertEquals(goog.string.countOf('', undefined), 0);
915 assertEquals(goog.string.countOf('', null), 0);
916 assertEquals(goog.string.countOf('', ''), 0);
917 assertEquals(goog.string.countOf('', 'REDSOXROX'), 0);
918 assertEquals(goog.string.countOf(undefined, 'R'), 0);
919 assertEquals(goog.string.countOf(null, 'R'), 0);
920 assertEquals(goog.string.countOf(undefined, undefined), 0);
921 assertEquals(goog.string.countOf(null, null), 0);
922
923 assertEquals(goog.string.countOf('REDSOXROX', 'R'), 2);
924 assertEquals(goog.string.countOf('REDSOXROX', 'E'), 1);
925 assertEquals(goog.string.countOf('REDSOXROX', 'X'), 2);
926 assertEquals(goog.string.countOf('REDSOXROX', 'RED'), 1);
927 assertEquals(goog.string.countOf('REDSOXROX', 'ROX'), 1);
928 assertEquals(goog.string.countOf('REDSOXROX', 'OX'), 2);
929 assertEquals(goog.string.countOf('REDSOXROX', 'Z'), 0);
930 assertEquals(goog.string.countOf('REDSOXROX', 'REDSOXROX'), 1);
931 assertEquals(goog.string.countOf('REDSOXROX', 'YANKEES'), 0);
932 assertEquals(goog.string.countOf('REDSOXROX', 'EVIL_EMPIRE'), 0);
933
934 assertEquals(goog.string.countOf('RRRRRRRRR', 'R'), 9);
935 assertEquals(goog.string.countOf('RRRRRRRRR', 'RR'), 4);
936 assertEquals(goog.string.countOf('RRRRRRRRR', 'RRR'), 3);
937 assertEquals(goog.string.countOf('RRRRRRRRR', 'RRRR'), 2);
938 assertEquals(goog.string.countOf('RRRRRRRRR', 'RRRRR'), 1);
939 assertEquals(goog.string.countOf('RRRRRRRRR', 'RRRRRR'), 1);
940 }
941
942 function testRemoveAt() {
943 var str = 'barfoobarbazbar';
944 str = goog.string.removeAt(str, 0, 3);
945 assertEquals('Remove first bar', 'foobarbazbar', str);
946 str = goog.string.removeAt(str, 3, 3);
947 assertEquals('Remove middle bar', 'foobazbar', str);
948 str = goog.string.removeAt(str, 6, 3);
949 assertEquals('Remove last bar', 'foobaz', str);
950 assertEquals(
951 'Invalid negative index', 'foobaz', goog.string.removeAt(str, -1, 0));
952 assertEquals(
953 'Invalid overflow index', 'foobaz', goog.string.removeAt(str, 9, 0));
954 assertEquals(
955 'Invalid negative stringLength', 'foobaz',
956 goog.string.removeAt(str, 0, -1));
957 assertEquals(
958 'Invalid overflow stringLength', '', goog.string.removeAt(str, 0, 9));
959 assertEquals(
960 'Invalid overflow index and stringLength', 'foobaz',
961 goog.string.removeAt(str, 9, 9));
962 assertEquals(
963 'Invalid zero stringLength', 'foobaz', goog.string.removeAt(str, 0, 0));
964 }
965
966 function testRemove() {
967 var str = 'barfoobarbazbar';
968 str = goog.string.remove(str, 'bar');
969 assertEquals('Remove first bar', 'foobarbazbar', str);
970 str = goog.string.remove(str, 'bar');
971 assertEquals('Remove middle bar', 'foobazbar', str);
972 str = goog.string.remove(str, 'bar');
973 assertEquals('Remove last bar', 'foobaz', str);
974 str = goog.string.remove(str, 'bar');
975 assertEquals('Original string', 'foobaz', str);
976 }
977
978 function testRemoveAll() {
979 var str = 'foobarbazbarfoobazfoo';
980 str = goog.string.removeAll(str, 'foo');
981 assertEquals('Remove all occurrences of foo', 'barbazbarbaz', str);
982 str = goog.string.removeAll(str, 'foo');
983 assertEquals('Original string', 'barbazbarbaz', str);
984 }
985
986 function testReplaceAll() {
987 var str = 'foobarbazbarfoobazfoo';
988 str = goog.string.replaceAll(str, 'foo', 'test');
989 assertEquals(
990 'Replace all occurrences of foo with test', 'testbarbazbartestbaztest',
991 str);
992 var str2 = 'foobarbazbar^foo$baz^foo$';
993 str2 = goog.string.replaceAll(str2, '^foo', '$&test');
994 assertEquals(
995 'Replace all occurrences of ^foo with $&test',
996 'foobarbazbar$&test$baz$&test$', str2);
997 }
998
999 function testRegExpEscape() {
1000 var spec = '()[]{}+-?*.$^|,:#<!\\';
1001 var escapedSpec = '\\' + spec.split('').join('\\');
1002 assertEquals('special chars', escapedSpec, goog.string.regExpEscape(spec));
1003 assertEquals('backslash b', '\\x08', goog.string.regExpEscape('\b'));
1004
1005 var s = allChars();
1006 var re = new RegExp('^' + goog.string.regExpEscape(s) + '$');
1007 assertTrue('All ASCII', re.test(s));
1008 s = '';
1009 re = new RegExp('^' + goog.string.regExpEscape(s) + '$');
1010 assertTrue('empty string', re.test(s));
1011 s = allChars(0, 10000);
1012 re = new RegExp('^' + goog.string.regExpEscape(s) + '$');
1013 assertTrue('Unicode', re.test(s));
1014 }
1015
1016 function testPadNumber() {
1017 assertEquals('01.250', goog.string.padNumber(1.25, 2, 3));
1018 assertEquals('01.25', goog.string.padNumber(1.25, 2));
1019 assertEquals('01.3', goog.string.padNumber(1.25, 2, 1));
1020 assertEquals('1.25', goog.string.padNumber(1.25, 0));
1021 assertEquals('10', goog.string.padNumber(9.9, 2, 0));
1022 assertEquals('7', goog.string.padNumber(7, 0));
1023 assertEquals('7', goog.string.padNumber(7, 1));
1024 assertEquals('07', goog.string.padNumber(7, 2));
1025 }
1026
1027 function testAsString() {
1028 assertEquals('', goog.string.makeSafe(null));
1029 assertEquals('', goog.string.makeSafe(undefined));
1030 assertEquals('', goog.string.makeSafe(''));
1031
1032 assertEquals('abc', goog.string.makeSafe('abc'));
1033 assertEquals('123', goog.string.makeSafe(123));
1034 assertEquals('0', goog.string.makeSafe(0));
1035
1036 assertEquals('true', goog.string.makeSafe(true));
1037 assertEquals('false', goog.string.makeSafe(false));
1038
1039 var funky = function() {};
1040 funky.toString = function() { return 'funky-thing' };
1041 assertEquals('funky-thing', goog.string.makeSafe(funky));
1042 }
1043
1044 function testStringRepeat() {
1045 assertEquals('', goog.string.repeat('*', 0));
1046 assertEquals('*', goog.string.repeat('*', 1));
1047 assertEquals(' ', goog.string.repeat(' ', 5));
1048 assertEquals('__________', goog.string.repeat('_', 10));
1049 assertEquals('aaa', goog.string.repeat('a', 3));
1050 assertEquals('foofoofoofoofoofoo', goog.string.repeat('foo', 6));
1051 }
1052
1053 function testBuildString() {
1054 assertEquals('', goog.string.buildString());
1055 assertEquals('a', goog.string.buildString('a'));
1056 assertEquals('ab', goog.string.buildString('ab'));
1057 assertEquals('ab', goog.string.buildString('a', 'b'));
1058 assertEquals('abcd', goog.string.buildString('a', 'b', 'c', 'd'));
1059 assertEquals('0', goog.string.buildString(0));
1060 assertEquals('0123', goog.string.buildString(0, 1, 2, 3));
1061 assertEquals('ab01', goog.string.buildString('a', 'b', 0, 1));
1062 assertEquals('', goog.string.buildString(null, undefined));
1063 }
1064
1065 function testCompareVersions() {
1066 var f = goog.string.compareVersions;
1067 assertTrue('numeric equality broken', f(1, 1) == 0);
1068 assertTrue('numeric less than broken', f(1.0, 1.1) < 0);
1069 assertTrue('numeric greater than broken', f(2.0, 1.1) > 0);
1070
1071 assertTrue('exact equality broken', f('1.0', '1.0') == 0);
1072 assertTrue('mutlidot equality broken', f('1.0.0.0', '1.0') == 0);
1073 assertTrue('mutlidigit equality broken', f('1.000', '1.0') == 0);
1074 assertTrue('less than broken', f('1.0.2.1', '1.1') < 0);
1075 assertTrue('greater than broken', f('1.1', '1.0.2.1') > 0);
1076
1077 assertTrue('substring less than broken', f('1', '1.1') < 0);
1078 assertTrue('substring greater than broken', f('2.2', '2') > 0);
1079
1080 assertTrue('b greater than broken', f('1.1', '1.1b') > 0);
1081 assertTrue('b less than broken', f('1.1b', '1.1') < 0);
1082 assertTrue('b equality broken', f('1.1b', '1.1b') == 0);
1083
1084 assertTrue('b > a broken', f('1.1b', '1.1a') > 0);
1085 assertTrue('a < b broken', f('1.1a', '1.1b') < 0);
1086
1087 assertTrue('9.5 < 9.10 broken', f('9.5', '9.10') < 0);
1088 assertTrue('9.5 < 9.11 broken', f('9.5', '9.11') < 0);
1089 assertTrue('9.11 > 9.10 broken', f('9.11', '9.10') > 0);
1090 assertTrue('9.1 < 9.10 broken', f('9.1', '9.10') < 0);
1091 assertTrue('9.1.1 < 9.10 broken', f('9.1.1', '9.10') < 0);
1092 assertTrue('9.1.1 < 9.11 broken', f('9.1.1', '9.11') < 0);
1093
1094 assertTrue('10a > 9b broken', f('1.10a', '1.9b') > 0);
1095 assertTrue('b < b2 broken', f('1.1b', '1.1b2') < 0);
1096 assertTrue('b10 > b9 broken', f('1.1b10', '1.1b9') > 0);
1097
1098 assertTrue('7 > 6 broken with leading whitespace', f(' 7', '6') > 0);
1099 assertTrue('7 > 6 broken with trailing whitespace', f('7 ', '6') > 0);
1100 }
1101
1102 function testIsUnicodeChar() {
1103 assertFalse('empty string broken', goog.string.isUnicodeChar(''));
1104 assertFalse(
1105 'non-single char string broken', goog.string.isUnicodeChar('abc'));
1106 assertTrue('space broken', goog.string.isUnicodeChar(' '));
1107 assertTrue('single char broken', goog.string.isUnicodeChar('a'));
1108 assertTrue('upper case broken', goog.string.isUnicodeChar('A'));
1109 assertTrue('unicode char broken', goog.string.isUnicodeChar('\u0C07'));
1110 }
1111
1112 function assertHashcodeEquals(expectedHashCode, str) {
1113 assertEquals(
1114 'wrong hashCode for ' + str.substring(0, 32), expectedHashCode,
1115 goog.string.hashCode(str));
1116 }
1117
1118
1119 /**
1120 * Verify we get random-ish looking values for hash of Strings.
1121 */
1122 function testHashCode() {
1123 try {
1124 goog.string.hashCode(null);
1125 fail('should throw exception for null');
1126 } catch (ex) {
1127 // success
1128 }
1129 assertHashcodeEquals(0, '');
1130 assertHashcodeEquals(101574, 'foo');
1131 assertHashcodeEquals(1301670364, '\uAAAAfoo');
1132 assertHashcodeEquals(92567585, goog.string.repeat('a', 5));
1133 assertHashcodeEquals(2869595232, goog.string.repeat('a', 6));
1134 assertHashcodeEquals(3058106369, goog.string.repeat('a', 7));
1135 assertHashcodeEquals(312017024, goog.string.repeat('a', 8));
1136 assertHashcodeEquals(2929737728, goog.string.repeat('a', 1024));
1137 }
1138
1139 function testUniqueString() {
1140 var TEST_COUNT = 20;
1141
1142 var obj = {};
1143 for (var i = 0; i < TEST_COUNT; i++) {
1144 obj[goog.string.createUniqueString()] = true;
1145 }
1146
1147 assertEquals(
1148 'All strings should be unique.', TEST_COUNT, goog.object.getCount(obj));
1149 }
1150
1151 function testToNumber() {
1152 // First, test the cases goog.string.toNumber() was primarily written for,
1153 // because JS built-ins are dumb.
1154 assertNaN(goog.string.toNumber('123a'));
1155 assertNaN(goog.string.toNumber('123.456.78'));
1156 assertNaN(goog.string.toNumber(''));
1157 assertNaN(goog.string.toNumber(' '));
1158
1159 // Now, sanity-check.
1160 assertEquals(123, goog.string.toNumber(' 123 '));
1161 assertEquals(321.123, goog.string.toNumber('321.123'));
1162 assertEquals(1.00001, goog.string.toNumber('1.00001'));
1163 assertEquals(1, goog.string.toNumber('1.00000'));
1164 assertEquals(0.2, goog.string.toNumber('0.20'));
1165 assertEquals(0, goog.string.toNumber('0'));
1166 assertEquals(0, goog.string.toNumber('0.0'));
1167 assertEquals(-1, goog.string.toNumber('-1'));
1168 assertEquals(-0.3, goog.string.toNumber('-.3'));
1169 assertEquals(-12.345, goog.string.toNumber('-12.345'));
1170 assertEquals(100, goog.string.toNumber('1e2'));
1171 assertEquals(0.123, goog.string.toNumber('12.3e-2'));
1172 assertNaN(goog.string.toNumber('abc'));
1173 }
1174
1175 function testGetRandomString() {
1176 stubs.set(goog, 'now', goog.functions.constant(1295726605874));
1177 stubs.set(Math, 'random', goog.functions.constant(0.6679361383522245));
1178 assertTrue(
1179 'String must be alphanumeric',
1180 goog.string.isAlphaNumeric(goog.string.getRandomString()));
1181 }
1182
1183 function testToCamelCase() {
1184 assertEquals('OneTwoThree', goog.string.toCamelCase('-one-two-three'));
1185 assertEquals('oneTwoThree', goog.string.toCamelCase('one-two-three'));
1186 assertEquals('oneTwo', goog.string.toCamelCase('one-two'));
1187 assertEquals('one', goog.string.toCamelCase('one'));
1188 assertEquals('oneTwo', goog.string.toCamelCase('oneTwo'));
1189 assertEquals(
1190 'String value matching a native function name.', 'toString',
1191 goog.string.toCamelCase('toString'));
1192 }
1193
1194 function testToSelectorCase() {
1195 assertEquals('-one-two-three', goog.string.toSelectorCase('OneTwoThree'));
1196 assertEquals('one-two-three', goog.string.toSelectorCase('oneTwoThree'));
1197 assertEquals('one-two', goog.string.toSelectorCase('oneTwo'));
1198 assertEquals('one', goog.string.toSelectorCase('one'));
1199 assertEquals('one-two', goog.string.toSelectorCase('one-two'));
1200 assertEquals(
1201 'String value matching a native function name.', 'to-string',
1202 goog.string.toSelectorCase('toString'));
1203 }
1204
1205 function testToTitleCase() {
1206 assertEquals('One', goog.string.toTitleCase('one'));
1207 assertEquals('CamelCase', goog.string.toTitleCase('camelCase'));
1208 assertEquals('Onelongword', goog.string.toTitleCase('onelongword'));
1209 assertEquals('One Two Three', goog.string.toTitleCase('one two three'));
1210 assertEquals(
1211 'One Two Three',
1212 goog.string.toTitleCase('one two three'));
1213 assertEquals(' Longword ', goog.string.toTitleCase(' longword '));
1214 assertEquals('One-two-three', goog.string.toTitleCase('one-two-three'));
1215 assertEquals('One_two_three', goog.string.toTitleCase('one_two_three'));
1216 assertEquals(
1217 'String value matching a native function name.', 'ToString',
1218 goog.string.toTitleCase('toString'));
1219
1220 // Verify results with no delimiter.
1221 assertEquals('One two three', goog.string.toTitleCase('one two three', ''));
1222 assertEquals('One-two-three', goog.string.toTitleCase('one-two-three', ''));
1223 assertEquals(' onetwothree', goog.string.toTitleCase(' onetwothree', ''));
1224
1225 // Verify results with one delimiter.
1226 assertEquals('One two', goog.string.toTitleCase('one two', '.'));
1227 assertEquals(' one two', goog.string.toTitleCase(' one two', '.'));
1228 assertEquals(' one.Two', goog.string.toTitleCase(' one.two', '.'));
1229 assertEquals('One.Two', goog.string.toTitleCase('one.two', '.'));
1230 assertEquals('One...Two...', goog.string.toTitleCase('one...two...', '.'));
1231
1232 // Verify results with multiple delimiters.
1233 var delimiters = '_-.';
1234 assertEquals(
1235 'One two three', goog.string.toTitleCase('one two three', delimiters));
1236 assertEquals(
1237 ' one two three',
1238 goog.string.toTitleCase(' one two three', delimiters));
1239 assertEquals(
1240 'One-Two-Three', goog.string.toTitleCase('one-two-three', delimiters));
1241 assertEquals(
1242 'One_Two_Three', goog.string.toTitleCase('one_two_three', delimiters));
1243 assertEquals(
1244 'One...Two...Three',
1245 goog.string.toTitleCase('one...two...three', delimiters));
1246 assertEquals(
1247 'One. two. three',
1248 goog.string.toTitleCase('one. two. three', delimiters));
1249 }
1250
1251 function testCapitalize() {
1252 assertEquals('Reptar', goog.string.capitalize('reptar'));
1253 assertEquals('Reptar reptar', goog.string.capitalize('reptar reptar'));
1254 assertEquals('Reptar', goog.string.capitalize('REPTAR'));
1255 assertEquals('Reptar', goog.string.capitalize('Reptar'));
1256 assertEquals('1234', goog.string.capitalize('1234'));
1257 assertEquals('$#@!', goog.string.capitalize('$#@!'));
1258 assertEquals('', goog.string.capitalize(''));
1259 assertEquals('R', goog.string.capitalize('r'));
1260 assertEquals('R', goog.string.capitalize('R'));
1261 }
1262
1263 function testParseInt() {
1264 // Many example values borrowed from
1265 // http://trac.webkit.org/browser/trunk/LayoutTests/fast/js/kde/
1266 // GlobalObject-expected.txt
1267
1268 // Check non-numbers and strings
1269 assertTrue(isNaN(goog.string.parseInt(undefined)));
1270 assertTrue(isNaN(goog.string.parseInt(null)));
1271 assertTrue(isNaN(goog.string.parseInt({})));
1272
1273 assertTrue(isNaN(goog.string.parseInt('')));
1274 assertTrue(isNaN(goog.string.parseInt(' ')));
1275 assertTrue(isNaN(goog.string.parseInt('a')));
1276 assertTrue(isNaN(goog.string.parseInt('FFAA')));
1277 assertEquals(1, goog.string.parseInt(1));
1278 assertEquals(1234567890123456, goog.string.parseInt(1234567890123456));
1279 assertEquals(2, goog.string.parseInt(' 2.3'));
1280 assertEquals(16, goog.string.parseInt('0x10'));
1281 assertEquals(11, goog.string.parseInt('11'));
1282 assertEquals(15, goog.string.parseInt('0xF'));
1283 assertEquals(15, goog.string.parseInt('0XF'));
1284 assertEquals(3735928559, goog.string.parseInt('0XDEADBEEF'));
1285 assertEquals(3, goog.string.parseInt('3x'));
1286 assertEquals(3, goog.string.parseInt('3 x'));
1287 assertFalse(isFinite(goog.string.parseInt('Infinity')));
1288 assertEquals(15, goog.string.parseInt('15'));
1289 assertEquals(15, goog.string.parseInt('015'));
1290 assertEquals(15, goog.string.parseInt('0xf'));
1291 assertEquals(15, goog.string.parseInt('15'));
1292 assertEquals(15, goog.string.parseInt('0xF'));
1293 assertEquals(15, goog.string.parseInt('15.99'));
1294 assertTrue(isNaN(goog.string.parseInt('FXX123')));
1295 assertEquals(15, goog.string.parseInt('15*3'));
1296 assertEquals(7, goog.string.parseInt('0x7'));
1297 assertEquals(1, goog.string.parseInt('1x7'));
1298
1299 // Strings have no special meaning
1300 assertTrue(isNaN(goog.string.parseInt('Infinity')));
1301 assertTrue(isNaN(goog.string.parseInt('NaN')));
1302
1303 // Test numbers and values
1304 assertEquals(3, goog.string.parseInt(3.3));
1305 assertEquals(-3, goog.string.parseInt(-3.3));
1306 assertEquals(0, goog.string.parseInt(-0));
1307 assertTrue(isNaN(goog.string.parseInt(Infinity)));
1308 assertTrue(isNaN(goog.string.parseInt(NaN)));
1309 assertTrue(isNaN(goog.string.parseInt(Number.POSITIVE_INFINITY)));
1310 assertTrue(isNaN(goog.string.parseInt(Number.NEGATIVE_INFINITY)));
1311
1312 // In Chrome (at least), parseInt(Number.MIN_VALUE) is 5 (5e-324) and
1313 // parseInt(Number.MAX_VALUE) is 1 (1.79...e+308) as they are converted
1314 // to strings. We do not attempt to correct this behavior.
1315
1316 // Additional values for negatives.
1317 assertEquals(-3, goog.string.parseInt('-3'));
1318 assertEquals(-32, goog.string.parseInt('-32 '));
1319 assertEquals(-32, goog.string.parseInt(' -32 '));
1320 assertEquals(-3, goog.string.parseInt('-0x3'));
1321 assertEquals(-50, goog.string.parseInt('-0x32 '));
1322 assertEquals(-243, goog.string.parseInt(' -0xF3 '));
1323 assertTrue(isNaN(goog.string.parseInt(' - 0x32 ')));
1324 }
1325
1326 function testIsLowerCamelCase() {
1327 assertTrue(goog.string.isLowerCamelCase('foo'));
1328 assertTrue(goog.string.isLowerCamelCase('fooBar'));
1329 assertTrue(goog.string.isLowerCamelCase('fooBarBaz'));
1330 assertTrue(goog.string.isLowerCamelCase('innerHTML'));
1331
1332 assertFalse(goog.string.isLowerCamelCase(''));
1333 assertFalse(goog.string.isLowerCamelCase('a3a'));
1334 assertFalse(goog.string.isLowerCamelCase('goog.dom'));
1335 assertFalse(goog.string.isLowerCamelCase('Foo'));
1336 assertFalse(goog.string.isLowerCamelCase('FooBar'));
1337 assertFalse(goog.string.isLowerCamelCase('ABCBBD'));
1338 }
1339
1340 function testIsUpperCamelCase() {
1341 assertFalse(goog.string.isUpperCamelCase(''));
1342 assertFalse(goog.string.isUpperCamelCase('foo'));
1343 assertFalse(goog.string.isUpperCamelCase('fooBar'));
1344 assertFalse(goog.string.isUpperCamelCase('fooBarBaz'));
1345 assertFalse(goog.string.isUpperCamelCase('innerHTML'));
1346 assertFalse(goog.string.isUpperCamelCase('a3a'));
1347 assertFalse(goog.string.isUpperCamelCase('goog.dom'));
1348 assertFalse(goog.string.isUpperCamelCase('Boyz2Men'));
1349
1350 assertTrue(goog.string.isUpperCamelCase('ABCBBD'));
1351 assertTrue(goog.string.isUpperCamelCase('Foo'));
1352 assertTrue(goog.string.isUpperCamelCase('FooBar'));
1353 assertTrue(goog.string.isUpperCamelCase('FooBarBaz'));
1354 }
1355
1356 function testSplitLimit() {
1357 assertArrayEquals(['a*a*a*a'], goog.string.splitLimit('a*a*a*a', '*', -1));
1358 assertArrayEquals(['a*a*a*a'], goog.string.splitLimit('a*a*a*a', '*', 0));
1359 assertArrayEquals(['a', 'a*a*a'], goog.string.splitLimit('a*a*a*a', '*', 1));
1360 assertArrayEquals(
1361 ['a', 'a', 'a*a'], goog.string.splitLimit('a*a*a*a', '*', 2));
1362 assertArrayEquals(
1363 ['a', 'a', 'a', 'a'], goog.string.splitLimit('a*a*a*a', '*', 3));
1364 assertArrayEquals(
1365 ['a', 'a', 'a', 'a'], goog.string.splitLimit('a*a*a*a', '*', 4));
1366
1367 assertArrayEquals(
1368 ['bbbbbbbbbbbb'], goog.string.splitLimit('bbbbbbbbbbbb', 'a', 10));
1369 assertArrayEquals(
1370 ['babab', 'bab', 'abb'],
1371 goog.string.splitLimit('bababaababaaabb', 'aa', 10));
1372 assertArrayEquals(
1373 ['babab', 'babaaabb'],
1374 goog.string.splitLimit('bababaababaaabb', 'aa', 1));
1375 assertArrayEquals(
1376 ['b', 'a', 'b', 'a', 'b', 'a', 'a', 'b', 'a', 'b', 'aaabb'],
1377 goog.string.splitLimit('bababaababaaabb', '', 10));
1378 }
1379
1380 function testContains() {
1381 assertTrue(goog.string.contains('moot', 'moo'));
1382 assertFalse(goog.string.contains('moo', 'moot'));
1383 assertFalse(goog.string.contains('Moot', 'moo'));
1384 assertTrue(goog.string.contains('moo', 'moo'));
1385 }
1386
1387 function testCaseInsensitiveContains() {
1388 assertTrue(goog.string.caseInsensitiveContains('moot', 'moo'));
1389 assertFalse(goog.string.caseInsensitiveContains('moo', 'moot'));
1390 assertTrue(goog.string.caseInsensitiveContains('Moot', 'moo'));
1391 assertTrue(goog.string.caseInsensitiveContains('moo', 'moo'));
1392 }
1393
1394 function testEditDistance() {
1395 assertEquals(
1396 'Empty string should match to length of other string', 4,
1397 goog.string.editDistance('goat', ''));
1398 assertEquals(
1399 'Empty string should match to length of other string', 4,
1400 goog.string.editDistance('', 'moat'));
1401
1402 assertEquals(
1403 'Equal strings should have zero edit distance', 0,
1404 goog.string.editDistance('abcd', 'abcd'));
1405 assertEquals(
1406 'Equal strings should have zero edit distance', 0,
1407 goog.string.editDistance('', ''));
1408
1409 assertEquals(
1410 'Edit distance for adding characters incorrect', 4,
1411 goog.string.editDistance('bdf', 'abcdefg'));
1412 assertEquals(
1413 'Edit distance for removing characters incorrect', 4,
1414 goog.string.editDistance('abcdefg', 'bdf'));
1415
1416 assertEquals(
1417 'Edit distance for substituting characters incorrect', 4,
1418 goog.string.editDistance('adef', 'ghij'));
1419 assertEquals(
1420 'Edit distance for substituting characters incorrect', 1,
1421 goog.string.editDistance('goat', 'boat'));
1422
1423 assertEquals(
1424 'Substitution should be preferred over insert/delete', 4,
1425 goog.string.editDistance('abcd', 'defg'));
1426 }
1427
1428 function testLastComponent() {
1429 assertEquals(
1430 'Last component of a string without separators should be the string',
1431 'abcdefgh', goog.string.lastComponent('abcdefgh', []));
1432 assertEquals(
1433 'Last component of a string without separators should be the string',
1434 'abcdefgh', goog.string.lastComponent('abcdefgh', null));
1435 assertEquals(
1436 'Last component of a string without separators should be the string',
1437 'abcdefgh', goog.string.lastComponent('abcdefgh', undefined));
1438 assertEquals(
1439 'Last component of a string without separators should be the string',
1440 'abcdefgh', goog.string.lastComponent('abcdefgh', ''));
1441 assertEquals(
1442 'Giving a simple string separator instead of an array should work', 'fgh',
1443 goog.string.lastComponent('abcdefgh', 'e'));
1444 assertEquals(
1445 'Last component of a string without separators should be the string',
1446 'abcdefgh', goog.string.lastComponent('abcdefgh', ['']));
1447 assertEquals(
1448 'Last component of a string without separators should be the string',
1449 'abcdefgh', goog.string.lastComponent('abcdefgh', ['', '']));
1450 assertEquals(
1451 'Last component of a string without separators should be the string',
1452 'abcdefgh', goog.string.lastComponent('abcdefgh', ['']));
1453 assertEquals(
1454 'Last component of a single character string should be the string', 'a',
1455 goog.string.lastComponent('a', ['']));
1456 assertEquals(
1457 'Last component of a single character string separated by its only' +
1458 'character should be the empty string',
1459 '', goog.string.lastComponent('a', ['a']));
1460 assertEquals(
1461 'Last component of the empty string should be the empty string', '',
1462 goog.string.lastComponent('', ['']));
1463 assertEquals(
1464 'Last component of the empty string should be the empty string', '',
1465 goog.string.lastComponent('', ['a']));
1466 assertEquals(
1467 'Last component of the empty string should be the empty string', '',
1468 goog.string.lastComponent('', ['']));
1469 assertEquals('ccc', goog.string.lastComponent('aaabbbccc', ['b']));
1470 assertEquals('baz', goog.string.lastComponent('foo/bar/baz', ['/']));
1471 assertEquals('baz', goog.string.lastComponent('foo.bar.baz', ['.']));
1472 assertEquals('baz', goog.string.lastComponent('foo.bar.baz', ['/', '.']));
1473 assertEquals('bar/baz', goog.string.lastComponent('foo.bar/baz', ['.']));
1474 assertEquals('bar-baz', goog.string.lastComponent('foo.bar-baz', ['/', '.']));
1475 assertEquals('baz', goog.string.lastComponent('foo.bar-baz', ['-', '', '.']));
1476 }