1 // Copyright 2017 Google Inc. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "src/utf8_fix.h"
16
17 #include "port/gtest.h"
18 #include "port/protobuf.h"
19
20 namespace protobuf_mutator {
21
22 protobuf::LogSilencer log_silincer;
23
24 class FixUtf8StringTest : public ::testing::TestWithParam<int> {
25 public:
IsStructurallyValid(const std::string & s)26 bool IsStructurallyValid(const std::string& s) {
27 using protobuf::internal::WireFormatLite;
28 return WireFormatLite::VerifyUtf8String(s.data(), s.length(),
29 WireFormatLite::PARSE, "");
30 }
31 };
32
TEST_F(FixUtf8StringTest,IsStructurallyValid)33 TEST_F(FixUtf8StringTest, IsStructurallyValid) {
34 EXPECT_TRUE(IsStructurallyValid(""));
35 EXPECT_TRUE(IsStructurallyValid("abc"));
36 EXPECT_TRUE(IsStructurallyValid("\xC2\xA2"));
37 EXPECT_TRUE(IsStructurallyValid("\xE2\x82\xAC"));
38 EXPECT_TRUE(IsStructurallyValid("\xF0\x90\x8D\x88"));
39 EXPECT_FALSE(IsStructurallyValid("\xFF\xFF\xFF\xFF"));
40 EXPECT_FALSE(IsStructurallyValid("\xFF\x8F"));
41 EXPECT_FALSE(IsStructurallyValid("\x3F\xBF"));
42 }
43
44 INSTANTIATE_TEST_CASE_P(Size, FixUtf8StringTest, ::testing::Range(0, 10));
45
TEST_P(FixUtf8StringTest,FixUtf8String)46 TEST_P(FixUtf8StringTest, FixUtf8String) {
47 RandomEngine random(GetParam());
48 std::uniform_int_distribution<uint8_t> random8(0, 0xFF);
49
50 std::string str(random8(random), 0);
51 for (uint32_t run = 0; run < 10000; ++run) {
52 for (size_t i = 0; i < str.size(); ++i) str[i] = random8(random);
53 std::string fixed = str;
54 FixUtf8String(&fixed, &random);
55 if (IsStructurallyValid(str)) {
56 EXPECT_EQ(str, fixed);
57 } else {
58 EXPECT_TRUE(IsStructurallyValid(fixed));
59 }
60 }
61 }
62
63 } // namespace protobuf_mutator
64