aboutsummaryrefslogtreecommitdiff
path: root/contexts/data/lib/closure-library/closure/goog/json/json_test.html
blob: 5cc01cacf901f2bcba9afb9b36f22c5901f18d16 (plain)
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
<!DOCTYPE html>
<html>
<!--
Copyright 2006 The Closure Library Authors. All Rights Reserved.

Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Closure Unit Tests - goog.json</title>
<script src="../base.js"></script>
<script>
  goog.require('goog.functions');
  goog.require('goog.json');
  goog.require('goog.testing.jsunit');
  goog.require('goog.userAgent');
</script>
</head>
<body>
<script>

function allChars(start, end, opt_allowControlCharacters) {
  var sb = [];
  for (var i = start; i < end; i++) {
    // unicode without the control characters 0x00 - 0x1f, 0x7f - 0x9f
    if (opt_allowControlCharacters || i > 0x1f && i < 0x7f || i > 0x9f) {
      sb.push(String.fromCharCode(i));
    }
  }
  return sb.join('');
}

// serialization

function testStringSerialize() {

  assertSerialize('""', '');

  // unicode
  var str = allChars(0, 10000);
  eval(goog.json.serialize(str));

  assertSerialize('"true"', 'true');
  assertSerialize('"false"', 'false');
  assertSerialize('"null"', 'null');
  assertSerialize('"0"', '0');
}

function testNullSerialize() {
  assertSerialize('null', null);
  assertSerialize('null', undefined);
  assertSerialize('null', NaN);

  assertSerialize('0', 0);
  assertSerialize('""', '');
  assertSerialize('false', false);
}

function testNullPropertySerialize() {
  assertSerialize('{"a":null}', {'a': null});
  assertSerialize('{"a":null}', {'a': undefined});
}

function testNumberSerialize() {
  assertSerialize('0', 0);
  assertSerialize('12345', 12345);
  assertSerialize('-12345', -12345);

  assertSerialize('0.1', 0.1);
  // the leading zero may not be omitted
  assertSerialize('0.1', .1);

  // no leading +
  assertSerialize('1', +1);

  // either format is OK
  var s = goog.json.serialize(1e50);
  assertTrue('1e50', s == "1e50" ||
                     s == "1E50" ||
                     s == "1e+50" ||
                     s == "1E+50");

  // either format is OK
  s = goog.json.serialize(1e-50);
  assertTrue('1e50', s == "1e-50" || s == "1E-50");

  // These numbers cannot be represented in JSON
  assertSerialize('null', NaN);
  assertSerialize('null', Infinity);
  assertSerialize('null', -Infinity);
}

function testBooleanSerialize() {
  assertSerialize('true', true);
  assertSerialize('"true"', 'true');

  assertSerialize('false', false);
  assertSerialize('"false"', 'false');
}

function testArraySerialize() {
  assertSerialize('[]', []);
  assertSerialize('[1]', [1]);
  assertSerialize('[1,2]', [1,2]);
  assertSerialize('[1,2,3]', [1,2,3]);
  assertSerialize('[[]]', [[]]);

  assertNotEquals('{length:0}', goog.json.serialize({length:0}), '[]');
}

function testObjectSerialize_emptyObject() {
  assertSerialize('{}', {});
}

function testObjectSerialize_oneItem() {
  assertSerialize('{"a":"b"}', {a:'b'});
}

function testObjectSerialize_twoItems() {
  assertEquals('{"a":"b","c":"d"}',
               goog.json.serialize({a:'b',c:'d'}),
               '{"a":"b","c":"d"}');
}

function testObjectSerialize_whitespace() {
  assertSerialize('{" ":" "}', {' ':' '});
}

function testSerializeSkipFunction() {
  var object = {
    s: 'string value',
    b: true,
    i: 100,
    f: function() { var x = 'x'; }
  };
  assertSerialize('', object.f);
  assertSerialize('{"s":"string value","b":true,"i":100}', object);
}

function testObjectSerialize_array() {
  assertNotEquals('[0,1]', goog.json.serialize([0,1]), '{"0":"0","1":"1"}');
}

