Debian Codegraph @

closure-library/closure/goog/json/processor_test.js

raw
1 // Copyright 2012 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 goog.provide('goog.json.processorTest');
16 goog.setTestOnly('goog.json.processorTest');
17
18 goog.require('goog.json.EvalJsonProcessor');
19 goog.require('goog.json.NativeJsonProcessor');
20 goog.require('goog.testing.jsunit');
21 goog.require('goog.userAgent');
22
23 var SUPPORTS_NATIVE_JSON = false;
24
25 function setUpPage() {
26 SUPPORTS_NATIVE_JSON = goog.global['JSON'] &&
27 !(goog.userAgent.GECKO && !goog.userAgent.isVersionOrHigher('5.0'));
28 }
29
30 var REPLACER = function(k, v) {
31 return !!k ? v + 'd' : v;
32 };
33
34 var REVIVER = function(k, v) {
35 return !!k ? v.substring(0, v.length - 1) : v;
36 };
37
38 // Just sanity check parsing and stringifying.
39 // Thorough tests are in json_test.html.
40
41 function testJsParser() {
42 var json = '{"a":1,"b":{"c":2}}';
43 runParsingTest(new goog.json.EvalJsonProcessor(), json, json);
44 }
45
46 function testNativeParser() {
47 if (!SUPPORTS_NATIVE_JSON) {
48 return;
49 }
50 var json = '{"a":1,"b":{"c":2}}';
51 runParsingTest(new goog.json.NativeJsonProcessor(), json, json);
52 }
53
54 function testJsParser_withReplacer() {
55 runParsingTest(
56 new goog.json.EvalJsonProcessor(REPLACER), '{"a":"foo","b":"goo"}',
57 '{"a":"food","b":"good"}');
58 }
59
60 function testNativeParser_withReplacer() {
61 if (!SUPPORTS_NATIVE_JSON) {
62 return;
63 }
64 runParsingTest(
65 new goog.json.NativeJsonProcessor(REPLACER), '{"a":"foo","b":"goo"}',
66 '{"a":"food","b":"good"}');
67 }
68
69 function testNativeParser_withReviver() {
70 if (!SUPPORTS_NATIVE_JSON) {
71 return;
72 }
73 var json = '{"a":"fod","b":"god"}';
74 runParsingTest(
75 new goog.json.NativeJsonProcessor(REPLACER, REVIVER), json, json);
76 }
77
78 function testUnsafeJsParser() {
79 var json = '{"a":1,"b":{"c":2}}';
80 runParsingTest(new goog.json.EvalJsonProcessor(null, true), json, json);
81 }
82
83 function testUnsafeJsParser_withReplacer() {
84 runParsingTest(
85 new goog.json.EvalJsonProcessor(REPLACER, true), '{"a":"foo","b":"goo"}',
86 '{"a":"food","b":"good"}');
87 }
88
89 function runParsingTest(parser, input, expected) {
90 assertEquals(expected, parser.stringify(parser.parse(input)));
91 }