Debian Codegraph @

src/test_lib_json/main.cpp

raw
1 // Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
2 // Distributed under MIT license, or public domain if desired and
3 // recognized in your jurisdiction.
4 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
5
6 #if defined(__GNUC__)
7 #pragma GCC diagnostic push
8 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
9 #elif defined(_MSC_VER)
10 #pragma warning(disable : 4996)
11 #endif
12
13 #include "fuzz.h"
14 #include "jsontest.h"
15 #include <algorithm>
16 #include <cmath>
17 #include <cstring>
18 #include <functional>
19 #include <iomanip>
20 #include <iostream>
21 #include <iterator>
22 #include <json/config.h>
23 #include <json/json.h>
24 #include <limits>
25 #include <memory>
26 #include <sstream>
27 #include <string>
28 #include <vector>
29
30 using CharReaderPtr = std::unique_ptr<Json::CharReader>;
31
32 // Make numeric limits more convenient to talk about.
33 // Assumes int type in 32 bits.
34 #define kint32max Json::Value::maxInt
35 #define kint32min Json::Value::minInt
36 #define kuint32max Json::Value::maxUInt
37 #define kint64max Json::Value::maxInt64
38 #define kint64min Json::Value::minInt64
39 #define kuint64max Json::Value::maxUInt64
40
41 // static const double kdint64max = double(kint64max);
42 // static const float kfint64max = float(kint64max);
43 static const float kfint32max = float(kint32max);
44 static const float kfuint32max = float(kuint32max);
45
46 // //////////////////////////////////////////////////////////////////
47 // //////////////////////////////////////////////////////////////////
48 // Json Library test cases
49 // //////////////////////////////////////////////////////////////////
50 // //////////////////////////////////////////////////////////////////
51
52 #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
53 static inline double uint64ToDouble(Json::UInt64 value) {
54 return static_cast<double>(value);
55 }
56 #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
57 static inline double uint64ToDouble(Json::UInt64 value) {
58 return static_cast<double>(Json::Int64(value / 2)) * 2.0 +
59 static_cast<double>(Json::Int64(value & 1));
60 }
61 #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
62
63 // local_ is the collection for the testcases in this code file.
64 static std::deque<JsonTest::TestCaseFactory> local_;
65 #define JSONTEST_FIXTURE_LOCAL(FixtureType, name) \
66 JSONTEST_FIXTURE_V2(FixtureType, name, local_)
67
68 struct ValueTest : JsonTest::TestCase {
69 Json::Value null_;
70 Json::Value emptyArray_{Json::arrayValue};
71 Json::Value emptyObject_{Json::objectValue};
72 Json::Value integer_{123456789};
73 Json::Value unsignedInteger_{34567890};
74 Json::Value smallUnsignedInteger_{Json::Value::UInt(Json::Value::maxInt)};
75 Json::Value real_{1234.56789};
76 Json::Value float_{0.00390625f};
77 Json::Value array1_;
78 Json::Value object1_;
79 Json::Value object2_;
80 Json::Value object3_;
81 Json::Value emptyString_{""};
82 Json::Value string1_{"a"};
83 Json::Value string_{"sometext with space"};
84 Json::Value true_{true};
85 Json::Value false_{false};
86
87 ValueTest() {
88 array1_.append(1234);
89 object1_["id"] = 1234;
90
91 // object2 with matching values
92 object2_["null"] = Json::nullValue;
93 object2_["bool"] = true;
94 object2_["int"] = Json::Int{Json::Value::maxInt};
95 object2_["int64"] = Json::Int64{Json::Value::maxInt64};
96 object2_["uint"] = Json::UInt{Json::Value::maxUInt};
97 object2_["uint64"] = Json::UInt64{Json::Value::maxUInt64};
98 object2_["integral"] = 1234;
99 object2_["double"] = 1234.56789;
100 object2_["numeric"] = 0.12345f;
101 object2_["string"] = "string";
102 object2_["array"] = Json::arrayValue;
103 object2_["object"] = Json::objectValue;
104
105 // object3 with not matching values
106 object3_["object"] = Json::nullValue;
107 object3_["null"] = true;
108 object3_["bool"] = Json::Int{Json::Value::maxInt};
109 object3_["int"] = "not_an_int";
110 object3_["int64"] = "not_an_int64";
111 object3_["uint"] = "not_an_uint";
112 object3_["uin64"] = "not_an_uint64";
113 object3_["integral"] = 1234.56789;
114 object3_["double"] = false;
115 object3_["numeric"] = "string";
116 object3_["string"] = Json::arrayValue;
117 object3_["array"] = Json::objectValue;
118 }
119
120 struct IsCheck {
121 /// Initialize all checks to \c false by default.
122 IsCheck();
123
124 bool isObject_{false};
125 bool isArray_{false};
126 bool isBool_{false};
127 bool isString_{false};
128 bool isNull_{false};
129
130 bool isInt_{false};
131 bool isInt64_{false};
132 bool isUInt_{false};
133 bool isUInt64_{false};
134 bool isIntegral_{false};
135 bool isDouble_{false};
136 bool isNumeric_{false};
137 };
138
139 void checkConstMemberCount(const Json::Value& value,
140 unsigned int expectedCount);
141
142 void checkMemberCount(Json::Value& value, unsigned int expectedCount);
143
144 void checkIs(const Json::Value& value, const IsCheck& check);
145
146 void checkIsLess(const Json::Value& x, const Json::Value& y);
147
148 void checkIsEqual(const Json::Value& x, const Json::Value& y);
149
150 /// Normalize the representation of floating-point number by stripped leading
151 /// 0 in exponent.
152 static Json::String normalizeFloatingPointStr(const Json::String& s);
153
154 void runCZStringTests();
155 };
156
157 Json::String ValueTest::normalizeFloatingPointStr(const Json::String& s) {
158 auto index = s.find_last_of("eE");
159 if (index == s.npos)
160 return s;
161 std::size_t signWidth = (s[index + 1] == '+' || s[index + 1] == '-') ? 1 : 0;
162 auto exponentStartIndex = index + 1 + signWidth;
163 Json::String normalized = s.substr(0, exponentStartIndex);
164 auto indexDigit = s.find_first_not_of('0', exponentStartIndex);
165 Json::String exponent = "0";
166 if (indexDigit != s.npos) { // nonzero exponent
167 exponent = s.substr(indexDigit);
168 }
169 return normalized + exponent;
170 }
171
172 void ValueTest::runCZStringTests() {
173 // 1. Copy Constructor (Index)
174 Json::Value::CZString idx1(123);
175 Json::Value::CZString idx2(idx1);
176 JSONTEST_ASSERT_EQUAL(idx2.index(), 123);
177
178 // 2. Move Constructor (Index)
179 Json::Value::CZString idx3(std::move(idx1));
180 JSONTEST_ASSERT_EQUAL(idx3.index(), 123);
181
182 // 3. Move Assignment (Index)
183 Json::Value::CZString idx4(456);
184 idx4 = std::move(idx3);
185 JSONTEST_ASSERT_EQUAL(idx4.index(), 123);
186
187 // 4. Copy Constructor (String)
188 Json::Value::CZString str1("param", 5,
189 Json::Value::CZString::duplicateOnCopy);
190 Json::Value::CZString str2((str1)); // copy makes it duplicate (owning)
191 JSONTEST_ASSERT_STRING_EQUAL(str2.data(), "param");
192
193 // 5. Move Constructor (String)
194 // Move from Owning string (str2)
195 Json::Value::CZString str3(std::move(str2));
196 JSONTEST_ASSERT_STRING_EQUAL(str3.data(), "param");
197
198 // 6. Move Assignment (String)
199 Json::Value::CZString str4("other", 5,
200 Json::Value::CZString::duplicateOnCopy);
201 Json::Value::CZString str5((str4)); // owning "other"
202 // Move-assign owning "param" (str3) into owning "other" (str5)
203 // This verifies we don't leak "other" (if fixed) and correctly take "param"
204 str5 = std::move(str3);
205 JSONTEST_ASSERT_STRING_EQUAL(str5.data(), "param");
206 }
207
208 JSONTEST_FIXTURE_LOCAL(ValueTest, CZStringCoverage) { runCZStringTests(); }
209
210 JSONTEST_FIXTURE_LOCAL(ValueTest, checkNormalizeFloatingPointStr) {
211 struct TestData {
212 std::string in;
213 std::string out;
214 } const testData[] = {
215 {"0.0", "0.0"},
216 {"0e0", "0e0"},
217 {"1234.0", "1234.0"},
218 {"1234.0e0", "1234.0e0"},
219 {"1234.0e-1", "1234.0e-1"},
220 {"1234.0e+0", "1234.0e+0"},
221 {"1234.0e+001", "1234.0e+1"},
222 {"1234e-1", "1234e-1"},
223 {"1234e+000", "1234e+0"},
224 {"1234e+001", "1234e+1"},
225 {"1234e10", "1234e10"},
226 {"1234e010", "1234e10"},
227 {"1234e+010", "1234e+10"},
228 {"1234e-010", "1234e-10"},
229 {"1234e+100", "1234e+100"},
230 {"1234e-100", "1234e-100"},
231 };
232 for (const auto& td : testData) {
233 JSONTEST_ASSERT_STRING_EQUAL(normalizeFloatingPointStr(td.in), td.out);
234 }
235 }
236
237 JSONTEST_FIXTURE_LOCAL(ValueTest, memberCount) {
238 JSONTEST_ASSERT_PRED(checkMemberCount(emptyArray_, 0));
239 JSONTEST_ASSERT_PRED(checkMemberCount(emptyObject_, 0));
240 JSONTEST_ASSERT_PRED(checkMemberCount(array1_, 1));
241 JSONTEST_ASSERT_PRED(checkMemberCount(object1_, 1));
242 JSONTEST_ASSERT_PRED(checkMemberCount(null_, 0));
243 JSONTEST_ASSERT_PRED(checkMemberCount(integer_, 0));
244 JSONTEST_ASSERT_PRED(checkMemberCount(unsignedInteger_, 0));
245 JSONTEST_ASSERT_PRED(checkMemberCount(smallUnsignedInteger_, 0));
246 JSONTEST_ASSERT_PRED(checkMemberCount(real_, 0));
247 JSONTEST_ASSERT_PRED(checkMemberCount(emptyString_, 0));
248 JSONTEST_ASSERT_PRED(checkMemberCount(string_, 0));
249 JSONTEST_ASSERT_PRED(checkMemberCount(true_, 0));
250 JSONTEST_ASSERT_PRED(checkMemberCount(false_, 0));
251 JSONTEST_ASSERT_PRED(checkMemberCount(string1_, 0));
252 JSONTEST_ASSERT_PRED(checkMemberCount(float_, 0));
253 }
254
255 JSONTEST_FIXTURE_LOCAL(ValueTest, objects) {
256 // Types
257 IsCheck checks;
258 checks.isObject_ = true;
259 JSONTEST_ASSERT_PRED(checkIs(emptyObject_, checks));
260 JSONTEST_ASSERT_PRED(checkIs(object1_, checks));
261
262 JSONTEST_ASSERT_EQUAL(Json::objectValue, emptyObject_.type());
263
264 // Empty object okay
265 JSONTEST_ASSERT(emptyObject_.isConvertibleTo(Json::nullValue));
266
267 // Non-empty object not okay
268 JSONTEST_ASSERT(!object1_.isConvertibleTo(Json::nullValue));
269
270 // Always okay
271 JSONTEST_ASSERT(emptyObject_.isConvertibleTo(Json::objectValue));
272
273 // Never okay
274 JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::arrayValue));
275 JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::intValue));
276 JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::uintValue));
277 JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::realValue));
278 JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::booleanValue));
279 JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::stringValue));
280
281 // Access through const reference
282 const Json::Value& constObject = object1_;
283
284 JSONTEST_ASSERT_EQUAL(Json::Value(1234), constObject["id"]);
285 JSONTEST_ASSERT_EQUAL(Json::Value(), constObject["unknown id"]);
286
287 // Access through find()
288 const char idKey[] = "id";
289 const Json::Value* foundId = object1_.find(idKey, idKey + strlen(idKey));
290 JSONTEST_ASSERT(foundId != nullptr);
291 JSONTEST_ASSERT_EQUAL(Json::Value(1234), *foundId);
292
293 const std::string stringIdKey = "id";
294 const Json::Value* stringFoundId = object1_.find(stringIdKey);
295 JSONTEST_ASSERT(stringFoundId != nullptr);
296 JSONTEST_ASSERT_EQUAL(Json::Value(1234), *stringFoundId);
297
298 const char unknownIdKey[] = "unknown id";
299 const Json::Value* foundUnknownId =
300 object1_.find(unknownIdKey, unknownIdKey + strlen(unknownIdKey));
301 JSONTEST_ASSERT_EQUAL(nullptr, foundUnknownId);
302
303 const std::string stringUnknownIdKey = "unknown id";
304 const Json::Value* stringFoundUnknownId = object1_.find(stringUnknownIdKey);
305 JSONTEST_ASSERT_EQUAL(nullptr, stringFoundUnknownId);
306
307 // Access through find<Type>()
308 const Json::Value* nullFound = object2_.findNull("null");
309 JSONTEST_ASSERT(nullFound != nullptr);
310 JSONTEST_ASSERT_EQUAL(Json::nullValue, *nullFound);
311 JSONTEST_ASSERT(object3_.findNull("null") == nullptr);
312
313 const Json::Value* boolFound = object2_.findBool("bool");
314 JSONTEST_ASSERT(boolFound != nullptr);
315 JSONTEST_ASSERT_EQUAL(true, *boolFound);
316 JSONTEST_ASSERT(object3_.findBool("bool") == nullptr);
317
318 const Json::Value* intFound = object2_.findInt("int");
319 JSONTEST_ASSERT(intFound != nullptr);
320 JSONTEST_ASSERT_EQUAL(Json::Int{Json::Value::maxInt}, *intFound);
321 JSONTEST_ASSERT(object3_.findInt("int") == nullptr);
322
323 const Json::Value* int64Found = object2_.findInt64("int64");
324 JSONTEST_ASSERT(int64Found != nullptr);
325 JSONTEST_ASSERT_EQUAL(Json::Int64{Json::Value::maxInt64}, *int64Found);
326 JSONTEST_ASSERT(object3_.findInt64("int64") == nullptr);
327
328 const Json::Value* uintFound = object2_.findUInt("uint");
329 JSONTEST_ASSERT(uintFound != nullptr);
330 JSONTEST_ASSERT_EQUAL(Json::UInt{Json::Value::maxUInt}, *uintFound);
331 JSONTEST_ASSERT(object3_.findUInt("uint") == nullptr);
332
333 const Json::Value* uint64Found = object2_.findUInt64("uint64");
334 JSONTEST_ASSERT(uint64Found != nullptr);
335 JSONTEST_ASSERT_EQUAL(Json::UInt64{Json::Value::maxUInt64}, *uint64Found);
336 JSONTEST_ASSERT(object3_.findUInt64("uint64") == nullptr);
337
338 const Json::Value* integralFound = object2_.findIntegral("integral");
339 JSONTEST_ASSERT(integralFound != nullptr);
340 JSONTEST_ASSERT_EQUAL(1234, *integralFound);
341 JSONTEST_ASSERT(object3_.findIntegral("integral") == nullptr);
342
343 const Json::Value* doubleFound = object2_.findDouble("double");
344 JSONTEST_ASSERT(doubleFound != nullptr);
345 JSONTEST_ASSERT_EQUAL(1234.56789, *doubleFound);
346 JSONTEST_ASSERT(object3_.findDouble("double") == nullptr);
347
348 const Json::Value* numericFound = object2_.findNumeric("numeric");
349 JSONTEST_ASSERT(numericFound != nullptr);
350 JSONTEST_ASSERT_EQUAL(0.12345f, *numericFound);
351 JSONTEST_ASSERT(object3_.findNumeric("numeric") == nullptr);
352
353 const Json::Value* stringFound = object2_.findString("string");
354 JSONTEST_ASSERT(stringFound != nullptr);
355 JSONTEST_ASSERT_EQUAL(std::string{"string"}, *stringFound);
356 JSONTEST_ASSERT(object3_.findString("string") == nullptr);
357
358 const Json::Value* arrayFound = object2_.findArray("array");
359 JSONTEST_ASSERT(arrayFound != nullptr);
360 JSONTEST_ASSERT_EQUAL(Json::arrayValue, *arrayFound);
361 JSONTEST_ASSERT(object3_.findArray("array") == nullptr);
362
363 // Access through demand()
364 const char yetAnotherIdKey[] = "yet another id";
365 const Json::Value* foundYetAnotherId =
366 object1_.find(yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey));
367 JSONTEST_ASSERT_EQUAL(nullptr, foundYetAnotherId);
368 Json::Value* demandedYetAnotherId = object1_.demand(
369 yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey));
370 JSONTEST_ASSERT(demandedYetAnotherId != nullptr);
371 *demandedYetAnotherId = "baz";
372
373 JSONTEST_ASSERT_EQUAL(Json::Value("baz"), object1_["yet another id"]);
374
375 // Access through non-const reference
376 JSONTEST_ASSERT_EQUAL(Json::Value(1234), object1_["id"]);
377 JSONTEST_ASSERT_EQUAL(Json::Value(), object1_["unknown id"]);
378
379 object1_["some other id"] = "foo";
380 JSONTEST_ASSERT_EQUAL(Json::Value("foo"), object1_["some other id"]);
381 JSONTEST_ASSERT_EQUAL(Json::Value("foo"), object1_["some other id"]);
382
383 // Remove.
384 Json::Value got;
385 bool did;
386 did = object1_.removeMember("some other id", &got);
387 JSONTEST_ASSERT_EQUAL(Json::Value("foo"), got);
388 JSONTEST_ASSERT_EQUAL(true, did);
389 got = Json::Value("bar");
390 did = object1_.removeMember("some other id", &got);
391 JSONTEST_ASSERT_EQUAL(Json::Value("bar"), got);
392 JSONTEST_ASSERT_EQUAL(false, did);
393
394 object1_["some other id"] = "foo";
395 Json::Value* gotPtr = nullptr;
396 did = object1_.removeMember("some other id", gotPtr);
397 JSONTEST_ASSERT_EQUAL(nullptr, gotPtr);
398 JSONTEST_ASSERT_EQUAL(true, did);
399
400 // Using other removeMember interfaces, the test idea is the same as above.
401 object1_["some other id"] = "foo";
402 const Json::String key("some other id");
403 did = object1_.removeMember(key, &got);
404 JSONTEST_ASSERT_EQUAL(Json::Value("foo"), got);
405 JSONTEST_ASSERT_EQUAL(true, did);
406 got = Json::Value("bar");
407 did = object1_.removeMember(key, &got);
408 JSONTEST_ASSERT_EQUAL(Json::Value("bar"), got);
409 JSONTEST_ASSERT_EQUAL(false, did);
410
411 object1_["some other id"] = "foo";
412 object1_.removeMember(key);
413 JSONTEST_ASSERT_EQUAL(Json::nullValue, object1_[key]);
414 }
415
416 JSONTEST_FIXTURE_LOCAL(ValueTest, arrays) {
417 const unsigned int index0 = 0;
418
419 // Types
420 IsCheck checks;
421 checks.isArray_ = true;
422 JSONTEST_ASSERT_PRED(checkIs(emptyArray_, checks));
423 JSONTEST_ASSERT_PRED(checkIs(array1_, checks));
424
425 JSONTEST_ASSERT_EQUAL(Json::arrayValue, array1_.type());
426
427 // Empty array okay
428 JSONTEST_ASSERT(emptyArray_.isConvertibleTo(Json::nullValue));
429
430 // Non-empty array not okay
431 JSONTEST_ASSERT(!array1_.isConvertibleTo(Json::nullValue));
432
433 // Always okay
434 JSONTEST_ASSERT(emptyArray_.isConvertibleTo(Json::arrayValue));
435
436 // Never okay
437 JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::objectValue));
438 JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::intValue));
439 JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::uintValue));
440 JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::realValue));
441 JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::booleanValue));
442 JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::stringValue));
443
444 // Access through const reference
445 const Json::Value& constArray = array1_;
446 JSONTEST_ASSERT_EQUAL(Json::Value(1234), constArray[index0]);
447 JSONTEST_ASSERT_EQUAL(Json::Value(1234), constArray[0]);
448 JSONTEST_ASSERT_EQUAL(Json::Value(1234), constArray.front());
449 JSONTEST_ASSERT_EQUAL(Json::Value(1234), constArray.back());
450
451 // Access through non-const reference
452 JSONTEST_ASSERT_EQUAL(Json::Value(1234), array1_[index0]);
453 JSONTEST_ASSERT_EQUAL(Json::Value(1234), array1_[0]);
454 JSONTEST_ASSERT_EQUAL(Json::Value(1234), array1_.front());
455 JSONTEST_ASSERT_EQUAL(Json::Value(1234), array1_.back());
456
457 array1_[2] = Json::Value(17);
458 JSONTEST_ASSERT_EQUAL(Json::Value(), array1_[1]);
459 JSONTEST_ASSERT_EQUAL(Json::Value(17), array1_[2]);
460 Json::Value got;
461 JSONTEST_ASSERT_EQUAL(true, array1_.removeIndex(2, &got));
462 JSONTEST_ASSERT_EQUAL(Json::Value(17), got);
463 JSONTEST_ASSERT_EQUAL(false, array1_.removeIndex(2, &got)); // gone now
464 }
465 JSONTEST_FIXTURE_LOCAL(ValueTest, resizeArray) {
466 Json::Value array;
467 {
468 for (Json::ArrayIndex i = 0; i < 10; i++)
469 array[i] = i;
470 JSONTEST_ASSERT_EQUAL(array.size(), 10);
471 // The length set is greater than the length of the array.
472 array.resize(15);
473 JSONTEST_ASSERT_EQUAL(array.size(), 15);
474
475 // The length set is less than the length of the array.
476 array.resize(5);
477 JSONTEST_ASSERT_EQUAL(array.size(), 5);
478
479 // The length of the array is set to 0.
480 array.resize(0);
481 JSONTEST_ASSERT_EQUAL(array.size(), 0);
482 }
483 {
484 for (Json::ArrayIndex i = 0; i < 10; i++)
485 array[i] = i;
486 JSONTEST_ASSERT_EQUAL(array.size(), 10);
487 array.clear();
488 JSONTEST_ASSERT_EQUAL(array.size(), 0);
489 }
490 }
491
492 JSONTEST_FIXTURE_LOCAL(ValueTest, copyMoveArray) {
493 Json::Value array;
494 array.append("item1");
495 array.append("item2");
496
497 // Test Copy Constructor (covers CZString(const CZString&) with index)
498 Json::Value copy(array);
499 JSONTEST_ASSERT_EQUAL(copy.size(), 2);
500 JSONTEST_ASSERT_EQUAL(Json::Value("item1"), copy[0]);
501 JSONTEST_ASSERT_EQUAL(Json::Value("item2"), copy[1]);
502
503 // Test Move Constructor (covers CZString(CZString&&) with index)
504 Json::Value moved(std::move(copy));
505 JSONTEST_ASSERT_EQUAL(moved.size(), 2);
506 JSONTEST_ASSERT_EQUAL(Json::Value("item1"), moved[0]);
507 JSONTEST_ASSERT_EQUAL(Json::Value("item2"), moved[1]);
508 }
509
510 JSONTEST_FIXTURE_LOCAL(ValueTest, resizePopulatesAllMissingElements) {
511 Json::ArrayIndex n = 10;
512 Json::Value v;
513 v.resize(n);
514 JSONTEST_ASSERT_EQUAL(n, v.size());
515 JSONTEST_ASSERT_EQUAL(n, std::distance(v.begin(), v.end()));
516 JSONTEST_ASSERT_EQUAL(v.front(), Json::Value{});
517 JSONTEST_ASSERT_EQUAL(v.back(), Json::Value{});
518 for (const Json::Value& e : v)
519 JSONTEST_ASSERT_EQUAL(e, Json::Value{});
520 }
521
522 JSONTEST_FIXTURE_LOCAL(ValueTest, getArrayValue) {
523 Json::Value array;
524 for (Json::ArrayIndex i = 0; i < 5; i++)
525 array[i] = i;
526
527 JSONTEST_ASSERT_EQUAL(array.size(), 5);
528 const Json::Value defaultValue(10);
529 Json::ArrayIndex index = 0;
530 for (; index <= 4; index++)
531 JSONTEST_ASSERT_EQUAL(index, array.get(index, defaultValue).asInt());
532
533 index = 4;
534 JSONTEST_ASSERT_EQUAL(array.isValidIndex(index), true);
535 index = 5;
536 JSONTEST_ASSERT_EQUAL(array.isValidIndex(index), false);
537 JSONTEST_ASSERT_EQUAL(defaultValue, array.get(index, defaultValue));
538 JSONTEST_ASSERT_EQUAL(array.isValidIndex(index), false);
539 }
540 JSONTEST_FIXTURE_LOCAL(ValueTest, arrayIssue252) {
541 int count = 5;
542 Json::Value root;
543 Json::Value item;
544 root["array"] = Json::Value::nullSingleton();
545 for (int i = 0; i < count; i++) {
546 item["a"] = i;
547 item["b"] = i;
548 root["array"][i] = item;
549 }
550 // JSONTEST_ASSERT_EQUAL(5, root["array"].size());
551 }
552
553 JSONTEST_FIXTURE_LOCAL(ValueTest, arrayInsertAtRandomIndex) {
554 Json::Value array;
555 const Json::Value str0("index2");
556 const Json::Value str1("index3");
557 array.append("index0"); // append rvalue
558 array.append("index1");
559 array.append(str0); // append lvalue
560
561 std::vector<Json::Value*> vec; // storage value address for checking
562 for (Json::ArrayIndex i = 0; i < 3; i++) {
563 vec.push_back(&array[i]);
564 }
565 JSONTEST_ASSERT_EQUAL(Json::Value("index0"), array[0]); // check append
566 JSONTEST_ASSERT_EQUAL(Json::Value("index1"), array[1]);
567 JSONTEST_ASSERT_EQUAL(Json::Value("index2"), array[2]);
568 JSONTEST_ASSERT_EQUAL(Json::Value("index0"), array.front());
569 JSONTEST_ASSERT_EQUAL(Json::Value("index2"), array.back());
570
571 // insert lvalue at the head
572 JSONTEST_ASSERT(array.insert(0, str1));
573 JSONTEST_ASSERT_EQUAL(Json::Value("index3"), array[0]);
574 JSONTEST_ASSERT_EQUAL(Json::Value("index0"), array[1]);
575 JSONTEST_ASSERT_EQUAL(Json::Value("index1"), array[2]);
576 JSONTEST_ASSERT_EQUAL(Json::Value("index2"), array[3]);
577 JSONTEST_ASSERT_EQUAL(Json::Value("index3"), array.front());
578 JSONTEST_ASSERT_EQUAL(Json::Value("index2"), array.back());
579 // checking address
580 for (Json::ArrayIndex i = 0; i < 3; i++) {
581 JSONTEST_ASSERT_EQUAL(vec[i], &array[i]);
582 }
583 vec.push_back(&array[3]);
584 // insert rvalue at middle
585 JSONTEST_ASSERT(array.insert(2, "index4"));
586 JSONTEST_ASSERT_EQUAL(Json::Value("index3"), array[0]);
587 JSONTEST_ASSERT_EQUAL(Json::Value("index0"), array[1]);
588 JSONTEST_ASSERT_EQUAL(Json::Value("index4"), array[2]);
589 JSONTEST_ASSERT_EQUAL(Json::Value("index1"), array[3]);
590 JSONTEST_ASSERT_EQUAL(Json::Value("index2"), array[4]);
591 JSONTEST_ASSERT_EQUAL(Json::Value("index3"), array.front());
592 JSONTEST_ASSERT_EQUAL(Json::Value("index2"), array.back());
593 // checking address
594 for (Json::ArrayIndex i = 0; i < 4; i++) {
595 JSONTEST_ASSERT_EQUAL(vec[i], &array[i]);
596 }
597 vec.push_back(&array[4]);
598 // insert rvalue at the tail
599 JSONTEST_ASSERT(array.insert(5, "index5"));
600 JSONTEST_ASSERT_EQUAL(Json::Value("index3"), array[0]);
601 JSONTEST_ASSERT_EQUAL(Json::Value("index0"), array[1]);
602 JSONTEST_ASSERT_EQUAL(Json::Value("index4"), array[2]);
603 JSONTEST_ASSERT_EQUAL(Json::Value("index1"), array[3]);
604 JSONTEST_ASSERT_EQUAL(Json::Value("index2"), array[4]);
605 JSONTEST_ASSERT_EQUAL(Json::Value("index5"), array[5]);
606 JSONTEST_ASSERT_EQUAL(Json::Value("index3"), array.front());
607 JSONTEST_ASSERT_EQUAL(Json::Value("index5"), array.back());
608 // checking address
609 for (Json::ArrayIndex i = 0; i < 5; i++) {
610 JSONTEST_ASSERT_EQUAL(vec[i], &array[i]);
611 }
612 vec.push_back(&array[5]);
613 // beyond max array size, it should not be allowed to insert into its tail
614 JSONTEST_ASSERT(!array.insert(10, "index10"));
615 }
616
617 JSONTEST_FIXTURE_LOCAL(ValueTest, null) {
618 JSONTEST_ASSERT_EQUAL(Json::nullValue, null_.type());
619
620 IsCheck checks;
621 checks.isNull_ = true;
622 JSONTEST_ASSERT_PRED(checkIs(null_, checks));
623
624 JSONTEST_ASSERT(null_.isConvertibleTo(Json::nullValue));
625 JSONTEST_ASSERT(null_.isConvertibleTo(Json::intValue));
626 JSONTEST_ASSERT(null_.isConvertibleTo(Json::uintValue));
627 JSONTEST_ASSERT(null_.isConvertibleTo(Json::realValue));
628 JSONTEST_ASSERT(null_.isConvertibleTo(Json::booleanValue));
629 JSONTEST_ASSERT(null_.isConvertibleTo(Json::stringValue));
630 JSONTEST_ASSERT(null_.isConvertibleTo(Json::arrayValue));
631 JSONTEST_ASSERT(null_.isConvertibleTo(Json::objectValue));
632
633 JSONTEST_ASSERT_EQUAL(Json::Int(0), null_.asInt());
634 JSONTEST_ASSERT_EQUAL(Json::LargestInt(0), null_.asLargestInt());
635 JSONTEST_ASSERT_EQUAL(Json::UInt(0), null_.asUInt());
636 JSONTEST_ASSERT_EQUAL(Json::LargestUInt(0), null_.asLargestUInt());
637 JSONTEST_ASSERT_EQUAL(0.0, null_.asDouble());
638 JSONTEST_ASSERT_EQUAL(0.0, null_.asFloat());
639 JSONTEST_ASSERT_STRING_EQUAL("", null_.asString());
640
641 JSONTEST_ASSERT_EQUAL(Json::Value::nullSingleton(), null_);
642
643 // Test using a Value in a boolean context (false iff null)
644 JSONTEST_ASSERT_EQUAL(null_, false);
645 JSONTEST_ASSERT_EQUAL(object1_, true);
646 JSONTEST_ASSERT_EQUAL(!null_, true);
647 JSONTEST_ASSERT_EQUAL(!object1_, false);
648 }
649
650 JSONTEST_FIXTURE_LOCAL(ValueTest, strings) {
651 JSONTEST_ASSERT_EQUAL(Json::stringValue, string1_.type());
652
653 IsCheck checks;
654 checks.isString_ = true;
655 JSONTEST_ASSERT_PRED(checkIs(emptyString_, checks));
656 JSONTEST_ASSERT_PRED(checkIs(string_, checks));
657 JSONTEST_ASSERT_PRED(checkIs(string1_, checks));
658
659 // Empty string okay
660 JSONTEST_ASSERT(emptyString_.isConvertibleTo(Json::nullValue));
661
662 // Non-empty string not okay
663 JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::nullValue));
664
665 // Always okay
666 JSONTEST_ASSERT(string1_.isConvertibleTo(Json::stringValue));
667
668 // Never okay
669 JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::objectValue));
670 JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::arrayValue));
671 JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::intValue));
672 JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::uintValue));
673 JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::realValue));
674
675 JSONTEST_ASSERT_STRING_EQUAL("a", string1_.asString());
676 JSONTEST_ASSERT_STRING_EQUAL("a", string1_.asCString());
677 }
678
679 JSONTEST_FIXTURE_LOCAL(ValueTest, bools) {
680 JSONTEST_ASSERT_EQUAL(Json::booleanValue, false_.type());
681
682 IsCheck checks;
683 checks.isBool_ = true;
684 JSONTEST_ASSERT_PRED(checkIs(false_, checks));
685 JSONTEST_ASSERT_PRED(checkIs(true_, checks));
686
687 // False okay
688 JSONTEST_ASSERT(false_.isConvertibleTo(Json::nullValue));
689
690 // True not okay
691 JSONTEST_ASSERT(!true_.isConvertibleTo(Json::nullValue));
692
693 // Always okay
694 JSONTEST_ASSERT(true_.isConvertibleTo(Json::intValue));
695 JSONTEST_ASSERT(true_.isConvertibleTo(Json::uintValue));
696 JSONTEST_ASSERT(true_.isConvertibleTo(Json::realValue));
697 JSONTEST_ASSERT(true_.isConvertibleTo(Json::booleanValue));
698 JSONTEST_ASSERT(true_.isConvertibleTo(Json::stringValue));
699
700 // Never okay
701 JSONTEST_ASSERT(!true_.isConvertibleTo(Json::arrayValue));
702 JSONTEST_ASSERT(!true_.isConvertibleTo(Json::objectValue));
703
704 JSONTEST_ASSERT_EQUAL(true, true_.asBool());
705 JSONTEST_ASSERT_EQUAL(1, true_.asInt());
706 JSONTEST_ASSERT_EQUAL(1, true_.asLargestInt());
707 JSONTEST_ASSERT_EQUAL(1, true_.asUInt());
708 JSONTEST_ASSERT_EQUAL(1, true_.asLargestUInt());
709 JSONTEST_ASSERT_EQUAL(1.0, true_.asDouble());
710 JSONTEST_ASSERT_EQUAL(1.0, true_.asFloat());
711
712 JSONTEST_ASSERT_EQUAL(false, false_.asBool());
713 JSONTEST_ASSERT_EQUAL(0, false_.asInt());
714 JSONTEST_ASSERT_EQUAL(0, false_.asLargestInt());
715 JSONTEST_ASSERT_EQUAL(0, false_.asUInt());
716 JSONTEST_ASSERT_EQUAL(0, false_.asLargestUInt());
717 JSONTEST_ASSERT_EQUAL(0.0, false_.asDouble());
718 JSONTEST_ASSERT_EQUAL(0.0, false_.asFloat());
719 }
720
721 JSONTEST_FIXTURE_LOCAL(ValueTest, integers) {
722 IsCheck checks;
723 Json::Value val;
724
725 // Conversions that don't depend on the value.
726 JSONTEST_ASSERT(Json::Value(17).isConvertibleTo(Json::realValue));
727 JSONTEST_ASSERT(Json::Value(17).isConvertibleTo(Json::stringValue));
728 JSONTEST_ASSERT(Json::Value(17).isConvertibleTo(Json::booleanValue));
729 JSONTEST_ASSERT(!Json::Value(17).isConvertibleTo(Json::arrayValue));
730 JSONTEST_ASSERT(!Json::Value(17).isConvertibleTo(Json::objectValue));
731
732 JSONTEST_ASSERT(Json::Value(17U).isConvertibleTo(Json::realValue));
733 JSONTEST_ASSERT(Json::Value(17U).isConvertibleTo(Json::stringValue));
734 JSONTEST_ASSERT(Json::Value(17U).isConvertibleTo(Json::booleanValue));
735 JSONTEST_ASSERT(!Json::Value(17U).isConvertibleTo(Json::arrayValue));
736 JSONTEST_ASSERT(!Json::Value(17U).isConvertibleTo(Json::objectValue));
737
738 JSONTEST_ASSERT(Json::Value(17.0).isConvertibleTo(Json::realValue));
739 JSONTEST_ASSERT(Json::Value(17.0).isConvertibleTo(Json::stringValue));
740 JSONTEST_ASSERT(Json::Value(17.0).isConvertibleTo(Json::booleanValue));
741 JSONTEST_ASSERT(!Json::Value(17.0).isConvertibleTo(Json::arrayValue));
742 JSONTEST_ASSERT(!Json::Value(17.0).isConvertibleTo(Json::objectValue));
743
744 // Default int
745 val = Json::Value(Json::intValue);
746
747 JSONTEST_ASSERT_EQUAL(Json::intValue, val.type());
748
749 checks = IsCheck();
750 checks.isInt_ = true;
751 checks.isInt64_ = true;
752 checks.isUInt_ = true;
753 checks.isUInt64_ = true;
754 checks.isIntegral_ = true;
755 checks.isDouble_ = true;
756 checks.isNumeric_ = true;
757 JSONTEST_ASSERT_PRED(checkIs(val, checks));
758
759 JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue));
760 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
761 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
762
763 JSONTEST_ASSERT_EQUAL(0, val.asInt());
764 JSONTEST_ASSERT_EQUAL(0, val.asLargestInt());
765 JSONTEST_ASSERT_EQUAL(0, val.asUInt());
766 JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt());
767 JSONTEST_ASSERT_EQUAL(0.0, val.asDouble());
768 JSONTEST_ASSERT_EQUAL(0.0, val.asFloat());
769 JSONTEST_ASSERT_EQUAL(false, val.asBool());
770 JSONTEST_ASSERT_STRING_EQUAL("0", val.asString());
771
772 // Default uint
773 val = Json::Value(Json::uintValue);
774
775 JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type());
776
777 checks = IsCheck();
778 checks.isInt_ = true;
779 checks.isInt64_ = true;
780 checks.isUInt_ = true;
781 checks.isUInt64_ = true;
782 checks.isIntegral_ = true;
783 checks.isDouble_ = true;
784 checks.isNumeric_ = true;
785 JSONTEST_ASSERT_PRED(checkIs(val, checks));
786
787 JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue));
788 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
789 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
790
791 JSONTEST_ASSERT_EQUAL(0, val.asInt());
792 JSONTEST_ASSERT_EQUAL(0, val.asLargestInt());
793 JSONTEST_ASSERT_EQUAL(0, val.asUInt());
794 JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt());
795 JSONTEST_ASSERT_EQUAL(0.0, val.asDouble());
796 JSONTEST_ASSERT_EQUAL(0.0, val.asFloat());
797 JSONTEST_ASSERT_EQUAL(false, val.asBool());
798 JSONTEST_ASSERT_STRING_EQUAL("0", val.asString());
799
800 // Default real
801 val = Json::Value(Json::realValue);
802
803 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
804
805 JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue));
806 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
807 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
808
809 checks = IsCheck();
810 checks.isInt_ = true;
811 checks.isInt64_ = true;
812 checks.isUInt_ = true;
813 checks.isUInt64_ = true;
814 checks.isIntegral_ = true;
815 checks.isDouble_ = true;
816 checks.isNumeric_ = true;
817 JSONTEST_ASSERT_PRED(checkIs(val, checks));
818
819 JSONTEST_ASSERT_EQUAL(0, val.asInt());
820 JSONTEST_ASSERT_EQUAL(0, val.asLargestInt());
821 JSONTEST_ASSERT_EQUAL(0, val.asUInt());
822 JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt());
823 JSONTEST_ASSERT_EQUAL(0.0, val.asDouble());
824 JSONTEST_ASSERT_EQUAL(0.0, val.asFloat());
825 JSONTEST_ASSERT_EQUAL(false, val.asBool());
826 JSONTEST_ASSERT_STRING_EQUAL("0.0", val.asString());
827
828 // Zero (signed constructor arg)
829 val = Json::Value(0);
830
831 JSONTEST_ASSERT_EQUAL(Json::intValue, val.type());
832
833 checks = IsCheck();
834 checks.isInt_ = true;
835 checks.isInt64_ = true;
836 checks.isUInt_ = true;
837 checks.isUInt64_ = true;
838 checks.isIntegral_ = true;
839 checks.isDouble_ = true;
840 checks.isNumeric_ = true;
841 JSONTEST_ASSERT_PRED(checkIs(val, checks));
842
843 JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue));
844 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
845 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
846
847 JSONTEST_ASSERT_EQUAL(0, val.asInt());
848 JSONTEST_ASSERT_EQUAL(0, val.asLargestInt());
849 JSONTEST_ASSERT_EQUAL(0, val.asUInt());
850 JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt());
851 JSONTEST_ASSERT_EQUAL(0.0, val.asDouble());
852 JSONTEST_ASSERT_EQUAL(0.0, val.asFloat());
853 JSONTEST_ASSERT_EQUAL(false, val.asBool());
854 JSONTEST_ASSERT_STRING_EQUAL("0", val.asString());
855
856 // Zero (unsigned constructor arg)
857 val = Json::Value(0u);
858
859 JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type());
860
861 checks = IsCheck();
862 checks.isInt_ = true;
863 checks.isInt64_ = true;
864 checks.isUInt_ = true;
865 checks.isUInt64_ = true;
866 checks.isIntegral_ = true;
867 checks.isDouble_ = true;
868 checks.isNumeric_ = true;
869 JSONTEST_ASSERT_PRED(checkIs(val, checks));
870
871 JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue));
872 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
873 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
874
875 JSONTEST_ASSERT_EQUAL(0, val.asInt());
876 JSONTEST_ASSERT_EQUAL(0, val.asLargestInt());
877 JSONTEST_ASSERT_EQUAL(0, val.asUInt());
878 JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt());
879 JSONTEST_ASSERT_EQUAL(0.0, val.asDouble());
880 JSONTEST_ASSERT_EQUAL(0.0, val.asFloat());
881 JSONTEST_ASSERT_EQUAL(false, val.asBool());
882 JSONTEST_ASSERT_STRING_EQUAL("0", val.asString());
883
884 // Zero (floating-point constructor arg)
885 val = Json::Value(0.0);
886
887 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
888
889 checks = IsCheck();
890 checks.isInt_ = true;
891 checks.isInt64_ = true;
892 checks.isUInt_ = true;
893 checks.isUInt64_ = true;
894 checks.isIntegral_ = true;
895 checks.isDouble_ = true;
896 checks.isNumeric_ = true;
897 JSONTEST_ASSERT_PRED(checkIs(val, checks));
898
899 JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue));
900 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
901 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
902
903 JSONTEST_ASSERT_EQUAL(0, val.asInt());
904 JSONTEST_ASSERT_EQUAL(0, val.asLargestInt());
905 JSONTEST_ASSERT_EQUAL(0, val.asUInt());
906 JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt());
907 JSONTEST_ASSERT_EQUAL(0.0, val.asDouble());
908 JSONTEST_ASSERT_EQUAL(0.0, val.asFloat());
909 JSONTEST_ASSERT_EQUAL(false, val.asBool());
910 JSONTEST_ASSERT_STRING_EQUAL("0.0", val.asString());
911
912 // 2^20 (signed constructor arg)
913 val = Json::Value(1 << 20);
914
915 JSONTEST_ASSERT_EQUAL(Json::intValue, val.type());
916 checks = IsCheck();
917 checks.isInt_ = true;
918 checks.isInt64_ = true;
919 checks.isUInt_ = true;
920 checks.isUInt64_ = true;
921 checks.isIntegral_ = true;
922 checks.isDouble_ = true;
923 checks.isNumeric_ = true;
924 JSONTEST_ASSERT_PRED(checkIs(val, checks));
925
926 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
927 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
928 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
929
930 JSONTEST_ASSERT_EQUAL((1 << 20), val.asInt());
931 JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestInt());
932 JSONTEST_ASSERT_EQUAL((1 << 20), val.asUInt());
933 JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestUInt());
934 JSONTEST_ASSERT_EQUAL((1 << 20), val.asDouble());
935 JSONTEST_ASSERT_EQUAL((1 << 20), val.asFloat());
936 JSONTEST_ASSERT_EQUAL(true, val.asBool());
937 JSONTEST_ASSERT_STRING_EQUAL("1048576", val.asString());
938
939 // 2^20 (unsigned constructor arg)
940 val = Json::Value(Json::UInt(1 << 20));
941
942 JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type());
943
944 checks = IsCheck();
945 checks.isInt_ = true;
946 checks.isInt64_ = true;
947 checks.isUInt_ = true;
948 checks.isUInt64_ = true;
949 checks.isIntegral_ = true;
950 checks.isDouble_ = true;
951 checks.isNumeric_ = true;
952 JSONTEST_ASSERT_PRED(checkIs(val, checks));
953
954 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
955 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
956 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
957
958 JSONTEST_ASSERT_EQUAL((1 << 20), val.asInt());
959 JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestInt());
960 JSONTEST_ASSERT_EQUAL((1 << 20), val.asUInt());
961 JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestUInt());
962 JSONTEST_ASSERT_EQUAL((1 << 20), val.asDouble());
963 JSONTEST_ASSERT_EQUAL((1 << 20), val.asFloat());
964 JSONTEST_ASSERT_EQUAL(true, val.asBool());
965 JSONTEST_ASSERT_STRING_EQUAL("1048576", val.asString());
966
967 // 2^20 (floating-point constructor arg)
968 val = Json::Value((1 << 20) / 1.0);
969
970 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
971
972 checks = IsCheck();
973 checks.isInt_ = true;
974 checks.isInt64_ = true;
975 checks.isUInt_ = true;
976 checks.isUInt64_ = true;
977 checks.isIntegral_ = true;
978 checks.isDouble_ = true;
979 checks.isNumeric_ = true;
980 JSONTEST_ASSERT_PRED(checkIs(val, checks));
981
982 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
983 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
984 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
985
986 JSONTEST_ASSERT_EQUAL((1 << 20), val.asInt());
987 JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestInt());
988 JSONTEST_ASSERT_EQUAL((1 << 20), val.asUInt());
989 JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestUInt());
990 JSONTEST_ASSERT_EQUAL((1 << 20), val.asDouble());
991 JSONTEST_ASSERT_EQUAL((1 << 20), val.asFloat());
992 JSONTEST_ASSERT_EQUAL(true, val.asBool());
993 JSONTEST_ASSERT_STRING_EQUAL(
994 "1048576.0",
995 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
996
997 // -2^20
998 val = Json::Value(-(1 << 20));
999
1000 JSONTEST_ASSERT_EQUAL(Json::intValue, val.type());
1001
1002 checks = IsCheck();
1003 checks.isInt_ = true;
1004 checks.isInt64_ = true;
1005 checks.isIntegral_ = true;
1006 checks.isDouble_ = true;
1007 checks.isNumeric_ = true;
1008 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1009
1010 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1011 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
1012 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1013
1014 JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asInt());
1015 JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asLargestInt());
1016 JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asDouble());
1017 JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asFloat());
1018 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1019 JSONTEST_ASSERT_STRING_EQUAL("-1048576", val.asString());
1020
1021 // int32 max
1022 val = Json::Value(kint32max);
1023
1024 JSONTEST_ASSERT_EQUAL(Json::intValue, val.type());
1025
1026 checks = IsCheck();
1027 checks.isInt_ = true;
1028 checks.isInt64_ = true;
1029 checks.isUInt_ = true;
1030 checks.isUInt64_ = true;
1031 checks.isIntegral_ = true;
1032 checks.isDouble_ = true;
1033 checks.isNumeric_ = true;
1034 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1035
1036 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1037 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
1038 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
1039
1040 JSONTEST_ASSERT_EQUAL(kint32max, val.asInt());
1041 JSONTEST_ASSERT_EQUAL(kint32max, val.asLargestInt());
1042 JSONTEST_ASSERT_EQUAL(kint32max, val.asUInt());
1043 JSONTEST_ASSERT_EQUAL(kint32max, val.asLargestUInt());
1044 JSONTEST_ASSERT_EQUAL(kint32max, val.asDouble());
1045 JSONTEST_ASSERT_EQUAL(kfint32max, val.asFloat());
1046 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1047 JSONTEST_ASSERT_STRING_EQUAL("2147483647", val.asString());
1048
1049 // int32 min
1050 val = Json::Value(kint32min);
1051
1052 JSONTEST_ASSERT_EQUAL(Json::intValue, val.type());
1053
1054 checks = IsCheck();
1055 checks.isInt_ = true;
1056 checks.isInt64_ = true;
1057 checks.isIntegral_ = true;
1058 checks.isDouble_ = true;
1059 checks.isNumeric_ = true;
1060 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1061
1062 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1063 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
1064 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1065
1066 JSONTEST_ASSERT_EQUAL(kint32min, val.asInt());
1067 JSONTEST_ASSERT_EQUAL(kint32min, val.asLargestInt());
1068 JSONTEST_ASSERT_EQUAL(kint32min, val.asDouble());
1069 JSONTEST_ASSERT_EQUAL(kint32min, val.asFloat());
1070 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1071 JSONTEST_ASSERT_STRING_EQUAL("-2147483648", val.asString());
1072
1073 // uint32 max
1074 val = Json::Value(kuint32max);
1075
1076 JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type());
1077
1078 checks = IsCheck();
1079 checks.isInt64_ = true;
1080 checks.isUInt_ = true;
1081 checks.isUInt64_ = true;
1082 checks.isIntegral_ = true;
1083 checks.isDouble_ = true;
1084 checks.isNumeric_ = true;
1085 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1086
1087 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1088 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1089 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
1090
1091 #ifndef JSON_NO_INT64
1092 JSONTEST_ASSERT_EQUAL(kuint32max, val.asLargestInt());
1093 #endif
1094 JSONTEST_ASSERT_EQUAL(kuint32max, val.asUInt());
1095 JSONTEST_ASSERT_EQUAL(kuint32max, val.asLargestUInt());
1096 JSONTEST_ASSERT_EQUAL(kuint32max, val.asDouble());
1097 JSONTEST_ASSERT_EQUAL(kfuint32max, val.asFloat());
1098 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1099 JSONTEST_ASSERT_STRING_EQUAL("4294967295", val.asString());
1100
1101 #ifdef JSON_NO_INT64
1102 // int64 max
1103 val = Json::Value(double(kint64max));
1104
1105 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1106
1107 checks = IsCheck();
1108 checks.isDouble_ = true;
1109 checks.isNumeric_ = true;
1110 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1111
1112 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1113 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1114 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1115
1116 JSONTEST_ASSERT_EQUAL(double(kint64max), val.asDouble());
1117 JSONTEST_ASSERT_EQUAL(float(kint64max), val.asFloat());
1118 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1119 JSONTEST_ASSERT_STRING_EQUAL("9.22337e+18", val.asString());
1120
1121 // int64 min
1122 val = Json::Value(double(kint64min));
1123
1124 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1125
1126 checks = IsCheck();
1127 checks.isDouble_ = true;
1128 checks.isNumeric_ = true;
1129 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1130
1131 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1132 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1133 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1134
1135 JSONTEST_ASSERT_EQUAL(double(kint64min), val.asDouble());
1136 JSONTEST_ASSERT_EQUAL(float(kint64min), val.asFloat());
1137 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1138 JSONTEST_ASSERT_STRING_EQUAL("-9.22337e+18", val.asString());
1139
1140 // uint64 max
1141 val = Json::Value(double(kuint64max));
1142
1143 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1144
1145 checks = IsCheck();
1146 checks.isDouble_ = true;
1147 checks.isNumeric_ = true;
1148 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1149
1150 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1151 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1152 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1153
1154 JSONTEST_ASSERT_EQUAL(double(kuint64max), val.asDouble());
1155 JSONTEST_ASSERT_EQUAL(float(kuint64max), val.asFloat());
1156 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1157 JSONTEST_ASSERT_STRING_EQUAL("1.84467e+19", val.asString());
1158 #else // ifdef JSON_NO_INT64
1159 // 2^40 (signed constructor arg)
1160 val = Json::Value(Json::Int64(1) << 40);
1161
1162 JSONTEST_ASSERT_EQUAL(Json::intValue, val.type());
1163
1164 checks = IsCheck();
1165 checks.isInt64_ = true;
1166 checks.isUInt64_ = true;
1167 checks.isIntegral_ = true;
1168 checks.isDouble_ = true;
1169 checks.isNumeric_ = true;
1170 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1171
1172 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1173 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1174 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1175
1176 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asInt64());
1177 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestInt());
1178 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asUInt64());
1179 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestUInt());
1180 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asDouble());
1181 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asFloat());
1182 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1183 JSONTEST_ASSERT_STRING_EQUAL("1099511627776", val.asString());
1184
1185 // 2^40 (unsigned constructor arg)
1186 val = Json::Value(Json::UInt64(1) << 40);
1187
1188 JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type());
1189
1190 checks = IsCheck();
1191 checks.isInt64_ = true;
1192 checks.isUInt64_ = true;
1193 checks.isIntegral_ = true;
1194 checks.isDouble_ = true;
1195 checks.isNumeric_ = true;
1196 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1197
1198 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1199 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1200 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1201
1202 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asInt64());
1203 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestInt());
1204 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asUInt64());
1205 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestUInt());
1206 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asDouble());
1207 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asFloat());
1208 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1209 JSONTEST_ASSERT_STRING_EQUAL("1099511627776", val.asString());
1210
1211 // 2^40 (floating-point constructor arg)
1212 val = Json::Value((Json::Int64(1) << 40) / 1.0);
1213
1214 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1215
1216 checks = IsCheck();
1217 checks.isInt64_ = true;
1218 checks.isUInt64_ = true;
1219 checks.isIntegral_ = true;
1220 checks.isDouble_ = true;
1221 checks.isNumeric_ = true;
1222 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1223
1224 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1225 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1226 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1227
1228 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asInt64());
1229 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestInt());
1230 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asUInt64());
1231 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestUInt());
1232 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asDouble());
1233 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asFloat());
1234 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1235 JSONTEST_ASSERT_STRING_EQUAL(
1236 "1099511627776.0",
1237 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1238
1239 // -2^40
1240 val = Json::Value(-(Json::Int64(1) << 40));
1241
1242 JSONTEST_ASSERT_EQUAL(Json::intValue, val.type());
1243
1244 checks = IsCheck();
1245 checks.isInt64_ = true;
1246 checks.isIntegral_ = true;
1247 checks.isDouble_ = true;
1248 checks.isNumeric_ = true;
1249 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1250
1251 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1252 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1253 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1254
1255 JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asInt64());
1256 JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asLargestInt());
1257 JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asDouble());
1258 JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asFloat());
1259 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1260 JSONTEST_ASSERT_STRING_EQUAL("-1099511627776", val.asString());
1261
1262 // int64 max
1263 val = Json::Value(Json::Int64(kint64max));
1264
1265 JSONTEST_ASSERT_EQUAL(Json::intValue, val.type());
1266
1267 checks = IsCheck();
1268 checks.isInt64_ = true;
1269 checks.isUInt64_ = true;
1270 checks.isIntegral_ = true;
1271 checks.isDouble_ = true;
1272 checks.isNumeric_ = true;
1273 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1274
1275 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1276 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1277 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1278
1279 JSONTEST_ASSERT_EQUAL(kint64max, val.asInt64());
1280 JSONTEST_ASSERT_EQUAL(kint64max, val.asLargestInt());
1281 JSONTEST_ASSERT_EQUAL(kint64max, val.asUInt64());
1282 JSONTEST_ASSERT_EQUAL(kint64max, val.asLargestUInt());
1283 JSONTEST_ASSERT_EQUAL(double(kint64max), val.asDouble());
1284 JSONTEST_ASSERT_EQUAL(float(kint64max), val.asFloat());
1285 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1286 JSONTEST_ASSERT_STRING_EQUAL("9223372036854775807", val.asString());
1287
1288 // int64 max (floating point constructor). Note that kint64max is not exactly
1289 // representable as a double, and will be rounded up to be higher.
1290 val = Json::Value(double(kint64max));
1291
1292 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1293
1294 checks = IsCheck();
1295 checks.isUInt64_ = true;
1296 checks.isIntegral_ = true;
1297 checks.isDouble_ = true;
1298 checks.isNumeric_ = true;
1299 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1300
1301 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1302 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1303 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1304
1305 JSONTEST_ASSERT_EQUAL(Json::UInt64(1) << 63, val.asUInt64());
1306 JSONTEST_ASSERT_EQUAL(Json::UInt64(1) << 63, val.asLargestUInt());
1307 JSONTEST_ASSERT_EQUAL(uint64ToDouble(Json::UInt64(1) << 63), val.asDouble());
1308 JSONTEST_ASSERT_EQUAL(float(Json::UInt64(1) << 63), val.asFloat());
1309
1310 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1311 JSONTEST_ASSERT_STRING_EQUAL(
1312 "9.2233720368547758e+18",
1313 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1314
1315 // int64 min
1316 val = Json::Value(Json::Int64(kint64min));
1317
1318 JSONTEST_ASSERT_EQUAL(Json::intValue, val.type());
1319
1320 checks = IsCheck();
1321 checks.isInt64_ = true;
1322 checks.isIntegral_ = true;
1323 checks.isDouble_ = true;
1324 checks.isNumeric_ = true;
1325 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1326
1327 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1328 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1329 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1330
1331 JSONTEST_ASSERT_EQUAL(kint64min, val.asInt64());
1332 JSONTEST_ASSERT_EQUAL(kint64min, val.asLargestInt());
1333 JSONTEST_ASSERT_EQUAL(double(kint64min), val.asDouble());
1334 JSONTEST_ASSERT_EQUAL(float(kint64min), val.asFloat());
1335 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1336 JSONTEST_ASSERT_STRING_EQUAL("-9223372036854775808", val.asString());
1337
1338 // int64 min (floating point constructor). Since double values in proximity of
1339 // kint64min are rounded to kint64min, we don't check for conversion to int64.
1340 val = Json::Value(double(kint64min));
1341
1342 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1343
1344 checks = IsCheck();
1345 checks.isDouble_ = true;
1346 checks.isNumeric_ = true;
1347 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1348
1349 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1350 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1351 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1352
1353 JSONTEST_ASSERT_EQUAL(-9223372036854775808.0, val.asDouble());
1354 JSONTEST_ASSERT_EQUAL(-9223372036854775808.0, val.asFloat());
1355 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1356 JSONTEST_ASSERT_STRING_EQUAL(
1357 "-9.2233720368547758e+18",
1358 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1359
1360 // 10^19
1361 const auto ten_to_19 = static_cast<Json::UInt64>(1e19);
1362 val = Json::Value(Json::UInt64(ten_to_19));
1363
1364 JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type());
1365
1366 checks = IsCheck();
1367 checks.isUInt64_ = true;
1368 checks.isIntegral_ = true;
1369 checks.isDouble_ = true;
1370 checks.isNumeric_ = true;
1371 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1372
1373 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1374 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1375 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1376
1377 JSONTEST_ASSERT_EQUAL(ten_to_19, val.asUInt64());
1378 JSONTEST_ASSERT_EQUAL(ten_to_19, val.asLargestUInt());
1379 JSONTEST_ASSERT_EQUAL(uint64ToDouble(ten_to_19), val.asDouble());
1380 JSONTEST_ASSERT_EQUAL(float(uint64ToDouble(ten_to_19)), val.asFloat());
1381 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1382 JSONTEST_ASSERT_STRING_EQUAL("10000000000000000000", val.asString());
1383
1384 // 10^19 (double constructor). Note that 10^19 is not exactly representable
1385 // as a double.
1386 val = Json::Value(uint64ToDouble(ten_to_19));
1387
1388 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1389
1390 checks = IsCheck();
1391 checks.isUInt64_ = true;
1392 checks.isIntegral_ = true;
1393 checks.isDouble_ = true;
1394 checks.isNumeric_ = true;
1395 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1396
1397 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1398 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1399 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1400
1401 JSONTEST_ASSERT_EQUAL(1e19, val.asDouble());
1402 JSONTEST_ASSERT_EQUAL(1e19, val.asFloat());
1403 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1404 JSONTEST_ASSERT_STRING_EQUAL(
1405 "1e+19",
1406 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1407
1408 // uint64 max
1409 val = Json::Value(Json::UInt64(kuint64max));
1410
1411 JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type());
1412
1413 checks = IsCheck();
1414 checks.isUInt64_ = true;
1415 checks.isIntegral_ = true;
1416 checks.isDouble_ = true;
1417 checks.isNumeric_ = true;
1418 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1419
1420 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1421 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1422 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1423
1424 JSONTEST_ASSERT_EQUAL(kuint64max, val.asUInt64());
1425 JSONTEST_ASSERT_EQUAL(kuint64max, val.asLargestUInt());
1426 JSONTEST_ASSERT_EQUAL(uint64ToDouble(kuint64max), val.asDouble());
1427 JSONTEST_ASSERT_EQUAL(float(uint64ToDouble(kuint64max)), val.asFloat());
1428 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1429 JSONTEST_ASSERT_STRING_EQUAL("18446744073709551615", val.asString());
1430
1431 // uint64 max (floating point constructor). Note that kuint64max is not
1432 // exactly representable as a double, and will be rounded up to be higher.
1433 val = Json::Value(uint64ToDouble(kuint64max));
1434
1435 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1436
1437 checks = IsCheck();
1438 checks.isDouble_ = true;
1439 checks.isNumeric_ = true;
1440 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1441
1442 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1443 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1444 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1445
1446 JSONTEST_ASSERT_EQUAL(18446744073709551616.0, val.asDouble());
1447 JSONTEST_ASSERT_EQUAL(18446744073709551616.0, val.asFloat());
1448 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1449 JSONTEST_ASSERT_STRING_EQUAL(
1450 "1.8446744073709552e+19",
1451 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1452 #endif
1453 }
1454
1455 JSONTEST_FIXTURE_LOCAL(ValueTest, nonIntegers) {
1456 IsCheck checks;
1457 Json::Value val;
1458
1459 // Small positive number
1460 val = Json::Value(1.5);
1461
1462 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1463
1464 checks = IsCheck();
1465 checks.isDouble_ = true;
1466 checks.isNumeric_ = true;
1467 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1468
1469 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
1470 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
1471 JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue));
1472 JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue));
1473 JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue));
1474 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1475 JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue));
1476 JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue));
1477
1478 JSONTEST_ASSERT_EQUAL(1.5, val.asDouble());
1479 JSONTEST_ASSERT_EQUAL(1.5, val.asFloat());
1480 JSONTEST_ASSERT_EQUAL(1, val.asInt());
1481 JSONTEST_ASSERT_EQUAL(1, val.asLargestInt());
1482 JSONTEST_ASSERT_EQUAL(1, val.asUInt());
1483 JSONTEST_ASSERT_EQUAL(1, val.asLargestUInt());
1484 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1485 JSONTEST_ASSERT_EQUAL("1.5", val.asString());
1486
1487 // Small negative number
1488 val = Json::Value(-1.5);
1489
1490 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1491
1492 checks = IsCheck();
1493 checks.isDouble_ = true;
1494 checks.isNumeric_ = true;
1495 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1496
1497 JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue));
1498 JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue));
1499 JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue));
1500 JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue));
1501 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1502 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1503 JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue));
1504 JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue));
1505
1506 JSONTEST_ASSERT_EQUAL(-1.5, val.asDouble());
1507 JSONTEST_ASSERT_EQUAL(-1.5, val.asFloat());
1508 JSONTEST_ASSERT_EQUAL(-1, val.asInt());
1509 JSONTEST_ASSERT_EQUAL(-1, val.asLargestInt());
1510 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1511 JSONTEST_ASSERT_EQUAL("-1.5", val.asString());
1512
1513 // A bit over int32 max
1514 val = Json::Value(kint32max + 0.5);
1515
1516 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1517
1518 checks = IsCheck();
1519 checks.isDouble_ = true;
1520 checks.isNumeric_ = true;
1521 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1522
1523 JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue));
1524 JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue));
1525 JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue));
1526 JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue));
1527 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1528 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1529 JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue));
1530 JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue));
1531
1532 JSONTEST_ASSERT_EQUAL(2147483647.5, val.asDouble());
1533 JSONTEST_ASSERT_EQUAL(float(2147483647.5), val.asFloat());
1534 JSONTEST_ASSERT_EQUAL(2147483647U, val.asUInt());
1535 #ifdef JSON_HAS_INT64
1536 JSONTEST_ASSERT_EQUAL(2147483647L, val.asLargestInt());
1537 JSONTEST_ASSERT_EQUAL(2147483647U, val.asLargestUInt());
1538 #endif
1539 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1540 JSONTEST_ASSERT_EQUAL(
1541 "2147483647.5",
1542 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1543
1544 // A bit under int32 min
1545 val = Json::Value(kint32min - 0.5);
1546
1547 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1548
1549 checks = IsCheck();
1550 checks.isDouble_ = true;
1551 checks.isNumeric_ = true;
1552 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1553
1554 JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue));
1555 JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue));
1556 JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue));
1557 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1558 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1559 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1560 JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue));
1561 JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue));
1562
1563 JSONTEST_ASSERT_EQUAL(-2147483648.5, val.asDouble());
1564 JSONTEST_ASSERT_EQUAL(float(-2147483648.5), val.asFloat());
1565 #ifdef JSON_HAS_INT64
1566 JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 31), val.asLargestInt());
1567 #endif
1568 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1569 JSONTEST_ASSERT_EQUAL(
1570 "-2147483648.5",
1571 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1572
1573 // A bit over uint32 max
1574 val = Json::Value(kuint32max + 0.5);
1575
1576 JSONTEST_ASSERT_EQUAL(Json::realValue, val.type());
1577
1578 checks = IsCheck();
1579 checks.isDouble_ = true;
1580 checks.isNumeric_ = true;
1581 JSONTEST_ASSERT_PRED(checkIs(val, checks));
1582
1583 JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue));
1584 JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue));
1585 JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue));
1586 JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue));
1587 JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue));
1588 JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue));
1589 JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue));
1590 JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue));
1591
1592 JSONTEST_ASSERT_EQUAL(4294967295.5, val.asDouble());
1593 JSONTEST_ASSERT_EQUAL(float(4294967295.5), val.asFloat());
1594 #ifdef JSON_HAS_INT64
1595 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 32) - 1, val.asLargestInt());
1596 JSONTEST_ASSERT_EQUAL((Json::UInt64(1) << 32) - Json::UInt64(1),
1597 val.asLargestUInt());
1598 #endif
1599 JSONTEST_ASSERT_EQUAL(true, val.asBool());
1600 JSONTEST_ASSERT_EQUAL(
1601 "4294967295.5",
1602 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1603
1604 val = Json::Value(1.2345678901234);
1605 JSONTEST_ASSERT_STRING_EQUAL(
1606 "1.2345678901234001",
1607 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1608
1609 // A 16-digit floating point number.
1610 val = Json::Value(2199023255552000.0f);
1611 JSONTEST_ASSERT_EQUAL(float(2199023255552000.0f), val.asFloat());
1612 JSONTEST_ASSERT_STRING_EQUAL(
1613 "2199023255552000.0",
1614 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1615
1616 // A very large floating point number.
1617 val = Json::Value(3.402823466385289e38);
1618 JSONTEST_ASSERT_EQUAL(float(3.402823466385289e38), val.asFloat());
1619 JSONTEST_ASSERT_STRING_EQUAL(
1620 "3.402823466385289e+38",
1621 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1622
1623 // An even larger floating point number.
1624 val = Json::Value(1.2345678e300);
1625 JSONTEST_ASSERT_EQUAL(double(1.2345678e300), val.asDouble());
1626 JSONTEST_ASSERT_STRING_EQUAL(
1627 "1.2345678e+300",
1628 normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString())));
1629 }
1630
1631 void ValueTest::checkConstMemberCount(const Json::Value& value,
1632 unsigned int expectedCount) {
1633 unsigned int count = 0;
1634 Json::Value::const_iterator itEnd = value.end();
1635 for (Json::Value::const_iterator it = value.begin(); it != itEnd; ++it) {
1636 ++count;
1637 }
1638 JSONTEST_ASSERT_EQUAL(expectedCount, count) << "Json::Value::const_iterator";
1639 }
1640
1641 void ValueTest::checkMemberCount(Json::Value& value,
1642 unsigned int expectedCount) {
1643 JSONTEST_ASSERT_EQUAL(expectedCount, value.size());
1644
1645 unsigned int count = 0;
1646 Json::Value::iterator itEnd = value.end();
1647 for (Json::Value::iterator it = value.begin(); it != itEnd; ++it) {
1648 ++count;
1649 }
1650 JSONTEST_ASSERT_EQUAL(expectedCount, count) << "Json::Value::iterator";
1651
1652 JSONTEST_ASSERT_PRED(checkConstMemberCount(value, expectedCount));
1653 }
1654
1655 ValueTest::IsCheck::IsCheck() = default;
1656
1657 void ValueTest::checkIs(const Json::Value& value, const IsCheck& check) {
1658 JSONTEST_ASSERT_EQUAL(check.isObject_, value.isObject());
1659 JSONTEST_ASSERT_EQUAL(check.isArray_, value.isArray());
1660 JSONTEST_ASSERT_EQUAL(check.isBool_, value.isBool());
1661 JSONTEST_ASSERT_EQUAL(check.isDouble_, value.isDouble());
1662 JSONTEST_ASSERT_EQUAL(check.isInt_, value.isInt());
1663 JSONTEST_ASSERT_EQUAL(check.isUInt_, value.isUInt());
1664 JSONTEST_ASSERT_EQUAL(check.isIntegral_, value.isIntegral());
1665 JSONTEST_ASSERT_EQUAL(check.isNumeric_, value.isNumeric());
1666 JSONTEST_ASSERT_EQUAL(check.isString_, value.isString());
1667 JSONTEST_ASSERT_EQUAL(check.isNull_, value.isNull());
1668
1669 #ifdef JSON_HAS_INT64
1670 JSONTEST_ASSERT_EQUAL(check.isInt64_, value.isInt64());
1671 JSONTEST_ASSERT_EQUAL(check.isUInt64_, value.isUInt64());
1672 #else
1673 JSONTEST_ASSERT_EQUAL(false, value.isInt64());
1674 JSONTEST_ASSERT_EQUAL(false, value.isUInt64());
1675 #endif
1676 }
1677
1678 JSONTEST_FIXTURE_LOCAL(ValueTest, compareNull) {
1679 JSONTEST_ASSERT_PRED(checkIsEqual(Json::Value(), Json::Value()));
1680 JSONTEST_ASSERT_PRED(
1681 checkIsEqual(Json::Value::nullSingleton(), Json::Value()));
1682 JSONTEST_ASSERT_PRED(
1683 checkIsEqual(Json::Value::nullSingleton(), Json::Value::nullSingleton()));
1684 }
1685
1686 JSONTEST_FIXTURE_LOCAL(ValueTest, compareInt) {
1687 JSONTEST_ASSERT_PRED(checkIsLess(0, 10));
1688 JSONTEST_ASSERT_PRED(checkIsEqual(10, 10));
1689 JSONTEST_ASSERT_PRED(checkIsEqual(-10, -10));
1690 JSONTEST_ASSERT_PRED(checkIsLess(-10, 0));
1691 }
1692
1693 JSONTEST_FIXTURE_LOCAL(ValueTest, compareUInt) {
1694 JSONTEST_ASSERT_PRED(checkIsLess(0u, 10u));
1695 JSONTEST_ASSERT_PRED(checkIsLess(0u, Json::Value::maxUInt));
1696 JSONTEST_ASSERT_PRED(checkIsEqual(10u, 10u));
1697 }
1698
1699 JSONTEST_FIXTURE_LOCAL(ValueTest, compareDouble) {
1700 JSONTEST_ASSERT_PRED(checkIsLess(0.0, 10.0));
1701 JSONTEST_ASSERT_PRED(checkIsEqual(10.0, 10.0));
1702 JSONTEST_ASSERT_PRED(checkIsEqual(-10.0, -10.0));
1703 JSONTEST_ASSERT_PRED(checkIsLess(-10.0, 0.0));
1704 }
1705
1706 JSONTEST_FIXTURE_LOCAL(ValueTest, compareString) {
1707 JSONTEST_ASSERT_PRED(checkIsLess("", " "));
1708 JSONTEST_ASSERT_PRED(checkIsLess("", "a"));
1709 JSONTEST_ASSERT_PRED(checkIsLess("abcd", "zyui"));
1710 JSONTEST_ASSERT_PRED(checkIsLess("abc", "abcd"));
1711 JSONTEST_ASSERT_PRED(checkIsEqual("abcd", "abcd"));
1712 JSONTEST_ASSERT_PRED(checkIsEqual(" ", " "));
1713 JSONTEST_ASSERT_PRED(checkIsLess("ABCD", "abcd"));
1714 JSONTEST_ASSERT_PRED(checkIsEqual("ABCD", "ABCD"));
1715 }
1716
1717 JSONTEST_FIXTURE_LOCAL(ValueTest, compareBoolean) {
1718 JSONTEST_ASSERT_PRED(checkIsLess(false, true));
1719 JSONTEST_ASSERT_PRED(checkIsEqual(false, false));
1720 JSONTEST_ASSERT_PRED(checkIsEqual(true, true));
1721 }
1722
1723 JSONTEST_FIXTURE_LOCAL(ValueTest, compareArray) {
1724 // array compare size then content
1725 Json::Value emptyArray(Json::arrayValue);
1726 Json::Value l1aArray;
1727 l1aArray.append(0);
1728 Json::Value l1bArray;
1729 l1bArray.append(10);
1730 Json::Value l2aArray;
1731 l2aArray.append(0);
1732 l2aArray.append(0);
1733 Json::Value l2bArray;
1734 l2bArray.append(0);
1735 l2bArray.append(10);
1736 JSONTEST_ASSERT_PRED(checkIsLess(emptyArray, l1aArray));
1737 JSONTEST_ASSERT_PRED(checkIsLess(emptyArray, l2aArray));
1738 JSONTEST_ASSERT_PRED(checkIsLess(l1aArray, l1bArray));
1739 JSONTEST_ASSERT_PRED(checkIsLess(l1bArray, l2aArray));
1740 JSONTEST_ASSERT_PRED(checkIsLess(l2aArray, l2bArray));
1741 JSONTEST_ASSERT_PRED(checkIsEqual(emptyArray, Json::Value(emptyArray)));
1742 JSONTEST_ASSERT_PRED(checkIsEqual(l1aArray, Json::Value(l1aArray)));
1743 JSONTEST_ASSERT_PRED(checkIsEqual(l1bArray, Json::Value(l1bArray)));
1744 JSONTEST_ASSERT_PRED(checkIsEqual(l2aArray, Json::Value(l2aArray)));
1745 JSONTEST_ASSERT_PRED(checkIsEqual(l2bArray, Json::Value(l2bArray)));
1746 }
1747
1748 JSONTEST_FIXTURE_LOCAL(ValueTest, compareObject) {
1749 // object compare size then content
1750 Json::Value emptyObject(Json::objectValue);
1751 Json::Value l1aObject;
1752 l1aObject["key1"] = 0;
1753 Json::Value l1bObject;
1754 l1bObject["key1"] = 10;
1755 Json::Value l2aObject;
1756 l2aObject["key1"] = 0;
1757 l2aObject["key2"] = 0;
1758 Json::Value l2bObject;
1759 l2bObject["key1"] = 10;
1760 l2bObject["key2"] = 0;
1761 JSONTEST_ASSERT_PRED(checkIsLess(emptyObject, l1aObject));
1762 JSONTEST_ASSERT_PRED(checkIsLess(l1aObject, l1bObject));
1763 JSONTEST_ASSERT_PRED(checkIsLess(l1bObject, l2aObject));
1764 JSONTEST_ASSERT_PRED(checkIsLess(l2aObject, l2bObject));
1765 JSONTEST_ASSERT_PRED(checkIsEqual(emptyObject, Json::Value(emptyObject)));
1766 JSONTEST_ASSERT_PRED(checkIsEqual(l1aObject, Json::Value(l1aObject)));
1767 JSONTEST_ASSERT_PRED(checkIsEqual(l1bObject, Json::Value(l1bObject)));
1768 JSONTEST_ASSERT_PRED(checkIsEqual(l2aObject, Json::Value(l2aObject)));
1769 JSONTEST_ASSERT_PRED(checkIsEqual(l2bObject, Json::Value(l2bObject)));
1770 {
1771 Json::Value aObject;
1772 aObject["a"] = 10;
1773 Json::Value bObject;
1774 bObject["b"] = 0;
1775 Json::Value cObject;
1776 cObject["c"] = 20;
1777 cObject["f"] = 15;
1778 Json::Value dObject;
1779 dObject["d"] = -2;
1780 dObject["e"] = 10;
1781 JSONTEST_ASSERT_PRED(checkIsLess(aObject, bObject));
1782 JSONTEST_ASSERT_PRED(checkIsLess(bObject, cObject));
1783 JSONTEST_ASSERT_PRED(checkIsLess(cObject, dObject));
1784 JSONTEST_ASSERT_PRED(checkIsEqual(aObject, Json::Value(aObject)));
1785 JSONTEST_ASSERT_PRED(checkIsEqual(bObject, Json::Value(bObject)));
1786 JSONTEST_ASSERT_PRED(checkIsEqual(cObject, Json::Value(cObject)));
1787 JSONTEST_ASSERT_PRED(checkIsEqual(dObject, Json::Value(dObject)));
1788 }
1789 }
1790
1791 JSONTEST_FIXTURE_LOCAL(ValueTest, compareType) {
1792 // object of different type are ordered according to their type
1793 JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(), Json::Value(1)));
1794 JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(1), Json::Value(1u)));
1795 JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(1u), Json::Value(1.0)));
1796 JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(1.0), Json::Value("a")));
1797 JSONTEST_ASSERT_PRED(checkIsLess(Json::Value("a"), Json::Value(true)));
1798 JSONTEST_ASSERT_PRED(
1799 checkIsLess(Json::Value(true), Json::Value(Json::arrayValue)));
1800 JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(Json::arrayValue),
1801 Json::Value(Json::objectValue)));
1802 }
1803
1804 JSONTEST_FIXTURE_LOCAL(ValueTest, CopyObject) {
1805 Json::Value arrayVal;
1806 arrayVal.append("val1");
1807 arrayVal.append("val2");
1808 arrayVal.append("val3");
1809 Json::Value stringVal("string value");
1810 Json::Value copy1, copy2;
1811 {
1812 Json::Value arrayCopy, stringCopy;
1813 arrayCopy.copy(arrayVal);
1814 stringCopy.copy(stringVal);
1815 JSONTEST_ASSERT_PRED(checkIsEqual(arrayCopy, arrayVal));
1816 JSONTEST_ASSERT_PRED(checkIsEqual(stringCopy, stringVal));
1817 arrayCopy.append("val4");
1818 JSONTEST_ASSERT(arrayCopy.size() == 4);
1819 arrayVal.append("new4");
1820 arrayVal.append("new5");
1821 JSONTEST_ASSERT(arrayVal.size() == 5);
1822 JSONTEST_ASSERT(!(arrayCopy == arrayVal));
1823 stringCopy = "another string";
1824 JSONTEST_ASSERT(!(stringCopy == stringVal));
1825 copy1.copy(arrayCopy);
1826 copy2.copy(stringCopy);
1827 }
1828 JSONTEST_ASSERT(arrayVal.size() == 5);
1829 JSONTEST_ASSERT(stringVal == "string value");
1830 JSONTEST_ASSERT(copy1.size() == 4);
1831 JSONTEST_ASSERT(copy2 == "another string");
1832 copy1.copy(stringVal);
1833 JSONTEST_ASSERT(copy1 == "string value");
1834 copy2.copy(arrayVal);
1835 JSONTEST_ASSERT(copy2.size() == 5);
1836 {
1837 Json::Value srcObject, objectCopy, otherObject;
1838 srcObject["key0"] = 10;
1839 objectCopy.copy(srcObject);
1840 JSONTEST_ASSERT(srcObject["key0"] == 10);
1841 JSONTEST_ASSERT(objectCopy["key0"] == 10);
1842 JSONTEST_ASSERT(srcObject.getMemberNames().size() == 1);
1843 JSONTEST_ASSERT(objectCopy.getMemberNames().size() == 1);
1844 otherObject["key1"] = 15;
1845 otherObject["key2"] = 16;
1846 JSONTEST_ASSERT(otherObject.getMemberNames().size() == 2);
1847 objectCopy.copy(otherObject);
1848 JSONTEST_ASSERT(objectCopy["key1"] == 15);
1849 JSONTEST_ASSERT(objectCopy["key2"] == 16);
1850 JSONTEST_ASSERT(objectCopy.getMemberNames().size() == 2);
1851 otherObject["key1"] = 20;
1852 JSONTEST_ASSERT(objectCopy["key1"] == 15);
1853 }
1854 }
1855
1856 void ValueTest::checkIsLess(const Json::Value& x, const Json::Value& y) {
1857 JSONTEST_ASSERT(x < y);
1858 JSONTEST_ASSERT(y > x);
1859 JSONTEST_ASSERT(x <= y);
1860 JSONTEST_ASSERT(y >= x);
1861 JSONTEST_ASSERT(!(x == y));
1862 JSONTEST_ASSERT(!(y == x));
1863 JSONTEST_ASSERT(!(x >= y));
1864 JSONTEST_ASSERT(!(y <= x));
1865 JSONTEST_ASSERT(!(x > y));
1866 JSONTEST_ASSERT(!(y < x));
1867 JSONTEST_ASSERT(x.compare(y) < 0);
1868 JSONTEST_ASSERT(y.compare(x) >= 0);
1869 }
1870
1871 void ValueTest::checkIsEqual(const Json::Value& x, const Json::Value& y) {
1872 JSONTEST_ASSERT(x == y);
1873 JSONTEST_ASSERT(y == x);
1874 JSONTEST_ASSERT(x <= y);
1875 JSONTEST_ASSERT(y <= x);
1876 JSONTEST_ASSERT(x >= y);
1877 JSONTEST_ASSERT(y >= x);
1878 JSONTEST_ASSERT(!(x < y));
1879 JSONTEST_ASSERT(!(y < x));
1880 JSONTEST_ASSERT(!(x > y));
1881 JSONTEST_ASSERT(!(y > x));
1882 JSONTEST_ASSERT(x.compare(y) == 0);
1883 JSONTEST_ASSERT(y.compare(x) == 0);
1884 }
1885
1886 JSONTEST_FIXTURE_LOCAL(ValueTest, typeChecksThrowExceptions) {
1887 #if JSON_USE_EXCEPTION
1888
1889 Json::Value intVal(1);
1890 Json::Value strVal("Test");
1891 Json::Value objVal(Json::objectValue);
1892 Json::Value arrVal(Json::arrayValue);
1893
1894 JSONTEST_ASSERT_THROWS(intVal["test"]);
1895 JSONTEST_ASSERT_THROWS(strVal["test"]);
1896 JSONTEST_ASSERT_THROWS(arrVal["test"]);
1897
1898 JSONTEST_ASSERT_THROWS(intVal.removeMember("test"));
1899 JSONTEST_ASSERT_THROWS(strVal.removeMember("test"));
1900 JSONTEST_ASSERT_THROWS(arrVal.removeMember("test"));
1901
1902 JSONTEST_ASSERT_THROWS(intVal.getMemberNames());
1903 JSONTEST_ASSERT_THROWS(strVal.getMemberNames());
1904 JSONTEST_ASSERT_THROWS(arrVal.getMemberNames());
1905
1906 JSONTEST_ASSERT_THROWS(intVal[0]);
1907 JSONTEST_ASSERT_THROWS(objVal[0]);
1908 JSONTEST_ASSERT_THROWS(strVal[0]);
1909
1910 JSONTEST_ASSERT_THROWS(intVal.clear());
1911
1912 JSONTEST_ASSERT_THROWS(intVal.resize(1));
1913 JSONTEST_ASSERT_THROWS(strVal.resize(1));
1914 JSONTEST_ASSERT_THROWS(objVal.resize(1));
1915
1916 JSONTEST_ASSERT_THROWS(intVal.asCString());
1917
1918 JSONTEST_ASSERT_THROWS(objVal.asString());
1919 JSONTEST_ASSERT_THROWS(arrVal.asString());
1920
1921 JSONTEST_ASSERT_THROWS(strVal.asInt());
1922 JSONTEST_ASSERT_THROWS(objVal.asInt());
1923 JSONTEST_ASSERT_THROWS(arrVal.asInt());
1924
1925 JSONTEST_ASSERT_THROWS(strVal.asUInt());
1926 JSONTEST_ASSERT_THROWS(objVal.asUInt());
1927 JSONTEST_ASSERT_THROWS(arrVal.asUInt());
1928
1929 JSONTEST_ASSERT_THROWS(strVal.asInt64());
1930 JSONTEST_ASSERT_THROWS(objVal.asInt64());
1931 JSONTEST_ASSERT_THROWS(arrVal.asInt64());
1932
1933 JSONTEST_ASSERT_THROWS(strVal.asUInt64());
1934 JSONTEST_ASSERT_THROWS(objVal.asUInt64());
1935 JSONTEST_ASSERT_THROWS(arrVal.asUInt64());
1936
1937 JSONTEST_ASSERT_THROWS(strVal.asDouble());
1938 JSONTEST_ASSERT_THROWS(objVal.asDouble());
1939 JSONTEST_ASSERT_THROWS(arrVal.asDouble());
1940
1941 JSONTEST_ASSERT_THROWS(strVal.asFloat());
1942 JSONTEST_ASSERT_THROWS(objVal.asFloat());
1943 JSONTEST_ASSERT_THROWS(arrVal.asFloat());
1944
1945 JSONTEST_ASSERT_THROWS(strVal.asBool());
1946 JSONTEST_ASSERT_THROWS(objVal.asBool());
1947 JSONTEST_ASSERT_THROWS(arrVal.asBool());
1948
1949 #endif // JSON_USE_EXCEPTION
1950 }
1951
1952 JSONTEST_FIXTURE_LOCAL(ValueTest, offsetAccessors) {
1953 Json::Value x;
1954 JSONTEST_ASSERT(x.getOffsetStart() == 0);
1955 JSONTEST_ASSERT(x.getOffsetLimit() == 0);
1956 x.setOffsetStart(10);
1957 x.setOffsetLimit(20);
1958 JSONTEST_ASSERT(x.getOffsetStart() == 10);
1959 JSONTEST_ASSERT(x.getOffsetLimit() == 20);
1960 Json::Value y(x);
1961 JSONTEST_ASSERT(y.getOffsetStart() == 10);
1962 JSONTEST_ASSERT(y.getOffsetLimit() == 20);
1963 Json::Value z;
1964 z.swap(y);
1965 JSONTEST_ASSERT(z.getOffsetStart() == 10);
1966 JSONTEST_ASSERT(z.getOffsetLimit() == 20);
1967 JSONTEST_ASSERT(y.getOffsetStart() == 0);
1968 JSONTEST_ASSERT(y.getOffsetLimit() == 0);
1969 }
1970
1971 JSONTEST_FIXTURE_LOCAL(ValueTest, StaticString) {
1972 char mutant[] = "hello";
1973 Json::StaticString ss(mutant);
1974 Json::String regular(mutant);
1975 mutant[1] = 'a';
1976 JSONTEST_ASSERT_STRING_EQUAL("hallo", ss.c_str());
1977 JSONTEST_ASSERT_STRING_EQUAL("hello", regular.c_str());
1978 {
1979 Json::Value root;
1980 root["top"] = ss;
1981 JSONTEST_ASSERT_STRING_EQUAL("hallo", root["top"].asString());
1982 mutant[1] = 'u';
1983 JSONTEST_ASSERT_STRING_EQUAL("hullo", root["top"].asString());
1984 }
1985 {
1986 Json::Value root;
1987 root["top"] = regular;
1988 JSONTEST_ASSERT_STRING_EQUAL("hello", root["top"].asString());
1989 mutant[1] = 'u';
1990 JSONTEST_ASSERT_STRING_EQUAL("hello", root["top"].asString());
1991 }
1992 }
1993
1994 JSONTEST_FIXTURE_LOCAL(ValueTest, WideString) {
1995 // https://github.com/open-source-parsers/jsoncpp/issues/756
1996 const std::string uni = u8"\u5f0f\uff0c\u8fdb"; // "式,进"
1997 std::string styled;
1998 {
1999 Json::Value v;
2000 v["abc"] = uni;
2001 styled = v.toStyledString();
2002 }
2003 Json::Value root;
2004 {
2005 JSONCPP_STRING errs;
2006 std::istringstream iss(styled);
2007 bool ok = parseFromStream(Json::CharReaderBuilder(), iss, &root, &errs);
2008 JSONTEST_ASSERT(ok);
2009 if (!ok) {
2010 std::cerr << "errs: " << errs << std::endl;
2011 }
2012 }
2013 JSONTEST_ASSERT_STRING_EQUAL(root["abc"].asString(), uni);
2014 }
2015
2016 JSONTEST_FIXTURE_LOCAL(ValueTest, CommentBefore) {
2017 Json::Value val; // fill val
2018 val.setComment(Json::String("// this comment should appear before"),
2019 Json::commentBefore);
2020 Json::StreamWriterBuilder wbuilder;
2021 wbuilder.settings_["commentStyle"] = "All";
2022 {
2023 char const expected[] = "// this comment should appear before\nnull";
2024 Json::String result = Json::writeString(wbuilder, val);
2025 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2026 Json::String res2 = val.toStyledString();
2027 Json::String exp2 = "\n";
2028 exp2 += expected;
2029 exp2 += "\n";
2030 JSONTEST_ASSERT_STRING_EQUAL(exp2, res2);
2031 }
2032 Json::Value other = "hello";
2033 val.swapPayload(other);
2034 {
2035 char const expected[] = "// this comment should appear before\n\"hello\"";
2036 Json::String result = Json::writeString(wbuilder, val);
2037 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2038 Json::String res2 = val.toStyledString();
2039 Json::String exp2 = "\n";
2040 exp2 += expected;
2041 exp2 += "\n";
2042 JSONTEST_ASSERT_STRING_EQUAL(exp2, res2);
2043 JSONTEST_ASSERT_STRING_EQUAL("null\n", other.toStyledString());
2044 }
2045 val = "hello";
2046 // val.setComment("// this comment should appear before",
2047 // Json::CommentPlacement::commentBefore); Assignment over-writes comments.
2048 {
2049 char const expected[] = "\"hello\"";
2050 Json::String result = Json::writeString(wbuilder, val);
2051 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2052 Json::String res2 = val.toStyledString();
2053 Json::String exp2;
2054 exp2 += expected;
2055 exp2 += "\n";
2056 JSONTEST_ASSERT_STRING_EQUAL(exp2, res2);
2057 }
2058 }
2059
2060 JSONTEST_FIXTURE_LOCAL(ValueTest, zeroes) {
2061 char const cstr[] = "h\0i";
2062 Json::String binary(cstr, sizeof(cstr)); // include trailing 0
2063 JSONTEST_ASSERT_EQUAL(4U, binary.length());
2064 Json::StreamWriterBuilder b;
2065 {
2066 Json::Value root;
2067 root = binary;
2068 JSONTEST_ASSERT_STRING_EQUAL(binary, root.asString());
2069 }
2070 {
2071 char const top[] = "top";
2072 Json::Value root;
2073 root[top] = binary;
2074 JSONTEST_ASSERT_STRING_EQUAL(binary, root[top].asString());
2075 Json::Value removed;
2076 bool did;
2077 did = root.removeMember(top, top + sizeof(top) - 1U, &removed);
2078 JSONTEST_ASSERT(did);
2079 JSONTEST_ASSERT_STRING_EQUAL(binary, removed.asString());
2080 did = root.removeMember(top, top + sizeof(top) - 1U, &removed);
2081 JSONTEST_ASSERT(!did);
2082 JSONTEST_ASSERT_STRING_EQUAL(binary, removed.asString()); // still
2083 }
2084 }
2085
2086 JSONTEST_FIXTURE_LOCAL(ValueTest, zeroesInKeys) {
2087 char const cstr[] = "h\0i";
2088 Json::String binary(cstr, sizeof(cstr)); // include trailing 0
2089 JSONTEST_ASSERT_EQUAL(4U, binary.length());
2090 {
2091 Json::Value root;
2092 root[binary] = "there";
2093 JSONTEST_ASSERT_STRING_EQUAL("there", root[binary].asString());
2094 JSONTEST_ASSERT(!root.isMember("h"));
2095 JSONTEST_ASSERT(root.isMember(binary));
2096 JSONTEST_ASSERT_STRING_EQUAL(
2097 "there", root.get(binary, Json::Value::nullSingleton()).asString());
2098 Json::Value removed;
2099 bool did;
2100 did = root.removeMember(binary.data(), binary.data() + binary.length(),
2101 &removed);
2102 JSONTEST_ASSERT(did);
2103 JSONTEST_ASSERT_STRING_EQUAL("there", removed.asString());
2104 did = root.removeMember(binary.data(), binary.data() + binary.length(),
2105 &removed);
2106 JSONTEST_ASSERT(!did);
2107 JSONTEST_ASSERT_STRING_EQUAL("there", removed.asString()); // still
2108 JSONTEST_ASSERT(!root.isMember(binary));
2109 JSONTEST_ASSERT_STRING_EQUAL(
2110 "", root.get(binary, Json::Value::nullSingleton()).asString());
2111 }
2112 }
2113
2114 JSONTEST_FIXTURE_LOCAL(ValueTest, specialFloats) {
2115 Json::StreamWriterBuilder b;
2116 b.settings_["useSpecialFloats"] = true;
2117
2118 Json::Value v = std::numeric_limits<double>::quiet_NaN();
2119 Json::String expected = "NaN";
2120 Json::String result = Json::writeString(b, v);
2121 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2122
2123 v = std::numeric_limits<double>::infinity();
2124 expected = "Infinity";
2125 result = Json::writeString(b, v);
2126 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2127
2128 v = -std::numeric_limits<double>::infinity();
2129 expected = "-Infinity";
2130 result = Json::writeString(b, v);
2131 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2132 }
2133
2134 JSONTEST_FIXTURE_LOCAL(ValueTest, precision) {
2135 Json::StreamWriterBuilder b;
2136 b.settings_["precision"] = 5;
2137
2138 Json::Value v = 100.0 / 3;
2139 Json::String expected = "33.333";
2140 Json::String result = Json::writeString(b, v);
2141 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2142
2143 v = 0.25000000;
2144 expected = "0.25";
2145 result = Json::writeString(b, v);
2146 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2147
2148 v = 0.2563456;
2149 expected = "0.25635";
2150 result = Json::writeString(b, v);
2151 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2152
2153 b.settings_["precision"] = 1;
2154 expected = "0.3";
2155 result = Json::writeString(b, v);
2156 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2157
2158 b.settings_["precision"] = 17;
2159 v = 1234857476305.256345694873740545068;
2160 expected = "1234857476305.2563";
2161 result = Json::writeString(b, v);
2162 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2163
2164 b.settings_["precision"] = 24;
2165 v = 0.256345694873740545068;
2166 expected = "0.25634569487374054";
2167 result = Json::writeString(b, v);
2168 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2169
2170 b.settings_["precision"] = 5;
2171 b.settings_["precisionType"] = "decimal";
2172 v = 0.256345694873740545068;
2173 expected = "0.25635";
2174 result = Json::writeString(b, v);
2175 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2176
2177 b.settings_["precision"] = 1;
2178 b.settings_["precisionType"] = "decimal";
2179 v = 0.256345694873740545068;
2180 expected = "0.3";
2181 result = Json::writeString(b, v);
2182 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2183
2184 b.settings_["precision"] = 0;
2185 b.settings_["precisionType"] = "decimal";
2186 v = 123.56345694873740545068;
2187 expected = "124";
2188 result = Json::writeString(b, v);
2189 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2190
2191 b.settings_["precision"] = 1;
2192 b.settings_["precisionType"] = "decimal";
2193 v = 1230.001;
2194 expected = "1230.0";
2195 result = Json::writeString(b, v);
2196 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2197
2198 b.settings_["precision"] = 0;
2199 b.settings_["precisionType"] = "decimal";
2200 v = 1230.001;
2201 expected = "1230";
2202 result = Json::writeString(b, v);
2203 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2204
2205 b.settings_["precision"] = 0;
2206 b.settings_["precisionType"] = "decimal";
2207 v = 1231.5;
2208 expected = "1232";
2209 result = Json::writeString(b, v);
2210 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2211
2212 b.settings_["precision"] = 10;
2213 b.settings_["precisionType"] = "decimal";
2214 v = 0.23300000;
2215 expected = "0.233";
2216 result = Json::writeString(b, v);
2217 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2218 }
2219 JSONTEST_FIXTURE_LOCAL(ValueTest, searchValueByPath) {
2220 Json::Value root, subroot;
2221 root["property1"][0] = 0;
2222 root["property1"][1] = 1;
2223 subroot["object"] = "object";
2224 root["property2"] = subroot;
2225
2226 const Json::Value defaultValue("error");
2227 Json::FastWriter writer;
2228
2229 {
2230 const Json::String expected("{"
2231 "\"property1\":[0,1],"
2232 "\"property2\":{\"object\":\"object\"}"
2233 "}\n");
2234 Json::String outcome = writer.write(root);
2235 JSONTEST_ASSERT_STRING_EQUAL(expected, outcome);
2236
2237 // Array member exists.
2238 const Json::Path path1(".property1.[%]", 1);
2239 Json::Value result = path1.resolve(root);
2240 JSONTEST_ASSERT_EQUAL(Json::Value(1), result);
2241 result = path1.resolve(root, defaultValue);
2242 JSONTEST_ASSERT_EQUAL(Json::Value(1), result);
2243
2244 // Array member does not exist.
2245 const Json::Path path2(".property1.[2]");
2246 result = path2.resolve(root);
2247 JSONTEST_ASSERT_EQUAL(Json::nullValue, result);
2248 result = path2.resolve(root, defaultValue);
2249 JSONTEST_ASSERT_EQUAL(defaultValue, result);
2250
2251 // Access array path form error
2252 const Json::Path path3(".property1.0");
2253 result = path3.resolve(root);
2254 JSONTEST_ASSERT_EQUAL(Json::nullValue, result);
2255 result = path3.resolve(root, defaultValue);
2256 JSONTEST_ASSERT_EQUAL(defaultValue, result);
2257
2258 // Object member exists.
2259 const Json::Path path4(".property2.%", "object");
2260 result = path4.resolve(root);
2261 JSONTEST_ASSERT_EQUAL(Json::Value("object"), result);
2262 result = path4.resolve(root, defaultValue);
2263 JSONTEST_ASSERT_EQUAL(Json::Value("object"), result);
2264
2265 // Object member does not exist.
2266 const Json::Path path5(".property2.hello");
2267 result = path5.resolve(root);
2268 JSONTEST_ASSERT_EQUAL(Json::nullValue, result);
2269 result = path5.resolve(root, defaultValue);
2270 JSONTEST_ASSERT_EQUAL(defaultValue, result);
2271
2272 // Access object path form error
2273 const Json::Path path6(".property2.[0]");
2274 result = path5.resolve(root);
2275 JSONTEST_ASSERT_EQUAL(Json::nullValue, result);
2276 result = path6.resolve(root, defaultValue);
2277 JSONTEST_ASSERT_EQUAL(defaultValue, result);
2278
2279 // resolve will not change the value
2280 outcome = writer.write(root);
2281 JSONTEST_ASSERT_STRING_EQUAL(expected, outcome);
2282 }
2283 {
2284 const Json::String expected("{"
2285 "\"property1\":[0,1,null],"
2286 "\"property2\":{"
2287 "\"hello\":null,"
2288 "\"object\":\"object\"}}\n");
2289 Json::Path path1(".property1.[%]", 2);
2290 Json::Value& value1 = path1.make(root);
2291 JSONTEST_ASSERT_EQUAL(Json::nullValue, value1);
2292
2293 Json::Path path2(".property2.%", "hello");
2294 Json::Value& value2 = path2.make(root);
2295 JSONTEST_ASSERT_EQUAL(Json::nullValue, value2);
2296
2297 // make will change the value
2298 const Json::String outcome = writer.write(root);
2299 JSONTEST_ASSERT_STRING_EQUAL(expected, outcome);
2300 }
2301 }
2302 struct FastWriterTest : JsonTest::TestCase {};
2303
2304 JSONTEST_FIXTURE_LOCAL(FastWriterTest, dropNullPlaceholders) {
2305 Json::FastWriter writer;
2306 Json::Value nullValue;
2307 JSONTEST_ASSERT(writer.write(nullValue) == "null\n");
2308
2309 writer.dropNullPlaceholders();
2310 JSONTEST_ASSERT(writer.write(nullValue) == "\n");
2311 }
2312
2313 JSONTEST_FIXTURE_LOCAL(FastWriterTest, enableYAMLCompatibility) {
2314 Json::FastWriter writer;
2315 Json::Value root;
2316 root["hello"] = "world";
2317
2318 JSONTEST_ASSERT(writer.write(root) == "{\"hello\":\"world\"}\n");
2319
2320 writer.enableYAMLCompatibility();
2321 JSONTEST_ASSERT(writer.write(root) == "{\"hello\": \"world\"}\n");
2322 }
2323
2324 JSONTEST_FIXTURE_LOCAL(FastWriterTest, omitEndingLineFeed) {
2325 Json::FastWriter writer;
2326 Json::Value nullValue;
2327
2328 JSONTEST_ASSERT(writer.write(nullValue) == "null\n");
2329
2330 writer.omitEndingLineFeed();
2331 JSONTEST_ASSERT(writer.write(nullValue) == "null");
2332 }
2333
2334 JSONTEST_FIXTURE_LOCAL(FastWriterTest, writeNumericValue) {
2335 Json::FastWriter writer;
2336 const Json::String expected("{"
2337 "\"emptyValue\":null,"
2338 "\"false\":false,"
2339 "\"null\":\"null\","
2340 "\"number\":-6200000000000000.0,"
2341 "\"real\":1.256,"
2342 "\"uintValue\":17"
2343 "}\n");
2344 Json::Value root;
2345 root["emptyValue"] = Json::nullValue;
2346 root["false"] = false;
2347 root["null"] = "null";
2348 root["number"] = -6.2e+15;
2349 root["real"] = 1.256;
2350 root["uintValue"] = Json::Value(17U);
2351
2352 const Json::String result = writer.write(root);
2353 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2354 }
2355
2356 JSONTEST_FIXTURE_LOCAL(FastWriterTest, writeArrays) {
2357 Json::FastWriter writer;
2358 const Json::String expected("{"
2359 "\"property1\":[\"value1\",\"value2\"],"
2360 "\"property2\":[]"
2361 "}\n");
2362 Json::Value root;
2363 root["property1"][0] = "value1";
2364 root["property1"][1] = "value2";
2365 root["property2"] = Json::arrayValue;
2366
2367 const Json::String result = writer.write(root);
2368 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2369 }
2370
2371 JSONTEST_FIXTURE_LOCAL(FastWriterTest, writeNestedObjects) {
2372 Json::FastWriter writer;
2373 const Json::String expected("{"
2374 "\"object1\":{"
2375 "\"bool\":true,"
2376 "\"nested\":123"
2377 "},"
2378 "\"object2\":{}"
2379 "}\n");
2380 Json::Value root, child;
2381 child["nested"] = 123;
2382 child["bool"] = true;
2383 root["object1"] = child;
2384 root["object2"] = Json::objectValue;
2385
2386 const Json::String result = writer.write(root);
2387 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2388 }
2389
2390 struct StyledWriterTest : JsonTest::TestCase {};
2391
2392 JSONTEST_FIXTURE_LOCAL(StyledWriterTest, writeNumericValue) {
2393 Json::StyledWriter writer;
2394 const Json::String expected("{\n"
2395 " \"emptyValue\" : null,\n"
2396 " \"false\" : false,\n"
2397 " \"null\" : \"null\",\n"
2398 " \"number\" : -6200000000000000.0,\n"
2399 " \"real\" : 1.256,\n"
2400 " \"uintValue\" : 17\n"
2401 "}\n");
2402 Json::Value root;
2403 root["emptyValue"] = Json::nullValue;
2404 root["false"] = false;
2405 root["null"] = "null";
2406 root["number"] = -6.2e+15;
2407 root["real"] = 1.256;
2408 root["uintValue"] = Json::Value(17U);
2409
2410 const Json::String result = writer.write(root);
2411 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2412 }
2413
2414 JSONTEST_FIXTURE_LOCAL(StyledWriterTest, writeArrays) {
2415 Json::StyledWriter writer;
2416 const Json::String expected("{\n"
2417 " \"property1\" : [ \"value1\", \"value2\" ],\n"
2418 " \"property2\" : []\n"
2419 "}\n");
2420 Json::Value root;
2421 root["property1"][0] = "value1";
2422 root["property1"][1] = "value2";
2423 root["property2"] = Json::arrayValue;
2424
2425 const Json::String result = writer.write(root);
2426 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2427 }
2428
2429 JSONTEST_FIXTURE_LOCAL(StyledWriterTest, writeNestedObjects) {
2430 Json::StyledWriter writer;
2431 const Json::String expected("{\n"
2432 " \"object1\" : {\n"
2433 " \"bool\" : true,\n"
2434 " \"nested\" : 123\n"
2435 " },\n"
2436 " \"object2\" : {}\n"
2437 "}\n");
2438 Json::Value root, child;
2439 child["nested"] = 123;
2440 child["bool"] = true;
2441 root["object1"] = child;
2442 root["object2"] = Json::objectValue;
2443
2444 const Json::String result = writer.write(root);
2445 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2446 }
2447
2448 JSONTEST_FIXTURE_LOCAL(StyledWriterTest, multiLineArray) {
2449 Json::StyledWriter writer;
2450 {
2451 // Array member has more than 20 print effect rendering lines
2452 const Json::String expected("[\n "
2453 "0,\n 1,\n 2,\n "
2454 "3,\n 4,\n 5,\n "
2455 "6,\n 7,\n 8,\n "
2456 "9,\n 10,\n 11,\n "
2457 "12,\n 13,\n 14,\n "
2458 "15,\n 16,\n 17,\n "
2459 "18,\n 19,\n 20\n]\n");
2460 Json::Value root;
2461 for (Json::ArrayIndex i = 0; i < 21; i++)
2462 root[i] = i;
2463 const Json::String result = writer.write(root);
2464 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2465 }
2466 {
2467 // Array members do not exceed 21 print effects to render a single line
2468 const Json::String expected("[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]\n");
2469 Json::Value root;
2470 for (Json::ArrayIndex i = 0; i < 10; i++)
2471 root[i] = i;
2472 const Json::String result = writer.write(root);
2473 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2474 }
2475 }
2476
2477 JSONTEST_FIXTURE_LOCAL(StyledWriterTest, writeValueWithComment) {
2478 Json::StyledWriter writer;
2479 {
2480 const Json::String expected("\n//commentBeforeValue\n\"hello\"\n");
2481 Json::Value root = "hello";
2482 root.setComment(Json::String("//commentBeforeValue"), Json::commentBefore);
2483 const Json::String result = writer.write(root);
2484 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2485 }
2486 {
2487 const Json::String expected("\"hello\" //commentAfterValueOnSameLine\n");
2488 Json::Value root = "hello";
2489 root.setComment(Json::String("//commentAfterValueOnSameLine"),
2490 Json::commentAfterOnSameLine);
2491 const Json::String result = writer.write(root);
2492 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2493 }
2494 {
2495 const Json::String expected("\"hello\"\n//commentAfter\n\n");
2496 Json::Value root = "hello";
2497 root.setComment(Json::String("//commentAfter"), Json::commentAfter);
2498 const Json::String result = writer.write(root);
2499 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2500 }
2501 }
2502
2503 struct StyledStreamWriterTest : JsonTest::TestCase {};
2504
2505 JSONTEST_FIXTURE_LOCAL(StyledStreamWriterTest, writeNumericValue) {
2506 Json::StyledStreamWriter writer;
2507 const Json::String expected("{\n"
2508 "\t\"emptyValue\" : null,\n"
2509 "\t\"false\" : false,\n"
2510 "\t\"null\" : \"null\",\n"
2511 "\t\"number\" : -6200000000000000.0,\n"
2512 "\t\"real\" : 1.256,\n"
2513 "\t\"uintValue\" : 17\n"
2514 "}\n");
2515
2516 Json::Value root;
2517 root["emptyValue"] = Json::nullValue;
2518 root["false"] = false;
2519 root["null"] = "null";
2520 root["number"] = -6.2e+15; // big float number
2521 root["real"] = 1.256; // float number
2522 root["uintValue"] = Json::Value(17U);
2523
2524 Json::OStringStream sout;
2525 writer.write(sout, root);
2526 const Json::String result = sout.str();
2527 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2528 }
2529
2530 JSONTEST_FIXTURE_LOCAL(StyledStreamWriterTest, writeArrays) {
2531 Json::StyledStreamWriter writer;
2532 const Json::String expected("{\n"
2533 "\t\"property1\" : [ \"value1\", \"value2\" ],\n"
2534 "\t\"property2\" : []\n"
2535 "}\n");
2536 Json::Value root;
2537 root["property1"][0] = "value1";
2538 root["property1"][1] = "value2";
2539 root["property2"] = Json::arrayValue;
2540
2541 Json::OStringStream sout;
2542 writer.write(sout, root);
2543 const Json::String result = sout.str();
2544 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2545 }
2546
2547 JSONTEST_FIXTURE_LOCAL(StyledStreamWriterTest, writeNestedObjects) {
2548 Json::StyledStreamWriter writer;
2549 const Json::String expected("{\n"
2550 "\t\"object1\" : \n"
2551 "\t"
2552 "{\n"
2553 "\t\t\"bool\" : true,\n"
2554 "\t\t\"nested\" : 123\n"
2555 "\t},\n"
2556 "\t\"object2\" : {}\n"
2557 "}\n");
2558 Json::Value root, child;
2559 child["nested"] = 123;
2560 child["bool"] = true;
2561 root["object1"] = child;
2562 root["object2"] = Json::objectValue;
2563
2564 Json::OStringStream sout;
2565 writer.write(sout, root);
2566 const Json::String result = sout.str();
2567 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2568 }
2569
2570 JSONTEST_FIXTURE_LOCAL(StyledStreamWriterTest, multiLineArray) {
2571 {
2572 // Array member has more than 20 print effect rendering lines
2573 const Json::String expected("[\n\t0,"
2574 "\n\t1,"
2575 "\n\t2,"
2576 "\n\t3,"
2577 "\n\t4,"
2578 "\n\t5,"
2579 "\n\t6,"
2580 "\n\t7,"
2581 "\n\t8,"
2582 "\n\t9,"
2583 "\n\t10,"
2584 "\n\t11,"
2585 "\n\t12,"
2586 "\n\t13,"
2587 "\n\t14,"
2588 "\n\t15,"
2589 "\n\t16,"
2590 "\n\t17,"
2591 "\n\t18,"
2592 "\n\t19,"
2593 "\n\t20\n]\n");
2594 Json::StyledStreamWriter writer;
2595 Json::Value root;
2596 for (Json::ArrayIndex i = 0; i < 21; i++)
2597 root[i] = i;
2598 Json::OStringStream sout;
2599 writer.write(sout, root);
2600 const Json::String result = sout.str();
2601 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2602 }
2603 {
2604 Json::StyledStreamWriter writer;
2605 // Array members do not exceed 21 print effects to render a single line
2606 const Json::String expected("[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]\n");
2607 Json::Value root;
2608 for (Json::ArrayIndex i = 0; i < 10; i++)
2609 root[i] = i;
2610 Json::OStringStream sout;
2611 writer.write(sout, root);
2612 const Json::String result = sout.str();
2613 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2614 }
2615 }
2616
2617 JSONTEST_FIXTURE_LOCAL(StyledStreamWriterTest, writeValueWithComment) {
2618 Json::StyledStreamWriter writer("\t");
2619 {
2620 const Json::String expected("//commentBeforeValue\n\"hello\"\n");
2621 Json::Value root = "hello";
2622 Json::OStringStream sout;
2623 root.setComment(Json::String("//commentBeforeValue"), Json::commentBefore);
2624 writer.write(sout, root);
2625 const Json::String result = sout.str();
2626 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2627 }
2628 {
2629 const Json::String expected("\"hello\" //commentAfterValueOnSameLine\n");
2630 Json::Value root = "hello";
2631 Json::OStringStream sout;
2632 root.setComment(Json::String("//commentAfterValueOnSameLine"),
2633 Json::commentAfterOnSameLine);
2634 writer.write(sout, root);
2635 const Json::String result = sout.str();
2636 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2637 }
2638 {
2639 const Json::String expected("\"hello\"\n//commentAfter\n");
2640 Json::Value root = "hello";
2641 Json::OStringStream sout;
2642 root.setComment(Json::String("//commentAfter"), Json::commentAfter);
2643 writer.write(sout, root);
2644 const Json::String result = sout.str();
2645 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2646 }
2647 }
2648
2649 struct StreamWriterTest : JsonTest::TestCase {};
2650
2651 JSONTEST_FIXTURE_LOCAL(StreamWriterTest, writeNumericValue) {
2652 Json::StreamWriterBuilder writer;
2653 const Json::String expected("{\n"
2654 "\t\"emptyValue\" : null,\n"
2655 "\t\"false\" : false,\n"
2656 "\t\"null\" : \"null\",\n"
2657 "\t\"number\" : -6200000000000000.0,\n"
2658 "\t\"real\" : 1.256,\n"
2659 "\t\"uintValue\" : 17\n"
2660 "}");
2661 Json::Value root;
2662 root["emptyValue"] = Json::nullValue;
2663 root["false"] = false;
2664 root["null"] = "null";
2665 root["number"] = -6.2e+15;
2666 root["real"] = 1.256;
2667 root["uintValue"] = Json::Value(17U);
2668
2669 const Json::String result = Json::writeString(writer, root);
2670 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2671 }
2672
2673 JSONTEST_FIXTURE_LOCAL(StreamWriterTest, writeArrays) {
2674 Json::StreamWriterBuilder writer;
2675 const Json::String expected("{\n"
2676 "\t\"property1\" : \n"
2677 "\t[\n"
2678 "\t\t\"value1\",\n"
2679 "\t\t\"value2\"\n"
2680 "\t],\n"
2681 "\t\"property2\" : []\n"
2682 "}");
2683
2684 Json::Value root;
2685 root["property1"][0] = "value1";
2686 root["property1"][1] = "value2";
2687 root["property2"] = Json::arrayValue;
2688
2689 const Json::String result = Json::writeString(writer, root);
2690 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2691 }
2692
2693 JSONTEST_FIXTURE_LOCAL(StreamWriterTest, writeNestedObjects) {
2694 Json::StreamWriterBuilder writer;
2695 const Json::String expected("{\n"
2696 "\t\"object1\" : \n"
2697 "\t{\n"
2698 "\t\t\"bool\" : true,\n"
2699 "\t\t\"nested\" : 123\n"
2700 "\t},\n"
2701 "\t\"object2\" : {}\n"
2702 "}");
2703
2704 Json::Value root, child;
2705 child["nested"] = 123;
2706 child["bool"] = true;
2707 root["object1"] = child;
2708 root["object2"] = Json::objectValue;
2709
2710 const Json::String result = Json::writeString(writer, root);
2711 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2712 }
2713
2714 JSONTEST_FIXTURE_LOCAL(StreamWriterTest, multiLineArray) {
2715 Json::StreamWriterBuilder wb;
2716 wb.settings_["commentStyle"] = "None";
2717 {
2718 // When wb.settings_["commentStyle"] = "None", the effect of
2719 // printing multiple lines will be displayed when there are
2720 // more than 20 array members.
2721 const Json::String expected("[\n\t0,"
2722 "\n\t1,"
2723 "\n\t2,"
2724 "\n\t3,"
2725 "\n\t4,"
2726 "\n\t5,"
2727 "\n\t6,"
2728 "\n\t7,"
2729 "\n\t8,"
2730 "\n\t9,"
2731 "\n\t10,"
2732 "\n\t11,"
2733 "\n\t12,"
2734 "\n\t13,"
2735 "\n\t14,"
2736 "\n\t15,"
2737 "\n\t16,"
2738 "\n\t17,"
2739 "\n\t18,"
2740 "\n\t19,"
2741 "\n\t20\n]");
2742 Json::Value root;
2743 for (Json::ArrayIndex i = 0; i < 21; i++)
2744 root[i] = i;
2745 const Json::String result = Json::writeString(wb, root);
2746 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2747 }
2748 {
2749 // Array members do not exceed 21 print effects to render a single line
2750 const Json::String expected("[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]");
2751 Json::Value root;
2752 for (Json::ArrayIndex i = 0; i < 10; i++)
2753 root[i] = i;
2754 const Json::String result = Json::writeString(wb, root);
2755 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
2756 }
2757 }
2758
2759 JSONTEST_FIXTURE_LOCAL(StreamWriterTest, dropNullPlaceholders) {
2760 Json::StreamWriterBuilder b;
2761 Json::Value nullValue;
2762 b.settings_["dropNullPlaceholders"] = false;
2763 JSONTEST_ASSERT(Json::writeString(b, nullValue) == "null");
2764 b.settings_["dropNullPlaceholders"] = true;
2765 JSONTEST_ASSERT(Json::writeString(b, nullValue).empty());
2766 }
2767
2768 JSONTEST_FIXTURE_LOCAL(StreamWriterTest, enableYAMLCompatibility) {
2769 Json::StreamWriterBuilder b;
2770 Json::Value root;
2771 root["hello"] = "world";
2772
2773 b.settings_["indentation"] = "";
2774 JSONTEST_ASSERT(Json::writeString(b, root) == "{\"hello\":\"world\"}");
2775
2776 b.settings_["enableYAMLCompatibility"] = true;
2777 JSONTEST_ASSERT(Json::writeString(b, root) == "{\"hello\": \"world\"}");
2778
2779 b.settings_["enableYAMLCompatibility"] = false;
2780 JSONTEST_ASSERT(Json::writeString(b, root) == "{\"hello\":\"world\"}");
2781 }
2782
2783 JSONTEST_FIXTURE_LOCAL(StreamWriterTest, indentation) {
2784 Json::StreamWriterBuilder b;
2785 Json::Value root;
2786 root["hello"] = "world";
2787
2788 b.settings_["indentation"] = "";
2789 JSONTEST_ASSERT(Json::writeString(b, root) == "{\"hello\":\"world\"}");
2790
2791 b.settings_["indentation"] = "\t";
2792 JSONTEST_ASSERT(Json::writeString(b, root) ==
2793 "{\n\t\"hello\" : \"world\"\n}");
2794 }
2795
2796 JSONTEST_FIXTURE_LOCAL(StreamWriterTest, writeZeroes) {
2797 Json::String binary("hi", 3); // include trailing 0
2798 JSONTEST_ASSERT_EQUAL(3, binary.length());
2799 Json::String expected(R"("hi\u0000")"); // unicoded zero
2800 Json::StreamWriterBuilder b;
2801 {
2802 Json::Value root;
2803 root = binary;
2804 JSONTEST_ASSERT_STRING_EQUAL(binary, root.asString());
2805 Json::String out = Json::writeString(b, root);
2806 JSONTEST_ASSERT_EQUAL(expected.size(), out.size());
2807 JSONTEST_ASSERT_STRING_EQUAL(expected, out);
2808 }
2809 {
2810 Json::Value root;
2811 root["top"] = binary;
2812 JSONTEST_ASSERT_STRING_EQUAL(binary, root["top"].asString());
2813 Json::String out = Json::writeString(b, root["top"]);
2814 JSONTEST_ASSERT_STRING_EQUAL(expected, out);
2815 }
2816 }
2817
2818 JSONTEST_FIXTURE_LOCAL(StreamWriterTest, unicode) {
2819 // Create a Json value containing UTF-8 string with some chars that need
2820 // escape (tab,newline).
2821 Json::Value root;
2822 root["test"] = "\t\n\xF0\x91\xA2\xA1\x3D\xC4\xB3\xF0\x9B\x84\x9B\xEF\xBD\xA7";
2823
2824 Json::StreamWriterBuilder b;
2825
2826 // Default settings - should be unicode escaped.
2827 JSONTEST_ASSERT(Json::writeString(b, root) ==
2828 "{\n\t\"test\" : "
2829 "\"\\t\\n\\ud806\\udca1=\\u0133\\ud82c\\udd1b\\uff67\"\n}");
2830
2831 b.settings_["emitUTF8"] = true;
2832
2833 // Should not be unicode escaped.
2834 JSONTEST_ASSERT(
2835 Json::writeString(b, root) ==
2836 "{\n\t\"test\" : "
2837 "\"\\t\\n\xF0\x91\xA2\xA1=\xC4\xB3\xF0\x9B\x84\x9B\xEF\xBD\xA7\"\n}");
2838
2839 b.settings_["emitUTF8"] = false;
2840
2841 // Should be unicode escaped.
2842 JSONTEST_ASSERT(Json::writeString(b, root) ==
2843 "{\n\t\"test\" : "
2844 "\"\\t\\n\\ud806\\udca1=\\u0133\\ud82c\\udd1b\\uff67\"\n}");
2845 }
2846
2847 // Control chars should be escaped regardless of UTF-8 input encoding.
2848 JSONTEST_FIXTURE_LOCAL(StreamWriterTest, escapeControlCharacters) {
2849 auto uEscape = [](unsigned ch) {
2850 static const char h[] = "0123456789abcdef";
2851 std::string r = "\\u";
2852 r += h[(ch >> (3 * 4)) & 0xf];
2853 r += h[(ch >> (2 * 4)) & 0xf];
2854 r += h[(ch >> (1 * 4)) & 0xf];
2855 r += h[(ch >> (0 * 4)) & 0xf];
2856 return r;
2857 };
2858 auto shortEscape = [](unsigned ch) -> const char* {
2859 switch (ch) {
2860 case '\"':
2861 return "\\\"";
2862 case '\\':
2863 return "\\\\";
2864 case '\b':
2865 return "\\b";
2866 case '\f':
2867 return "\\f";
2868 case '\n':
2869 return "\\n";
2870 case '\r':
2871 return "\\r";
2872 case '\t':
2873 return "\\t";
2874 default:
2875 return nullptr;
2876 }
2877 };
2878
2879 Json::StreamWriterBuilder b;
2880
2881 for (bool emitUTF8 : {true, false}) {
2882 b.settings_["emitUTF8"] = emitUTF8;
2883
2884 for (unsigned i = 0; i != 0x100; ++i) {
2885 if (!emitUTF8 && i >= 0x80)
2886 break; // The algorithm would try to parse UTF-8, so stop here.
2887
2888 std::string raw({static_cast<char>(i)});
2889 std::string esc = raw;
2890 if (i < 0x20)
2891 esc = uEscape(i);
2892 if (const char* shEsc = shortEscape(i))
2893 esc = shEsc;
2894
2895 // std::cout << "emit=" << emitUTF8 << ", i=" << std::hex << i << std::dec
2896 // << std::endl;
2897
2898 Json::Value root;
2899 root["test"] = raw;
2900 JSONTEST_ASSERT_STRING_EQUAL(
2901 std::string("{\n\t\"test\" : \"").append(esc).append("\"\n}"),
2902 Json::writeString(b, root))
2903 << ", emit=" << emitUTF8 << ", i=" << i << ", raw=\"" << raw << "\""
2904 << ", esc=\"" << esc << "\"";
2905 }
2906 }
2907 }
2908
2909 #ifdef _WIN32
2910 JSONTEST_FIXTURE_LOCAL(StreamWriterTest, escapeTabCharacterWindows) {
2911 // Get the current locale before changing it
2912 std::string currentLocale = setlocale(LC_ALL, NULL);
2913 setlocale(LC_ALL, "English_United States.1252");
2914
2915 Json::Value root;
2916 root["test"] = "\tTabTesting\t";
2917
2918 Json::StreamWriterBuilder b;
2919
2920 JSONTEST_ASSERT(Json::writeString(b, root) == "{\n\t\"test\" : "
2921 "\"\\tTabTesting\\t\"\n}");
2922
2923 b.settings_["emitUTF8"] = true;
2924 JSONTEST_ASSERT(Json::writeString(b, root) == "{\n\t\"test\" : "
2925 "\"\\tTabTesting\\t\"\n}");
2926
2927 b.settings_["emitUTF8"] = false;
2928 JSONTEST_ASSERT(Json::writeString(b, root) == "{\n\t\"test\" : "
2929 "\"\\tTabTesting\\t\"\n}");
2930
2931 // Restore the locale
2932 if (!currentLocale.empty())
2933 setlocale(LC_ALL, currentLocale.c_str());
2934 }
2935 #endif
2936
2937 struct ReaderTest : JsonTest::TestCase {
2938 void setStrictMode() {
2939 reader = std::unique_ptr<Json::Reader>(
2940 new Json::Reader(Json::Features{}.strictMode()));
2941 }
2942
2943 void setFeatures(Json::Features& features) {
2944 reader = std::unique_ptr<Json::Reader>(new Json::Reader(features));
2945 }
2946
2947 void checkStructuredErrors(
2948 const std::vector<Json::Reader::StructuredError>& actual,
2949 const std::vector<Json::Reader::StructuredError>& expected) {
2950 JSONTEST_ASSERT_EQUAL(expected.size(), actual.size());
2951 for (size_t i = 0; i < actual.size(); ++i) {
2952 const auto& a = actual[i];
2953 const auto& e = expected[i];
2954 JSONTEST_ASSERT_EQUAL(e.offset_start, a.offset_start) << i;
2955 JSONTEST_ASSERT_EQUAL(e.offset_limit, a.offset_limit) << i;
2956 JSONTEST_ASSERT_EQUAL(e.message, a.message) << i;
2957 }
2958 }
2959
2960 template <typename Input> void checkParse(Input&& input) {
2961 JSONTEST_ASSERT(reader->parse(input, root));
2962 }
2963
2964 template <typename Input>
2965 void
2966 checkParse(Input&& input,
2967 const std::vector<Json::Reader::StructuredError>& structured) {
2968 JSONTEST_ASSERT(!reader->parse(input, root));
2969 checkStructuredErrors(reader->getStructuredErrors(), structured);
2970 }
2971
2972 template <typename Input>
2973 void checkParse(Input&& input,
2974 const std::vector<Json::Reader::StructuredError>& structured,
2975 const std::string& formatted) {
2976 checkParse(input, structured);
2977 JSONTEST_ASSERT_EQUAL(formatted, reader->getFormattedErrorMessages());
2978 }
2979
2980 std::unique_ptr<Json::Reader> reader{new Json::Reader()};
2981 Json::Value root;
2982 };
2983
2984 JSONTEST_FIXTURE_LOCAL(ReaderTest, parseWithNoErrors) {
2985 checkParse(R"({ "property" : "value" })");
2986 }
2987
2988 JSONTEST_FIXTURE_LOCAL(ReaderTest, parseObject) {
2989 checkParse(R"({"property"})",
2990 {{11, 12, "Missing ':' after object member name"}},
2991 "* Line 1, Column 12\n Missing ':' after object member name\n");
2992 checkParse(
2993 R"({"property" : "value" )",
2994 {{22, 22, "Missing ',' or '}' in object declaration"}},
2995 "* Line 1, Column 23\n Missing ',' or '}' in object declaration\n");
2996 checkParse(R"({"property" : "value", )",
2997 {{23, 23, "Missing '}' or object member name"}},
2998 "* Line 1, Column 24\n Missing '}' or object member name\n");
2999 }
3000
3001 JSONTEST_FIXTURE_LOCAL(ReaderTest, parseArray) {
3002 checkParse(
3003 R"([ "value" )", {{10, 10, "Missing ',' or ']' in array declaration"}},
3004 "* Line 1, Column 11\n Missing ',' or ']' in array declaration\n");
3005 checkParse(
3006 R"([ "value1" "value2" ] )",
3007 {{11, 19, "Missing ',' or ']' in array declaration"}},
3008 "* Line 1, Column 12\n Missing ',' or ']' in array declaration\n");
3009 }
3010
3011 JSONTEST_FIXTURE_LOCAL(ReaderTest, parseString) {
3012 checkParse(R"([ "\u8a2a" ])");
3013 checkParse(
3014 R"([ "\ud801" ])",
3015 {{2, 10,
3016 "additional six characters expected to parse unicode surrogate "
3017 "pair."}},
3018 "* Line 1, Column 3\n"
3019 " additional six characters expected to parse unicode surrogate pair.\n"
3020 "See Line 1, Column 10 for detail.\n");
3021 checkParse(R"([ "\ud801\d1234" ])",
3022 {{2, 16,
3023 "expecting another \\u token to begin the "
3024 "second half of a unicode surrogate pair"}},
3025 "* Line 1, Column 3\n"
3026 " expecting another \\u token to begin the "
3027 "second half of a unicode surrogate pair\n"
3028 "See Line 1, Column 12 for detail.\n");
3029 checkParse(R"([ "\ua3t@" ])",
3030 {{2, 10,
3031 "Bad unicode escape sequence in string: "
3032 "hexadecimal digit expected."}},
3033 "* Line 1, Column 3\n"
3034 " Bad unicode escape sequence in string: "
3035 "hexadecimal digit expected.\n"
3036 "See Line 1, Column 9 for detail.\n");
3037 checkParse(
3038 R"([ "\ua3t" ])",
3039 {{2, 9, "Bad unicode escape sequence in string: four digits expected."}},
3040 "* Line 1, Column 3\n"
3041 " Bad unicode escape sequence in string: four digits expected.\n"
3042 "See Line 1, Column 6 for detail.\n");
3043 }
3044
3045 JSONTEST_FIXTURE_LOCAL(ReaderTest, parseComment) {
3046 checkParse(
3047 R"({ /*commentBeforeValue*/ "property" : "value" }//commentAfterValue)"
3048 "\n");
3049 checkParse(" true //comment1\n//comment2\r//comment3\r\n");
3050 }
3051
3052 JSONTEST_FIXTURE_LOCAL(ReaderTest, streamParseWithNoErrors) {
3053 std::string styled = R"({ "property" : "value" })";
3054 std::istringstream iss(styled);
3055 checkParse(iss);
3056 }
3057
3058 JSONTEST_FIXTURE_LOCAL(ReaderTest, parseWithNoErrorsTestingOffsets) {
3059 checkParse(R"({)"
3060 R"( "property" : ["value", "value2"],)"
3061 R"( "obj" : { "nested" : -6.2e+15, "bool" : true},)"
3062 R"( "null" : null,)"
3063 R"( "false" : false)"
3064 R"( })");
3065 auto checkOffsets = [&](const Json::Value& v, int start, int limit) {
3066 JSONTEST_ASSERT_EQUAL(start, v.getOffsetStart());
3067 JSONTEST_ASSERT_EQUAL(limit, v.getOffsetLimit());
3068 };
3069 checkOffsets(root, 0, 115);
3070 checkOffsets(root["property"], 15, 34);
3071 checkOffsets(root["property"][0], 16, 23);
3072 checkOffsets(root["property"][1], 25, 33);
3073 checkOffsets(root["obj"], 44, 81);
3074 checkOffsets(root["obj"]["nested"], 57, 65);
3075 checkOffsets(root["obj"]["bool"], 76, 80);
3076 checkOffsets(root["null"], 92, 96);
3077 checkOffsets(root["false"], 108, 113);
3078 }
3079
3080 JSONTEST_FIXTURE_LOCAL(ReaderTest, parseWithOneError) {
3081 checkParse(R"({ "property" :: "value" })",
3082 {{14, 15, "Syntax error: value, object or array expected."}},
3083 "* Line 1, Column 15\n Syntax error: value, object or array "
3084 "expected.\n");
3085 checkParse("s", {{0, 1, "Syntax error: value, object or array expected."}},
3086 "* Line 1, Column 1\n Syntax error: value, object or array "
3087 "expected.\n");
3088 }
3089
3090 JSONTEST_FIXTURE_LOCAL(ReaderTest, parseSpecialFloat) {
3091 checkParse(R"({ "a" : Infi })",
3092 {{8, 9, "Syntax error: value, object or array expected."}},
3093 "* Line 1, Column 9\n Syntax error: value, object or array "
3094 "expected.\n");
3095 checkParse(R"({ "a" : Infiniaa })",
3096 {{8, 9, "Syntax error: value, object or array expected."}},
3097 "* Line 1, Column 9\n Syntax error: value, object or array "
3098 "expected.\n");
3099 }
3100
3101 JSONTEST_FIXTURE_LOCAL(ReaderTest, strictModeParseNumber) {
3102 setStrictMode();
3103 checkParse(
3104 "123",
3105 {{0, 3,
3106 "A valid JSON document must be either an array or an object value."}},
3107 "* Line 1, Column 1\n"
3108 " A valid JSON document must be either an array or an object value.\n");
3109 }
3110
3111 JSONTEST_FIXTURE_LOCAL(ReaderTest, parseChineseWithOneError) {
3112 checkParse(R"({ "pr)"
3113 u8"\u4f50\u85e4" // 佐藤
3114 R"(erty" :: "value" })",
3115 {{18, 19, "Syntax error: value, object or array expected."}},
3116 "* Line 1, Column 19\n Syntax error: value, object or array "
3117 "expected.\n");
3118 }
3119
3120 JSONTEST_FIXTURE_LOCAL(ReaderTest, parseWithDetailError) {
3121 checkParse(R"({ "property" : "v\alue" })",
3122 {{15, 23, "Bad escape sequence in string"}},
3123 "* Line 1, Column 16\n"
3124 " Bad escape sequence in string\n"
3125 "See Line 1, Column 20 for detail.\n");
3126 }
3127
3128 JSONTEST_FIXTURE_LOCAL(ReaderTest, pushErrorTest) {
3129 checkParse(R"({ "AUTHOR" : 123 })");
3130 if (!root["AUTHOR"].isString()) {
3131 JSONTEST_ASSERT(
3132 reader->pushError(root["AUTHOR"], "AUTHOR must be a string"));
3133 }
3134 JSONTEST_ASSERT_STRING_EQUAL(reader->getFormattedErrorMessages(),
3135 "* Line 1, Column 14\n"
3136 " AUTHOR must be a string\n");
3137
3138 checkParse(R"({ "AUTHOR" : 123 })");
3139 if (!root["AUTHOR"].isString()) {
3140 JSONTEST_ASSERT(reader->pushError(root["AUTHOR"], "AUTHOR must be a string",
3141 root["AUTHOR"]));
3142 }
3143 JSONTEST_ASSERT_STRING_EQUAL(reader->getFormattedErrorMessages(),
3144 "* Line 1, Column 14\n"
3145 " AUTHOR must be a string\n"
3146 "See Line 1, Column 14 for detail.\n");
3147 }
3148
3149 JSONTEST_FIXTURE_LOCAL(ReaderTest, allowNumericKeysTest) {
3150 Json::Features features;
3151 features.allowNumericKeys_ = true;
3152 setFeatures(features);
3153 checkParse(R"({ 123 : "abc" })");
3154 }
3155
3156 JSONTEST_FIXTURE_LOCAL(ReaderTest, allowDroppedNullPlaceholders) {
3157 Json::Features features;
3158 features.allowDroppedNullPlaceholders_ = true;
3159 setFeatures(features);
3160 checkParse(R"([1,,2])");
3161 JSONTEST_ASSERT_EQUAL(3, root.size());
3162 JSONTEST_ASSERT_EQUAL(1, root[0].asInt());
3163 JSONTEST_ASSERT(root[1].isNull());
3164 JSONTEST_ASSERT_EQUAL(2, root[2].asInt());
3165 }
3166
3167 struct CharReaderTest : JsonTest::TestCase {};
3168
3169 JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseWithNoErrors) {
3170 Json::CharReaderBuilder b;
3171 CharReaderPtr reader(b.newCharReader());
3172 Json::String errs;
3173 Json::Value root;
3174 char const doc[] = R"({ "property" : "value" })";
3175 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3176 JSONTEST_ASSERT(ok);
3177 JSONTEST_ASSERT(errs.empty());
3178 }
3179
3180 JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseWithNoErrorsTestingOffsets) {
3181 Json::CharReaderBuilder b;
3182 CharReaderPtr reader(b.newCharReader());
3183 Json::String errs;
3184 Json::Value root;
3185 char const doc[] = "{ \"property\" : [\"value\", \"value2\"], \"obj\" : "
3186 "{ \"nested\" : -6.2e+15, \"num\" : +123, \"bool\" : "
3187 "true}, \"null\" : null, \"false\" : false }";
3188 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3189 JSONTEST_ASSERT(ok);
3190 JSONTEST_ASSERT(errs.empty());
3191 }
3192
3193 JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseNumber) {
3194 Json::CharReaderBuilder b;
3195 CharReaderPtr reader(b.newCharReader());
3196 Json::String errs;
3197 Json::Value root;
3198 {
3199 // if intvalue > threshold, treat the number as a double.
3200 // 21 digits
3201 char const doc[] = "[111111111111111111111]";
3202 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3203 JSONTEST_ASSERT(ok);
3204 JSONTEST_ASSERT(errs.empty());
3205 JSONTEST_ASSERT_EQUAL(1.1111111111111111e+020, root[0]);
3206 }
3207 }
3208
3209 JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseString) {
3210 Json::CharReaderBuilder b;
3211 CharReaderPtr reader(b.newCharReader());
3212 Json::Value root;
3213 Json::String errs;
3214 {
3215 char const doc[] = "[\"\"]";
3216 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3217 JSONTEST_ASSERT(ok);
3218 JSONTEST_ASSERT(errs.empty());
3219 JSONTEST_ASSERT_EQUAL("", root[0]);
3220 }
3221 {
3222 char const doc[] = R"(["\u8A2a"])";
3223 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3224 JSONTEST_ASSERT(ok);
3225 JSONTEST_ASSERT(errs.empty());
3226 JSONTEST_ASSERT_EQUAL(u8"\u8A2a", root[0].asString()); // "訪"
3227 }
3228 {
3229 char const doc[] = R"([ "\uD801" ])";
3230 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3231 JSONTEST_ASSERT(!ok);
3232 JSONTEST_ASSERT(errs == "* Line 1, Column 3\n"
3233 " additional six characters expected to "
3234 "parse unicode surrogate pair.\n"
3235 "See Line 1, Column 10 for detail.\n");
3236 }
3237 {
3238 char const doc[] = R"([ "\uD801\d1234" ])";
3239 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3240 JSONTEST_ASSERT(!ok);
3241 JSONTEST_ASSERT(errs == "* Line 1, Column 3\n"
3242 " expecting another \\u token to begin the "
3243 "second half of a unicode surrogate pair\n"
3244 "See Line 1, Column 12 for detail.\n");
3245 }
3246 {
3247 char const doc[] = R"([ "\ua3t@" ])";
3248 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3249 JSONTEST_ASSERT(!ok);
3250 JSONTEST_ASSERT(errs == "* Line 1, Column 3\n"
3251 " Bad unicode escape sequence in string: "
3252 "hexadecimal digit expected.\n"
3253 "See Line 1, Column 9 for detail.\n");
3254 }
3255 {
3256 char const doc[] = R"([ "\ua3t" ])";
3257 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3258 JSONTEST_ASSERT(!ok);
3259 JSONTEST_ASSERT(
3260 errs ==
3261 "* Line 1, Column 3\n"
3262 " Bad unicode escape sequence in string: four digits expected.\n"
3263 "See Line 1, Column 6 for detail.\n");
3264 }
3265 {
3266 b.settings_["allowSingleQuotes"] = true;
3267 CharReaderPtr charreader(b.newCharReader());
3268 char const doc[] = R"({'a': 'x\ty', "b":'x\\y'})";
3269 bool ok = charreader->parse(doc, doc + std::strlen(doc), &root, &errs);
3270 JSONTEST_ASSERT(ok);
3271 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3272 JSONTEST_ASSERT_EQUAL(2u, root.size());
3273 JSONTEST_ASSERT_STRING_EQUAL("x\ty", root["a"].asString());
3274 JSONTEST_ASSERT_STRING_EQUAL("x\\y", root["b"].asString());
3275 }
3276 }
3277
3278 JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseComment) {
3279 Json::CharReaderBuilder b;
3280 CharReaderPtr reader(b.newCharReader());
3281 Json::Value root;
3282 Json::String errs;
3283 {
3284 char const doc[] = "//comment1\n { //comment2\n \"property\" :"
3285 " \"value\" //comment3\n } //comment4\n";
3286 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3287 JSONTEST_ASSERT(ok);
3288 JSONTEST_ASSERT(errs.empty());
3289 JSONTEST_ASSERT_EQUAL("value", root["property"]);
3290 }
3291 {
3292 char const doc[] = "{ \"property\" //comment\n : \"value\" }";
3293 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3294 JSONTEST_ASSERT(!ok);
3295 JSONTEST_ASSERT(errs == "* Line 1, Column 14\n"
3296 " Missing ':' after object member name\n");
3297 }
3298 {
3299 char const doc[] = "//comment1\n [ //comment2\n \"value\" //comment3\n,"
3300 " //comment4\n true //comment5\n ] //comment6\n";
3301 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3302 JSONTEST_ASSERT(ok);
3303 JSONTEST_ASSERT(errs.empty());
3304 JSONTEST_ASSERT_EQUAL("value", root[0]);
3305 JSONTEST_ASSERT_EQUAL(true, root[1]);
3306 }
3307 }
3308
3309 JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseObjectWithErrors) {
3310 Json::CharReaderBuilder b;
3311 CharReaderPtr reader(b.newCharReader());
3312 Json::Value root;
3313 Json::String errs;
3314 {
3315 char const doc[] = R"({ "property" : "value" )";
3316 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3317 JSONTEST_ASSERT(!ok);
3318 JSONTEST_ASSERT(errs == "* Line 1, Column 24\n"
3319 " Missing ',' or '}' in object declaration\n");
3320 JSONTEST_ASSERT_EQUAL("value", root["property"]);
3321 }
3322 {
3323 char const doc[] = R"({ "property" : "value" ,)";
3324 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3325 JSONTEST_ASSERT(!ok);
3326 JSONTEST_ASSERT(errs == "* Line 1, Column 25\n"
3327 " Missing '}' or object member name\n");
3328 JSONTEST_ASSERT_EQUAL("value", root["property"]);
3329 }
3330 }
3331
3332 JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseArrayWithErrors) {
3333 Json::CharReaderBuilder b;
3334 CharReaderPtr reader(b.newCharReader());
3335 Json::Value root;
3336 Json::String errs;
3337 {
3338 char const doc[] = "[ \"value\" ";
3339 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3340 JSONTEST_ASSERT(!ok);
3341 JSONTEST_ASSERT(errs == "* Line 1, Column 11\n"
3342 " Missing ',' or ']' in array declaration\n");
3343 JSONTEST_ASSERT_EQUAL("value", root[0]);
3344 }
3345 {
3346 char const doc[] = R"([ "value1" "value2" ])";
3347 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3348 JSONTEST_ASSERT(!ok);
3349 JSONTEST_ASSERT(errs == "* Line 1, Column 12\n"
3350 " Missing ',' or ']' in array declaration\n");
3351 JSONTEST_ASSERT_EQUAL("value1", root[0]);
3352 }
3353 }
3354
3355 JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseWithOneError) {
3356 Json::CharReaderBuilder b;
3357 CharReaderPtr reader(b.newCharReader());
3358 Json::String errs;
3359 Json::Value root;
3360 char const doc[] = R"({ "property" :: "value" })";
3361 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3362 JSONTEST_ASSERT(!ok);
3363 JSONTEST_ASSERT(errs ==
3364 "* Line 1, Column 15\n Syntax error: value, object or array "
3365 "expected.\n");
3366 }
3367
3368 JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseChineseWithOneError) {
3369 Json::CharReaderBuilder b;
3370 CharReaderPtr reader(b.newCharReader());
3371 Json::String errs;
3372 Json::Value root;
3373 char const doc[] = "{ \"pr佐藤erty\" :: \"value\" }";
3374 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3375 JSONTEST_ASSERT(!ok);
3376 JSONTEST_ASSERT(errs ==
3377 "* Line 1, Column 19\n Syntax error: value, object or array "
3378 "expected.\n");
3379 }
3380
3381 JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseWithDetailError) {
3382 Json::CharReaderBuilder b;
3383 CharReaderPtr reader(b.newCharReader());
3384 Json::String errs;
3385 Json::Value root;
3386 char const doc[] = R"({ "property" : "v\alue" })";
3387 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3388 JSONTEST_ASSERT(!ok);
3389 JSONTEST_ASSERT(errs ==
3390 "* Line 1, Column 16\n Bad escape sequence in string\nSee "
3391 "Line 1, Column 20 for detail.\n");
3392 }
3393
3394 JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseWithStackLimit) {
3395 #if JSON_USE_EXCEPTION
3396
3397 Json::CharReaderBuilder b;
3398 Json::Value root;
3399 char const doc[] = R"({ "property" : "value" })";
3400 {
3401 b.settings_["stackLimit"] = 2;
3402 CharReaderPtr reader(b.newCharReader());
3403 Json::String errs;
3404 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3405 JSONTEST_ASSERT(ok);
3406 JSONTEST_ASSERT(errs.empty());
3407 JSONTEST_ASSERT_EQUAL("value", root["property"]);
3408 }
3409 {
3410 b.settings_["stackLimit"] = 1;
3411 CharReaderPtr reader(b.newCharReader());
3412 Json::String errs;
3413 JSONTEST_ASSERT_THROWS(
3414 reader->parse(doc, doc + std::strlen(doc), &root, &errs));
3415 }
3416 // Default stack limit should reject deeply nested input (regression test for
3417 // stack exhaustion from fuzz input like [[[[...]]]])
3418 {
3419 Json::CharReaderBuilder defaultBuilder;
3420 Json::String nested(300, '[');
3421 CharReaderPtr reader(defaultBuilder.newCharReader());
3422 Json::String errs;
3423 JSONTEST_ASSERT_THROWS(reader->parse(
3424 nested.data(), nested.data() + nested.size(), &root, &errs));
3425 }
3426
3427 #endif // JSON_USE_EXCEPTION
3428 }
3429
3430 JSONTEST_FIXTURE_LOCAL(CharReaderTest, testOperator) {
3431 const std::string styled = R"({ "property" : "value" })";
3432 std::istringstream iss(styled);
3433 Json::Value root;
3434 iss >> root;
3435 JSONTEST_ASSERT_EQUAL("value", root["property"]);
3436 }
3437
3438 struct CharReaderStrictModeTest : JsonTest::TestCase {};
3439
3440 JSONTEST_FIXTURE_LOCAL(CharReaderStrictModeTest, dupKeys) {
3441 Json::CharReaderBuilder b;
3442 Json::Value root;
3443 char const doc[] =
3444 R"({ "property" : "value", "key" : "val1", "key" : "val2" })";
3445 {
3446 b.strictMode(&b.settings_);
3447 CharReaderPtr reader(b.newCharReader());
3448 Json::String errs;
3449 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3450 JSONTEST_ASSERT(!ok);
3451 JSONTEST_ASSERT_STRING_EQUAL("* Line 1, Column 41\n"
3452 " Duplicate key: 'key'\n",
3453 errs);
3454 JSONTEST_ASSERT_EQUAL("val1", root["key"]); // so far
3455 }
3456 }
3457 struct CharReaderFailIfExtraTest : JsonTest::TestCase {};
3458
3459 JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, issue164) {
3460 // This is interpreted as a string value followed by a colon.
3461 Json::CharReaderBuilder b;
3462 Json::Value root;
3463 char const doc[] = R"( "property" : "value" })";
3464 {
3465 b.settings_["failIfExtra"] = false;
3466 CharReaderPtr reader(b.newCharReader());
3467 Json::String errs;
3468 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3469 JSONTEST_ASSERT(ok);
3470 JSONTEST_ASSERT(errs.empty());
3471 JSONTEST_ASSERT_EQUAL("property", root);
3472 }
3473 {
3474 b.settings_["failIfExtra"] = true;
3475 CharReaderPtr reader(b.newCharReader());
3476 Json::String errs;
3477 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3478 JSONTEST_ASSERT(!ok);
3479 JSONTEST_ASSERT_STRING_EQUAL("* Line 1, Column 13\n"
3480 " Extra non-whitespace after JSON value.\n",
3481 errs);
3482 JSONTEST_ASSERT_EQUAL("property", root);
3483 }
3484 {
3485 b.strictMode(&b.settings_);
3486 CharReaderPtr reader(b.newCharReader());
3487 Json::String errs;
3488 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3489 JSONTEST_ASSERT(!ok);
3490 JSONTEST_ASSERT_STRING_EQUAL("* Line 1, Column 13\n"
3491 " Extra non-whitespace after JSON value.\n",
3492 errs);
3493 JSONTEST_ASSERT_EQUAL("property", root);
3494 }
3495 {
3496 b.strictMode(&b.settings_);
3497 b.settings_["failIfExtra"] = false;
3498 CharReaderPtr reader(b.newCharReader());
3499 Json::String errs;
3500 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3501 JSONTEST_ASSERT(!ok);
3502 JSONTEST_ASSERT_STRING_EQUAL(
3503 "* Line 1, Column 1\n"
3504 " A valid JSON document must be either an array or an object value.\n",
3505 errs);
3506 JSONTEST_ASSERT_EQUAL("property", root);
3507 }
3508 }
3509
3510 JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, issue107) {
3511 // This is interpreted as an int value followed by a colon.
3512 Json::CharReaderBuilder b;
3513 Json::Value root;
3514 char const doc[] = "1:2:3";
3515 b.settings_["failIfExtra"] = true;
3516 CharReaderPtr reader(b.newCharReader());
3517 Json::String errs;
3518 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3519 JSONTEST_ASSERT(!ok);
3520 JSONTEST_ASSERT_STRING_EQUAL("* Line 1, Column 2\n"
3521 " Extra non-whitespace after JSON value.\n",
3522 errs);
3523 JSONTEST_ASSERT_EQUAL(1, root.asInt());
3524 }
3525 JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, commentAfterObject) {
3526 Json::CharReaderBuilder b;
3527 Json::Value root;
3528 {
3529 char const doc[] = "{ \"property\" : \"value\" } //trailing\n//comment\n";
3530 b.settings_["failIfExtra"] = true;
3531 CharReaderPtr reader(b.newCharReader());
3532 Json::String errs;
3533 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3534 JSONTEST_ASSERT(ok);
3535 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3536 JSONTEST_ASSERT_EQUAL("value", root["property"]);
3537 }
3538 }
3539 JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, commentAfterArray) {
3540 Json::CharReaderBuilder b;
3541 Json::Value root;
3542 char const doc[] = "[ \"property\" , \"value\" ] //trailing\n//comment\n";
3543 b.settings_["failIfExtra"] = true;
3544 CharReaderPtr reader(b.newCharReader());
3545 Json::String errs;
3546 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3547 JSONTEST_ASSERT(ok);
3548 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3549 JSONTEST_ASSERT_EQUAL("value", root[1u]);
3550 }
3551 JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, commentAfterBool) {
3552 Json::CharReaderBuilder b;
3553 Json::Value root;
3554 char const doc[] = " true /*trailing\ncomment*/";
3555 b.settings_["failIfExtra"] = true;
3556 CharReaderPtr reader(b.newCharReader());
3557 Json::String errs;
3558 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3559 JSONTEST_ASSERT(ok);
3560 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3561 JSONTEST_ASSERT_EQUAL(true, root.asBool());
3562 }
3563
3564 JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, parseComment) {
3565 Json::CharReaderBuilder b;
3566 b.settings_["failIfExtra"] = true;
3567 CharReaderPtr reader(b.newCharReader());
3568 Json::Value root;
3569 Json::String errs;
3570 {
3571 char const doc[] = " true //comment1\n//comment2\r//comment3\r\n";
3572 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3573 JSONTEST_ASSERT(ok);
3574 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3575 JSONTEST_ASSERT_EQUAL(true, root.asBool());
3576 }
3577 {
3578 char const doc[] = " true //com\rment";
3579 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3580 JSONTEST_ASSERT(!ok);
3581 JSONTEST_ASSERT_STRING_EQUAL("* Line 2, Column 1\n"
3582 " Extra non-whitespace after JSON value.\n",
3583 errs);
3584 JSONTEST_ASSERT_EQUAL(true, root.asBool());
3585 }
3586 {
3587 char const doc[] = " true //com\nment";
3588 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3589 JSONTEST_ASSERT(!ok);
3590 JSONTEST_ASSERT_STRING_EQUAL("* Line 2, Column 1\n"
3591 " Extra non-whitespace after JSON value.\n",
3592 errs);
3593 JSONTEST_ASSERT_EQUAL(true, root.asBool());
3594 }
3595 }
3596
3597 struct CharReaderAllowDropNullTest : JsonTest::TestCase {
3598 using Value = Json::Value;
3599 using ValueCheck = std::function<void(const Value&)>;
3600
3601 Value nullValue = Value{Json::nullValue};
3602 Value emptyArray = Value{Json::arrayValue};
3603
3604 ValueCheck checkEq(const Value& v) {
3605 return [=](const Value& root) { JSONTEST_ASSERT_EQUAL(root, v); };
3606 }
3607
3608 static ValueCheck objGetAnd(std::string idx, ValueCheck f) {
3609 return [=](const Value& root) { f(root.get(idx, true)); };
3610 }
3611
3612 static ValueCheck arrGetAnd(int idx, ValueCheck f) {
3613 return [=](const Value& root) { f(root[idx]); };
3614 }
3615 };
3616
3617 JSONTEST_FIXTURE_LOCAL(CharReaderAllowDropNullTest, issue178) {
3618 struct TestSpec {
3619 int line;
3620 std::string doc;
3621 size_t rootSize;
3622 ValueCheck onRoot;
3623 };
3624 const TestSpec specs[] = {
3625 {__LINE__, R"({"a":,"b":true})", 2, objGetAnd("a", checkEq(nullValue))},
3626 {__LINE__, R"({"a":,"b":true})", 2, objGetAnd("a", checkEq(nullValue))},
3627 {__LINE__, R"({"a":})", 1, objGetAnd("a", checkEq(nullValue))},
3628 {__LINE__, "[]", 0, checkEq(emptyArray)},
3629 {__LINE__, "[null]", 1, nullptr},
3630 {__LINE__, "[,]", 2, nullptr},
3631 {__LINE__, "[,,,]", 4, nullptr},
3632 {__LINE__, "[null,]", 2, nullptr},
3633 {__LINE__, "[,null]", 2, nullptr},
3634 {__LINE__, "[,,]", 3, nullptr},
3635 {__LINE__, "[null,,]", 3, nullptr},
3636 {__LINE__, "[,null,]", 3, nullptr},
3637 {__LINE__, "[,,null]", 3, nullptr},
3638 {__LINE__, "[[],,,]", 4, arrGetAnd(0, checkEq(emptyArray))},
3639 {__LINE__, "[,[],,]", 4, arrGetAnd(1, checkEq(emptyArray))},
3640 {__LINE__, "[,,,[]]", 4, arrGetAnd(3, checkEq(emptyArray))},
3641 };
3642 for (const auto& spec : specs) {
3643 Json::CharReaderBuilder b;
3644 b.settings_["allowDroppedNullPlaceholders"] = true;
3645 std::unique_ptr<Json::CharReader> reader(b.newCharReader());
3646
3647 Json::Value root;
3648 Json::String errs;
3649 bool ok = reader->parse(spec.doc.data(), spec.doc.data() + spec.doc.size(),
3650 &root, &errs);
3651 JSONTEST_ASSERT(ok);
3652 JSONTEST_ASSERT_STRING_EQUAL(errs, "");
3653 if (spec.onRoot) {
3654 spec.onRoot(root);
3655 }
3656 }
3657 }
3658
3659 struct CharReaderAllowNumericKeysTest : JsonTest::TestCase {};
3660
3661 JSONTEST_FIXTURE_LOCAL(CharReaderAllowNumericKeysTest, allowNumericKeys) {
3662 Json::CharReaderBuilder b;
3663 b.settings_["allowNumericKeys"] = true;
3664 Json::Value root;
3665 Json::String errs;
3666 CharReaderPtr reader(b.newCharReader());
3667 char const doc[] = "{15:true,-16:true,12.01:true}";
3668 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3669 JSONTEST_ASSERT(ok);
3670 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3671 JSONTEST_ASSERT_EQUAL(3u, root.size());
3672 JSONTEST_ASSERT_EQUAL(true, root.get("15", false));
3673 JSONTEST_ASSERT_EQUAL(true, root.get("-16", false));
3674 JSONTEST_ASSERT_EQUAL(true, root.get("12.01", false));
3675 }
3676
3677 struct CharReaderAllowSingleQuotesTest : JsonTest::TestCase {};
3678
3679 JSONTEST_FIXTURE_LOCAL(CharReaderAllowSingleQuotesTest, issue182) {
3680 Json::CharReaderBuilder b;
3681 b.settings_["allowSingleQuotes"] = true;
3682 Json::Value root;
3683 Json::String errs;
3684 CharReaderPtr reader(b.newCharReader());
3685 {
3686 char const doc[] = "{'a':true,\"b\":true}";
3687 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3688 JSONTEST_ASSERT(ok);
3689 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3690 JSONTEST_ASSERT_EQUAL(2u, root.size());
3691 JSONTEST_ASSERT_EQUAL(true, root.get("a", false));
3692 JSONTEST_ASSERT_EQUAL(true, root.get("b", false));
3693 }
3694 {
3695 char const doc[] = "{'a': 'x', \"b\":'y'}";
3696 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3697 JSONTEST_ASSERT(ok);
3698 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3699 JSONTEST_ASSERT_EQUAL(2u, root.size());
3700 JSONTEST_ASSERT_STRING_EQUAL("x", root["a"].asString());
3701 JSONTEST_ASSERT_STRING_EQUAL("y", root["b"].asString());
3702 }
3703 }
3704
3705 struct CharReaderAllowZeroesTest : JsonTest::TestCase {};
3706
3707 JSONTEST_FIXTURE_LOCAL(CharReaderAllowZeroesTest, issue176) {
3708 Json::CharReaderBuilder b;
3709 b.settings_["allowSingleQuotes"] = true;
3710 Json::Value root;
3711 Json::String errs;
3712 CharReaderPtr reader(b.newCharReader());
3713 {
3714 char const doc[] = "{'a':true,\"b\":true}";
3715 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3716 JSONTEST_ASSERT(ok);
3717 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3718 JSONTEST_ASSERT_EQUAL(2u, root.size());
3719 JSONTEST_ASSERT_EQUAL(true, root.get("a", false));
3720 JSONTEST_ASSERT_EQUAL(true, root.get("b", false));
3721 }
3722 {
3723 char const doc[] = "{'a': 'x', \"b\":'y'}";
3724 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3725 JSONTEST_ASSERT(ok);
3726 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3727 JSONTEST_ASSERT_EQUAL(2u, root.size());
3728 JSONTEST_ASSERT_STRING_EQUAL("x", root["a"].asString());
3729 JSONTEST_ASSERT_STRING_EQUAL("y", root["b"].asString());
3730 }
3731 }
3732
3733 struct CharReaderAllowSpecialFloatsTest : JsonTest::TestCase {};
3734
3735 JSONTEST_FIXTURE_LOCAL(CharReaderAllowSpecialFloatsTest, specialFloat) {
3736 Json::CharReaderBuilder b;
3737 CharReaderPtr reader(b.newCharReader());
3738 Json::Value root;
3739 Json::String errs;
3740 {
3741 char const doc[] = "{\"a\": NaN}";
3742 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3743 JSONTEST_ASSERT(!ok);
3744 JSONTEST_ASSERT_STRING_EQUAL(
3745 "* Line 1, Column 7\n"
3746 " Syntax error: value, object or array expected.\n",
3747 errs);
3748 }
3749 {
3750 char const doc[] = "{\"a\": Infinity}";
3751 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3752 JSONTEST_ASSERT(!ok);
3753 JSONTEST_ASSERT_STRING_EQUAL(
3754 "* Line 1, Column 7\n"
3755 " Syntax error: value, object or array expected.\n",
3756 errs);
3757 }
3758 }
3759
3760 JSONTEST_FIXTURE_LOCAL(CharReaderAllowSpecialFloatsTest, issue209) {
3761 Json::CharReaderBuilder b;
3762 b.settings_["allowSpecialFloats"] = true;
3763 Json::Value root;
3764 Json::String errs;
3765 CharReaderPtr reader(b.newCharReader());
3766 {
3767 char const doc[] = R"({"a":NaN,"b":Infinity,"c":-Infinity,"d":+Infinity})";
3768 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3769 JSONTEST_ASSERT(ok);
3770 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3771 JSONTEST_ASSERT_EQUAL(4u, root.size());
3772 double n = root["a"].asDouble();
3773 JSONTEST_ASSERT(std::isnan(n));
3774 JSONTEST_ASSERT_EQUAL(std::numeric_limits<double>::infinity(),
3775 root.get("b", 0.0));
3776 JSONTEST_ASSERT_EQUAL(-std::numeric_limits<double>::infinity(),
3777 root.get("c", 0.0));
3778 JSONTEST_ASSERT_EQUAL(std::numeric_limits<double>::infinity(),
3779 root.get("d", 0.0));
3780 }
3781
3782 struct TestData {
3783 int line;
3784 bool ok;
3785 Json::String in;
3786 };
3787 const TestData test_data[] = {
3788 {__LINE__, true, "{\"a\":9}"}, //
3789 {__LINE__, false, "{\"a\":0Infinity}"}, //
3790 {__LINE__, false, "{\"a\":1Infinity}"}, //
3791 {__LINE__, false, "{\"a\":9Infinity}"}, //
3792 {__LINE__, false, "{\"a\":0nfinity}"}, //
3793 {__LINE__, false, "{\"a\":1nfinity}"}, //
3794 {__LINE__, false, "{\"a\":9nfinity}"}, //
3795 {__LINE__, false, "{\"a\":nfinity}"}, //
3796 {__LINE__, false, "{\"a\":.nfinity}"}, //
3797 {__LINE__, false, "{\"a\":9nfinity}"}, //
3798 {__LINE__, false, "{\"a\":-nfinity}"}, //
3799 {__LINE__, true, "{\"a\":Infinity}"}, //
3800 {__LINE__, false, "{\"a\":.Infinity}"}, //
3801 {__LINE__, false, "{\"a\":_Infinity}"}, //
3802 {__LINE__, false, "{\"a\":_nfinity}"}, //
3803 {__LINE__, true, "{\"a\":-Infinity}"}, //
3804 {__LINE__, true, "{\"a\":+Infinity}"} //
3805 };
3806 for (const auto& td : test_data) {
3807 bool ok = reader->parse(&*td.in.begin(), &*td.in.begin() + td.in.size(),
3808 &root, &errs);
3809 // clang-format off
3810 JSONTEST_ASSERT(td.ok == ok) <<
3811 "line:" << td.line << "\n " <<
3812 "expected: {ok:" << td.ok << ", in:\'" << td.in << "\'}\n " <<
3813 "actual: {ok:" << ok << "}\n";
3814 // clang-format on
3815 }
3816
3817 {
3818 char const doc[] = R"({"posInf": +Infinity, "NegInf": -Infinity})";
3819 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3820 JSONTEST_ASSERT(ok);
3821 JSONTEST_ASSERT_STRING_EQUAL("", errs);
3822 JSONTEST_ASSERT_EQUAL(2u, root.size());
3823 JSONTEST_ASSERT_EQUAL(std::numeric_limits<double>::infinity(),
3824 root["posInf"].asDouble());
3825 JSONTEST_ASSERT_EQUAL(-std::numeric_limits<double>::infinity(),
3826 root["NegInf"].asDouble());
3827 }
3828 }
3829
3830 struct EscapeSequenceTest : JsonTest::TestCase {};
3831
3832 JSONTEST_FIXTURE_LOCAL(EscapeSequenceTest, readerParseEscapeSequence) {
3833 Json::Reader reader;
3834 Json::Value root;
3835 bool ok = reader.parse("[\"\\\"\",\"\\/\",\"\\\\\",\"\\b\","
3836 "\"\\f\",\"\\n\",\"\\r\",\"\\t\","
3837 "\"\\u0278\",\"\\ud852\\udf62\"]\n",
3838 root);
3839 JSONTEST_ASSERT(ok);
3840 JSONTEST_ASSERT(reader.getFormattedErrorMessages().empty());
3841 JSONTEST_ASSERT(reader.getStructuredErrors().empty());
3842 }
3843
3844 JSONTEST_FIXTURE_LOCAL(EscapeSequenceTest, charReaderParseEscapeSequence) {
3845 Json::CharReaderBuilder b;
3846 CharReaderPtr reader(b.newCharReader());
3847 Json::Value root;
3848 Json::String errs;
3849 char const doc[] = "[\"\\\"\",\"\\/\",\"\\\\\",\"\\b\","
3850 "\"\\f\",\"\\n\",\"\\r\",\"\\t\","
3851 "\"\\u0278\",\"\\ud852\\udf62\"]";
3852 bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs);
3853 JSONTEST_ASSERT(ok);
3854 JSONTEST_ASSERT(errs.empty());
3855 }
3856
3857 JSONTEST_FIXTURE_LOCAL(EscapeSequenceTest, writeEscapeSequence) {
3858 Json::FastWriter writer;
3859 const Json::String expected("[\"\\\"\",\"\\\\\",\"\\b\","
3860 "\"\\f\",\"\\n\",\"\\r\",\"\\t\","
3861 "\"\\u0278\",\"\\ud852\\udf62\"]\n");
3862 Json::Value root;
3863 root[0] = "\"";
3864 root[1] = "\\";
3865 root[2] = "\b";
3866 root[3] = "\f";
3867 root[4] = "\n";
3868 root[5] = "\r";
3869 root[6] = "\t";
3870 root[7] = "ɸ";
3871 root[8] = "𤭢";
3872 const Json::String result = writer.write(root);
3873 JSONTEST_ASSERT_STRING_EQUAL(expected, result);
3874 }
3875
3876 struct BuilderTest : JsonTest::TestCase {};
3877
3878 JSONTEST_FIXTURE_LOCAL(BuilderTest, settings) {
3879 {
3880 Json::Value errs;
3881 Json::CharReaderBuilder rb;
3882 JSONTEST_ASSERT_EQUAL(false, rb.settings_.isMember("foo"));
3883 JSONTEST_ASSERT_EQUAL(true, rb.validate(&errs));
3884 rb["foo"] = "bar";
3885 JSONTEST_ASSERT_EQUAL(true, rb.settings_.isMember("foo"));
3886 JSONTEST_ASSERT_EQUAL(false, rb.validate(&errs));
3887 }
3888 {
3889 Json::Value errs;
3890 Json::StreamWriterBuilder wb;
3891 JSONTEST_ASSERT_EQUAL(false, wb.settings_.isMember("foo"));
3892 JSONTEST_ASSERT_EQUAL(true, wb.validate(&errs));
3893 wb["foo"] = "bar";
3894 JSONTEST_ASSERT_EQUAL(true, wb.settings_.isMember("foo"));
3895 JSONTEST_ASSERT_EQUAL(false, wb.validate(&errs));
3896 }
3897 }
3898
3899 struct BomTest : JsonTest::TestCase {};
3900
3901 JSONTEST_FIXTURE_LOCAL(BomTest, skipBom) {
3902 const std::string with_bom = "\xEF\xBB\xBF{\"key\" : \"value\"}";
3903 Json::Value root;
3904 JSONCPP_STRING errs;
3905 std::istringstream iss(with_bom);
3906 bool ok = parseFromStream(Json::CharReaderBuilder(), iss, &root, &errs);
3907 // The default behavior is to skip the BOM, so we can parse it normally.
3908 JSONTEST_ASSERT(ok);
3909 JSONTEST_ASSERT(errs.empty());
3910 JSONTEST_ASSERT_STRING_EQUAL(root["key"].asString(), "value");
3911 }
3912 JSONTEST_FIXTURE_LOCAL(BomTest, notSkipBom) {
3913 const std::string with_bom = "\xEF\xBB\xBF{\"key\" : \"value\"}";
3914 Json::Value root;
3915 JSONCPP_STRING errs;
3916 std::istringstream iss(with_bom);
3917 Json::CharReaderBuilder b;
3918 b.settings_["skipBom"] = false;
3919 bool ok = parseFromStream(b, iss, &root, &errs);
3920 // Detect the BOM, and failed on it.
3921 JSONTEST_ASSERT(!ok);
3922 JSONTEST_ASSERT(!errs.empty());
3923 }
3924
3925 struct IteratorTest : JsonTest::TestCase {};
3926
3927 JSONTEST_FIXTURE_LOCAL(IteratorTest, convert) {
3928 Json::Value j;
3929 const Json::Value& cj = j;
3930 auto it = j.begin();
3931 Json::Value::const_iterator cit;
3932 cit = it;
3933 JSONTEST_ASSERT(cit == cj.begin());
3934 }
3935
3936 JSONTEST_FIXTURE_LOCAL(IteratorTest, decrement) {
3937 Json::Value json;
3938 json["k1"] = "a";
3939 json["k2"] = "b";
3940 std::vector<std::string> values;
3941 for (auto it = json.end(); it != json.begin();) {
3942 --it;
3943 values.push_back(it->asString());
3944 }
3945 JSONTEST_ASSERT((values == std::vector<std::string>{"b", "a"}));
3946 }
3947
3948 JSONTEST_FIXTURE_LOCAL(IteratorTest, reverseIterator) {
3949 Json::Value json;
3950 json["k1"] = "a";
3951 json["k2"] = "b";
3952 std::vector<std::string> values;
3953 using Iter = decltype(json.begin());
3954 auto re = std::reverse_iterator<Iter>(json.begin());
3955 for (auto it = std::reverse_iterator<Iter>(json.end()); it != re; ++it) {
3956 values.push_back(it->asString());
3957 }
3958 JSONTEST_ASSERT((values == std::vector<std::string>{"b", "a"}));
3959 }
3960
3961 JSONTEST_FIXTURE_LOCAL(IteratorTest, distance) {
3962 {
3963 Json::Value json;
3964 json["k1"] = "a";
3965 json["k2"] = "b";
3966 int i = 0;
3967 auto it = json.begin();
3968 for (;; ++it, ++i) {
3969 auto dist = it - json.begin();
3970 JSONTEST_ASSERT_EQUAL(i, dist);
3971 if (it == json.end())
3972 break;
3973 }
3974 }
3975 {
3976 Json::Value empty;
3977 JSONTEST_ASSERT_EQUAL(0, empty.end() - empty.end());
3978 JSONTEST_ASSERT_EQUAL(0, empty.end() - empty.begin());
3979 }
3980 }
3981
3982 JSONTEST_FIXTURE_LOCAL(IteratorTest, nullValues) {
3983 {
3984 Json::Value json;
3985 auto end = json.end();
3986 auto endCopy = end;
3987 JSONTEST_ASSERT(endCopy == end);
3988 endCopy = end;
3989 JSONTEST_ASSERT(endCopy == end);
3990 }
3991 {
3992 // Same test, now with const Value.
3993 const Json::Value json;
3994 auto end = json.end();
3995 auto endCopy = end;
3996 JSONTEST_ASSERT(endCopy == end);
3997 endCopy = end;
3998 JSONTEST_ASSERT(endCopy == end);
3999 }
4000 }
4001
4002 JSONTEST_FIXTURE_LOCAL(IteratorTest, staticStringKey) {
4003 Json::Value json;
4004 json[Json::StaticString("k1")] = "a";
4005 JSONTEST_ASSERT_EQUAL(Json::Value("k1"), json.begin().key());
4006 }
4007
4008 JSONTEST_FIXTURE_LOCAL(IteratorTest, names) {
4009 Json::Value json;
4010 json["k1"] = "a";
4011 json["k2"] = "b";
4012 Json::ValueIterator it = json.begin();
4013 JSONTEST_ASSERT(it != json.end());
4014 JSONTEST_ASSERT_EQUAL(Json::Value("k1"), it.key());
4015 JSONTEST_ASSERT_STRING_EQUAL("k1", it.name());
4016 JSONTEST_ASSERT_STRING_EQUAL("k1", it.memberName());
4017 JSONTEST_ASSERT_EQUAL(-1, it.index());
4018 ++it;
4019 JSONTEST_ASSERT(it != json.end());
4020 JSONTEST_ASSERT_EQUAL(Json::Value("k2"), it.key());
4021 JSONTEST_ASSERT_STRING_EQUAL("k2", it.name());
4022 JSONTEST_ASSERT_STRING_EQUAL("k2", it.memberName());
4023 JSONTEST_ASSERT_EQUAL(-1, it.index());
4024 ++it;
4025 JSONTEST_ASSERT(it == json.end());
4026 }
4027
4028 JSONTEST_FIXTURE_LOCAL(IteratorTest, indexes) {
4029 Json::Value json;
4030 json[0] = "a";
4031 json[1] = "b";
4032 Json::ValueIterator it = json.begin();
4033 JSONTEST_ASSERT(it != json.end());
4034 JSONTEST_ASSERT_EQUAL(Json::Value(Json::ArrayIndex(0)), it.key());
4035 JSONTEST_ASSERT_STRING_EQUAL("", it.name());
4036 JSONTEST_ASSERT_EQUAL(0, it.index());
4037 ++it;
4038 JSONTEST_ASSERT(it != json.end());
4039 JSONTEST_ASSERT_EQUAL(Json::Value(Json::ArrayIndex(1)), it.key());
4040 JSONTEST_ASSERT_STRING_EQUAL("", it.name());
4041 JSONTEST_ASSERT_EQUAL(1, it.index());
4042 ++it;
4043 JSONTEST_ASSERT(it == json.end());
4044 }
4045
4046 JSONTEST_FIXTURE_LOCAL(IteratorTest, constness) {
4047 #if JSON_USE_EXCEPTION
4048
4049 Json::Value const v;
4050 JSONTEST_ASSERT_THROWS(
4051 Json::Value::iterator it(v.begin())); // Compile, but throw.
4052
4053 Json::Value value;
4054
4055 for (int i = 9; i < 12; ++i) {
4056 Json::OStringStream out;
4057 out << std::setw(2) << i;
4058 Json::String str = out.str();
4059 value[str] = str;
4060 }
4061
4062 Json::OStringStream out;
4063 // in old code, this will get a compile error
4064 Json::Value::const_iterator iter = value.begin();
4065 for (; iter != value.end(); ++iter) {
4066 out << *iter << ',';
4067 }
4068 Json::String expected = R"(" 9","10","11",)";
4069 JSONTEST_ASSERT_STRING_EQUAL(expected, out.str());
4070
4071 #endif // JSON_USE_EXCEPTION
4072 }
4073
4074 struct RValueTest : JsonTest::TestCase {};
4075
4076 JSONTEST_FIXTURE_LOCAL(RValueTest, moveConstruction) {
4077 Json::Value json;
4078 json["key"] = "value";
4079 Json::Value moved = std::move(json);
4080 JSONTEST_ASSERT(moved != json); // Possibly not nullValue; definitely not
4081 // equal.
4082 JSONTEST_ASSERT_EQUAL(Json::objectValue, moved.type());
4083 JSONTEST_ASSERT_EQUAL(Json::stringValue, moved["key"].type());
4084 }
4085
4086 struct FuzzTest : JsonTest::TestCase {};
4087
4088 // Build and run the fuzz test without any fuzzer, so that it's guaranteed not
4089 // go out of date, even if it's never run as an actual fuzz test.
4090 JSONTEST_FIXTURE_LOCAL(FuzzTest, fuzzDoesntCrash) {
4091 const std::string example = "{}";
4092 JSONTEST_ASSERT_EQUAL(
4093 0,
4094 LLVMFuzzerTestOneInput(reinterpret_cast<const uint8_t*>(example.c_str()),
4095 example.size()));
4096 }
4097
4098 struct ParseWithStructuredErrorsTest : JsonTest::TestCase {
4099 void testErrors(
4100 const std::string& doc, bool success,
4101 const std::vector<Json::CharReader::StructuredError>& expectedErrors) {
4102 Json::CharReaderBuilder b;
4103 CharReaderPtr reader(b.newCharReader());
4104 Json::Value root;
4105 JSONTEST_ASSERT_EQUAL(
4106 reader->parse(doc.data(), doc.data() + doc.length(), &root, nullptr),
4107 success);
4108 auto actualErrors = reader->getStructuredErrors();
4109 JSONTEST_ASSERT_EQUAL(expectedErrors.size(), actualErrors.size());
4110 for (std::size_t i = 0; i < actualErrors.size(); i++) {
4111 const auto& a = actualErrors[i];
4112 const auto& e = expectedErrors[i];
4113 JSONTEST_ASSERT_EQUAL(a.offset_start, e.offset_start);
4114 JSONTEST_ASSERT_EQUAL(a.offset_limit, e.offset_limit);
4115 JSONTEST_ASSERT_STRING_EQUAL(a.message, e.message);
4116 }
4117 }
4118 };
4119
4120 JSONTEST_FIXTURE_LOCAL(ParseWithStructuredErrorsTest, success) {
4121 testErrors("{}", true, {});
4122 }
4123
4124 JSONTEST_FIXTURE_LOCAL(ParseWithStructuredErrorsTest, singleError) {
4125 testErrors("{ 1 : 2 }", false, {{2, 3, "Missing '}' or object member name"}});
4126 }
4127
4128 int main(int argc, const char* argv[]) {
4129 JsonTest::Runner runner;
4130
4131 for (auto& local : local_) {
4132 runner.add(local);
4133 }
4134
4135 return runner.runCommandLine(argc, argv);
4136 }
4137
4138 struct MemberTemplateAs : JsonTest::TestCase {
4139 template <typename T, typename F>
4140 JsonTest::TestResult& EqEval(T v, F f) const {
4141 const Json::Value j = v;
4142 return JSONTEST_ASSERT_EQUAL(j.as<T>(), f(j));
4143 }
4144 };
4145
4146 JSONTEST_FIXTURE_LOCAL(MemberTemplateAs, BehavesSameAsNamedAs) {
4147 const Json::Value jstr = "hello world";
4148 JSONTEST_ASSERT_STRING_EQUAL(jstr.as<const char*>(), jstr.asCString());
4149 JSONTEST_ASSERT_STRING_EQUAL(jstr.as<Json::String>(), jstr.asString());
4150 EqEval(Json::Int(64), [](const Json::Value& j) { return j.asInt(); });
4151 EqEval(Json::UInt(64), [](const Json::Value& j) { return j.asUInt(); });
4152 #if defined(JSON_HAS_INT64)
4153 EqEval(Json::Int64(64), [](const Json::Value& j) { return j.asInt64(); });
4154 EqEval(Json::UInt64(64), [](const Json::Value& j) { return j.asUInt64(); });
4155 #endif // if defined(JSON_HAS_INT64)
4156 EqEval(Json::LargestInt(64),
4157 [](const Json::Value& j) { return j.asLargestInt(); });
4158 EqEval(Json::LargestUInt(64),
4159 [](const Json::Value& j) { return j.asLargestUInt(); });
4160
4161 EqEval(69.69f, [](const Json::Value& j) { return j.asFloat(); });
4162 EqEval(69.69, [](const Json::Value& j) { return j.asDouble(); });
4163 EqEval(false, [](const Json::Value& j) { return j.asBool(); });
4164 EqEval(true, [](const Json::Value& j) { return j.asBool(); });
4165 }
4166
4167 class MemberTemplateIs : public JsonTest::TestCase {};
4168
4169 JSONTEST_FIXTURE_LOCAL(MemberTemplateIs, BehavesSameAsNamedIs) {
4170 const Json::Value values[] = {true, 142, 40.63, "hello world"};
4171 for (const Json::Value& j : values) {
4172 JSONTEST_ASSERT_EQUAL(j.is<bool>(), j.isBool());
4173 JSONTEST_ASSERT_EQUAL(j.is<Json::Int>(), j.isInt());
4174 JSONTEST_ASSERT_EQUAL(j.is<Json::Int64>(), j.isInt64());
4175 JSONTEST_ASSERT_EQUAL(j.is<Json::UInt>(), j.isUInt());
4176 JSONTEST_ASSERT_EQUAL(j.is<Json::UInt64>(), j.isUInt64());
4177 JSONTEST_ASSERT_EQUAL(j.is<double>(), j.isDouble());
4178 JSONTEST_ASSERT_EQUAL(j.is<Json::String>(), j.isString());
4179 }
4180 }
4181
4182 class VersionTest : public JsonTest::TestCase {};
4183
4184 JSONTEST_FIXTURE_LOCAL(VersionTest, VersionNumbersMatch) {
4185 std::ostringstream vstr;
4186 vstr << JSONCPP_VERSION_MAJOR << '.' << JSONCPP_VERSION_MINOR << '.'
4187 << JSONCPP_VERSION_PATCH;
4188 JSONTEST_ASSERT_EQUAL(vstr.str(), std::string(JSONCPP_VERSION_STRING));
4189 }
4190
4191 #if defined(__GNUC__)
4192 #pragma GCC diagnostic pop
4193 #endif