function testObjectSerialize_recursion() {
  if (goog.userAgent.WEBKIT) {
    return; // this makes safari 4 crash.
  }

  var anObject = {};
  anObject.thisObject = anObject;
  assertThrows('expected recursion exception', function() {
      goog.json.serialize(anObject);
  });
}

function testObjectSerializeWithHasOwnProperty() {
  var object = {'hasOwnProperty': null};
  if (goog.userAgent.IE && !goog.userAgent.isVersion('9')) {
    assertEquals('{}', goog.json.serialize(object));
  } else {
    assertEquals('{"hasOwnProperty":null}', goog.json.serialize(object));
  }
}

// parsing

function testStringParse() {

  assertEquals('Empty string', goog.json.parse('""'), '');
  assertEquals('whitespace string', goog.json.parse('" "'), ' ');

  // unicode without the control characters 0x00 - 0x1f, 0x7f - 0x9f
  var str = allChars(0, 1000);
  var jsonString = goog.json.serialize(str);
  var a = eval(jsonString);
  assertEquals('unicode string', goog.json.parse(jsonString), a);

  assertEquals('true as a string', goog.json.parse('"true"'), 'true');
  assertEquals('false as a string', goog.json.parse('"false"'), 'false');
  assertEquals('null as a string', goog.json.parse('"null"'), 'null');
  assertEquals('number as a string', goog.json.parse('"0"'), '0');
}

function testStringUnsafeParse() {

  assertEquals('Empty string', goog.json.unsafeParse('""'), '');
  assertEquals('whitespace string', goog.json.unsafeParse('" "'), ' ');

  // unicode
  var str = allChars(0, 1000);
  var jsonString = goog.json.serialize(str);
  var a = eval(jsonString);
  assertEquals('unicode string', goog.json.unsafeParse(jsonString), a);

  assertEquals('true as a string', goog.json.unsafeParse('"true"'), 'true');
  assertEquals('false as a string', goog.json.unsafeParse('"false"'), 'false');
  assertEquals('null as a string', goog.json.unsafeParse('"null"'), 'null');
  assertEquals('number as a string', goog.json.unsafeParse('"0"'), '0');
}

function testNullParse() {
  assertEquals('null', goog.json.parse('null'), null);

  assertNotEquals('0', goog.json.parse('0'), null);
  assertNotEquals('""', goog.json.parse('""'), null);
  assertNotEquals('false', goog.json.parse('false'), null);
}

function testNullUnsafeParse() {
  assertEquals('null', goog.json.unsafeParse('null'), null);

  assertNotEquals('0', goog.json.unsafeParse('0'), null);
  assertNotEquals('""', goog.json.unsafeParse('""'), null);
  assertNotEquals('false', goog.json.unsafeParse('false'), null);
}

function testNumberParse() {
  assertEquals('0', goog.json.parse('0'), 0);
  assertEquals('12345', goog.json.parse('12345'), 12345);
  assertEquals('-12345', goog.json.parse('-12345'), -12345);

  assertEquals('0.1', goog.json.parse('0.1'), 0.1);

  // either format is OK
  assertEquals(1e50, goog.json.parse('1e50'));
  assertEquals(1e50, goog.json.parse('1E50'));
  assertEquals(1e50, goog.json.parse('1e+50'));
  assertEquals(1e50, goog.json.parse('1E+50'));

  // either format is OK
  assertEquals(1e-50, goog.json.parse('1e-50'));
  assertEquals(1e-50, goog.json.parse('1E-50'));
}

function testNumberUnsafeParse() {
  assertEquals('0', goog.json.unsafeParse('0'), 0);
  assertEquals('12345', goog.json.unsafeParse('12345'), 12345);
  assertEquals('-12345', goog.json.unsafeParse('-12345'), -12345);

  assertEquals('0.1', goog.json.unsafeParse('0.1'), 0.1);

  // either format is OK
  assertEquals(1e50, goog.json.unsafeParse('1e50'));
  assertEquals(1e50, goog.json.unsafeParse('1E50'));
  assertEquals(1e50, goog.json.unsafeParse('1e+50'));
  assertEquals(1e50, goog.json.unsafeParse('1E+50'));

  // either format is OK
  assertEquals(1e-50, goog.json.unsafeParse('1e-50'));
  assertEquals(1e-50, goog.json.unsafeParse('1E-50'));
}

