1 // Copyright 2017 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.
7 #include "base/functional/bind.h"
8 #include "base/functional/callback_helpers.h"
9 #include "base/json/json_reader.h"
10 #include "base/strings/string_piece.h"
11 #include "base/test/gmock_expected_support.h"
12 #include "base/token.h"
13 #include "base/values.h"
14 #include "chrome/test/base/in_process_browser_test.h"
15 #include "content/public/test/browser_test.h"
16 #include "content/public/test/test_utils.h"
17 #include "services/data_decoder/public/cpp/data_decoder.h"
18 #include "services/data_decoder/public/cpp/safe_xml_parser.h"
19 #include "services/data_decoder/public/mojom/xml_parser.mojom.h"
20 #include "testing/gmock/include/gmock/gmock.h"
21 #include "testing/gtest/include/gtest/gtest.h"
25 constexpr char kTestXml[] = "<hello>bonjour</hello>";
26 constexpr char kTestJson[] = R"(
29 "children": [{"type": "text", "text": "bonjour"}]
32 class SafeXmlParserTest : public InProcessBrowserTest {
34 SafeXmlParserTest() = default;
36 SafeXmlParserTest(const SafeXmlParserTest&) = delete;
37 SafeXmlParserTest& operator=(const SafeXmlParserTest&) = delete;
39 ~SafeXmlParserTest() override = default;
42 // Parses |xml| and compares its parsed representation with |expected_json|.
43 // If |expected_json| is empty, the XML parsing is expected to fail.
44 void TestParse(base::StringPiece xml, const std::string& expected_json) {
47 base::RunLoop run_loop;
48 absl::optional<base::Value> expected_value;
49 if (!expected_json.empty()) {
50 expected_value = base::JSONReader::Read(expected_json);
51 DCHECK(expected_value) << "Bad test, incorrect JSON: " << expected_json;
54 data_decoder::DataDecoder::ParseXmlIsolated(
56 data_decoder::mojom::XmlParser::WhitespaceBehavior::kIgnore,
57 base::BindOnce(&SafeXmlParserTest::XmlParsingDone,
58 base::Unretained(this), run_loop.QuitClosure(),
59 std::move(expected_value)));
64 void XmlParsingDone(base::OnceClosure quit_loop_closure,
65 absl::optional<base::Value> expected_value,
66 data_decoder::DataDecoder::ValueOrError result) {
67 base::ScopedClosureRunner runner(std::move(quit_loop_closure));
69 ASSERT_THAT(result, base::test::ValueIs(::testing::Eq(
70 ::testing::ByRef(*expected_value))));
72 EXPECT_FALSE(result.has_value());
79 // Tests that SafeXmlParser does parse. (actual XML parsing is tested in the
80 // service unit-tests).
81 IN_PROC_BROWSER_TEST_F(SafeXmlParserTest, Parse) {
82 TestParse("[\"this is JSON not XML\"]", "");
83 TestParse(kTestXml, kTestJson);