blob: bf7f4ae96d0887305a18a1d748bb94fc22b25ac4 [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}}));
30}
31
32TEST(JSONTest, Constructors) {
33 // Lots of edge cases around empty and singleton init lists.
34 EXPECT_EQ("[[[3]]]", s({{{3}}}));
35 EXPECT_EQ("[[[]]]", s({{{}}}));
36 EXPECT_EQ("[[{}]]", s({{Object{}}}));
37 EXPECT_EQ(R"({"A":{"B":{}}})", s(Object{{"A", Object{{"B", Object{}}}}}));
38 EXPECT_EQ(R"({"A":{"B":{"X":"Y"}}})",
39 s(Object{{"A", Object{{"B", Object{{"X", "Y"}}}}}}));
40}
41
42TEST(JSONTest, StringOwnership) {
43 char X[] = "Hello";
44 Value Alias = static_cast<const char *>(X);
45 X[1] = 'a';
46 EXPECT_EQ(R"("Hallo")", s(Alias));
47
48 std::string Y = "Hello";
49 Value Copy = Y;
50 Y[1] = 'a';
51 EXPECT_EQ(R"("Hello")", s(Copy));
52}
53
54TEST(JSONTest, CanonicalOutput) {
55 // Objects are sorted (but arrays aren't)!
56 EXPECT_EQ(R"({"a":1,"b":2,"c":3})", s(Object{{"a", 1}, {"c", 3}, {"b", 2}}));
57 EXPECT_EQ(R"(["a","c","b"])", s({"a", "c", "b"}));
58 EXPECT_EQ("3", s(3.0));
59}
60
61TEST(JSONTest, Escaping) {
62 std::string test = {
63 0, // Strings may contain nulls.
64 '\b', '\f', // Have mnemonics, but we escape numerically.
65 '\r', '\n', '\t', // Escaped with mnemonics.
66 'S', '\"', '\\', // Printable ASCII characters.
67 '\x7f', // Delete is not escaped.
68 '\xce', '\x94', // Non-ASCII UTF-8 is not escaped.
69 };
70
71 std::string teststring = R"("\u0000\u0008\u000c\r\n\tS\"\\)"
72 "\x7f\xCE\x94\"";
73
74 EXPECT_EQ(teststring, s(test));
75
76 EXPECT_EQ(R"({"object keys are\nescaped":true})",
77 s(Object{{"object keys are\nescaped", true}}));
78}
79
80TEST(JSONTest, PrettyPrinting) {
81 const char str[] = R"({
82 "empty_array": [],
83 "empty_object": {},
84 "full_array": [
85 1,
86 null
87 ],
88 "full_object": {
89 "nested_array": [
90 {
91 "property": "value"
92 }
93 ]
94 }
95})";
96
97 EXPECT_EQ(str, sp(Object{
98 {"empty_object", Object{}},
99 {"empty_array", {}},
100 {"full_array", {1, nullptr}},
101 {"full_object",
102 Object{
103 {"nested_array",
104 {Object{
105 {"property", "value"},
106 }}},
107 }},
108 }));
109}
110
111TEST(JSONTest, Parse) {
112 auto Compare = [](llvm::StringRef S, Value Expected) {
113 if (auto E = parse(S)) {
114 // Compare both string forms and with operator==, in case we have bugs.
115 EXPECT_EQ(*E, Expected);
116 EXPECT_EQ(sp(*E), sp(Expected));
117 } else {
118 handleAllErrors(E.takeError(), [S](const llvm::ErrorInfoBase &E) {
119 FAIL() << "Failed to parse JSON >>> " << S << " <<<: " << E.message();
120 });
121 }
122 };
123
124 Compare(R"(true)", true);
125 Compare(R"(false)", false);
126 Compare(R"(null)", nullptr);
127
128 Compare(R"(42)", 42);
129 Compare(R"(2.5)", 2.5);
130 Compare(R"(2e50)", 2e50);
131 Compare(R"(1.2e3456789)", std::numeric_limits<double>::infinity());
132
133 Compare(R"("foo")", "foo");
134 Compare(R"("\"\\\b\f\n\r\t")", "\"\\\b\f\n\r\t");
135 Compare(R"("\u0000")", llvm::StringRef("\0", 1));
136 Compare("\"\x7f\"", "\x7f");
137 Compare(R"("\ud801\udc37")", u8"\U00010437"); // UTF16 surrogate pair escape.
138 Compare("\"\xE2\x82\xAC\xF0\x9D\x84\x9E\"", u8"\u20ac\U0001d11e"); // UTF8
139 Compare(
140 R"("LoneLeading=\ud801, LoneTrailing=\udc01, LeadingLeadingTrailing=\ud801\ud801\udc37")",
141 u8"LoneLeading=\ufffd, LoneTrailing=\ufffd, "
142 u8"LeadingLeadingTrailing=\ufffd\U00010437"); // Invalid unicode.
143
144 Compare(R"({"":0,"":0})", Object{{"", 0}});
145 Compare(R"({"obj":{},"arr":[]})", Object{{"obj", Object{}}, {"arr", {}}});
146 Compare(R"({"\n":{"\u0000":[[[[]]]]}})",
147 Object{{"\n", Object{
148 {llvm::StringRef("\0", 1), {{{{}}}}},
149 }}});
150 Compare("\r[\n\t] ", {});
151}
152
153TEST(JSONTest, ParseErrors) {
154 auto ExpectErr = [](llvm::StringRef Msg, llvm::StringRef S) {
155 if (auto E = parse(S)) {
156 // Compare both string forms and with operator==, in case we have bugs.
157 FAIL() << "Parsed JSON >>> " << S << " <<< but wanted error: " << Msg;
158 } else {
159 handleAllErrors(E.takeError(), [S, Msg](const llvm::ErrorInfoBase &E) {
160 EXPECT_THAT(E.message(), testing::HasSubstr(Msg)) << S;
161 });
162 }
163 };
164 ExpectErr("Unexpected EOF", "");
165 ExpectErr("Unexpected EOF", "[");
166 ExpectErr("Text after end of document", "[][]");
167 ExpectErr("Invalid JSON value (false?)", "fuzzy");
168 ExpectErr("Expected , or ]", "[2?]");
169 ExpectErr("Expected object key", "{a:2}");
170 ExpectErr("Expected : after object key", R"({"a",2})");
171 ExpectErr("Expected , or } after object property", R"({"a":2 "b":3})");
172 ExpectErr("Invalid JSON value", R"([&%!])");
173 ExpectErr("Invalid JSON value (number?)", "1e1.0");
174 ExpectErr("Unterminated string", R"("abc\"def)");
175 ExpectErr("Control character in string", "\"abc\ndef\"");
176 ExpectErr("Invalid escape sequence", R"("\030")");
177 ExpectErr("Invalid \\u escape sequence", R"("\usuck")");
178 ExpectErr("[3:3, byte=19]", R"({
179 "valid": 1,
180 invalid: 2
181})");
182}
183
184TEST(JSONTest, Inspection) {
185 llvm::Expected<Value> Doc = parse(R"(
186 {
187 "null": null,
188 "boolean": false,
189 "number": 2.78,
190 "string": "json",
191 "array": [null, true, 3.14, "hello", [1,2,3], {"time": "arrow"}],
192 "object": {"fruit": "banana"}
193 }
194 )");
195 EXPECT_TRUE(!!Doc);
196
197 Object *O = Doc->getAsObject();
198 ASSERT_TRUE(O);
199
200 EXPECT_FALSE(O->getNull("missing"));
201 EXPECT_FALSE(O->getNull("boolean"));
202 EXPECT_TRUE(O->getNull("null"));
203
204 EXPECT_EQ(O->getNumber("number"), llvm::Optional<double>(2.78));
205 EXPECT_FALSE(O->getInteger("number"));
206 EXPECT_EQ(O->getString("string"), llvm::Optional<llvm::StringRef>("json"));
207 ASSERT_FALSE(O->getObject("missing"));
208 ASSERT_FALSE(O->getObject("array"));
209 ASSERT_TRUE(O->getObject("object"));
210 EXPECT_EQ(*O->getObject("object"), (Object{{"fruit", "banana"}}));
211
212 Array *A = O->getArray("array");
213 ASSERT_TRUE(A);
214 EXPECT_EQ((*A)[1].getAsBoolean(), llvm::Optional<bool>(true));
215 ASSERT_TRUE((*A)[4].getAsArray());
216 EXPECT_EQ(*(*A)[4].getAsArray(), (Array{1, 2, 3}));
217 EXPECT_EQ((*(*A)[4].getAsArray())[1].getAsInteger(),
218 llvm::Optional<int64_t>(2));
219 int I = 0;
220 for (Value &E : *A) {
221 if (I++ == 5) {
222 ASSERT_TRUE(E.getAsObject());
223 EXPECT_EQ(E.getAsObject()->getString("time"),
224 llvm::Optional<llvm::StringRef>("arrow"));
225 } else
226 EXPECT_FALSE(E.getAsObject());
227 }
228}
229
230// Sample struct with typical JSON-mapping rules.
231struct CustomStruct {
232 CustomStruct() : B(false) {}
233 CustomStruct(std::string S, llvm::Optional<int> I, bool B)
234 : S(S), I(I), B(B) {}
235 std::string S;
236 llvm::Optional<int> I;
237 bool B;
238};
239inline bool operator==(const CustomStruct &L, const CustomStruct &R) {
240 return L.S == R.S && L.I == R.I && L.B == R.B;
241}
242inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
243 const CustomStruct &S) {
244 return OS << "(" << S.S << ", " << (S.I ? std::to_string(*S.I) : "None")
245 << ", " << S.B << ")";
246}
247bool fromJSON(const Value &E, CustomStruct &R) {
248 ObjectMapper O(E);
249 if (!O || !O.map("str", R.S) || !O.map("int", R.I))
250 return false;
251 O.map("bool", R.B);
252 return true;
253}
254
255TEST(JSONTest, Deserialize) {
256 std::map<std::string, std::vector<CustomStruct>> R;
257 CustomStruct ExpectedStruct = {"foo", 42, true};
258 std::map<std::string, std::vector<CustomStruct>> Expected;
259 Value J = Object{
260 {"foo",
261 Array{
262 Object{
263 {"str", "foo"},
264 {"int", 42},
265 {"bool", true},
266 {"unknown", "ignored"},
267 },
268 Object{{"str", "bar"}},
269 Object{
270 {"str", "baz"}, {"bool", "string"}, // OK, deserialize ignores.
271 },
272 }}};
273 Expected["foo"] = {
274 CustomStruct("foo", 42, true),
275 CustomStruct("bar", llvm::None, false),
276 CustomStruct("baz", llvm::None, false),
277 };
278 ASSERT_TRUE(fromJSON(J, R));
279 EXPECT_EQ(R, Expected);
280
281 CustomStruct V;
282 EXPECT_FALSE(fromJSON(nullptr, V)) << "Not an object " << V;
283 EXPECT_FALSE(fromJSON(Object{}, V)) << "Missing required field " << V;
284 EXPECT_FALSE(fromJSON(Object{{"str", 1}}, V)) << "Wrong type " << V;
285 // Optional<T> must parse as the correct type if present.
286 EXPECT_FALSE(fromJSON(Object{{"str", 1}, {"int", "string"}}, V))
287 << "Wrong type for Optional<T> " << V;
288}
289
290} // namespace
291} // namespace json
292} // namespace llvm