function testBooleanParse() {
  assertEquals('true', goog.json.parse('true'), true);
  assertEquals('false', goog.json.parse('false'), false);

  assertNotEquals('0', goog.json.parse('0'), false);
  assertNotEquals('"false"', goog.json.parse('"false"'), false);
  assertNotEquals('null', goog.json.parse('null'), false);

  assertNotEquals('1', goog.json.parse('1'), true);
  assertNotEquals('"true"', goog.json.parse('"true"'), true);
  assertNotEquals('{}', goog.json.parse('{}'), true);
  assertNotEquals('[]', goog.json.parse('[]'), true);
}

function testBooleanUnsafeParse() {
  assertEquals('true', goog.json.unsafeParse('true'), true);
  assertEquals('false', goog.json.unsafeParse('false'), false);

  assertNotEquals('0', goog.json.unsafeParse('0'), false);
  assertNotEquals('"false"', goog.json.unsafeParse('"false"'), false);
  assertNotEquals('null', goog.json.unsafeParse('null'), false);

  assertNotEquals('1', goog.json.unsafeParse('1'), true);
  assertNotEquals('"true"', goog.json.unsafeParse('"true"'), true);
  assertNotEquals('{}', goog.json.unsafeParse('{}'), true);
  assertNotEquals('[]', goog.json.unsafeParse('[]'), true);
}

function testArrayParse() {
  function arrayEquals(a1, a2) {
    if (a1.length != a2.length) {
      return false;
    }
    for (var i = 0; i < a1.length; i++) {
      if (a1[i] != a2[i]) {
        return false;
      }
    }
    return true;
  }

  assertTrue('[]', arrayEquals(goog.json.parse('[]'), []));
  assertTrue('[1]', arrayEquals(goog.json.parse('[1]'), [1]));
  assertTrue('[1,2]', arrayEquals(goog.json.parse('[1,2]'), [1,2]));
  assertTrue('[1,2,3]', arrayEquals(goog.json.parse('[1,2,3]'), [1,2,3]));
  assertTrue('[[]]', arrayEquals(goog.json.parse('[[]]')[0], []));

  // make sure we do not get an array for something that looks like an array
  assertFalse('{length:0}', 'push' in goog.json.parse('{"length":0}'));
}

function testArrayUnsafeParse() {
  function arrayEquals(a1, a2) {
    if (a1.length != a2.length) {
      return false;
    }
    for (var i = 0; i < a1.length; i++) {
      if (a1[i] != a2[i]) {
        return false;
      }
    }
    return true;
  }

  assertTrue('[]', arrayEquals(goog.json.unsafeParse('[]'), []));
  assertTrue('[1]', arrayEquals(goog.json.unsafeParse('[1]'), [1]));
  assertTrue('[1,2]', arrayEquals(goog.json.unsafeParse('[1,2]'), [1,2]));
  assertTrue('[1,2,3]', arrayEquals(goog.json.unsafeParse('[1,2,3]'), [1,2,3]));
  assertTrue('[[]]', arrayEquals(goog.json.unsafeParse('[[]]')[0], []));

  // make sure we do not get an array for something that looks like an array
  assertFalse('{length:0}', 'push' in goog.json.unsafeParse('{"length":0}'));
}

function testObjectParse() {
  function objectEquals(a1, a2) {
    for (var key in a1) {
      if (a1[key] != a2[key]) {
        return false;
      }
    }
    return true;
  }

  assertTrue('{}', objectEquals(goog.json.parse('{}'), {}));
  assertTrue('{"a":"b"}', objectEquals(goog.json.parse('{"a":"b"}'), {a:'b'}));
  assertTrue('{"a":"b","c":"d"}',
             objectEquals(goog.json.parse('{"a":"b","c":"d"}'),
             {a:'b',c:'d'}));
  assertTrue('{" ":" "}', objectEquals(goog.json.parse('{" ":" "}'), {' ':' '}));

  // make sure we do not get an Object when it is really an array
  assertTrue('[0,1]', 'length' in goog.json.parse('[0,1]'));
}

