1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include <memory> 6 #include <string> 7 8 #include "base/files/file_util.h" 9 #include "base/files/scoped_temp_dir.h" 10 #include "base/json/json_file_value_serializer.h" 11 #include "base/json/json_reader.h" 12 #include "base/json/json_string_value_serializer.h" 13 #include "base/json/json_writer.h" 14 #if !defined(__ANDROID__) && !defined(__ANDROID_HOST__) 15 #include "base/path_service.h" 16 #endif 17 #include "base/strings/string_piece.h" 18 #include "base/strings/string_util.h" 19 #include "base/strings/utf_string_conversions.h" 20 #include "base/values.h" 21 #include "build/build_config.h" 22 #include "testing/gtest/include/gtest/gtest.h" 23 24 namespace base { 25 26 namespace { 27 28 // Some proper JSON to test with: 29 const char kProperJSON[] = 30 "{\n" 31 " \"compound\": {\n" 32 " \"a\": 1,\n" 33 " \"b\": 2\n" 34 " },\n" 35 " \"some_String\": \"1337\",\n" 36 " \"some_int\": 42,\n" 37 " \"the_list\": [ \"val1\", \"val2\" ]\n" 38 "}\n"; 39 40 // Some proper JSON with trailing commas: 41 const char kProperJSONWithCommas[] = 42 "{\n" 43 "\t\"some_int\": 42,\n" 44 "\t\"some_String\": \"1337\",\n" 45 "\t\"the_list\": [\"val1\", \"val2\", ],\n" 46 "\t\"compound\": { \"a\": 1, \"b\": 2, },\n" 47 "}\n"; 48 49 // kProperJSON with a few misc characters at the begin and end. 50 const char kProperJSONPadded[] = 51 ")]}'\n" 52 "{\n" 53 " \"compound\": {\n" 54 " \"a\": 1,\n" 55 " \"b\": 2\n" 56 " },\n" 57 " \"some_String\": \"1337\",\n" 58 " \"some_int\": 42,\n" 59 " \"the_list\": [ \"val1\", \"val2\" ]\n" 60 "}\n" 61 "?!ab\n"; 62 63 const char kWinLineEnds[] = "\r\n"; 64 const char kLinuxLineEnds[] = "\n"; 65 66 // Verifies the generated JSON against the expected output. 67 void CheckJSONIsStillTheSame(const Value& value) { 68 // Serialize back the output. 69 std::string serialized_json; 70 JSONStringValueSerializer str_serializer(&serialized_json); 71 str_serializer.set_pretty_print(true); 72 ASSERT_TRUE(str_serializer.Serialize(value)); 73 // Unify line endings between platforms. 74 ReplaceSubstringsAfterOffset(&serialized_json, 0, 75 kWinLineEnds, kLinuxLineEnds); 76 // Now compare the input with the output. 77 ASSERT_EQ(kProperJSON, serialized_json); 78 } 79 80 void ValidateJsonList(const std::string& json) { 81 std::unique_ptr<ListValue> list = ListValue::From(JSONReader::Read(json)); 82 ASSERT_TRUE(list); 83 ASSERT_EQ(1U, list->GetSize()); 84 Value* elt = nullptr; 85 ASSERT_TRUE(list->Get(0, &elt)); 86 int value = 0; 87 ASSERT_TRUE(elt && elt->GetAsInteger(&value)); 88 ASSERT_EQ(1, value); 89 } 90 91 // Test proper JSON deserialization from string is working. 92 TEST(JSONValueDeserializerTest, ReadProperJSONFromString) { 93 // Try to deserialize it through the serializer. 94 JSONStringValueDeserializer str_deserializer(kProperJSON); 95 96 int error_code = 0; 97 std::string error_message; 98 std::unique_ptr<Value> value = 99 str_deserializer.Deserialize(&error_code, &error_message); 100 ASSERT_TRUE(value); 101 ASSERT_EQ(0, error_code); 102 ASSERT_TRUE(error_message.empty()); 103 // Verify if the same JSON is still there. 104 CheckJSONIsStillTheSame(*value); 105 } 106 107 // Test proper JSON deserialization from a StringPiece substring. 108 TEST(JSONValueDeserializerTest, ReadProperJSONFromStringPiece) { 109 // Create a StringPiece for the substring of kProperJSONPadded that matches 110 // kProperJSON. 111 StringPiece proper_json(kProperJSONPadded); 112 proper_json = proper_json.substr(5, proper_json.length() - 10); 113 JSONStringValueDeserializer str_deserializer(proper_json); 114 115 int error_code = 0; 116 std::string error_message; 117 std::unique_ptr<Value> value = 118 str_deserializer.Deserialize(&error_code, &error_message); 119 ASSERT_TRUE(value); 120 ASSERT_EQ(0, error_code); 121 ASSERT_TRUE(error_message.empty()); 122 // Verify if the same JSON is still there. 123 CheckJSONIsStillTheSame(*value); 124 } 125 126 // Test that trialing commas are only properly deserialized from string when 127 // the proper flag for that is set. 128 TEST(JSONValueDeserializerTest, ReadJSONWithTrailingCommasFromString) { 129 // Try to deserialize it through the serializer. 130 JSONStringValueDeserializer str_deserializer(kProperJSONWithCommas); 131 132 int error_code = 0; 133 std::string error_message; 134 std::unique_ptr<Value> value = 135 str_deserializer.Deserialize(&error_code, &error_message); 136 ASSERT_FALSE(value); 137 ASSERT_NE(0, error_code); 138 ASSERT_FALSE(error_message.empty()); 139 // Repeat with commas allowed. 140 JSONStringValueDeserializer str_deserializer2(kProperJSONWithCommas, 141 JSON_ALLOW_TRAILING_COMMAS); 142 value = str_deserializer2.Deserialize(&error_code, &error_message); 143 ASSERT_TRUE(value); 144 ASSERT_EQ(JSONReader::JSON_TRAILING_COMMA, error_code); 145 // Verify if the same JSON is still there. 146 CheckJSONIsStillTheSame(*value); 147 } 148 149 // Test proper JSON deserialization from file is working. 150 TEST(JSONValueDeserializerTest, ReadProperJSONFromFile) { 151 ScopedTempDir tempdir; 152 ASSERT_TRUE(tempdir.CreateUniqueTempDir()); 153 // Write it down in the file. 154 FilePath temp_file(tempdir.GetPath().AppendASCII("test.json")); 155 ASSERT_EQ(static_cast<int>(strlen(kProperJSON)), 156 WriteFile(temp_file, kProperJSON, strlen(kProperJSON))); 157 158 // Try to deserialize it through the serializer. 159 JSONFileValueDeserializer file_deserializer(temp_file); 160 161 int error_code = 0; 162 std::string error_message; 163 std::unique_ptr<Value> value = 164 file_deserializer.Deserialize(&error_code, &error_message); 165 ASSERT_TRUE(value); 166 ASSERT_EQ(0, error_code); 167 ASSERT_TRUE(error_message.empty()); 168 // Verify if the same JSON is still there. 169 CheckJSONIsStillTheSame(*value); 170 } 171 172 // Test that trialing commas are only properly deserialized from file when 173 // the proper flag for that is set. 174 TEST(JSONValueDeserializerTest, ReadJSONWithCommasFromFile) { 175 ScopedTempDir tempdir; 176 ASSERT_TRUE(tempdir.CreateUniqueTempDir()); 177 // Write it down in the file. 178 FilePath temp_file(tempdir.GetPath().AppendASCII("test.json")); 179 ASSERT_EQ(static_cast<int>(strlen(kProperJSONWithCommas)), 180 WriteFile(temp_file, kProperJSONWithCommas, 181 strlen(kProperJSONWithCommas))); 182 183 // Try to deserialize it through the serializer. 184 JSONFileValueDeserializer file_deserializer(temp_file); 185 // This must fail without the proper flag. 186 int error_code = 0; 187 std::string error_message; 188 std::unique_ptr<Value> value = 189 file_deserializer.Deserialize(&error_code, &error_message); 190 ASSERT_FALSE(value); 191 ASSERT_NE(0, error_code); 192 ASSERT_FALSE(error_message.empty()); 193 // Repeat with commas allowed. 194 JSONFileValueDeserializer file_deserializer2(temp_file, 195 JSON_ALLOW_TRAILING_COMMAS); 196 value = file_deserializer2.Deserialize(&error_code, &error_message); 197 ASSERT_TRUE(value); 198 ASSERT_EQ(JSONReader::JSON_TRAILING_COMMA, error_code); 199 // Verify if the same JSON is still there. 200 CheckJSONIsStillTheSame(*value); 201 } 202 203 TEST(JSONValueDeserializerTest, AllowTrailingComma) { 204 static const char kTestWithCommas[] = "{\"key\": [true,],}"; 205 static const char kTestNoCommas[] = "{\"key\": [true]}"; 206 207 JSONStringValueDeserializer deserializer(kTestWithCommas, 208 JSON_ALLOW_TRAILING_COMMAS); 209 JSONStringValueDeserializer deserializer_expected(kTestNoCommas); 210 std::unique_ptr<Value> root = deserializer.Deserialize(nullptr, nullptr); 211 ASSERT_TRUE(root); 212 std::unique_ptr<Value> root_expected; 213 root_expected = deserializer_expected.Deserialize(nullptr, nullptr); 214 ASSERT_TRUE(root_expected); 215 ASSERT_TRUE(root->Equals(root_expected.get())); 216 } 217 218 TEST(JSONValueSerializerTest, Roundtrip) { 219 static const char kOriginalSerialization[] = 220 "{\"bool\":true,\"double\":3.14,\"int\":42,\"list\":[1,2],\"null\":null}"; 221 JSONStringValueDeserializer deserializer(kOriginalSerialization); 222 std::unique_ptr<DictionaryValue> root_dict = 223 DictionaryValue::From(deserializer.Deserialize(nullptr, nullptr)); 224 ASSERT_TRUE(root_dict); 225 226 Value* null_value = nullptr; 227 ASSERT_TRUE(root_dict->Get("null", &null_value)); 228 ASSERT_TRUE(null_value); 229 ASSERT_TRUE(null_value->IsType(Value::Type::NONE)); 230 231 bool bool_value = false; 232 ASSERT_TRUE(root_dict->GetBoolean("bool", &bool_value)); 233 ASSERT_TRUE(bool_value); 234 235 int int_value = 0; 236 ASSERT_TRUE(root_dict->GetInteger("int", &int_value)); 237 ASSERT_EQ(42, int_value); 238 239 double double_value = 0.0; 240 ASSERT_TRUE(root_dict->GetDouble("double", &double_value)); 241 ASSERT_DOUBLE_EQ(3.14, double_value); 242 243 std::string test_serialization; 244 JSONStringValueSerializer mutable_serializer(&test_serialization); 245 ASSERT_TRUE(mutable_serializer.Serialize(*root_dict)); 246 ASSERT_EQ(kOriginalSerialization, test_serialization); 247 248 mutable_serializer.set_pretty_print(true); 249 ASSERT_TRUE(mutable_serializer.Serialize(*root_dict)); 250 // JSON output uses a different newline style on Windows than on other 251 // platforms. 252 #if defined(OS_WIN) 253 #define JSON_NEWLINE "\r\n" 254 #else 255 #define JSON_NEWLINE "\n" 256 #endif 257 const std::string pretty_serialization = 258 "{" JSON_NEWLINE 259 " \"bool\": true," JSON_NEWLINE 260 " \"double\": 3.14," JSON_NEWLINE 261 " \"int\": 42," JSON_NEWLINE 262 " \"list\": [ 1, 2 ]," JSON_NEWLINE 263 " \"null\": null" JSON_NEWLINE 264 "}" JSON_NEWLINE; 265 #undef JSON_NEWLINE 266 ASSERT_EQ(pretty_serialization, test_serialization); 267 } 268 269 TEST(JSONValueSerializerTest, StringEscape) { 270 string16 all_chars; 271 for (int i = 1; i < 256; ++i) { 272 all_chars += static_cast<char16>(i); 273 } 274 // Generated in in Firefox using the following js (with an extra backslash for 275 // double quote): 276 // var s = ''; 277 // for (var i = 1; i < 256; ++i) { s += String.fromCharCode(i); } 278 // uneval(s).replace(/\\/g, "\\\\"); 279 std::string all_chars_expected = 280 "\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000B\\f\\r" 281 "\\u000E\\u000F\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017" 282 "\\u0018\\u0019\\u001A\\u001B\\u001C\\u001D\\u001E\\u001F !\\\"#$%&'()*+," 283 "-./0123456789:;\\u003C=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcde" 284 "fghijklmnopqrstuvwxyz{|}~\x7F\xC2\x80\xC2\x81\xC2\x82\xC2\x83\xC2\x84" 285 "\xC2\x85\xC2\x86\xC2\x87\xC2\x88\xC2\x89\xC2\x8A\xC2\x8B\xC2\x8C\xC2\x8D" 286 "\xC2\x8E\xC2\x8F\xC2\x90\xC2\x91\xC2\x92\xC2\x93\xC2\x94\xC2\x95\xC2\x96" 287 "\xC2\x97\xC2\x98\xC2\x99\xC2\x9A\xC2\x9B\xC2\x9C\xC2\x9D\xC2\x9E\xC2\x9F" 288 "\xC2\xA0\xC2\xA1\xC2\xA2\xC2\xA3\xC2\xA4\xC2\xA5\xC2\xA6\xC2\xA7\xC2\xA8" 289 "\xC2\xA9\xC2\xAA\xC2\xAB\xC2\xAC\xC2\xAD\xC2\xAE\xC2\xAF\xC2\xB0\xC2\xB1" 290 "\xC2\xB2\xC2\xB3\xC2\xB4\xC2\xB5\xC2\xB6\xC2\xB7\xC2\xB8\xC2\xB9\xC2\xBA" 291 "\xC2\xBB\xC2\xBC\xC2\xBD\xC2\xBE\xC2\xBF\xC3\x80\xC3\x81\xC3\x82\xC3\x83" 292 "\xC3\x84\xC3\x85\xC3\x86\xC3\x87\xC3\x88\xC3\x89\xC3\x8A\xC3\x8B\xC3\x8C" 293 "\xC3\x8D\xC3\x8E\xC3\x8F\xC3\x90\xC3\x91\xC3\x92\xC3\x93\xC3\x94\xC3\x95" 294 "\xC3\x96\xC3\x97\xC3\x98\xC3\x99\xC3\x9A\xC3\x9B\xC3\x9C\xC3\x9D\xC3\x9E" 295 "\xC3\x9F\xC3\xA0\xC3\xA1\xC3\xA2\xC3\xA3\xC3\xA4\xC3\xA5\xC3\xA6\xC3\xA7" 296 "\xC3\xA8\xC3\xA9\xC3\xAA\xC3\xAB\xC3\xAC\xC3\xAD\xC3\xAE\xC3\xAF\xC3\xB0" 297 "\xC3\xB1\xC3\xB2\xC3\xB3\xC3\xB4\xC3\xB5\xC3\xB6\xC3\xB7\xC3\xB8\xC3\xB9" 298 "\xC3\xBA\xC3\xBB\xC3\xBC\xC3\xBD\xC3\xBE\xC3\xBF"; 299 300 std::string expected_output = "{\"all_chars\":\"" + all_chars_expected + 301 "\"}"; 302 // Test JSONWriter interface 303 std::string output_js; 304 DictionaryValue valueRoot; 305 valueRoot.SetString("all_chars", all_chars); 306 JSONWriter::Write(valueRoot, &output_js); 307 ASSERT_EQ(expected_output, output_js); 308 309 // Test JSONValueSerializer interface (uses JSONWriter). 310 JSONStringValueSerializer serializer(&output_js); 311 ASSERT_TRUE(serializer.Serialize(valueRoot)); 312 ASSERT_EQ(expected_output, output_js); 313 } 314 315 TEST(JSONValueSerializerTest, UnicodeStrings) { 316 // unicode string json -> escaped ascii text 317 DictionaryValue root; 318 string16 test(WideToUTF16(L"\x7F51\x9875")); 319 root.SetString("web", test); 320 321 static const char kExpected[] = "{\"web\":\"\xE7\xBD\x91\xE9\xA1\xB5\"}"; 322 323 std::string actual; 324 JSONStringValueSerializer serializer(&actual); 325 ASSERT_TRUE(serializer.Serialize(root)); 326 ASSERT_EQ(kExpected, actual); 327 328 // escaped ascii text -> json 329 JSONStringValueDeserializer deserializer(kExpected); 330 std::unique_ptr<Value> deserial_root = 331 deserializer.Deserialize(nullptr, nullptr); 332 ASSERT_TRUE(deserial_root); 333 DictionaryValue* dict_root = 334 static_cast<DictionaryValue*>(deserial_root.get()); 335 string16 web_value; 336 ASSERT_TRUE(dict_root->GetString("web", &web_value)); 337 ASSERT_EQ(test, web_value); 338 } 339 340 TEST(JSONValueSerializerTest, HexStrings) { 341 // hex string json -> escaped ascii text 342 DictionaryValue root; 343 string16 test(WideToUTF16(L"\x01\x02")); 344 root.SetString("test", test); 345 346 static const char kExpected[] = "{\"test\":\"\\u0001\\u0002\"}"; 347 348 std::string actual; 349 JSONStringValueSerializer serializer(&actual); 350 ASSERT_TRUE(serializer.Serialize(root)); 351 ASSERT_EQ(kExpected, actual); 352 353 // escaped ascii text -> json 354 JSONStringValueDeserializer deserializer(kExpected); 355 std::unique_ptr<Value> deserial_root = 356 deserializer.Deserialize(nullptr, nullptr); 357 ASSERT_TRUE(deserial_root); 358 DictionaryValue* dict_root = 359 static_cast<DictionaryValue*>(deserial_root.get()); 360 string16 test_value; 361 ASSERT_TRUE(dict_root->GetString("test", &test_value)); 362 ASSERT_EQ(test, test_value); 363 364 // Test converting escaped regular chars 365 static const char kEscapedChars[] = "{\"test\":\"\\u0067\\u006f\"}"; 366 JSONStringValueDeserializer deserializer2(kEscapedChars); 367 deserial_root = deserializer2.Deserialize(nullptr, nullptr); 368 ASSERT_TRUE(deserial_root); 369 dict_root = static_cast<DictionaryValue*>(deserial_root.get()); 370 ASSERT_TRUE(dict_root->GetString("test", &test_value)); 371 ASSERT_EQ(ASCIIToUTF16("go"), test_value); 372 } 373 374 TEST(JSONValueSerializerTest, JSONReaderComments) { 375 ValidateJsonList("[ // 2, 3, ignore me ] \n1 ]"); 376 ValidateJsonList("[ /* 2, \n3, ignore me ]*/ \n1 ]"); 377 ValidateJsonList("//header\n[ // 2, \n// 3, \n1 ]// footer"); 378 ValidateJsonList("/*\n[ // 2, \n// 3, \n1 ]*/[1]"); 379 ValidateJsonList("[ 1 /* one */ ] /* end */"); 380 ValidateJsonList("[ 1 //// ,2\r\n ]"); 381 382 // It's ok to have a comment in a string. 383 std::unique_ptr<ListValue> list = 384 ListValue::From(JSONReader::Read("[\"// ok\\n /* foo */ \"]")); 385 ASSERT_TRUE(list); 386 ASSERT_EQ(1U, list->GetSize()); 387 Value* elt = nullptr; 388 ASSERT_TRUE(list->Get(0, &elt)); 389 std::string value; 390 ASSERT_TRUE(elt && elt->GetAsString(&value)); 391 ASSERT_EQ("// ok\n /* foo */ ", value); 392 393 // You can't nest comments. 394 ASSERT_FALSE(JSONReader::Read("/* /* inner */ outer */ [ 1 ]")); 395 396 // Not a open comment token. 397 ASSERT_FALSE(JSONReader::Read("/ * * / [1]")); 398 } 399 400 #if !defined(__ANDROID__) && !defined(__ANDROID_HOST__) 401 402 class JSONFileValueSerializerTest : public testing::Test { 403 protected: 404 void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } 405 406 ScopedTempDir temp_dir_; 407 }; 408 409 TEST_F(JSONFileValueSerializerTest, Roundtrip) { 410 FilePath original_file_path; 411 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &original_file_path)); 412 original_file_path = original_file_path.AppendASCII("serializer_test.json"); 413 414 ASSERT_TRUE(PathExists(original_file_path)); 415 416 JSONFileValueDeserializer deserializer(original_file_path); 417 std::unique_ptr<DictionaryValue> root_dict = 418 DictionaryValue::From(deserializer.Deserialize(nullptr, nullptr)); 419 ASSERT_TRUE(root_dict); 420 421 Value* null_value = nullptr; 422 ASSERT_TRUE(root_dict->Get("null", &null_value)); 423 ASSERT_TRUE(null_value); 424 ASSERT_TRUE(null_value->IsType(Value::Type::NONE)); 425 426 bool bool_value = false; 427 ASSERT_TRUE(root_dict->GetBoolean("bool", &bool_value)); 428 ASSERT_TRUE(bool_value); 429 430 int int_value = 0; 431 ASSERT_TRUE(root_dict->GetInteger("int", &int_value)); 432 ASSERT_EQ(42, int_value); 433 434 std::string string_value; 435 ASSERT_TRUE(root_dict->GetString("string", &string_value)); 436 ASSERT_EQ("hello", string_value); 437 438 // Now try writing. 439 const FilePath written_file_path = 440 temp_dir_.GetPath().AppendASCII("test_output.js"); 441 442 ASSERT_FALSE(PathExists(written_file_path)); 443 JSONFileValueSerializer serializer(written_file_path); 444 ASSERT_TRUE(serializer.Serialize(*root_dict)); 445 ASSERT_TRUE(PathExists(written_file_path)); 446 447 // Now compare file contents. 448 EXPECT_TRUE(TextContentsEqual(original_file_path, written_file_path)); 449 EXPECT_TRUE(DeleteFile(written_file_path, false)); 450 } 451 452 TEST_F(JSONFileValueSerializerTest, RoundtripNested) { 453 FilePath original_file_path; 454 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &original_file_path)); 455 original_file_path = 456 original_file_path.AppendASCII("serializer_nested_test.json"); 457 458 ASSERT_TRUE(PathExists(original_file_path)); 459 460 JSONFileValueDeserializer deserializer(original_file_path); 461 std::unique_ptr<Value> root = deserializer.Deserialize(nullptr, nullptr); 462 ASSERT_TRUE(root); 463 464 // Now try writing. 465 FilePath written_file_path = 466 temp_dir_.GetPath().AppendASCII("test_output.json"); 467 468 ASSERT_FALSE(PathExists(written_file_path)); 469 JSONFileValueSerializer serializer(written_file_path); 470 ASSERT_TRUE(serializer.Serialize(*root)); 471 ASSERT_TRUE(PathExists(written_file_path)); 472 473 // Now compare file contents. 474 EXPECT_TRUE(TextContentsEqual(original_file_path, written_file_path)); 475 EXPECT_TRUE(DeleteFile(written_file_path, false)); 476 } 477 478 TEST_F(JSONFileValueSerializerTest, NoWhitespace) { 479 FilePath source_file_path; 480 ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &source_file_path)); 481 source_file_path = 482 source_file_path.AppendASCII("serializer_test_nowhitespace.json"); 483 ASSERT_TRUE(PathExists(source_file_path)); 484 JSONFileValueDeserializer deserializer(source_file_path); 485 std::unique_ptr<Value> root = deserializer.Deserialize(nullptr, nullptr); 486 ASSERT_TRUE(root); 487 } 488 #endif // !__ANDROID__ && !__ANDROID_HOST__ 489 490 } // namespace 491 492 } // namespace base 493