blob: 64a2bb97bd8bef9ec6688c25290b5182f6d4fa01 [file] [log] [blame]
Sam McCall6be38242018-07-09 10:05:41 +00001//===-- JSONTest.cpp - JSON unit tests --------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Support/JSON.h"
11
12#include "gmock/gmock.h"
13#include "gtest/gtest.h"
14
15namespace llvm {
16namespace json {
17
18namespace {
19
20std::string s(const Value &E) { return llvm::formatv("{0}", E).str(); }
21std::string sp(const Value &E) { return llvm::formatv("{0:2}", E).str(); }
22
23TEST(JSONTest, Types) {
24 EXPECT_EQ("true", s(true));
25 EXPECT_EQ("null", s(nullptr));
26 EXPECT_EQ("2.5", s(2.5));
27 EXPECT_EQ(R"("foo")", s("foo"));
28 EXPECT_EQ("[1,2,3]", s({1, 2, 3}));
29 EXPECT_EQ(R"({"x":10,"y":20})", s(Object{{"x", 10}, {"y", 20}}));
Sam McCalle6057bc2018-07-10 11:51:26 +000030
31#ifdef NDEBUG
32 EXPECT_EQ(R"("��")", s("\xC0\x80"));
33 EXPECT_EQ(R"({"��":0})", s(Object{{"\xC0\x80", 0}}));
34#else
35 EXPECT_DEATH(s("\xC0\x80"), "Invalid UTF-8");
36 EXPECT_DEATH(s(Object{{"\xC0\x80", 0}}), "Invalid UTF-8");
37#endif
Sam McCall6be38242018-07-09 10:05:41 +000038}
39
40TEST(JSONTest, Constructors) {
41 // Lots of edge cases around empty and singleton init lists.
42 EXPECT_EQ("[[[3]]]", s({{{3}}}));
43 EXPECT_EQ("[[[]]]", s({{{}}}));
44 EXPECT_EQ("[[{}]]", s({{Object{}}}));
45 EXPECT_EQ(R"({"A":{"B":{}}})", s(Object{{"A", Object{{"B", Object{}}}}}));
46 EXPECT_EQ(R"({"A":{"B":{"X":"Y"}}})",
47 s(Object{{"A", Object{{"B", Object{{"X", "Y"}}}}}}));
Sam McCall7e4234f2018-07-09 12:26:09 +000048 EXPECT_EQ("null", s(llvm::Optional<double>()));
49 EXPECT_EQ("2.5", s(llvm::Optional<double>(2.5)));
Sam McCall6be38242018-07-09 10:05:41 +000050}
51
52TEST(JSONTest, StringOwnership) {
53 char X[] = "Hello";
54 Value Alias = static_cast<const char *>(X);
55 X[1] = 'a';
56 EXPECT_EQ(R"("Hallo")", s(Alias));
57
58 std::string Y = "Hello";
59 Value Copy = Y;
60 Y[1] = 'a';
61 EXPECT_EQ(R"("Hello")", s(Copy));
62}
63
64TEST(JSONTest, CanonicalOutput) {
65 // Objects are sorted (but arrays aren't)!
66 EXPECT_EQ(R"({"a":1,"b":2,"c":3})", s(Object{{"a", 1}, {"c", 3}, {"b", 2}}));
67 EXPECT_EQ(R"(["a","c","b"])", s({"a", "c", "b"}));
68 EXPECT_EQ("3", s(3.0));
69}
70
71TEST(JSONTest, Escaping) {
72 std::string test = {
73 0, // Strings may contain nulls.
74 '\b', '\f', // Have mnemonics, but we escape numerically.
75 '\r', '\n', '\t', // Escaped with mnemonics.
76 'S', '\"', '\\', // Printable ASCII characters.
77 '\x7f', // Delete is not escaped.
78 '\xce', '\x94', // Non-ASCII UTF-8 is not escaped.
79 };
80
81 std::string teststring = R"("\u0000\u0008\u000c\r\n\tS\"\\)"
82 "\x7f\xCE\x94\"";
83
84 EXPECT_EQ(teststring, s(test));
85
86 EXPECT_EQ(R"({"object keys are\nescaped":true})",
87 s(Object{{"object keys are\nescaped", true}}));
88}
89
90TEST(JSONTest, PrettyPrinting) {
91 const char str[] = R"({
92 "empty_array": [],
93 "empty_object": {},
94 "full_array": [
95 1,
96 null
97 ],
98 "full_object": {
99 "nested_array": [
100 {
101 "property": "value"
102 }
103 ]
104 }
105})";
106
107 EXPECT_EQ(str, sp(Object{
108 {"empty_object", Object{}},
109 {"empty_array", {}},
110 {"full_array", {1, nullptr}},
111 {"full_object",
112 Object{
113 {"nested_array",
114 {Object{
115 {"property", "value"},
116 }}},
117 }},
118 }));
119}
120
121TEST(JSONTest, Parse) {
122 auto Compare = [](llvm::StringRef S, Value Expected) {
123 if (auto E = parse(S)) {
124 // Compare both string forms and with operator==, in case we have bugs.
125 EXPECT_EQ(*E, Expected);
126 EXPECT_EQ(sp(*E), sp(Expected));
127 } else {
128 handleAllErrors(E.takeError(), [S](const llvm::ErrorInfoBase &E) {
129 FAIL() << "Failed to parse JSON >>> " << S << " <<<: " << E.message();
130 });
131 }
132 };
133
134 Compare(R"(true)", true);
135 Compare(R"(false)", false);
136 Compare(R"(null)", nullptr);
137
138 Compare(R"(42)", 42);
139 Compare(R"(2.5)", 2.5);
140 Compare(R"(2e50)", 2e50);
141 Compare(R"(1.2e3456789)", std::numeric_limits<double>::infinity());
142
143 Compare(R"("foo")", "foo");
144 Compare(R"("\"\\\b\f\n\r\t")", "\"\\\b\f\n\r\t");
145 Compare(R"("\u0000")", llvm::StringRef("\0", 1));
146 Compare("\"\x7f\"", "\x7f");
147 Compare(R"("\ud801\udc37")", u8"\U00010437"); // UTF16 surrogate pair escape.
148 Compare("\"\xE2\x82\xAC\xF0\x9D\x84\x9E\"", u8"\u20ac\U0001d11e"); // UTF8
149 Compare(
150 R"("LoneLeading=\ud801, LoneTrailing=\udc01, LeadingLeadingTrailing=\ud801\ud801\udc37")",
151 u8"LoneLeading=\ufffd, LoneTrailing=\ufffd, "
152 u8"LeadingLeadingTrailing=\ufffd\U00010437"); // Invalid unicode.
153
154 Compare(R"({"":0,"":0})", Object{{"", 0}});
155 Compare(R"({"obj":{},"arr":[]})", Object{{"obj", Object{}}, {"arr", {}}});
156 Compare(R"({"\n":{"\u0000":[[[[]]]]}})",
157 Object{{"\n", Object{
158 {llvm::StringRef("\0", 1), {{{{}}}}},
159 }}});
160 Compare("\r[\n\t] ", {});
161}
162
163TEST(JSONTest, ParseErrors) {
164 auto ExpectErr = [](llvm::StringRef Msg, llvm::StringRef S) {
165 if (auto E = parse(S)) {
166 // Compare both string forms and with operator==, in case we have bugs.
167 FAIL() << "Parsed JSON >>> " << S << " <<< but wanted error: " << Msg;
168 } else {
169 handleAllErrors(E.takeError(), [S, Msg](const llvm::ErrorInfoBase &E) {
170 EXPECT_THAT(E.message(), testing::HasSubstr(Msg)) << S;
171 });
172 }
173 };
174 ExpectErr("Unexpected EOF", "");
175 ExpectErr("Unexpected EOF", "[");
176 ExpectErr("Text after end of document", "[][]");
177 ExpectErr("Invalid JSON value (false?)", "fuzzy");
178 ExpectErr("Expected , or ]", "[2?]");
179 ExpectErr("Expected object key", "{a:2}");
180 ExpectErr("Expected : after object key", R"({"a",2})");
181 ExpectErr("Expected , or } after object property", R"({"a":2 "b":3})");
182 ExpectErr("Invalid JSON value", R"([&%!])");
183 ExpectErr("Invalid JSON value (number?)", "1e1.0");
184 ExpectErr("Unterminated string", R"("abc\"def)");
185 ExpectErr("Control character in string", "\"abc\ndef\"");
186 ExpectErr("Invalid escape sequence", R"("\030")");
187 ExpectErr("Invalid \\u escape sequence", R"("\usuck")");
188 ExpectErr("[3:3, byte=19]", R"({
189 "valid": 1,
190 invalid: 2
191})");
Sam McCalle6057bc2018-07-10 11:51:26 +0000192 ExpectErr("Invalid UTF-8 sequence", "\"\xC0\x80\""); // WTF-8 null
193}
194
195// Direct tests of isUTF8 and fixUTF8. Internal uses are also tested elsewhere.
196TEST(JSONTest, UTF8) {
197 for (const char *Valid : {
198 "this is ASCII text",
199 "thïs tëxt häs BMP chäräctërs",
200 "𐌶𐌰L𐌾𐍈 C𐍈𐌼𐌴𐍃",
201 }) {
202 EXPECT_TRUE(isUTF8(Valid)) << Valid;
203 EXPECT_EQ(fixUTF8(Valid), Valid);
204 }
205 for (auto Invalid : std::vector<std::pair<const char *, const char *>>{
206 {"lone trailing \x81\x82 bytes", "lone trailing �� bytes"},
207 {"missing trailing \xD0 bytes", "missing trailing � bytes"},
208 {"truncated character \xD0", "truncated character �"},
209 {"not \xC1\x80 the \xE0\x9f\xBF shortest \xF0\x83\x83\x83 encoding",
210 "not �� the ��� shortest ���� encoding"},
211 {"too \xF9\x80\x80\x80\x80 long", "too ����� long"},
212 {"surrogate \xED\xA0\x80 invalid \xF4\x90\x80\x80",
213 "surrogate ��� invalid ����"}}) {
214 EXPECT_FALSE(isUTF8(Invalid.first)) << Invalid.first;
215 EXPECT_EQ(fixUTF8(Invalid.first), Invalid.second);
216 }
Sam McCall6be38242018-07-09 10:05:41 +0000217}
218
219TEST(JSONTest, Inspection) {
220 llvm::Expected<Value> Doc = parse(R"(
221 {
222 "null": null,
223 "boolean": false,
224 "number": 2.78,
225 "string": "json",
226 "array": [null, true, 3.14, "hello", [1,2,3], {"time": "arrow"}],
227 "object": {"fruit": "banana"}
228 }
229 )");
230 EXPECT_TRUE(!!Doc);
231
232 Object *O = Doc->getAsObject();
233 ASSERT_TRUE(O);
234
235 EXPECT_FALSE(O->getNull("missing"));
236 EXPECT_FALSE(O->getNull("boolean"));
237 EXPECT_TRUE(O->getNull("null"));
238
239 EXPECT_EQ(O->getNumber("number"), llvm::Optional<double>(2.78));
240 EXPECT_FALSE(O->getInteger("number"));
241 EXPECT_EQ(O->getString("string"), llvm::Optional<llvm::StringRef>("json"));
242 ASSERT_FALSE(O->getObject("missing"));
243 ASSERT_FALSE(O->getObject("array"));
244 ASSERT_TRUE(O->getObject("object"));
245 EXPECT_EQ(*O->getObject("object"), (Object{{"fruit", "banana"}}));
246
247 Array *A = O->getArray("array");
248 ASSERT_TRUE(A);
249 EXPECT_EQ((*A)[1].getAsBoolean(), llvm::Optional<bool>(true));
250 ASSERT_TRUE((*A)[4].getAsArray());
251 EXPECT_EQ(*(*A)[4].getAsArray(), (Array{1, 2, 3}));
252 EXPECT_EQ((*(*A)[4].getAsArray())[1].getAsInteger(),
253 llvm::Optional<int64_t>(2));
254 int I = 0;
255 for (Value &E : *A) {
256 if (I++ == 5) {
257 ASSERT_TRUE(E.getAsObject());
258 EXPECT_EQ(E.getAsObject()->getString("time"),
259 llvm::Optional<llvm::StringRef>("arrow"));
260 } else
261 EXPECT_FALSE(E.getAsObject());
262 }
263}
264
Sam McCalld93eaeb2018-07-09 12:16:40 +0000265// Verify special integer handling - we try to preserve exact int64 values.
266TEST(JSONTest, Integers) {
267 struct {
268 const char *Desc;
269 Value Val;
270 const char *Str;
271 llvm::Optional<int64_t> AsInt;
272 llvm::Optional<double> AsNumber;
273 } TestCases[] = {
274 {
275 "Non-integer. Stored as double, not convertible.",
276 double{1.5},
277 "1.5",
278 llvm::None,
279 1.5,
280 },
281
282 {
283 "Integer, not exact double. Stored as int64, convertible.",
284 int64_t{0x4000000000000001},
285 "4611686018427387905",
286 int64_t{0x4000000000000001},
287 double{0x4000000000000000},
288 },
289
290 {
291 "Negative integer, not exact double. Stored as int64, convertible.",
292 int64_t{-0x4000000000000001},
293 "-4611686018427387905",
294 int64_t{-0x4000000000000001},
295 double{-0x4000000000000000},
296 },
297
298 {
299 "Dynamically exact integer. Stored as double, convertible.",
300 double{0x6000000000000000},
301 "6.9175290276410819e+18",
302 int64_t{0x6000000000000000},
303 double{0x6000000000000000},
304 },
305
306 {
307 "Dynamically integer, >64 bits. Stored as double, not convertible.",
308 1.5 * double{0x8000000000000000},
309 "1.3835058055282164e+19",
310 llvm::None,
311 1.5 * double{0x8000000000000000},
312 },
313 };
314 for (const auto &T : TestCases) {
315 EXPECT_EQ(T.Str, s(T.Val)) << T.Desc;
316 llvm::Expected<Value> Doc = parse(T.Str);
317 EXPECT_TRUE(!!Doc) << T.Desc;
318 EXPECT_EQ(Doc->getAsInteger(), T.AsInt) << T.Desc;
319 EXPECT_EQ(Doc->getAsNumber(), T.AsNumber) << T.Desc;
320 EXPECT_EQ(T.Val, *Doc) << T.Desc;
321 EXPECT_EQ(T.Str, s(*Doc)) << T.Desc;
322 }
323}
324
Sam McCall6be38242018-07-09 10:05:41 +0000325// Sample struct with typical JSON-mapping rules.
326struct CustomStruct {
327 CustomStruct() : B(false) {}
328 CustomStruct(std::string S, llvm::Optional<int> I, bool B)
329 : S(S), I(I), B(B) {}
330 std::string S;
331 llvm::Optional<int> I;
332 bool B;
333};
334inline bool operator==(const CustomStruct &L, const CustomStruct &R) {
335 return L.S == R.S && L.I == R.I && L.B == R.B;
336}
337inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
338 const CustomStruct &S) {
339 return OS << "(" << S.S << ", " << (S.I ? std::to_string(*S.I) : "None")
340 << ", " << S.B << ")";
341}
342bool fromJSON(const Value &E, CustomStruct &R) {
343 ObjectMapper O(E);
344 if (!O || !O.map("str", R.S) || !O.map("int", R.I))
345 return false;
346 O.map("bool", R.B);
347 return true;
348}
349
350TEST(JSONTest, Deserialize) {
351 std::map<std::string, std::vector<CustomStruct>> R;
352 CustomStruct ExpectedStruct = {"foo", 42, true};
353 std::map<std::string, std::vector<CustomStruct>> Expected;
354 Value J = Object{
355 {"foo",
356 Array{
357 Object{
358 {"str", "foo"},
359 {"int", 42},
360 {"bool", true},
361 {"unknown", "ignored"},
362 },
363 Object{{"str", "bar"}},
364 Object{
365 {"str", "baz"}, {"bool", "string"}, // OK, deserialize ignores.
366 },
367 }}};
368 Expected["foo"] = {
369 CustomStruct("foo", 42, true),
370 CustomStruct("bar", llvm::None, false),
371 CustomStruct("baz", llvm::None, false),
372 };
373 ASSERT_TRUE(fromJSON(J, R));
374 EXPECT_EQ(R, Expected);
375
376 CustomStruct V;
377 EXPECT_FALSE(fromJSON(nullptr, V)) << "Not an object " << V;
378 EXPECT_FALSE(fromJSON(Object{}, V)) << "Missing required field " << V;
379 EXPECT_FALSE(fromJSON(Object{{"str", 1}}, V)) << "Wrong type " << V;
380 // Optional<T> must parse as the correct type if present.
381 EXPECT_FALSE(fromJSON(Object{{"str", 1}, {"int", "string"}}, V))
382 << "Wrong type for Optional<T> " << V;
383}
384
385} // namespace
386} // namespace json
387} // namespace llvm