function testObjectUnsafeParse() {
  function objectEquals(a1, a2) {
    for (var key in a1) {
      if (a1[key] != a2[key]) {
        return false;
      }
    }
    return true;
  }

  assertTrue('{}', objectEquals(goog.json.unsafeParse('{}'), {}));
  assertTrue('{"a":"b"}', objectEquals(goog.json.unsafeParse('{"a":"b"}'), {a:'b'}));
  assertTrue('{"a":"b","c":"d"}',
             objectEquals(goog.json.unsafeParse('{"a":"b","c":"d"}'),
             {a:'b',c:'d'}));
  assertTrue('{" ":" "}', objectEquals(goog.json.unsafeParse('{" ":" "}'), {' ':' '}));

  // make sure we do not get an Object when it is really an array
  assertTrue('[0,1]', 'length' in goog.json.unsafeParse('[0,1]'));
}


function testForValidJson() {
  function error_(msg, s) {
    assertThrows(msg + ', Should have raised an exception: ' + s,
        goog.partial(goog.json.parse, s));
  }

  error_('Non closed string', '"dasdas');
  error_('undefined is not valid json', 'undefined');

  // These numbers cannot be represented in JSON
  error_('NaN cannot be presented in JSON', 'NaN');
  error_('Infinity cannot be presented in JSON', 'Infinity');
  error_('-Infinity cannot be presented in JSON', '-Infinity');
}

function testIsNotValid() {
  assertFalse(goog.json.isValid_('t'));
  assertFalse(goog.json.isValid_('r'));
  assertFalse(goog.json.isValid_('u'));
  assertFalse(goog.json.isValid_('e'));
  assertFalse(goog.json.isValid_('f'));
  assertFalse(goog.json.isValid_('a'));
  assertFalse(goog.json.isValid_('l'));
  assertFalse(goog.json.isValid_('s'));
  assertFalse(goog.json.isValid_('n'));
  assertFalse(goog.json.isValid_('E'));

  assertFalse(goog.json.isValid_('+'));
  assertFalse(goog.json.isValid_('-'));

  assertFalse(goog.json.isValid_('t++'));
  assertFalse(goog.json.isValid_('++t'));
  assertFalse(goog.json.isValid_('t--'));
  assertFalse(goog.json.isValid_('--t'));
  assertFalse(goog.json.isValid_('-t'));
  assertFalse(goog.json.isValid_('+t'));

  assertFalse(goog.json.isValid_('"\\"')); // "\"
  assertFalse(goog.json.isValid_('"\\'));  // "\

  // multiline string using \ at the end is not valid
  assertFalse(goog.json.isValid_('"a\\\nb"'));


  assertFalse(goog.json.isValid_('"\n"'));
  assertFalse(goog.json.isValid_('"\r"'));
  assertFalse(goog.json.isValid_('"\r\n"'));
  // Disallow the unicode newlines
  assertFalse(goog.json.isValid_('"\u2028"'));
  assertFalse(goog.json.isValid_('"\u2029"'));

  assertFalse(goog.json.isValid_(' '));
  assertFalse(goog.json.isValid_('\n'));
  assertFalse(goog.json.isValid_('\r'));
  assertFalse(goog.json.isValid_('\r\n'));

  assertFalse(goog.json.isValid_('t.r'));

  assertFalse(goog.json.isValid_('1e'));
  assertFalse(goog.json.isValid_('1e-'));
  assertFalse(goog.json.isValid_('1e+'));

  assertFalse(goog.json.isValid_('1e-'));

  assertFalse(goog.json.isValid_('"\\\u200D\\"'));
  assertFalse(goog.json.isValid_('"\\\0\\"'));
  assertFalse(goog.json.isValid_('"\\\0"'));
  assertFalse(goog.json.isValid_('"\\0"'));

  assertFalse(goog.json.isValid_('"\\\u200D\\", alert(\'foo\') //"\n'));
}

