ec27a901605612c9b0b62cccc7d71e3775d8f061
[folly.git] / folly / test / JsonTest.cpp
1 /*
2  * Copyright 2016 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 #include <limits>
17 #include <strstream>
18
19 #include <boost/next_prior.hpp>
20 #include <folly/json.h>
21 #include <gflags/gflags.h>
22 #include <gtest/gtest.h>
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, BoolConversion) {
154   EXPECT_TRUE(parseJson("42").asBool());
155 }
156
157 TEST(Json, JavascriptSafe) {
158   auto badDouble = (1ll << 63ll) + 1;
159   dynamic badDyn = badDouble;
160   EXPECT_EQ(folly::toJson(badDouble), folly::to<folly::fbstring>(badDouble));
161   folly::json::serialization_opts opts;
162   opts.javascript_safe = true;
163   EXPECT_ANY_THROW(folly::json::serialize(badDouble, opts));
164
165   auto okDouble = 1ll << 63ll;
166   dynamic okDyn = okDouble;
167   EXPECT_EQ(folly::toJson(okDouble), folly::to<folly::fbstring>(okDouble));
168 }
169
170 TEST(Json, Produce) {
171   auto value = parseJson(R"( "f\"oo" )");
172   EXPECT_EQ(toJson(value), R"("f\"oo")");
173   value = parseJson("\"Control code: \001 \002 \x1f\"");
174   EXPECT_EQ(toJson(value), R"("Control code: \u0001 \u0002 \u001f")");
175
176   // We're not allowed to have non-string keys in json.
177   EXPECT_THROW(toJson(dynamic::object("abc", "xyz")(42.33, "asd")),
178                std::runtime_error);
179
180   // Check Infinity/Nan
181   folly::json::serialization_opts opts;
182   opts.allow_nan_inf = true;
183   EXPECT_EQ("Infinity",
184             folly::json::serialize(parseJson("Infinity"), opts).toStdString());
185   EXPECT_EQ("NaN",
186             folly::json::serialize(parseJson("NaN"), opts).toStdString());
187 }
188
189 TEST(Json, JsonEscape) {
190   folly::json::serialization_opts opts;
191   EXPECT_EQ(
192     folly::json::serialize("\b\f\n\r\x01\t\\\"/\v\a", opts),
193     R"("\b\f\n\r\u0001\t\\\"/\u000b\u0007")");
194 }
195
196 TEST(Json, JsonNonAsciiEncoding) {
197   folly::json::serialization_opts opts;
198   opts.encode_non_ascii = true;
199
200   // simple tests
201   EXPECT_EQ(folly::json::serialize("\x1f", opts), R"("\u001f")");
202   EXPECT_EQ(folly::json::serialize("\xc2\xa2", opts), R"("\u00a2")");
203   EXPECT_EQ(folly::json::serialize("\xe2\x82\xac", opts), R"("\u20ac")");
204
205   // multiple unicode encodings
206   EXPECT_EQ(
207     folly::json::serialize("\x1f\xe2\x82\xac", opts),
208     R"("\u001f\u20ac")");
209   EXPECT_EQ(
210     folly::json::serialize("\x1f\xc2\xa2\xe2\x82\xac", opts),
211     R"("\u001f\u00a2\u20ac")");
212   EXPECT_EQ(
213     folly::json::serialize("\xc2\x80\xef\xbf\xbf", opts),
214     R"("\u0080\uffff")");
215   EXPECT_EQ(
216     folly::json::serialize("\xe0\xa0\x80\xdf\xbf", opts),
217     R"("\u0800\u07ff")");
218
219   // first possible sequence of a certain length
220   EXPECT_EQ(folly::json::serialize("\xc2\x80", opts), R"("\u0080")");
221   EXPECT_EQ(folly::json::serialize("\xe0\xa0\x80", opts), R"("\u0800")");
222
223   // last possible sequence of a certain length
224   EXPECT_EQ(folly::json::serialize("\xdf\xbf", opts), R"("\u07ff")");
225   EXPECT_EQ(folly::json::serialize("\xef\xbf\xbf", opts), R"("\uffff")");
226
227   // other boundary conditions
228   EXPECT_EQ(folly::json::serialize("\xed\x9f\xbf", opts), R"("\ud7ff")");
229   EXPECT_EQ(folly::json::serialize("\xee\x80\x80", opts), R"("\ue000")");
230   EXPECT_EQ(folly::json::serialize("\xef\xbf\xbd", opts), R"("\ufffd")");
231
232   // incomplete sequences
233   EXPECT_ANY_THROW(folly::json::serialize("a\xed\x9f", opts));
234   EXPECT_ANY_THROW(folly::json::serialize("b\xee\x80", opts));
235   EXPECT_ANY_THROW(folly::json::serialize("c\xef\xbf", opts));
236
237   // impossible bytes
238   EXPECT_ANY_THROW(folly::json::serialize("\xfe", opts));
239   EXPECT_ANY_THROW(folly::json::serialize("\xff", opts));
240
241   // Sample overlong sequences
242   EXPECT_ANY_THROW(folly::json::serialize("\xc0\xaf", opts));
243   EXPECT_ANY_THROW(folly::json::serialize("\xe0\x80\xaf", opts));
244
245   // Maximum overlong sequences
246   EXPECT_ANY_THROW(folly::json::serialize("\xc1\xbf", opts));
247   EXPECT_ANY_THROW(folly::json::serialize("\x30\x9f\xbf", opts));
248
249   // illegal code positions
250   EXPECT_ANY_THROW(folly::json::serialize("\xed\xa0\x80", opts));
251   EXPECT_ANY_THROW(folly::json::serialize("\xed\xbf\xbf", opts));
252
253   // Overlong representation of NUL character
254   EXPECT_ANY_THROW(folly::json::serialize("\xc0\x80", opts));
255   EXPECT_ANY_THROW(folly::json::serialize("\xe0\x80\x80", opts));
256
257   // Longer than 3 byte encodings
258   EXPECT_ANY_THROW(folly::json::serialize("\xf4\x8f\xbf\xbf", opts));
259   EXPECT_ANY_THROW(folly::json::serialize("\xed\xaf\xbf\xed\xbf\xbf", opts));
260 }
261
262 TEST(Json, UTF8Retention) {
263
264   // test retention with valid utf8 strings
265   folly::fbstring input = "\u2665";
266   folly::fbstring jsonInput = folly::toJson(input);
267   folly::fbstring output = folly::parseJson(jsonInput).asString();
268   folly::fbstring jsonOutput = folly::toJson(output);
269
270   EXPECT_EQ(input, output);
271   EXPECT_EQ(jsonInput, jsonOutput);
272
273   // test retention with invalid utf8 - note that non-ascii chars are retained
274   // as is, and no unicode encoding is attempted so no exception is thrown.
275   EXPECT_EQ(
276     folly::toJson("a\xe0\xa0\x80z\xc0\x80"),
277     "\"a\xe0\xa0\x80z\xc0\x80\""
278   );
279 }
280
281 TEST(Json, UTF8EncodeNonAsciiRetention) {
282
283   folly::json::serialization_opts opts;
284   opts.encode_non_ascii = true;
285
286   // test encode_non_ascii valid utf8 strings
287   folly::fbstring input = "\u2665";
288   folly::fbstring jsonInput = folly::json::serialize(input, opts);
289   folly::fbstring output = folly::parseJson(jsonInput).asString();
290   folly::fbstring jsonOutput = folly::json::serialize(output, opts);
291
292   EXPECT_EQ(input, output);
293   EXPECT_EQ(jsonInput, jsonOutput);
294
295   // test encode_non_ascii with invalid utf8 - note that an attempt to encode
296   // non-ascii to unicode will result is a utf8 validation and throw exceptions.
297   EXPECT_ANY_THROW(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80", opts));
298   EXPECT_ANY_THROW(folly::json::serialize("a\xe0\xa0\x80z\xe0\x80\x80", opts));
299 }
300
301 TEST(Json, UTF8Validation) {
302   folly::json::serialization_opts opts;
303   opts.validate_utf8 = true;
304
305   // test validate_utf8 valid utf8 strings - note that we only validate the
306   // for utf8 but don't encode non-ascii to unicode so they are retained as is.
307   EXPECT_EQ(folly::json::serialize("a\xc2\x80z", opts), "\"a\xc2\x80z\"");
308   EXPECT_EQ(
309     folly::json::serialize("a\xe0\xa0\x80z", opts),
310     "\"a\xe0\xa0\x80z\"");
311   EXPECT_EQ(
312     folly::json::serialize("a\xe0\xa0\x80m\xc2\x80z", opts),
313     "\"a\xe0\xa0\x80m\xc2\x80z\"");
314
315   // test validate_utf8 with invalid utf8
316   EXPECT_ANY_THROW(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80", opts));
317   EXPECT_ANY_THROW(folly::json::serialize("a\xe0\xa0\x80z\xe0\x80\x80", opts));
318
319   opts.skip_invalid_utf8 = true;
320   EXPECT_EQ(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80", opts),
321             "\"a\xe0\xa0\x80z\ufffd\ufffd\"");
322   EXPECT_EQ(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80\x80", opts),
323             "\"a\xe0\xa0\x80z\ufffd\ufffd\ufffd\"");
324   EXPECT_EQ(folly::json::serialize("z\xc0\x80z\xe0\xa0\x80", opts),
325             "\"z\ufffd\ufffdz\xe0\xa0\x80\"");
326
327   opts.encode_non_ascii = true;
328   EXPECT_EQ(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80", opts),
329             "\"a\\u0800z\\ufffd\\ufffd\"");
330   EXPECT_EQ(folly::json::serialize("a\xe0\xa0\x80z\xc0\x80\x80", opts),
331             "\"a\\u0800z\\ufffd\\ufffd\\ufffd\"");
332   EXPECT_EQ(folly::json::serialize("z\xc0\x80z\xe0\xa0\x80", opts),
333             "\"z\\ufffd\\ufffdz\\u0800\"");
334
335 }
336
337
338 TEST(Json, ParseNonStringKeys) {
339   // test string keys
340   EXPECT_EQ("a", parseJson("{\"a\":[]}").items().begin()->first.asString());
341
342   // check that we don't allow non-string keys as this violates the
343   // strict JSON spec (though it is emitted by the output of
344   // folly::dynamic with operator <<).
345   EXPECT_THROW(parseJson("{1:[]}"), std::runtime_error);
346
347   // check that we can parse colloquial JSON if the option is set
348   folly::json::serialization_opts opts;
349   opts.allow_non_string_keys = true;
350
351   auto val = parseJson("{1:[]}", opts);
352   EXPECT_EQ(1, val.items().begin()->first.asInt());
353
354
355   // test we can still read in strings
356   auto sval = parseJson("{\"a\":[]}", opts);
357   EXPECT_EQ("a", sval.items().begin()->first.asString());
358
359   // test we can read in doubles
360   auto dval = parseJson("{1.5:[]}", opts);
361   EXPECT_EQ(1.5, dval.items().begin()->first.asDouble());
362 }
363
364 TEST(Json, ParseDoubleFallback) {
365   // default behavior
366   EXPECT_THROW(parseJson("{\"a\":847605071342477600000000000000}"),
367       std::range_error);
368   EXPECT_THROW(parseJson("{\"a\":-9223372036854775809}"),
369       std::range_error);
370   EXPECT_THROW(parseJson("{\"a\":9223372036854775808}"),
371       std::range_error);
372   EXPECT_EQ(std::numeric_limits<int64_t>::min(),
373       parseJson("{\"a\":-9223372036854775808}").items().begin()
374         ->second.asInt());
375   EXPECT_EQ(std::numeric_limits<int64_t>::max(),
376       parseJson("{\"a\":9223372036854775807}").items().begin()->second.asInt());
377   // with double_fallback
378   folly::json::serialization_opts opts;
379   opts.double_fallback = true;
380   EXPECT_EQ(847605071342477600000000000000.0,
381       parseJson("{\"a\":847605071342477600000000000000}",
382         opts).items().begin()->second.asDouble());
383   EXPECT_EQ(847605071342477600000000000000.0,
384       parseJson("{\"a\": 847605071342477600000000000000}",
385         opts).items().begin()->second.asDouble());
386   EXPECT_EQ(847605071342477600000000000000.0,
387       parseJson("{\"a\":847605071342477600000000000000 }",
388         opts).items().begin()->second.asDouble());
389   EXPECT_EQ(847605071342477600000000000000.0,
390       parseJson("{\"a\": 847605071342477600000000000000 }",
391         opts).items().begin()->second.asDouble());
392   EXPECT_EQ(std::numeric_limits<int64_t>::min(),
393       parseJson("{\"a\":-9223372036854775808}",
394         opts).items().begin()->second.asInt());
395   EXPECT_EQ(std::numeric_limits<int64_t>::max(),
396       parseJson("{\"a\":9223372036854775807}",
397         opts).items().begin()->second.asInt());
398   // show that some precision gets lost
399   EXPECT_EQ(847605071342477612345678900000.0,
400       parseJson("{\"a\":847605071342477612345678912345}",
401         opts).items().begin()->second.asDouble());
402 }
403
404 TEST(Json, ParseNumbersAsStrings) {
405   folly::json::serialization_opts opts;
406   opts.parse_numbers_as_strings = true;
407   auto parse = [&](folly::fbstring number) {
408     return parseJson(number, opts).asString();
409   };
410
411   EXPECT_EQ("0", parse("0"));
412   EXPECT_EQ("1234", parse("1234"));
413   EXPECT_EQ("3.00", parse("3.00"));
414   EXPECT_EQ("3.14", parse("3.14"));
415   EXPECT_EQ("0.1234", parse("0.1234"));
416   EXPECT_EQ("0.0", parse("0.0"));
417   EXPECT_EQ("46845131213548676854213265486468451312135486768542132",
418       parse("46845131213548676854213265486468451312135486768542132"));
419   EXPECT_EQ("-468451312135486768542132654864684513121354867685.5e4",
420       parse("-468451312135486768542132654864684513121354867685.5e4"));
421   EXPECT_EQ("6.62607004e-34", parse("6.62607004e-34"));
422   EXPECT_EQ("6.62607004E+34", parse("6.62607004E+34"));
423   EXPECT_EQ("Infinity", parse("Infinity"));
424   EXPECT_EQ("-Infinity", parse("-Infinity"));
425   EXPECT_EQ("NaN", parse("NaN"));
426
427   EXPECT_THROW(parse("ThisIsWrong"), std::runtime_error);
428   EXPECT_THROW(parse("34-2"), std::runtime_error);
429   EXPECT_THROW(parse(""), std::runtime_error);
430   EXPECT_THROW(parse("-"), std::runtime_error);
431   EXPECT_THROW(parse("34-e2"), std::runtime_error);
432   EXPECT_THROW(parse("34e2.4"), std::runtime_error);
433   EXPECT_THROW(parse("infinity"), std::runtime_error);
434   EXPECT_THROW(parse("nan"), std::runtime_error);
435 }
436
437 TEST(Json, SortKeys) {
438   folly::json::serialization_opts opts_on, opts_off;
439   opts_on.sort_keys = true;
440   opts_off.sort_keys = false;
441
442   dynamic value = dynamic::object
443     ("foo", "bar")
444     ("junk", 12)
445     ("another", 32.2)
446     ("a",
447       {
448         dynamic::object("a", "b")
449                        ("c", "d"),
450         12.5,
451         "Yo Dawg",
452         { "heh" },
453         nullptr
454       }
455     )
456     ;
457
458   std::string sorted_keys =
459     R"({"a":[{"a":"b","c":"d"},12.5,"Yo Dawg",["heh"],null],)"
460     R"("another":32.2,"foo":"bar","junk":12})";
461
462   EXPECT_EQ(value, parseJson(folly::json::serialize(value, opts_on)));
463   EXPECT_EQ(value, parseJson(folly::json::serialize(value, opts_off)));
464
465   EXPECT_EQ(sorted_keys, folly::json::serialize(value, opts_on));
466 }
467
468 TEST(Json, PrintTo) {
469   std::ostringstream oss;
470
471   dynamic value = dynamic::object
472     ("foo", "bar")
473     ("junk", 12)
474     ("another", 32.2)
475     (true, false) // include non-string keys
476     (false, true)
477     (2, 3)
478     (0, 1)
479     (1, 2)
480     (1.5, 2.25)
481     (0.5, 0.25)
482     (0, 1)
483     (1, 2)
484     ("a",
485       {
486         dynamic::object("a", "b")
487                        ("c", "d"),
488         12.5,
489         "Yo Dawg",
490         { "heh" },
491         nullptr
492       }
493     )
494     ;
495
496   std::string expected =
497       R"({
498   false : true,
499   true : false,
500   0.5 : 0.25,
501   1.5 : 2.25,
502   0 : 1,
503   1 : 2,
504   2 : 3,
505   "a" : [
506     {
507       "a" : "b",
508       "c" : "d"
509     },
510     12.5,
511     "Yo Dawg",
512     [
513       "heh"
514     ],
515     null
516   ],
517   "another" : 32.2,
518   "foo" : "bar",
519   "junk" : 12
520 })";
521   PrintTo(value, &oss);
522   EXPECT_EQ(expected, oss.str());
523 }
524
525 int main(int argc, char** argv) {
526   testing::InitGoogleTest(&argc, argv);
527   gflags::ParseCommandLineFlags(&argc, &argv, true);
528   return RUN_ALL_TESTS();
529 }