1 /*
2  * Copyright (c) 2021 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 #include <cerrno>
16 #include <unistd.h>
17 #include <sys/socket.h>
18 #include "param_stub.h"
19 #include "init_utils.h"
20 #include "init_service_socket.h"
21 #include "init_socket.h"
22 #include "securec.h"
23 using namespace std;
24 using namespace testing::ext;
25 
26 extern "C" {
27 float ConvertMicrosecondToSecond(int x);
28 }
29 #define MAX_BUFFER_FOR_TEST 128
30 
31 namespace init_ut {
32 class UtilsUnitTest : public testing::Test {
33 public:
SetUpTestCase(void)34     static void SetUpTestCase(void) {}
TearDownTestCase(void)35     static void TearDownTestCase(void) {}
SetUp()36     void SetUp() {};
TearDown()37     void TearDown() {};
38 };
39 
40 HWTEST_F(UtilsUnitTest, TestMakeDir, TestSize.Level0)
41 {
42     const char *dir = "/data/init_ut/mkdir_test";
43     mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IXOTH | S_IROTH;
44     int ret = MakeDirRecursive(dir, mode);
45     EXPECT_EQ(ret, 0);
46     dir = nullptr;
47     ret = MakeDirRecursive(dir, mode);
48     EXPECT_EQ(ret, -1);
49     ret = MakeDir(dir, 9999);
50     EXPECT_EQ(ret, -1);
51 }
52 
53 HWTEST_F(UtilsUnitTest, TestString, TestSize.Level0)
54 {
55     const char *str = nullptr;
56     int defaultValue = 1;
57     int ret = StringToInt(str, defaultValue);
58     EXPECT_EQ(ret, 1);
59     str = "10";
60     ret = StringToInt(str, defaultValue);
61     EXPECT_EQ(ret, 10);
62     char rStr[] = "abc";
63     char oldChr = 'a';
64     char newChr = 'd';
65     ret = StringReplaceChr(rStr, oldChr, newChr);
66     EXPECT_EQ(ret, 0);
67     EXPECT_STREQ(rStr, "dbc");
68 }
69 HWTEST_F(UtilsUnitTest, TestUtilsApi, TestSize.Level0)
70 {
71     float sec = ConvertMicrosecondToSecond(1000000); // 1000000 microseconds
72     EXPECT_EQ(sec, 1);
73     EXPECT_EQ(WriteAll(2, "test", strlen("test")), 4);
74     mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
75     CheckAndCreatFile("/data/init_ut/testcreatfile", mode);
76     CheckAndCreatFile("/data/init_ut/nodir/testcreatfile", mode);
77     char testStr[] = ".trim";
78     EXPECT_STREQ(TrimHead(testStr, '.'), "trim");
79 }
80 } // namespace init_ut
81