function testIsValid() {
  assertTrue(goog.json.isValid_('\n""\n'));
  assertTrue(goog.json.isValid_('[1\n,2\r,3\u2028\n,4\u2029]'));
  assertTrue(goog.json.isValid_('"\x7f"'));
  // Test tab characters in json.
  assertTrue(goog.json.isValid_('{"\t":"\t"}'));
}

function testDoNotSerializeProto() {
  function F() {};
  F.prototype = {
    c: 3
  };

  var obj = new F;
  obj.a = 1;
  obj.b = 2;

  assertEquals('Should not follow the prototype chain',
               '{"a":1,"b":2}',
               goog.json.serialize(obj));
}

function testEscape() {
  var unescaped = '1a*/]';
  assertEquals('Should not escape',
               '"' + unescaped + '"',
               goog.json.serialize(unescaped));

  var escaped = '\n\x7f\u1049';
  assertEquals('Should escape',
               '',
               findCommonChar(escaped, goog.json.serialize(escaped)));
  assertEquals('Should eval to the same string after escaping',
               escaped,
               goog.json.parse(goog.json.serialize(escaped)));
}

function testReplacer() {
  assertSerialize('[null,null,0]', [,,0]);

  assertSerialize('[0,0,{"x":0}]', [,,{x:0}], function(k, v) {
    if (v === undefined && goog.isArray(this)) {
      return 0;
    }
    return v;
  });

  assertSerialize('[0,1,2,3]', [0, 0, 0, 0], function(k, v) {
    var kNum = Number(k);
    if (k && !isNaN(kNum)) {
      return kNum;
    }
    return v;
  });

  assertSerialize(
      '{"a":1,"b":{"c":2}}',
      {'a': 0, 'b': {'c': 1}},
      function(k, v) {
    return typeof v == 'number' ? v + 1 : v;
  });
}

function testDateSerialize() {
  assertSerialize('{}', new Date(0));
}

function testToJSONSerialize() {
  assertSerialize('{}', {toJSON: goog.functions.constant('serialized')});
  assertSerialize('{"toJSON":"normal"}', {toJSON: 'normal'});
}

/**
 * Asserts that the given object serializes to the given value.
 * If the current browser has an implementation of JSON.serialize,
 * we make sure our version matches that one.
 */
function assertSerialize(expected, obj, opt_replacer) {
  assertEquals(expected, goog.json.serialize(obj, opt_replacer));

  // I'm pretty sure that the goog.json.serialize behavior is correct by the ES5
  // spec, but JSON.stringify(undefined) is undefined on all browsers.
  if (obj === undefined) return;

  // Browsers don't serialize undefined properties, but goog.json.serialize does
  if (goog.isObject(obj) && ('a' in obj) && obj['a'] === undefined) return;

  // Replacers are broken on IE and older versions of firefox.
  if (opt_replacer && !goog.userAgent.WEBKIT) return;

  // goog.json.serialize does not stringify dates the same way.
  if (obj instanceof Date) return;

  // goog.json.serialize does not stringify functions the same way.
  if (obj instanceof Function) return;

  // goog.json.serialize doesn't use the toJSON method.
  if (goog.isObject(obj) && goog.isFunction(obj.toJSON)) return;

  if (typeof JSON != 'undefined') {
    assertEquals(
        'goog.json.serialize does not match JSON.stringify',
        expected,
        JSON.stringify(obj, opt_replacer));
  }
}

/**
 * @param {string} a
 * @param {string} b
 * @return {string} any common character between two strings a and b.
 */
function findCommonChar(a, b) {
  for (var i = 0; i < b.length; i++) {
    if (a.indexOf(b.charAt(i)) >= 0) {
      return b.charAt(i);
    }
  }
  return '';
}

</script>
</body>
</html>