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/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 std::string in
= json_narrow_cases
[i
].to_escape
;
30 JsonDoubleQuote(in
, false, &out
);
31 EXPECT_EQ(std::string(json_narrow_cases
[i
].escaped
), out
);
34 std::string in
= json_narrow_cases
[0].to_escape
;
36 JsonDoubleQuote(in
, false, &out
);
39 std::string out_quoted
;
40 JsonDoubleQuote(in
, true, &out_quoted
);
41 EXPECT_EQ(out
.length() + 2, out_quoted
.length());
42 EXPECT_EQ(out_quoted
.find(out
), 1U);
44 // now try with a NULL in the string
45 std::string null_prepend
= "test";
46 null_prepend
.push_back(0);
47 in
= null_prepend
+ in
;
48 std::string expected
= "test\\u0000";
49 expected
+= json_narrow_cases
[0].escaped
;
51 JsonDoubleQuote(in
, false, &out
);
52 EXPECT_EQ(expected
, out
);
57 const struct json_wide_test_data
{
58 const wchar_t* to_escape
;
60 } json_wide_cases
[] = {
61 {L
"b\uffb1\u00ff", "b\\uFFB1\\u00FF"},
62 {L
"\b\001aZ\"\\wee", "\\b\\u0001aZ\\\"\\\\wee"},
63 {L
"a\b\f\n\r\t\v\1\\.\"z",
64 "a\\b\\f\\n\\r\\t\\u000B\\u0001\\\\.\\\"z"},
65 {L
"b\x0f\x7f\xf0\xff!", "b\\u000F\\u007F\\u00F0\\u00FF!"},
66 {L
"c<>d", "c\\u003C\\u003Ed"},
71 TEST(StringEscapeTest
, JsonDoubleQuoteWide
) {
72 for (size_t i
= 0; i
< arraysize(json_wide_cases
); ++i
) {
74 string16 in
= WideToUTF16(json_wide_cases
[i
].to_escape
);
75 JsonDoubleQuote(in
, false, &out
);
76 EXPECT_EQ(std::string(json_wide_cases
[i
].escaped
), out
);
79 string16 in
= WideToUTF16(json_wide_cases
[0].to_escape
);
81 JsonDoubleQuote(in
, false, &out
);
84 std::string out_quoted
;
85 JsonDoubleQuote(in
, true, &out_quoted
);
86 EXPECT_EQ(out
.length() + 2, out_quoted
.length());
87 EXPECT_EQ(out_quoted
.find(out
), 1U);
89 // now try with a NULL in the string
90 string16 null_prepend
= WideToUTF16(L
"test");
91 null_prepend
.push_back(0);
92 in
= null_prepend
+ in
;
93 std::string expected
= "test\\u0000";
94 expected
+= json_wide_cases
[0].escaped
;
96 JsonDoubleQuote(in
, false, &out
);
97 EXPECT_EQ(expected
, out
);