Fix Infinity
[folly.git] / folly / test / JsonTest.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/json.h>
18
19 #include <gtest/gtest.h>
20 #include <gflags/gflags.h>
21 #include <limits>
22 #include <boost/next_prior.hpp>
23
24 using folly::dynamic;
25 using folly::parseJson;
26 using folly::toJson;
27
28 TEST(Json, Unicode) {
29   auto val = parseJson("\"I \u2665 UTF-8\"");
30   EXPECT_EQ("I \u2665 UTF-8", val.asString());
31   val = parseJson("\"I \\u2665 UTF-8\"");
32   EXPECT_EQ("I \u2665 UTF-8", val.asString());
33   val = parseJson("\"I \U0001D11E playing in G-clef\"");
34   EXPECT_EQ("I \U0001D11E playing in G-clef", val.asString());
35
36   val = parseJson("\"I \\uD834\\uDD1E playing in G-clef\"");
37   EXPECT_EQ("I \U0001D11E playing in G-clef", val.asString());
38 }
39
40 TEST(Json, Parse) {
41   auto num = parseJson("12");
42   EXPECT_TRUE(num.isInt());
43   EXPECT_EQ(num, 12);
44   num = parseJson("12e5");
45   EXPECT_TRUE(num.isDouble());
46   EXPECT_EQ(num, 12e5);
47   auto numAs1 = num.asDouble();
48   EXPECT_EQ(numAs1, 12e5);
49   EXPECT_EQ(num, 12e5);
50   EXPECT_EQ(num, 1200000);
51
52   auto largeNumber = parseJson("4611686018427387904");
53   EXPECT_TRUE(largeNumber.isInt());
54   EXPECT_EQ(largeNumber, 4611686018427387904L);
55
56   auto negative = parseJson("-123");
57   EXPECT_EQ(negative, -123);
58
59   auto bfalse = parseJson("false");
60   auto btrue = parseJson("true");
61   EXPECT_EQ(bfalse, false);
62   EXPECT_EQ(btrue, true);
63
64   auto null = parseJson("null");
65   EXPECT_TRUE(null == nullptr);
66
67   auto doub1 = parseJson("12.0");
68   auto doub2 = parseJson("12e2");
69   EXPECT_EQ(doub1, 12.0);
70   EXPECT_EQ(doub2, 12e2);
71   EXPECT_EQ(std::numeric_limits<double>::infinity(),
72             parseJson("Infinity").asDouble());
73   EXPECT_EQ(-std::numeric_limits<double>::infinity(),
74             parseJson("-Infinity").asDouble());
75   EXPECT_TRUE(std::isnan(parseJson("NaN").asDouble()));
76
77   // case matters
78   EXPECT_THROW(parseJson("infinity"), std::runtime_error);
79   EXPECT_THROW(parseJson("inf"), std::runtime_error);
80   EXPECT_THROW(parseJson("Inf"), std::runtime_error);
81   EXPECT_THROW(parseJson("INF"), std::runtime_error);
82   EXPECT_THROW(parseJson("nan"), std::runtime_error);
83   EXPECT_THROW(parseJson("NAN"), std::runtime_error);
84
85   auto array = parseJson(
86     "[12,false, false  , null , [12e4,32, [], 12]]");
87   EXPECT_EQ(array.size(), 5);
88   if (array.size() == 5) {
89     EXPECT_EQ(boost::prior(array.end())->size(), 4);
90   }
91
92   EXPECT_THROW(parseJson("\n[12,\n\nnotvalidjson"),
93                std::runtime_error);
94
95   EXPECT_THROW(parseJson("12e2e2"),
96                std::runtime_error);
97
98   EXPECT_THROW(parseJson("{\"foo\":12,\"bar\":42} \"something\""),
99                std::runtime_error);
100
101   dynamic value = dynamic::object
102     ("foo", "bar")
103     ("junk", 12)
104     ("another", 32.2)
105     ("a",
106       {
107         dynamic::object("a", "b")
108                        ("c", "d"),
109         12.5,
110         "Yo Dawg",
111         { "heh" },
112         nullptr
113       }
114     )
115     ;
116
117   // Print then parse and get the same thing, hopefully.
118   EXPECT_EQ(value, parseJson(toJson(value)));
119
120
121   // Test an object with non-string values.
122   dynamic something = parseJson(
123     "{\"old_value\":40,\"changed\":true,\"opened\":false}");
124   dynamic expected = dynamic::object
125     ("old_value", 40)
126     ("changed", true)
127     ("opened", false);
128   EXPECT_EQ(something, expected);
129 }
130
131 TEST(Json, ParseTrailingComma) {
132   folly::json::serialization_opts on, off;
133   on.allow_trailing_comma = true;
134   off.allow_trailing_comma = false;
135
136   dynamic arr { 1, 2 };
137   EXPECT_EQ(arr, parseJson("[1, 2]", on));
138   EXPECT_EQ(arr, parseJson("[1, 2,]", on));
139   EXPECT_EQ(arr, parseJson("[1, 2, ]", on));
140   EXPECT_EQ(arr, parseJson("[1, 2 , ]", on));
141   EXPECT_EQ(arr, parseJson("[1, 2 ,]", on));
142   EXPECT_THROW(parseJson("[1, 2,]", off), std::runtime_error);
143
144   dynamic obj = dynamic::object("a", 1);
145   EXPECT_EQ(obj, parseJson("{\"a\": 1}", on));
146   EXPECT_EQ(obj, parseJson("{\"a\": 1,}", on));
147   EXPECT_EQ(obj, parseJson("{\"a\": 1, }", on));
148   EXPECT_EQ(obj, parseJson("{\"a\": 1 , }", on));
149   EXPECT_EQ(obj, parseJson("{\"a\": 1 ,}", on));
150   EXPECT_THROW(parseJson("{\"a\":1,}", off), std::runtime_error);
151 }
152
153 TEST(Json, JavascriptSafe) {
154   auto badDouble = (1ll << 63ll) + 1;
155   dynamic badDyn = badDouble;
156   EXPECT_EQ(folly::toJson(badDouble), folly::to<folly::fbstring>(badDouble));
157   folly::json::serialization_opts opts;
158   opts.javascript_safe = true;
159   EXPECT_ANY_THROW(folly::json::serialize(badDouble, opts));
160
161   auto okDouble = 1ll << 63ll;
162   dynamic okDyn = okDouble;
163   EXPECT_EQ(folly::toJson(okDouble), folly::to<folly::fbstring>(okDouble));
164 }
165
166 TEST(Json, Produce) {
167   auto value = parseJson(R"( "f\"oo" )");
168   EXPECT_EQ(toJson(value), R"("f\"oo")");
169   value = parseJson("\"Control code: \001 \002 \x1f\"");
170   EXPECT_EQ(toJson(value), R"("Control code: \u0001 \u0002 \u001f")");
171
172   // We're not allowed to have non-string keys in json.
173   EXPECT_THROW(toJson(dynamic::object("abc", "xyz")(42.33, "asd")),
174                std::runtime_error);
175
176   // Check Infinity/Nan
177   folly::json::serialization_opts opts;
178   opts.allow_nan_inf = true;
179   EXPECT_EQ("Infinity",
180             folly::json::serialize(parseJson("Infinity"), opts).toStdString());
181   EXPECT_EQ("NaN",
182             folly::json::serialize(parseJson("NaN"), opts).toStdString());
183 }
184
185 TEST(Json, JsonEscape) {
186   folly::json::serialization_opts opts;
187   EXPECT_EQ(
188     folly::json::serialize("\b\f\n\r\x01\t\\\"/\v\a", opts),
189     R"("\b\f\n\r\u0001\t\\\"/\u000b\u0007")");
190 }
191
192 TEST(Json, JsonNonAsciiEncoding) {
193   folly::json::serialization_opts opts;
194   opts.encode_non_ascii = true;
195
196   // simple tests
197   EXPECT_EQ(folly::json::serialize("\x1f", opts), R"("\u001f")");
198   EXPECT_EQ(folly::json::serialize("\xc2\xa2", opts), R"("\u00a2")");
199   EXPECT_EQ(folly::json::serialize("\xe2\x82\xac", opts), R"("\u20ac")");
200
201   // multiple unicode encodings
202   EXPECT_EQ(
203     folly::json::serialize("\x1f\xe2\x82\xac", opts),
204     R"("\u001f\u20ac")");
205   EXPECT_EQ(
206     folly::json::serialize("\x1f\xc2\xa2\xe2\x82\xac", opts),
207     R"("\u001f\u00a2\u20ac")");
208   EXPECT_EQ(
209     folly::json::serialize("\xc2\x80\xef\xbf\xbf", opts),
210     R"("\u0080\uffff")");
211   EXPECT_EQ(
212     folly::json::serialize("\xe0\xa0\x80\xdf\xbf", opts),
213     R"("\u0800\u07ff")");
214
215   // first possible sequence of a certain length
216   EXPECT_EQ(folly::json::serialize("\xc2\x80", opts), R"("\u0080")");
217   EXPECT_EQ(folly::json::serialize("\xe0\xa0\x80", opts), R"("\u0800")");
218
219   // last possible sequence of a certain length
220   EXPECT_EQ(folly::json::serialize("\xdf\xbf", opts), R"("\u07ff")");
221   EXPECT_EQ(folly::json::serialize("\xef\xbf\xbf", opts), R"("\uffff")");
222
223   // other boundary conditions
224   EXPECT_EQ(folly::json::serialize("\xed\x9f\xbf", opts), R"("\ud7ff")");
225   EXPECT_EQ(folly::json::serialize("\xee\x80\x80", opts), R"("\ue000")");
226   EXPECT_EQ(folly::json::serialize("\xef\xbf\xbd", opts), R"("\ufffd")");
227
228   // incomplete sequences
229   EXPECT_ANY_THROW(folly::json::serialize("a\xed\x9f", opts));
230   EXPECT_ANY_THROW(folly::json::serialize("b\xee\x80", opts));
231   EXPECT_ANY_THROW(folly::json::serialize("c\xef\xbf", opts));
232
233   // impossible bytes
234   EXPECT_ANY_THROW(folly::json::serialize("\xfe", opts));
235   EXPECT_ANY_THROW(folly::json::serialize("\xff", opts));
236
237   // Sample overlong sequences
238   EXPECT_ANY_THROW(folly::json::serialize("\xc0\xaf", opts));
239   EXPECT_ANY_THROW(folly::json::serialize("\xe0\x80\xaf", opts));
240
241   // Maximum overlong sequences
242   EXPECT_ANY_THROW(folly::json::serialize("\xc1\xbf", opts));
243   EXPECT_ANY_THROW(folly::json::serialize("\x30\x9f\xbf", opts));
244
245   // illegal code positions
246   EXPECT_ANY_THROW(folly::json::serialize("\xed\xa0\x80", opts));
247   EXPECT_ANY_THROW(folly::json::serialize("\xed\xbf\xbf", opts));
248
249   // Overlong representation of NUL character
250   EXPECT_ANY_THROW(folly::json::serialize("\xc0\x80", opts));
251   EXPECT_ANY_THROW(folly::json::serialize("\xe0\x80\x80", opts));
252
253   // Longer than 3 byte encodings
254   EXPECT_ANY_THROW(folly::json::serialize("\xf4\x8f\xbf\xbf", opts));
255   EXPECT_ANY_THROW(folly::json::serialize("\xed\xaf\xbf\xed\xbf\xbf", opts));
256 }
257
258 TEST(Json, UTF8Retention) {
259
260   // test retention with valid utf8 strings
261   folly::fbstring input = "\u2665";
262   folly::fbstring jsonInput = folly::toJson(input);
263   folly::fbstring output = folly::parseJson(jsonInput).asString();
264   folly::fbstring jsonOutput = folly::toJson(output);
265
266   EXPECT_EQ(input, output);
267   EXPECT_EQ(jsonInput, jsonOutput);
268
269   // test retention with invalid utf8 - note that non-ascii chars are retained
270   // as is, and no unicode encoding is attempted so no exception is thrown.
271   EXPECT_EQ(
272     folly::toJson("a\xe0\xa0\x80z\xc0\x80"),
273     "\"a\xe0\xa0\x80z\xc0\x80\""
274   );
275 }
276
277 TEST(Json, UTF8EncodeNonAsciiRetention) {
278
279   folly::json::serialization_opts opts;
280   opts.encode_non_ascii = true;
281
282   // test encode_non_ascii valid utf8 strings
283   folly::fbstring input = "\u2665";
284   folly::fbstring jsonInput = folly::json::serialize(input, opts);
285   folly::fbstring output = folly::parseJson(jsonInput).asString();
286   folly::fbstring jsonOutput = folly::json::serialize(output, opts);
287
288   EXPECT_EQ(input, output);
289   EXPECT_EQ(jsonInput, jsonOutput);
290
291   // test encode_non_ascii with invalid utf8 - note that an attempt to encode
292   // non-ascii to unicode will result is a utf8 validation and throw exceptions.
293   EXPECT_ANY_THROW(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80", opts));
294   EXPECT_ANY_THROW(folly::json::serialize("a\xe0\xa0\x80z\xe0\x80\x80", opts));
295 }
296
297 TEST(Json, UTF8Validation) {
298   folly::json::serialization_opts opts;
299   opts.validate_utf8 = true;
300
301   // test validate_utf8 valid utf8 strings - note that we only validate the
302   // for utf8 but don't encode non-ascii to unicode so they are retained as is.
303   EXPECT_EQ(folly::json::serialize("a\xc2\x80z", opts), "\"a\xc2\x80z\"");
304   EXPECT_EQ(
305     folly::json::serialize("a\xe0\xa0\x80z", opts),
306     "\"a\xe0\xa0\x80z\"");
307   EXPECT_EQ(
308     folly::json::serialize("a\xe0\xa0\x80m\xc2\x80z", opts),
309     "\"a\xe0\xa0\x80m\xc2\x80z\"");
310
311   // test validate_utf8 with invalid utf8
312   EXPECT_ANY_THROW(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80", opts));
313   EXPECT_ANY_THROW(folly::json::serialize("a\xe0\xa0\x80z\xe0\x80\x80", opts));
314
315   opts.skip_invalid_utf8 = true;
316   EXPECT_EQ(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80", opts),
317             "\"a\xe0\xa0\x80z\ufffd\ufffd\"");
318   EXPECT_EQ(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80\x80", opts),
319             "\"a\xe0\xa0\x80z\ufffd\ufffd\ufffd\"");
320   EXPECT_EQ(folly::json::serialize("z\xc0\x80z\xe0\xa0\x80", opts),
321             "\"z\ufffd\ufffdz\xe0\xa0\x80\"");
322
323   opts.encode_non_ascii = true;
324   EXPECT_EQ(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80", opts),
325             "\"a\\u0800z\\ufffd\\ufffd\"");
326   EXPECT_EQ(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80\x80", opts),
327             "\"a\\u0800z\\ufffd\\ufffd\\ufffd\"");
328   EXPECT_EQ(folly::json::serialize("z\xc0\x80z\xe0\xa0\x80", opts),
329             "\"z\\ufffd\\ufffdz\\u0800\"");
330
331 }
332
333
334 TEST(Json, ParseNonStringKeys) {
335   // test string keys
336   EXPECT_EQ("a", parseJson("{\"a\":[]}").items().begin()->first.asString());
337
338   // check that we don't allow non-string keys as this violates the
339   // strict JSON spec (though it is emitted by the output of
340   // folly::dynamic with operator <<).
341   EXPECT_THROW(parseJson("{1:[]}"), std::runtime_error);
342
343   // check that we can parse colloquial JSON if the option is set
344   folly::json::serialization_opts opts;
345   opts.allow_non_string_keys = true;
346
347   auto val = parseJson("{1:[]}", opts);
348   EXPECT_EQ(1, val.items().begin()->first.asInt());
349
350
351   // test we can still read in strings
352   auto sval = parseJson("{\"a\":[]}", opts);
353   EXPECT_EQ("a", sval.items().begin()->first.asString());
354
355   // test we can read in doubles
356   auto dval = parseJson("{1.5:[]}", opts);
357   EXPECT_EQ(1.5, dval.items().begin()->first.asDouble());
358 }
359
360 TEST(Json, SortKeys) {
361   folly::json::serialization_opts opts_on, opts_off;
362   opts_on.sort_keys = true;
363   opts_off.sort_keys = false;
364
365   dynamic value = dynamic::object
366     ("foo", "bar")
367     ("junk", 12)
368     ("another", 32.2)
369     ("a",
370       {
371         dynamic::object("a", "b")
372                        ("c", "d"),
373         12.5,
374         "Yo Dawg",
375         { "heh" },
376         nullptr
377       }
378     )
379     ;
380
381   std::string sorted_keys =
382     R"({"a":[{"a":"b","c":"d"},12.5,"Yo Dawg",["heh"],null],)"
383     R"("another":32.2,"foo":"bar","junk":12})";
384
385   EXPECT_EQ(value, parseJson(folly::json::serialize(value, opts_on)));
386   EXPECT_EQ(value, parseJson(folly::json::serialize(value, opts_off)));
387
388   EXPECT_EQ(sorted_keys, folly::json::serialize(value, opts_on));
389 }
390
391 int main(int argc, char** argv) {
392   testing::InitGoogleTest(&argc, argv);
393   gflags::ParseCommandLineFlags(&argc, &argv, true);
394   return RUN_ALL_TESTS();
395 }