| 1 |
//===-- JSONTest.cpp - JSON unit tests --------------------------*- C++ -*-===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
#include "llvm/Support/JSON.h" |
| 10 |
#include "llvm/Support/raw_ostream.h" |
| 11 |
#include "llvm/Testing/Support/Error.h" |
| 12 |
|
| 13 |
#include "gmock/gmock.h" |
| 14 |
#include "gtest/gtest.h" |
| 15 |
|
| 16 |
namespace llvm { |
| 17 |
namespace json { |
| 18 |
|
| 19 |
namespace { |
| 20 |
|
| 21 |
std::string s(const Value &E) { return llvm::formatv("{0}", E).str(); } |
| 22 |
std::string sp(const Value &E) { return llvm::formatv("{0:2}", E).str(); } |
| 23 |
|
| 24 |
TEST(JSONTest, Types) { |
| 25 |
EXPECT_EQ("true", s(true)); |
| 26 |
EXPECT_EQ("null", s(nullptr)); |
| 27 |
EXPECT_EQ("2.5", s(2.5)); |
| 28 |
EXPECT_EQ(R"("foo")", s("foo")); |
| 29 |
EXPECT_EQ("[1,2,3]", s({1, 2, 3})); |
| 30 |
EXPECT_EQ(R"({"x":10,"y":20})", s(Object{{"x", 10}, {"y", 20}})); |
| 31 |
|
| 32 |
#ifdef NDEBUG |
| 33 |
EXPECT_EQ(R"("��")", s("\xC0\x80")); |
| 34 |
EXPECT_EQ(R"({"��":0})", s(Object{{"\xC0\x80", 0}})); |
| 35 |
#else |
| 36 |
EXPECT_DEATH(s("\xC0\x80"), "Invalid UTF-8"); |
| 37 |
EXPECT_DEATH(s(Object{{"\xC0\x80", 0}}), "Invalid UTF-8"); |
| 38 |
#endif |
| 39 |
} |
| 40 |
|
| 41 |
TEST(JSONTest, Constructors) { |
| 42 |
// Lots of edge cases around empty and singleton init lists. |
| 43 |
EXPECT_EQ("[[[3]]]", s({{{3}}})); |
| 44 |
EXPECT_EQ("[[[]]]", s({{{}}})); |
| 45 |
EXPECT_EQ("[[{}]]", s({{Object{}}})); |
| 46 |
EXPECT_EQ(R"({"A":{"B":{}}})", s(Object{{"A", Object{{"B", Object{}}}}})); |
| 47 |
EXPECT_EQ(R"({"A":{"B":{"X":"Y"}}})", |
| 48 |
s(Object{{"A", Object{{"B", Object{{"X", "Y"}}}}}})); |
| 49 |
EXPECT_EQ("null", s(std::optional<double>())); |
| 50 |
EXPECT_EQ("2.5", s(std::optional<double>(2.5))); |
| 51 |
EXPECT_EQ("[[2.5,null]]", s(std::vector<std::vector<std::optional<double>>>{ |
| 52 |
{2.5, std::nullopt}})); |
| 53 |
} |
| 54 |
|
| 55 |
TEST(JSONTest, StringOwnership) { |
| 56 |
char X[] = "Hello"; |
| 57 |
Value Alias = static_cast<const char *>(X); |
| 58 |
X[1] = 'a'; |
| 59 |
EXPECT_EQ(R"("Hallo")", s(Alias)); |
| 60 |
|
| 61 |
std::string Y = "Hello"; |
| 62 |
Value Copy = Y; |
| 63 |
Y[1] = 'a'; |
| 64 |
EXPECT_EQ(R"("Hello")", s(Copy)); |
| 65 |
} |
| 66 |
|
| 67 |
TEST(JSONTest, CanonicalOutput) { |
| 68 |
// Objects are sorted (but arrays aren't)! |
| 69 |
EXPECT_EQ(R"({"a":1,"b":2,"c":3})", s(Object{{"a", 1}, {"c", 3}, {"b", 2}})); |
| 70 |
EXPECT_EQ(R"(["a","c","b"])", s({"a", "c", "b"})); |
| 71 |
EXPECT_EQ("3", s(3.0)); |
| 72 |
} |
| 73 |
|
| 74 |
TEST(JSONTest, Escaping) { |
| 75 |
std::string Test = { |
| 76 |
0, // Strings may contain nulls. |
| 77 |
'\b', '\f', // Have mnemonics, but we escape numerically. |
| 78 |
'\r', '\n', '\t', // Escaped with mnemonics. |
| 79 |
'S', '\"', '\\', // Printable ASCII characters. |
| 80 |
'\x7f', // Delete is not escaped. |
| 81 |
'\xce', '\x94', // Non-ASCII UTF-8 is not escaped. |
| 82 |
}; |
| 83 |
|
| 84 |
std::string TestString = R"("\u0000\u0008\u000c\r\n\tS\"\\)" |
| 85 |
"\x7f\xCE\x94\""; |
| 86 |
|
| 87 |
EXPECT_EQ(TestString, s(Test)); |
| 88 |
|
| 89 |
EXPECT_EQ(R"({"object keys are\nescaped":true})", |
| 90 |
s(Object{{"object keys are\nescaped", true}})); |
| 91 |
} |
| 92 |
|
| 93 |
TEST(JSONTest, PrettyPrinting) { |
| 94 |
const char Str[] = R"({ |
| 95 |
"empty_array": [], |
| 96 |
"empty_object": {}, |
| 97 |
"full_array": [ |
| 98 |
1, |
| 99 |
null |
| 100 |
], |
| 101 |
"full_object": { |
| 102 |
"nested_array": [ |
| 103 |
{ |
| 104 |
"property": "value" |
| 105 |
} |
| 106 |
] |
| 107 |
} |
| 108 |
})"; |
| 109 |
|
| 110 |
EXPECT_EQ(Str, sp(Object{ |
| 111 |
{"empty_object", Object{}}, |
| 112 |
{"empty_array", {}}, |
| 113 |
{"full_array", {1, nullptr}}, |
| 114 |
{"full_object", |
| 115 |
Object{ |
| 116 |
{"nested_array", |
| 117 |
{Object{ |
| 118 |
{"property", "value"}, |
| 119 |
}}}, |
| 120 |
}}, |
| 121 |
})); |
| 122 |
} |
| 123 |
|
| 124 |
TEST(JSONTest, Array) { |
| 125 |
Array A{1, 2}; |
| 126 |
A.emplace_back(3); |
| 127 |
A.emplace(++A.begin(), 0); |
| 128 |
A.push_back(4); |
| 129 |
A.insert(++++A.begin(), 99); |
| 130 |
|
| 131 |
EXPECT_EQ(A.size(), 6u); |
| 132 |
EXPECT_EQ(R"([1,0,99,2,3,4])", s(std::move(A))); |
| 133 |
} |
| 134 |
|
| 135 |
TEST(JSONTest, Object) { |
| 136 |
Object O{{"a", 1}, {"b", 2}, {"c", 3}}; |
| 137 |
EXPECT_TRUE(O.try_emplace("d", 4).second); |
| 138 |
EXPECT_FALSE(O.try_emplace("a", 4).second); |
| 139 |
|
| 140 |
auto D = O.find("d"); |
| 141 |
EXPECT_NE(D, O.end()); |
| 142 |
auto E = O.find("e"); |
| 143 |
EXPECT_EQ(E, O.end()); |
| 144 |
|
| 145 |
O.erase("b"); |
| 146 |
O.erase(D); |
| 147 |
EXPECT_EQ(O.size(), 2u); |
| 148 |
EXPECT_EQ(R"({"a":1,"c":3})", s(std::move(O))); |
| 149 |
} |
| 150 |
|
| 151 |
TEST(JSONTest, Parse) { |
| 152 |
auto Compare = [](llvm::StringRef S, Value Expected) { |
| 153 |
if (auto E = parse(S)) { |
| 154 |
// Compare both string forms and with operator==, in case we have bugs. |
| 155 |
EXPECT_EQ(*E, Expected); |
| 156 |
EXPECT_EQ(sp(*E), sp(Expected)); |
| 157 |
} else { |
| 158 |
handleAllErrors(E.takeError(), [S](const llvm::ErrorInfoBase &E) { |
| 159 |
FAIL() << "Failed to parse JSON >>> " << S << " <<<: " << E.message(); |
| 160 |
}); |
| 161 |
} |
| 162 |
}; |
| 163 |
|
| 164 |
Compare(R"(true)", true); |
| 165 |
Compare(R"(false)", false); |
| 166 |
Compare(R"(null)", nullptr); |
| 167 |
|
| 168 |
Compare(R"(42)", 42); |
| 169 |
Compare(R"(2.5)", 2.5); |
| 170 |
Compare(R"(2e50)", 2e50); |
| 171 |
Compare(R"(1.2e3456789)", std::numeric_limits<double>::infinity()); |
| 172 |
|
| 173 |
Compare(R"("foo")", "foo"); |
| 174 |
Compare(R"("\"\\\b\f\n\r\t")", "\"\\\b\f\n\r\t"); |
| 175 |
Compare(R"("\u0000")", llvm::StringRef("\0", 1)); |
| 176 |
Compare("\"\x7f\"", "\x7f"); |
| 177 |
Compare(R"("\ud801\udc37")", // UTF-16 surrogate pair escape. |
| 178 |
/*U+10437*/ "\xf0\x90\x90\xb7"); |
| 179 |
Compare("\"\xE2\x82\xAC\xF0\x9D\x84\x9E\"", // UTF-8 |
| 180 |
/*U+20AC U+1D11E*/ "\xe2\x82\xac\xf0\x9d\x84\x9e"); |
| 181 |
Compare( |
| 182 |
// Invalid unicode. |
| 183 |
R"("LoneLeading=\ud801, LoneTrailing=\udc01, LeadLeadTrail=\ud801\ud801\udc37")", |
| 184 |
"LoneLeading=" /*U+FFFD*/ "\xef\xbf\xbd, " |
| 185 |
"LoneTrailing=" /*U+FFFD*/ "\xef\xbf\xbd, " |
| 186 |
"LeadLeadTrail=" /*U+FFFD U+10437*/ "\xef\xbf\xbd\xf0\x90\x90\xb7"); |
| 187 |
|
| 188 |
Compare(R"({"":0,"":0})", Object{{"", 0}}); |
| 189 |
Compare(R"({"obj":{},"arr":[]})", Object{{"obj", Object{}}, {"arr", {}}}); |
| 190 |
Compare(R"({"\n":{"\u0000":[[[[]]]]}})", |
| 191 |
Object{{"\n", Object{ |
| 192 |
{llvm::StringRef("\0", 1), {{{{}}}}}, |
| 193 |
}}}); |
| 194 |
Compare("\r[\n\t] ", {}); |
| 195 |
} |
| 196 |
|
| 197 |
TEST(JSONTest, ParseErrors) { |
| 198 |
auto ExpectErr = [](llvm::StringRef Msg, llvm::StringRef S) { |
| 199 |
if (auto E = parse(S)) { |
| 200 |
// Compare both string forms and with operator==, in case we have bugs. |
| 201 |
FAIL() << "Parsed JSON >>> " << S << " <<< but wanted error: " << Msg; |
| 202 |
} else { |
| 203 |
handleAllErrors(E.takeError(), [S, Msg](const llvm::ErrorInfoBase &E) { |
| 204 |
EXPECT_THAT(E.message(), testing::HasSubstr(std::string(Msg))) << S; |
| 205 |
}); |
| 206 |
} |
| 207 |
}; |
| 208 |
ExpectErr("Unexpected EOF", ""); |
| 209 |
ExpectErr("Unexpected EOF", "["); |
| 210 |
ExpectErr("Text after end of document", "[][]"); |
| 211 |
ExpectErr("Invalid JSON value (false?)", "fuzzy"); |
| 212 |
ExpectErr("Expected , or ]", "[2?]"); |
| 213 |
ExpectErr("Expected object key", "{a:2}"); |
| 214 |
ExpectErr("Expected : after object key", R"({"a",2})"); |
| 215 |
ExpectErr("Expected , or } after object property", R"({"a":2 "b":3})"); |
| 216 |
ExpectErr("Invalid JSON value", R"([&%!])"); |
| 217 |
ExpectErr("Invalid JSON value (number?)", "1e1.0"); |
| 218 |
ExpectErr("Unterminated string", R"("abc\"def)"); |
| 219 |
ExpectErr("Control character in string", "\"abc\ndef\""); |
| 220 |
ExpectErr("Invalid escape sequence", R"("\030")"); |
| 221 |
ExpectErr("Invalid \\u escape sequence", R"("\usuck")"); |
| 222 |
ExpectErr("[3:3, byte=19]", R"({ |
| 223 |
"valid": 1, |
| 224 |
invalid: 2 |
| 225 |
})"); |
| 226 |
ExpectErr("Invalid UTF-8 sequence", "\"\xC0\x80\""); // WTF-8 null |
| 227 |
} |
| 228 |
|
| 229 |
// Direct tests of isUTF8 and fixUTF8. Internal uses are also tested elsewhere. |
| 230 |
TEST(JSONTest, UTF8) { |
| 231 |
for (const char *Valid : { |
| 232 |
"this is ASCII text", |
| 233 |
"thïs tëxt häs BMP chäräctërs", |
| 234 |
"𐌶𐌰L𐌾𐍈 C𐍈𐌼𐌴𐍃", |
| 235 |
}) { |
| 236 |
EXPECT_TRUE(isUTF8(Valid)) << Valid; |
| 237 |
EXPECT_EQ(fixUTF8(Valid), Valid); |
| 238 |
} |
| 239 |
for (auto Invalid : std::vector<std::pair<const char *, const char *>>{ |
| 240 |
{"lone trailing \x81\x82 bytes", "lone trailing �� bytes"}, |
| 241 |
{"missing trailing \xD0 bytes", "missing trailing � bytes"}, |
| 242 |
{"truncated character \xD0", "truncated character �"}, |
| 243 |
{"not \xC1\x80 the \xE0\x9f\xBF shortest \xF0\x83\x83\x83 encoding", |
| 244 |
"not �� the ��� shortest ���� encoding"}, |
| 245 |
{"too \xF9\x80\x80\x80\x80 long", "too ����� long"}, |
| 246 |
{"surrogate \xED\xA0\x80 invalid \xF4\x90\x80\x80", |
| 247 |
"surrogate ��� invalid ����"}}) { |
| 248 |
EXPECT_FALSE(isUTF8(Invalid.first)) << Invalid.first; |
| 249 |
EXPECT_EQ(fixUTF8(Invalid.first), Invalid.second); |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
TEST(JSONTest, Inspection) { |
| 254 |
llvm::Expected<Value> Doc = parse(R"( |
| 255 |
{ |
| 256 |
"null": null, |
| 257 |
"boolean": false, |
| 258 |
"number": 2.78, |
| 259 |
"string": "json", |
| 260 |
"array": [null, true, 3.14, "hello", [1,2,3], {"time": "arrow"}], |
| 261 |
"object": {"fruit": "banana"} |
| 262 |
} |
| 263 |
)"); |
| 264 |
EXPECT_TRUE(!!Doc); |
| 265 |
|
| 266 |
Object *O = Doc->getAsObject(); |
| 267 |
ASSERT_TRUE(O); |
| 268 |
|
| 269 |
EXPECT_FALSE(O->getNull("missing")); |
| 270 |
EXPECT_FALSE(O->getNull("boolean")); |
| 271 |
EXPECT_TRUE(O->getNull("null")); |
| 272 |
|
| 273 |
EXPECT_EQ(O->getNumber("number"), std::optional<double>(2.78)); |
| 274 |
EXPECT_FALSE(O->getInteger("number")); |
| 275 |
EXPECT_EQ(O->getString("string"), std::optional<llvm::StringRef>("json")); |
| 276 |
ASSERT_FALSE(O->getObject("missing")); |
| 277 |
ASSERT_FALSE(O->getObject("array")); |
| 278 |
ASSERT_TRUE(O->getObject("object")); |
| 279 |
EXPECT_EQ(*O->getObject("object"), (Object{{"fruit", "banana"}})); |
| 280 |
|
| 281 |
Array *A = O->getArray("array"); |
| 282 |
ASSERT_TRUE(A); |
| 283 |
EXPECT_EQ((*A)[1].getAsBoolean(), std::optional<bool>(true)); |
| 284 |
ASSERT_TRUE((*A)[4].getAsArray()); |
| 285 |
EXPECT_EQ(*(*A)[4].getAsArray(), (Array{1, 2, 3})); |
| 286 |
EXPECT_EQ((*(*A)[4].getAsArray())[1].getAsInteger(), |
| 287 |
std::optional<int64_t>(2)); |
| 288 |
int I = 0; |
| 289 |
for (Value &E : *A) { |
| 290 |
if (I++ == 5) { |
| 291 |
ASSERT_TRUE(E.getAsObject()); |
| 292 |
EXPECT_EQ(E.getAsObject()->getString("time"), |
| 293 |
std::optional<llvm::StringRef>("arrow")); |
| 294 |
} else |
| 295 |
EXPECT_FALSE(E.getAsObject()); |
| 296 |
} |
| 297 |
} |
| 298 |
|
| 299 |
// Verify special integer handling - we try to preserve exact int64 values. |
| 300 |
TEST(JSONTest, Integers) { |
| 301 |
struct { |
| 302 |
const char *Desc; |
| 303 |
Value Val; |
| 304 |
const char *Str; |
| 305 |
std::optional<int64_t> AsInt; |
| 306 |
std::optional<double> AsNumber; |
| 307 |
} TestCases[] = { |
| 308 |
{ |
| 309 |
"Non-integer. Stored as double, not convertible.", |
| 310 |
double{1.5}, |
| 311 |
"1.5", |
| 312 |
std::nullopt, |
| 313 |
1.5, |
| 314 |
}, |
| 315 |
|
| 316 |
{ |
| 317 |
"Integer, not exact double. Stored as int64, convertible.", |
| 318 |
int64_t{0x4000000000000001}, |
| 319 |
"4611686018427387905", |
| 320 |
int64_t{0x4000000000000001}, |
| 321 |
double{0x4000000000000000}, |
| 322 |
}, |
| 323 |
|
| 324 |
{ |
| 325 |
"Negative integer, not exact double. Stored as int64, convertible.", |
| 326 |
int64_t{-0x4000000000000001}, |
| 327 |
"-4611686018427387905", |
| 328 |
int64_t{-0x4000000000000001}, |
| 329 |
double{-0x4000000000000000}, |
| 330 |
}, |
| 331 |
|
| 332 |
// PR46470, |
| 333 |
// https://developercommunity.visualstudio.com/content/problem/1093399/incorrect-result-when-printing-6917529027641081856.html |
| 334 |
#if !defined(_MSC_VER) || _MSC_VER < 1926 |
| 335 |
{ |
| 336 |
"Dynamically exact integer. Stored as double, convertible.", |
| 337 |
double{0x6000000000000000}, |
| 338 |
"6.9175290276410819e+18", |
| 339 |
int64_t{0x6000000000000000}, |
| 340 |
double{0x6000000000000000}, |
| 341 |
}, |
| 342 |
#endif |
| 343 |
|
| 344 |
{ |
| 345 |
"Dynamically integer, >64 bits. Stored as double, not convertible.", |
| 346 |
1.5 * double{0x8000000000000000}, |
| 347 |
"1.3835058055282164e+19", |
| 348 |
std::nullopt, |
| 349 |
1.5 * double{0x8000000000000000}, |
| 350 |
}, |
| 351 |
}; |
| 352 |
for (const auto &T : TestCases) { |
| 353 |
EXPECT_EQ(T.Str, s(T.Val)) << T.Desc; |
| 354 |
llvm::Expected<Value> Doc = parse(T.Str); |
| 355 |
EXPECT_TRUE(!!Doc) << T.Desc; |
| 356 |
EXPECT_EQ(Doc->getAsInteger(), T.AsInt) << T.Desc; |
| 357 |
EXPECT_EQ(Doc->getAsNumber(), T.AsNumber) << T.Desc; |
| 358 |
EXPECT_EQ(T.Val, *Doc) << T.Desc; |
| 359 |
EXPECT_EQ(T.Str, s(*Doc)) << T.Desc; |
| 360 |
} |
| 361 |
} |
| 362 |
|
| 363 |
// Verify uint64_t type. |
| 364 |
TEST(JSONTest, U64Integers) { |
| 365 |
Value Val = uint64_t{3100100100}; |
| 366 |
uint64_t Var = 3100100100; |
| 367 |
EXPECT_EQ(Val, Var); |
| 368 |
|
| 369 |
Val = uint64_t{std::numeric_limits<uint64_t>::max()}; |
| 370 |
Var = std::numeric_limits<uint64_t>::max(); |
| 371 |
EXPECT_EQ(Val, Var); |
| 372 |
|
| 373 |
// Test the parse() part. |
| 374 |
{ |
| 375 |
const char *Str = "4611686018427387905"; |
| 376 |
llvm::Expected<Value> Doc = parse(Str); |
| 377 |
|
| 378 |
EXPECT_TRUE(!!Doc); |
| 379 |
EXPECT_EQ(Doc->getAsInteger(), int64_t{4611686018427387905}); |
| 380 |
EXPECT_EQ(Doc->getAsUINT64(), uint64_t{4611686018427387905}); |
| 381 |
} |
| 382 |
|
| 383 |
{ |
| 384 |
const char *Str = "-78278238238328222"; |
| 385 |
llvm::Expected<Value> Doc = parse(Str); |
| 386 |
|
| 387 |
EXPECT_TRUE(!!Doc); |
| 388 |
EXPECT_EQ(Doc->getAsInteger(), int64_t{-78278238238328222}); |
| 389 |
EXPECT_EQ(Doc->getAsUINT64(), std::nullopt); |
| 390 |
} |
| 391 |
|
| 392 |
// Test with the largest 64 signed int. |
| 393 |
{ |
| 394 |
const char *Str = "9223372036854775807"; |
| 395 |
llvm::Expected<Value> Doc = parse(Str); |
| 396 |
|
| 397 |
EXPECT_TRUE(!!Doc); |
| 398 |
EXPECT_EQ(Doc->getAsInteger(), int64_t{9223372036854775807}); |
| 399 |
EXPECT_EQ(Doc->getAsUINT64(), uint64_t{9223372036854775807}); |
| 400 |
} |
| 401 |
|
| 402 |
// Test with the largest 64 unsigned int. |
| 403 |
{ |
| 404 |
const char *Str = "18446744073709551615"; |
| 405 |
llvm::Expected<Value> Doc = parse(Str); |
| 406 |
|
| 407 |
EXPECT_TRUE(!!Doc); |
| 408 |
EXPECT_EQ(Doc->getAsInteger(), std::nullopt); |
| 409 |
EXPECT_EQ(Doc->getAsUINT64(), uint64_t{18446744073709551615u}); |
| 410 |
} |
| 411 |
|
| 412 |
// Test with a number that is too big for 64 bits. |
| 413 |
{ |
| 414 |
const char *Str = "184467440737095516150"; |
| 415 |
llvm::Expected<Value> Doc = parse(Str); |
| 416 |
|
| 417 |
EXPECT_TRUE(!!Doc); |
| 418 |
EXPECT_EQ(Doc->getAsInteger(), std::nullopt); |
| 419 |
EXPECT_EQ(Doc->getAsUINT64(), std::nullopt); |
| 420 |
// The number was parsed as a double. |
| 421 |
EXPECT_TRUE(!!Doc->getAsNumber()); |
| 422 |
} |
| 423 |
|
| 424 |
// Test with a negative number that is too small for 64 bits. |
| 425 |
{ |
| 426 |
const char *Str = "-18446744073709551615"; |
| 427 |
llvm::Expected<Value> Doc = parse(Str); |
| 428 |
|
| 429 |
EXPECT_TRUE(!!Doc); |
| 430 |
EXPECT_EQ(Doc->getAsInteger(), std::nullopt); |
| 431 |
EXPECT_EQ(Doc->getAsUINT64(), std::nullopt); |
| 432 |
// The number was parsed as a double. |
| 433 |
EXPECT_TRUE(!!Doc->getAsNumber()); |
| 434 |
} |
| 435 |
// Test with a large number that is malformed. |
| 436 |
{ |
| 437 |
const char *Str = "184467440737095516150.12.12"; |
| 438 |
llvm::Expected<Value> Doc = parse(Str); |
| 439 |
|
| 440 |
EXPECT_EQ("[1:27, byte=27]: Invalid JSON value (number?)", |
| 441 |
llvm::toString(Doc.takeError())); |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
// Sample struct with typical JSON-mapping rules. |
| 446 |
struct CustomStruct { |
| 447 |
CustomStruct() : B(false) {} |
| 448 |
CustomStruct(std::string S, std::optional<int> I, bool B) |
| 449 |
: S(S), I(I), B(B) {} |
| 450 |
std::string S; |
| 451 |
std::optional<int> I; |
| 452 |
bool B; |
| 453 |
}; |
| 454 |
inline bool operator==(const CustomStruct &L, const CustomStruct &R) { |
| 455 |
return L.S == R.S && L.I == R.I && L.B == R.B; |
| 456 |
} |
| 457 |
inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, |
| 458 |
const CustomStruct &S) { |
| 459 |
return OS << "(" << S.S << ", " << (S.I ? std::to_string(*S.I) : "None") |
| 460 |
<< ", " << S.B << ")"; |
| 461 |
} |
| 462 |
bool fromJSON(const Value &E, CustomStruct &R, Path P) { |
| 463 |
ObjectMapper O(E, P); |
| 464 |
return O && O.map("str", R.S) && O.map("int", R.I) && |
| 465 |
O.mapOptional("bool", R.B); |
| 466 |
} |
| 467 |
|
| 468 |
static std::string errorContext(const Value &V, const Path::Root &R) { |
| 469 |
std::string Context; |
| 470 |
llvm::raw_string_ostream OS(Context); |
| 471 |
R.printErrorContext(V, OS); |
| 472 |
return OS.str(); |
| 473 |
} |
| 474 |
|
| 475 |
TEST(JSONTest, Deserialize) { |
| 476 |
std::map<std::string, std::vector<CustomStruct>> R; |
| 477 |
CustomStruct ExpectedStruct = {"foo", 42, true}; |
| 478 |
std::map<std::string, std::vector<CustomStruct>> Expected; |
| 479 |
Value J = Object{{"foo", Array{ |
| 480 |
Object{ |
| 481 |
{"str", "foo"}, |
| 482 |
{"int", 42}, |
| 483 |
{"bool", true}, |
| 484 |
{"unknown", "ignored"}, |
| 485 |
}, |
| 486 |
Object{{"str", "bar"}}, |
| 487 |
}}}; |
| 488 |
Expected["foo"] = { |
| 489 |
CustomStruct("foo", 42, true), |
| 490 |
CustomStruct("bar", std::nullopt, false), |
| 491 |
}; |
| 492 |
Path::Root Root("CustomStruct"); |
| 493 |
ASSERT_TRUE(fromJSON(J, R, Root)); |
| 494 |
EXPECT_EQ(R, Expected); |
| 495 |
|
| 496 |
(*J.getAsObject()->getArray("foo"))[0] = 123; |
| 497 |
ASSERT_FALSE(fromJSON(J, R, Root)); |
| 498 |
EXPECT_EQ("expected object at CustomStruct.foo[0]", |
| 499 |
toString(Root.getError())); |
| 500 |
const char *ExpectedDump = R"({ |
| 501 |
"foo": [ |
| 502 |
/* error: expected object */ |
| 503 |
123, |
| 504 |
{ ... } |
| 505 |
] |
| 506 |
})"; |
| 507 |
EXPECT_EQ(ExpectedDump, errorContext(J, Root)); |
| 508 |
|
| 509 |
CustomStruct V; |
| 510 |
EXPECT_FALSE(fromJSON(nullptr, V, Root)); |
| 511 |
EXPECT_EQ("expected object when parsing CustomStruct", |
| 512 |
toString(Root.getError())); |
| 513 |
|
| 514 |
EXPECT_FALSE(fromJSON(Object{}, V, Root)); |
| 515 |
EXPECT_EQ("missing value at CustomStruct.str", toString(Root.getError())); |
| 516 |
|
| 517 |
EXPECT_FALSE(fromJSON(Object{{"str", 1}}, V, Root)); |
| 518 |
EXPECT_EQ("expected string at CustomStruct.str", toString(Root.getError())); |
| 519 |
|
| 520 |
// std::optional<T> must parse as the correct type if present. |
| 521 |
EXPECT_FALSE(fromJSON(Object{{"str", "1"}, {"int", "string"}}, V, Root)); |
| 522 |
EXPECT_EQ("expected integer at CustomStruct.int", toString(Root.getError())); |
| 523 |
|
| 524 |
// mapOptional must parse as the correct type if present. |
| 525 |
EXPECT_FALSE(fromJSON(Object{{"str", "1"}, {"bool", "string"}}, V, Root)); |
| 526 |
EXPECT_EQ("expected boolean at CustomStruct.bool", toString(Root.getError())); |
| 527 |
} |
| 528 |
|
| 529 |
TEST(JSONTest, ParseDeserialize) { |
| 530 |
auto E = parse<std::vector<CustomStruct>>(R"json( |
| 531 |
[{"str": "foo", "int": 42}, {"int": 42}] |
| 532 |
)json"); |
| 533 |
EXPECT_THAT_EXPECTED(E, FailedWithMessage("missing value at (root)[1].str")); |
| 534 |
|
| 535 |
E = parse<std::vector<CustomStruct>>(R"json( |
| 536 |
[{"str": "foo", "int": 42}, {"str": "bar"} |
| 537 |
)json"); |
| 538 |
EXPECT_THAT_EXPECTED( |
| 539 |
E, |
| 540 |
FailedWithMessage("[3:2, byte=50]: Expected , or ] after array element")); |
| 541 |
|
| 542 |
E = parse<std::vector<CustomStruct>>(R"json( |
| 543 |
[{"str": "foo", "int": 42}] |
| 544 |
)json"); |
| 545 |
EXPECT_THAT_EXPECTED(E, Succeeded()); |
| 546 |
EXPECT_THAT(*E, testing::SizeIs(1)); |
| 547 |
} |
| 548 |
|
| 549 |
TEST(JSONTest, Stream) { |
| 550 |
auto StreamStuff = [](unsigned Indent) { |
| 551 |
std::string S; |
| 552 |
llvm::raw_string_ostream OS(S); |
| 553 |
OStream J(OS, Indent); |
| 554 |
J.comment("top*/level"); |
| 555 |
J.object([&] { |
| 556 |
J.attributeArray("foo", [&] { |
| 557 |
J.value(nullptr); |
| 558 |
J.comment("element"); |
| 559 |
J.value(42.5); |
| 560 |
J.arrayBegin(); |
| 561 |
J.value(43); |
| 562 |
J.arrayEnd(); |
| 563 |
J.rawValue([](raw_ostream &OS) { OS << "'unverified\nraw value'"; }); |
| 564 |
}); |
| 565 |
J.comment("attribute"); |
| 566 |
J.attributeBegin("bar"); |
| 567 |
J.comment("attribute value"); |
| 568 |
J.objectBegin(); |
| 569 |
J.objectEnd(); |
| 570 |
J.attributeEnd(); |
| 571 |
J.attribute("baz", "xyz"); |
| 572 |
}); |
| 573 |
return OS.str(); |
| 574 |
}; |
| 575 |
|
| 576 |
const char *Plain = |
| 577 |
R"(/*top* /level*/{"foo":[null,/*element*/42.5,[43],'unverified |
| 578 |
raw value'],/*attribute*/"bar":/*attribute value*/{},"baz":"xyz"})"; |
| 579 |
EXPECT_EQ(Plain, StreamStuff(0)); |
| 580 |
const char *Pretty = R"(/* top* /level */ |
| 581 |
{ |
| 582 |
"foo": [ |
| 583 |
null, |
| 584 |
/* element */ |
| 585 |
42.5, |
| 586 |
[ |
| 587 |
43 |
| 588 |
], |
| 589 |
'unverified |
| 590 |
raw value' |
| 591 |
], |
| 592 |
/* attribute */ |
| 593 |
"bar": /* attribute value */ {}, |
| 594 |
"baz": "xyz" |
| 595 |
})"; |
| 596 |
EXPECT_EQ(Pretty, StreamStuff(2)); |
| 597 |
} |
| 598 |
|
| 599 |
TEST(JSONTest, Path) { |
| 600 |
Path::Root R("foo"); |
| 601 |
Path P = R, A = P.field("a"), B = P.field("b"); |
| 602 |
P.report("oh no"); |
| 603 |
EXPECT_THAT_ERROR(R.getError(), FailedWithMessage("oh no when parsing foo")); |
| 604 |
A.index(1).field("c").index(2).report("boom"); |
| 605 |
EXPECT_THAT_ERROR(R.getError(), FailedWithMessage("boom at foo.a[1].c[2]")); |
| 606 |
B.field("d").field("e").report("bam"); |
| 607 |
EXPECT_THAT_ERROR(R.getError(), FailedWithMessage("bam at foo.b.d.e")); |
| 608 |
|
| 609 |
Value V = Object{ |
| 610 |
{"a", Array{42}}, |
| 611 |
{"b", |
| 612 |
Object{{"d", |
| 613 |
Object{ |
| 614 |
{"e", Array{1, Object{{"x", "y"}}}}, |
| 615 |
{"f", "a moderately long string: 48 characters in total"}, |
| 616 |
}}}}, |
| 617 |
}; |
| 618 |
const char *Expected = R"({ |
| 619 |
"a": [ ... ], |
| 620 |
"b": { |
| 621 |
"d": { |
| 622 |
"e": /* error: bam */ [ |
| 623 |
1, |
| 624 |
{ ... } |
| 625 |
], |
| 626 |
"f": "a moderately long string: 48 characte..." |
| 627 |
} |
| 628 |
} |
| 629 |
})"; |
| 630 |
EXPECT_EQ(Expected, errorContext(V, R)); |
| 631 |
} |
| 632 |
|
| 633 |
} // namespace |
| 634 |
} // namespace json |
| 635 |
} // namespace llvm |