1 // Copyright (c) 2006-2008 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.
5 #include "base/json/string_escape.h"
6 #include "base/strings/utf_string_conversions.h"
7 #include "testing/gtest/include/gtest/gtest.h"
13 const struct json_narrow_test_data {
14 const char* to_escape;
16 } json_narrow_cases[] = {
17 {"\b\001aZ\"\\wee", "\\b\\u0001aZ\\\"\\\\wee"},
18 {"a\b\f\n\r\t\v\1\\.\"z",
19 "a\\b\\f\\n\\r\\t\\u000B\\u0001\\\\.\\\"z"},
20 {"b\x0f\x7f\xf0\xff!", "b\\u000F\\u007F\\u00F0\\u00FF!"},
21 {"c<>d", "c\\u003C\\u003Ed"},
26 TEST(StringEscapeTest, JsonDoubleQuoteNarrow) {
27 for (size_t i = 0; i < arraysize(json_narrow_cases); ++i) {
28 const char* in_ptr = json_narrow_cases[i].to_escape;
29 std::string in_str = in_ptr;
31 JsonDoubleQuote(in_ptr, false, &out);
32 EXPECT_EQ(std::string(json_narrow_cases[i].escaped), out);
34 JsonDoubleQuote(in_str, false, &out);
35 EXPECT_EQ(std::string(json_narrow_cases[i].escaped), out);
38 std::string in = json_narrow_cases[0].to_escape;
40 JsonDoubleQuote(in, false, &out);
43 std::string out_quoted;
44 JsonDoubleQuote(in, true, &out_quoted);
45 EXPECT_EQ(out.length() + 2, out_quoted.length());
46 EXPECT_EQ(out_quoted.find(out), 1U);
48 // now try with a NULL in the string
49 std::string null_prepend = "test";
50 null_prepend.push_back(0);
51 in = null_prepend + in;
52 std::string expected = "test\\u0000";
53 expected += json_narrow_cases[0].escaped;
55 JsonDoubleQuote(in, false, &out);
56 EXPECT_EQ(expected, out);
61 const struct json_wide_test_data {
62 const wchar_t* to_escape;
64 } json_wide_cases[] = {
65 {L"b\uffb1\u00ff", "b\\uFFB1\\u00FF"},
66 {L"\b\001aZ\"\\wee", "\\b\\u0001aZ\\\"\\\\wee"},
67 {L"a\b\f\n\r\t\v\1\\.\"z",
68 "a\\b\\f\\n\\r\\t\\u000B\\u0001\\\\.\\\"z"},
69 {L"b\x0f\x7f\xf0\xff!", "b\\u000F\\u007F\\u00F0\\u00FF!"},
70 {L"c<>d", "c\\u003C\\u003Ed"},
75 TEST(StringEscapeTest, JsonDoubleQuoteWide) {
76 for (size_t i = 0; i < arraysize(json_wide_cases); ++i) {
78 string16 in = WideToUTF16(json_wide_cases[i].to_escape);
79 JsonDoubleQuote(in, false, &out);
80 EXPECT_EQ(std::string(json_wide_cases[i].escaped), out);
83 string16 in = WideToUTF16(json_wide_cases[0].to_escape);
85 JsonDoubleQuote(in, false, &out);
88 std::string out_quoted;
89 JsonDoubleQuote(in, true, &out_quoted);
90 EXPECT_EQ(out.length() + 2, out_quoted.length());
91 EXPECT_EQ(out_quoted.find(out), 1U);
93 // now try with a NULL in the string
94 string16 null_prepend = WideToUTF16(L"test");
95 null_prepend.push_back(0);
96 in = null_prepend + in;
97 std::string expected = "test\\u0000";
98 expected += json_wide_cases[0].escaped;
100 JsonDoubleQuote(in, false, &out);
101 EXPECT_EQ(expected, out);