• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
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 "base/json/json_writer.h"
6 #include "base/json/json_reader.h"
7 
8 #include "base/containers/span.h"
9 #include "base/strings/stringprintf.h"
10 #include "base/values.h"
11 #include "build/build_config.h"
12 #include "testing/gtest/include/gtest/gtest.h"
13 #include "third_party/abseil-cpp/absl/types/optional.h"
14 
15 #if BUILDFLAG(IS_WIN)
16 #include "base/strings/string_util.h"
17 #endif
18 
19 namespace base {
20 
21 namespace {
22 
FixNewlines(const std::string & json)23 std::string FixNewlines(const std::string& json) {
24   // The pretty-printer uses a different newline style on Windows than on
25   // other platforms.
26 #if BUILDFLAG(IS_WIN)
27   std::string result;
28   ReplaceChars(json, "\n", "\r\n", &result);
29   return result;
30 #else
31   return json;
32 #endif
33 }
34 
35 }  // namespace
36 
TEST(JsonWriterTest,BasicTypes)37 TEST(JsonWriterTest, BasicTypes) {
38   // Test null.
39   EXPECT_EQ(WriteJson(Value()), "null");
40 
41   // Test empty dict.
42   EXPECT_EQ(WriteJson(Value(Value::Type::DICT)), "{}");
43 
44   // Test empty list.
45   EXPECT_EQ(WriteJson(Value(Value::Type::LIST)), "[]");
46 
47   // Test integer values.
48   EXPECT_EQ(WriteJson(Value(42)), "42");
49 
50   // Test boolean values.
51   EXPECT_EQ(WriteJson(Value(true)), "true");
52 
53   // Test Real values should always have a decimal or an 'e'.
54   EXPECT_EQ(WriteJson(Value(1.0)), "1.0");
55 
56   // Test Real values in the range (-1, 1) must have leading zeros
57   EXPECT_EQ(WriteJson(Value(0.2)), "0.2");
58 
59   // Test Real values in the range (-1, 1) must have leading zeros
60   EXPECT_EQ(WriteJson(Value(-0.8)), "-0.8");
61 
62   // Test String values.
63   EXPECT_EQ(WriteJson(Value("foo")), "\"foo\"");
64 }
65 
TEST(JsonWriterTest,NestedTypes)66 TEST(JsonWriterTest, NestedTypes) {
67   // Writer unittests like empty list/dict nesting,
68   // list list nesting, etc.
69   auto dict =
70       Value::Dict().Set("list", Value::List()
71                                     .Append(Value::Dict().Set("inner int", 10))
72                                     .Append(Value::Dict())
73                                     .Append(Value::List())
74                                     .Append(true));
75 
76   EXPECT_EQ(WriteJson(dict), "{\"list\":[{\"inner int\":10},{},[],true]}");
77 
78   // Test the pretty-printer.
79   EXPECT_EQ(WriteJsonWithOptions(dict, JSONWriter::OPTIONS_PRETTY_PRINT),
80             FixNewlines(R"({
81    "list": [ {
82       "inner int": 10
83    }, {
84    }, [  ], true ]
85 }
86 )"));
87 }
88 
TEST(JsonWriterTest,KeysWithPeriods)89 TEST(JsonWriterTest, KeysWithPeriods) {
90   EXPECT_EQ(WriteJson(Value::Dict()  //
91                           .Set("a.b", 3)
92                           .Set("c", 2)
93                           .Set("d.e.f", Value::Dict().Set("g.h.i.j", 1))),
94             R"({"a.b":3,"c":2,"d.e.f":{"g.h.i.j":1}})");
95 
96   EXPECT_EQ(WriteJson(Value::Dict()  //
97                           .Set("a", Value::Dict().Set("b", 2))
98                           .Set("a.b", 1)),
99             R"({"a":{"b":2},"a.b":1})");
100 }
101 
TEST(JsonWriterTest,BinaryValues)102 TEST(JsonWriterTest, BinaryValues) {
103   const auto kBinaryData =
104       base::make_span(reinterpret_cast<const uint8_t*>("asdf"), 4u);
105 
106   // Binary values should return errors unless suppressed via the
107   // `OPTIONS_OMIT_BINARY_VALUES` flag.
108   EXPECT_EQ(WriteJson(Value(kBinaryData)), absl::nullopt);
109   EXPECT_EQ(WriteJsonWithOptions(Value(kBinaryData),
110                                  JsonOptions::OPTIONS_OMIT_BINARY_VALUES),
111             "");
112 
113   auto binary_list = Value::List()
114                          .Append(Value(kBinaryData))
115                          .Append(5)
116                          .Append(Value(kBinaryData))
117                          .Append(2)
118                          .Append(Value(kBinaryData));
119   EXPECT_EQ(WriteJson(binary_list), absl::nullopt);
120   EXPECT_EQ(
121       WriteJsonWithOptions(binary_list, JSONWriter::OPTIONS_OMIT_BINARY_VALUES),
122       "[5,2]");
123 
124   auto binary_dict = Value::Dict()
125                          .Set("a", Value(kBinaryData))
126                          .Set("b", 5)
127                          .Set("c", Value(kBinaryData))
128                          .Set("d", 2)
129                          .Set("e", Value(kBinaryData));
130   EXPECT_EQ(WriteJson(binary_dict), absl::nullopt);
131   EXPECT_EQ(
132       WriteJsonWithOptions(binary_dict, JSONWriter::OPTIONS_OMIT_BINARY_VALUES),
133       R"({"b":5,"d":2})");
134 }
135 
TEST(JsonWriterTest,DoublesAsInts)136 TEST(JsonWriterTest, DoublesAsInts) {
137   // Test allowing a double with no fractional part to be written as an integer.
138   Value double_value(1e10);
139   EXPECT_EQ(
140       WriteJsonWithOptions(double_value,
141                            JSONWriter::OPTIONS_OMIT_DOUBLE_TYPE_PRESERVATION),
142       "10000000000");
143 }
144 
TEST(JsonWriterTest,StackOverflow)145 TEST(JsonWriterTest, StackOverflow) {
146   Value::List deep_list;
147   const size_t max_depth = 100000;
148 
149   for (size_t i = 0; i < max_depth; ++i) {
150     Value::List new_top_list;
151     new_top_list.Append(std::move(deep_list));
152     deep_list = std::move(new_top_list);
153   }
154 
155   Value deep_list_value(std::move(deep_list));
156   EXPECT_EQ(WriteJson(deep_list_value), absl::nullopt);
157   EXPECT_EQ(
158       WriteJsonWithOptions(deep_list_value, JSONWriter::OPTIONS_PRETTY_PRINT),
159       absl::nullopt);
160 
161   // We cannot just let `deep_list` tear down since it
162   // would cause a stack overflow. Therefore, we tear
163   // down the deep list manually.
164   deep_list = std::move(deep_list_value).TakeList();
165   while (!deep_list.empty()) {
166     DCHECK_EQ(deep_list.size(), 1u);
167     Value::List inner_list = std::move(deep_list[0]).TakeList();
168     deep_list = std::move(inner_list);
169   }
170 }
171 
TEST(JsonWriterTest,TestMaxDepthWithValidNodes)172 TEST(JsonWriterTest, TestMaxDepthWithValidNodes) {
173   // Create JSON to the max depth - 1.  Nodes at that depth are still valid
174   // for writing which matches the JSONParser logic.
175   std::string nested_json;
176   for (int i = 0; i < 199; ++i) {
177     std::string node = "[";
178     for (int j = 0; j < 5; j++) {
179       node.append(StringPrintf("%d,", j));
180     }
181     nested_json.insert(0, node);
182     nested_json.append("]");
183   }
184 
185   // Ensure we can read and write the JSON
186   auto json_val = JSONReader::ReadAndReturnValueWithError(
187       nested_json, JSON_ALLOW_TRAILING_COMMAS);
188   EXPECT_TRUE(json_val.has_value());
189   const Value& value = *json_val;
190   EXPECT_NE(WriteJson(value), absl::nullopt);
191 }
192 
193 // Test that the JSONWriter::Write method still works.
TEST(JsonWriterTest,JSONWriterWriteSuccess)194 TEST(JsonWriterTest, JSONWriterWriteSuccess) {
195   std::string output_js;
196 
197   EXPECT_TRUE(
198       JSONWriter::Write(base::Value::Dict().Set("key", "value"), &output_js));
199   EXPECT_EQ(output_js, R"({"key":"value"})");
200 }
201 
202 // Test that the JSONWriter::Write method still works.
TEST(JsonWriterTest,JSONWriterWriteFailure)203 TEST(JsonWriterTest, JSONWriterWriteFailure) {
204   std::string output_js;
205 
206   EXPECT_FALSE(JSONWriter::Write(
207       base::Value::Dict()  //
208           .Set("key",
209                base::Value::Dict().Set("nested-key", base::Value::Dict())),
210       &output_js, /*max_depth=*/1));
211 }
212 
213 // Test that the JSONWriter::WriteWithOptions method still works.
TEST(JsonWriterTest,JSONWriterWriteWithOptionsSuccess)214 TEST(JsonWriterTest, JSONWriterWriteWithOptionsSuccess) {
215   std::string output_js;
216   EXPECT_TRUE(JSONWriter::WriteWithOptions(
217       base::Value::Dict().Set("key", "value"), JSONWriter::OPTIONS_PRETTY_PRINT,
218       &output_js));
219   EXPECT_EQ(output_js, FixNewlines(R"({
220    "key": "value"
221 }
222 )"));
223 }
224 
225 // Test that the JSONWriter::WriteWithOptions method still works.
TEST(JsonWriterTest,JSONWriterWriteWithOptionsFailure)226 TEST(JsonWriterTest, JSONWriterWriteWithOptionsFailure) {
227   std::string output_js;
228 
229   EXPECT_FALSE(JSONWriter::WriteWithOptions(
230       base::Value::Dict().Set(
231           "key", base::Value::Dict().Set("nested-key", base::Value::Dict())),
232       JSONWriter::OPTIONS_PRETTY_PRINT, &output_js, /*max_depth=*/1));
233 }
234 
235 }  // namespace base
236