xref: /aosp_15_r20/external/cronet/base/test/values_test_util.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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/test/values_test_util.h"
6 
7 #include <optional>
8 #include <ostream>
9 #include <string_view>
10 #include <utility>
11 
12 #include "base/files/file_util.h"
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/memory/ptr_util.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/types/optional_util.h"
18 #include "base/values.h"
19 #include "testing/gtest/include/gtest/gtest.h"
20 
21 namespace base {
22 
ExpectDictBooleanValue(bool expected_value,const Value::Dict & dict,std::string_view path)23 void ExpectDictBooleanValue(bool expected_value,
24                             const Value::Dict& dict,
25                             std::string_view path) {
26   EXPECT_EQ(dict.FindBoolByDottedPath(path), std::make_optional(expected_value))
27       << path;
28 }
29 
ExpectDictIntegerValue(int expected_value,const Value::Dict & dict,std::string_view path)30 void ExpectDictIntegerValue(int expected_value,
31                             const Value::Dict& dict,
32                             std::string_view path) {
33   EXPECT_EQ(dict.FindIntByDottedPath(path), std::make_optional(expected_value))
34       << path;
35 }
36 
ExpectDictStringValue(std::string_view expected_value,const Value::Dict & dict,std::string_view path)37 void ExpectDictStringValue(std::string_view expected_value,
38                            const Value::Dict& dict,
39                            std::string_view path) {
40   EXPECT_EQ(OptionalFromPtr(dict.FindStringByDottedPath(path)),
41             std::make_optional(expected_value))
42       << path;
43 }
44 
ExpectDictValue(const Value::Dict & expected_value,const Value::Dict & dict,std::string_view path)45 void ExpectDictValue(const Value::Dict& expected_value,
46                      const Value::Dict& dict,
47                      std::string_view path) {
48   const Value* found_value = dict.FindByDottedPath(path);
49   ASSERT_TRUE(found_value) << path;
50   EXPECT_EQ(*found_value, expected_value) << path;
51 }
52 
ExpectDictValue(const Value & expected_value,const Value::Dict & dict,std::string_view path)53 void ExpectDictValue(const Value& expected_value,
54                      const Value::Dict& dict,
55                      std::string_view path) {
56   const Value* found_value = dict.FindByDottedPath(path);
57   ASSERT_TRUE(found_value) << path;
58   EXPECT_EQ(*found_value, expected_value) << path;
59 }
60 
ExpectStringValue(const std::string & expected_str,const Value & actual)61 void ExpectStringValue(const std::string& expected_str, const Value& actual) {
62   const std::string* maybe_string = actual.GetIfString();
63   ASSERT_TRUE(maybe_string);
64   EXPECT_EQ(expected_str, *maybe_string);
65 }
66 
67 namespace test {
68 
69 namespace {
70 
FormatAsJSON(ValueView value)71 std::string FormatAsJSON(ValueView value) {
72   std::string json;
73   JSONWriter::Write(value, &json);
74   return json;
75 }
76 
77 class DictionaryHasValueMatcher
78     : public testing::MatcherInterface<const base::Value::Dict&> {
79  public:
DictionaryHasValueMatcher(const std::string & key,const base::Value & expected_value)80   DictionaryHasValueMatcher(const std::string& key,
81                             const base::Value& expected_value)
82       : key_(key), expected_value_(expected_value.Clone()) {}
83 
84   DictionaryHasValueMatcher(const DictionaryHasValueMatcher& other) = delete;
85   DictionaryHasValueMatcher& operator=(const DictionaryHasValueMatcher& other) =
86       delete;
87 
MatchAndExplain(const base::Value::Dict & value,testing::MatchResultListener * listener) const88   bool MatchAndExplain(const base::Value::Dict& value,
89                        testing::MatchResultListener* listener) const override {
90     const base::Value* sub_value = value.Find(key_);
91     if (!sub_value) {
92       *listener << "Dictionary '" << FormatAsJSON(value)
93                 << "' does not have key '" << key_ << "'";
94       return false;
95     }
96     if (*sub_value != expected_value_) {
97       *listener << "Dictionary value under key '" << key_ << "' is '"
98                 << FormatAsJSON(*sub_value) << "', expected '"
99                 << FormatAsJSON(expected_value_) << "'";
100       return false;
101     }
102     return true;
103   }
104 
DescribeTo(std::ostream * os) const105   void DescribeTo(std::ostream* os) const override {
106     *os << "has key '" << key_ << "' with value '"
107         << FormatAsJSON(expected_value_) << "'";
108   }
109 
DescribeNegationTo(std::ostream * os) const110   void DescribeNegationTo(std::ostream* os) const override {
111     *os << "does not have key '" << key_ << "' with value '"
112         << FormatAsJSON(expected_value_) << "'";
113   }
114 
115  private:
116   const std::string key_;
117   const base::Value expected_value_;
118 };
119 
120 class DictionaryHasValuesMatcher
121     : public testing::MatcherInterface<const base::Value::Dict&> {
122  public:
DictionaryHasValuesMatcher(const base::Value::Dict & template_value)123   explicit DictionaryHasValuesMatcher(const base::Value::Dict& template_value)
124       : template_value_(template_value.Clone()) {}
125 
126   DictionaryHasValuesMatcher(const DictionaryHasValuesMatcher& other) = delete;
127   DictionaryHasValuesMatcher& operator=(
128       const DictionaryHasValuesMatcher& other) = delete;
129 
MatchAndExplain(const base::Value::Dict & value,testing::MatchResultListener * listener) const130   bool MatchAndExplain(const base::Value::Dict& value,
131                        testing::MatchResultListener* listener) const override {
132     bool ok = true;
133     for (auto template_dict_item : template_value_) {
134       const base::Value* sub_value = value.Find(template_dict_item.first);
135       if (!sub_value) {
136         *listener << "\nDictionary does not have key '"
137                   << template_dict_item.first << "'";
138         ok = false;
139         continue;
140       }
141       if (*sub_value != template_dict_item.second) {
142         *listener << "\nDictionary value under key '"
143                   << template_dict_item.first << "' is '"
144                   << FormatAsJSON(*sub_value) << "', expected '"
145                   << FormatAsJSON(template_dict_item.second) << "'";
146         ok = false;
147       }
148     }
149     return ok;
150   }
151 
DescribeTo(std::ostream * os) const152   void DescribeTo(std::ostream* os) const override {
153     *os << "contains all key-values from '" << FormatAsJSON(template_value_)
154         << "'";
155   }
156 
DescribeNegationTo(std::ostream * os) const157   void DescribeNegationTo(std::ostream* os) const override {
158     *os << "does not contain key-values from '" << FormatAsJSON(template_value_)
159         << "'";
160   }
161 
162  private:
163   const base::Value::Dict template_value_;
164 };
165 
166 // Attempts to parse `json` as JSON. Returns resulting Value on success, has an
167 // EXPECT failure and returns nullopt on failure. If `expected_type` is
168 // provided, treats `json` parsing as a Value of a different type as a failure.
169 //
ParseJsonHelper(std::string_view json,std::optional<Value::Type> expected_type)170 std::optional<Value> ParseJsonHelper(std::string_view json,
171                                      std::optional<Value::Type> expected_type) {
172   auto result = JSONReader::ReadAndReturnValueWithError(
173       json, JSON_PARSE_CHROMIUM_EXTENSIONS | JSON_ALLOW_TRAILING_COMMAS);
174   if (!result.has_value()) {
175     ADD_FAILURE() << "Failed to parse \"" << json
176                   << "\": " << result.error().message;
177     return std::nullopt;
178   }
179   if (expected_type && result->type() != *expected_type) {
180     ADD_FAILURE() << "JSON is of wrong type: " << json;
181     return std::nullopt;
182   }
183   return std::move(*result);
184 }
185 
186 }  // namespace
187 
DictionaryHasValue(const std::string & key,const base::Value & expected_value)188 testing::Matcher<const base::Value::Dict&> DictionaryHasValue(
189     const std::string& key,
190     const base::Value& expected_value) {
191   return testing::MakeMatcher(
192       new DictionaryHasValueMatcher(key, expected_value));
193 }
194 
DictionaryHasValues(const base::Value::Dict & template_value)195 testing::Matcher<const base::Value::Dict&> DictionaryHasValues(
196     const base::Value::Dict& template_value) {
197   return testing::MakeMatcher(new DictionaryHasValuesMatcher(template_value));
198 }
199 
IsJsonMatcher(std::string_view json)200 IsJsonMatcher::IsJsonMatcher(std::string_view json)
201     : expected_value_(test::ParseJson(json)) {}
202 
IsJsonMatcher(const base::Value & value)203 IsJsonMatcher::IsJsonMatcher(const base::Value& value)
204     : expected_value_(value.Clone()) {}
205 
IsJsonMatcher(const base::Value::Dict & value)206 IsJsonMatcher::IsJsonMatcher(const base::Value::Dict& value)
207     : expected_value_(base::Value(value.Clone())) {}
208 
IsJsonMatcher(const base::Value::List & value)209 IsJsonMatcher::IsJsonMatcher(const base::Value::List& value)
210     : expected_value_(base::Value(value.Clone())) {}
211 
IsJsonMatcher(const IsJsonMatcher & other)212 IsJsonMatcher::IsJsonMatcher(const IsJsonMatcher& other)
213     : expected_value_(other.expected_value_.Clone()) {}
214 
operator =(const IsJsonMatcher & other)215 IsJsonMatcher& IsJsonMatcher::operator=(const IsJsonMatcher& other) {
216   expected_value_ = other.expected_value_.Clone();
217   return *this;
218 }
219 
220 IsJsonMatcher::~IsJsonMatcher() = default;
221 
MatchAndExplain(std::string_view json,testing::MatchResultListener * listener) const222 bool IsJsonMatcher::MatchAndExplain(
223     std::string_view json,
224     testing::MatchResultListener* listener) const {
225   // This is almost the same logic as ParseJson, but the parser uses stricter
226   // options for JSON data that is assumed to be generated by the code under
227   // test rather than written by hand as part of a unit test.
228   auto ret = JSONReader::ReadAndReturnValueWithError(json, JSON_PARSE_RFC);
229   if (!ret.has_value()) {
230     *listener << "Failed to parse \"" << json << "\": " << ret.error().message;
231     return false;
232   }
233   return MatchAndExplain(*ret, listener);
234 }
235 
MatchAndExplain(const base::Value & value,testing::MatchResultListener *) const236 bool IsJsonMatcher::MatchAndExplain(
237     const base::Value& value,
238     testing::MatchResultListener* /* listener */) const {
239   return expected_value_ == value;
240 }
241 
MatchAndExplain(const base::Value::Dict & dict,testing::MatchResultListener *) const242 bool IsJsonMatcher::MatchAndExplain(
243     const base::Value::Dict& dict,
244     testing::MatchResultListener* /* listener */) const {
245   return expected_value_.is_dict() && expected_value_.GetDict() == dict;
246 }
247 
MatchAndExplain(const base::Value::List & list,testing::MatchResultListener *) const248 bool IsJsonMatcher::MatchAndExplain(
249     const base::Value::List& list,
250     testing::MatchResultListener* /* listener */) const {
251   return expected_value_.is_list() && expected_value_.GetList() == list;
252 }
253 
DescribeTo(std::ostream * os) const254 void IsJsonMatcher::DescribeTo(std::ostream* os) const {
255   *os << "is the JSON value " << expected_value_;
256 }
257 
DescribeNegationTo(std::ostream * os) const258 void IsJsonMatcher::DescribeNegationTo(std::ostream* os) const {
259   *os << "is not the JSON value " << expected_value_;
260 }
261 
ParseJson(std::string_view json)262 Value ParseJson(std::string_view json) {
263   std::optional<Value> result =
264       ParseJsonHelper(json, /*expected_type=*/std::nullopt);
265   return result.has_value() ? std::move(*result) : Value();
266 }
267 
ParseJsonDict(std::string_view json)268 Value::Dict ParseJsonDict(std::string_view json) {
269   std::optional<Value> result =
270       ParseJsonHelper(json, /*expected_type=*/Value::Type::DICT);
271   return result.has_value() ? std::move(*result).TakeDict() : Value::Dict();
272 }
273 
ParseJsonList(std::string_view json)274 Value::List ParseJsonList(std::string_view json) {
275   std::optional<Value> result =
276       ParseJsonHelper(json, /*expected_type=*/Value::Type::LIST);
277   return result.has_value() ? std::move(*result).TakeList() : Value::List();
278 }
279 
ParseJsonDictFromFile(const FilePath & json_file_path)280 Value::Dict ParseJsonDictFromFile(const FilePath& json_file_path) {
281   std::string json;
282   if (!ReadFileToString(json_file_path, &json)) {
283     ADD_FAILURE() << "Failed to load json file for parsing. path="
284                   << json_file_path;
285     return {};
286   }
287   return ParseJsonDict(json);
288 }
289 
WriteJsonFile(const FilePath & json_file_path,ValueView root)290 expected<void, WriteJsonError> WriteJsonFile(const FilePath& json_file_path,
291                                              ValueView root) {
292   std::string json;
293   if (!JSONWriter::Write(root, &json)) {
294     return unexpected(WriteJsonError::kGenerateJsonFailure);
295   }
296   if (!WriteFile(json_file_path, json)) {
297     return unexpected(WriteJsonError::kWriteFileFailure);
298   }
299   return {};
300 }
301 
302 }  // namespace test
303 }  // namespace base
304