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 "init_service.h"
19 #include "init_service_manager.h"
20 #include "init_service_socket.h"
21 #include "init_socket.h"
22 #include "param_stub.h"
23 #include "securec.h"
24 #include "le_task.h"
25 using namespace std;
26 using namespace testing::ext;
27 namespace init_ut {
28 class ServiceSocketUnitTest : public testing::Test {
29 public:
SetUpTestCase(void)30     static void SetUpTestCase(void) {}
TearDownTestCase(void)31     static void TearDownTestCase(void) {}
SetUp()32     void SetUp() {};
TearDown()33     void TearDown() {};
34 };
35 HWTEST_F(ServiceSocketUnitTest, TestCreateSocket, TestSize.Level0)
36 {
37     const char *testSocName = "test_socket";
38     uint32_t eventid = 1;
39     Service *service = (Service *)AddService("TestCreateSocket");
40     ASSERT_NE(service, nullptr);
41     service->socketCfg = nullptr;
42     service->attribute = SERVICE_ATTR_ONDEMAND;
43     ServiceSocket *sockopt = (ServiceSocket *)calloc(1, sizeof(ServiceSocket) + strlen(testSocName) + 1);
44     ASSERT_NE(sockopt, nullptr);
45     sockopt->type = SOCK_STREAM;
46     sockopt->protocol = 0;
47     sockopt->family = PF_UNIX;
48     sockopt->sockFd = -1;
49     sockopt->uid = 1000;
50     sockopt->gid = 1000;
51     sockopt->perm = 0660;
52     sockopt->option = SOCKET_OPTION_PASSCRED;
53     errno_t ret = strncpy_s(sockopt->name, strlen(testSocName) + 1, testSocName, strlen(testSocName));
54     sockopt->next = nullptr;
55     EXPECT_EQ(ret, EOK);
56     if (service->socketCfg == nullptr) {
57         service->socketCfg = sockopt;
58     } else {
59         sockopt->next = service->socketCfg->next;
60         service->socketCfg->next = sockopt;
61     }
62     int ret1 = CreateSocketForService(service);
63     if (((ServiceSocket *)service->socketCfg)->watcher != nullptr) {
64         ((WatcherTask *)((ServiceSocket *)service->socketCfg)->watcher)->processEvent(
65             LE_GetDefaultLoop(), 0, &eventid, service);
66     }
67     EXPECT_EQ(ret1, 0);
68     GetControlSocket(nullptr);
69     ret1 = GetControlSocket(testSocName);
70     EXPECT_GE(ret1, -1);
71     CloseServiceSocket(service);
72     ReleaseService(service);
73 }
74 } // namespace init_ut
75