1 /**
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
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
16 #include "utils/string_helpers.h"
17
18 #include <cerrno>
19 #include <cstdarg>
20
21 #include <sstream>
22
23 #include <gtest/gtest.h>
24
25 namespace panda::helpers::string::test {
26
TEST(StringHelpers,Format)27 TEST(StringHelpers, Format)
28 {
29 EXPECT_EQ(Format("abc"), "abc");
30 EXPECT_EQ(Format("%s %d %c", "a", 10, 0x31), "a 10 1");
31
32 std::stringstream ss;
33 for (size_t i = 0; i < 10000; i++) {
34 ss << " ";
35 }
36
37 ss << "abc";
38
39 EXPECT_EQ(Format("%10003s", "abc"), ss.str());
40 }
41
TEST(StringHelpers,ParseIntFormat)42 TEST(StringHelpers, ParseIntFormat)
43 {
44 errno = 0;
45 int i = 0;
46 // check format
47 ASSERT_FALSE(ParseInt("x", &i));
48 ASSERT_EQ(EINVAL, errno);
49 errno = 0;
50 ASSERT_FALSE(ParseInt("123x", &i));
51 ASSERT_EQ(EINVAL, errno);
52
53 ASSERT_TRUE(ParseInt("123", &i));
54 ASSERT_EQ(123, i);
55 ASSERT_EQ(0, errno);
56 i = 0;
57 EXPECT_TRUE(ParseInt(" 123", &i));
58 EXPECT_EQ(123, i);
59 ASSERT_TRUE(ParseInt("-123", &i));
60 ASSERT_EQ(-123, i);
61 i = 0;
62 EXPECT_TRUE(ParseInt(" -123", &i));
63 EXPECT_EQ(-123, i);
64
65 short s = 0;
66 ASSERT_TRUE(ParseInt("1234", &s));
67 ASSERT_EQ(1234, s);
68 }
69
TEST(StringHelpers,ParseIntRange)70 TEST(StringHelpers, ParseIntRange)
71 {
72 errno = 0;
73 int i = 0;
74 // check range
75 ASSERT_TRUE(ParseInt("12", &i, 0, 15));
76 ASSERT_EQ(12, i);
77 errno = 0;
78 ASSERT_FALSE(ParseInt("-12", &i, 0, 15));
79 ASSERT_EQ(ERANGE, errno);
80 errno = 0;
81 ASSERT_FALSE(ParseInt("16", &i, 0, 15));
82 ASSERT_EQ(ERANGE, errno);
83
84 errno = 0;
85 ASSERT_FALSE(ParseInt<int>("x", nullptr));
86 ASSERT_EQ(EINVAL, errno);
87 errno = 0;
88 ASSERT_FALSE(ParseInt<int>("123x", nullptr));
89 ASSERT_EQ(EINVAL, errno);
90 ASSERT_TRUE(ParseInt<int>("1234", nullptr));
91
92 i = 0;
93 ASSERT_TRUE(ParseInt("0123", &i));
94 ASSERT_EQ(123, i);
95
96 i = 0;
97 ASSERT_TRUE(ParseInt("0x123", &i));
98 ASSERT_EQ(0x123, i);
99 i = 0;
100 EXPECT_TRUE(ParseInt(" 0x123", &i));
101 EXPECT_EQ(0x123, i);
102
103 i = 0;
104 ASSERT_TRUE(ParseInt(std::string("123"), &i));
105 ASSERT_EQ(123, i);
106
107 i = 123;
108 ASSERT_FALSE(ParseInt("456x", &i));
109 ASSERT_EQ(123, i);
110 }
111
112 } // namespace panda::helpers::string::test
113