diff --git a/services/begetctl/param_cmd.c b/services/begetctl/param_cmd.c index 9df5825a540e3636eff64176f17c1779833f9f2e..e8c0ac4e1cd3a5050a9f4d597223080b8776eb14 100755 --- a/services/begetctl/param_cmd.c +++ b/services/begetctl/param_cmd.c @@ -43,7 +43,9 @@ void demoExit(void) { BShellEnvDestory(GetShellHandle()); if (g_shellPid != 0) { +#ifndef STARTUP_INIT_TEST kill(g_shellPid, SIGKILL); +#endif } if (g_isSetTerminal != 0) { tcsetattr(0, TCSAFLUSH, &g_terminalState); @@ -391,6 +393,7 @@ static int32_t BShellParamCmdPwd(BShellHandle shell, int32_t argc, char *argv[]) static int32_t BShellParamCmdShell(BShellHandle shell, int32_t argc, char *argv[]) { +#ifndef STARTUP_INIT_TEST BSH_CHECK(shell != NULL, return BSH_INVALID_PARAM, "Invalid shell env"); BSH_LOGV("BShellParamCmdShell %d %s", argc, argv[1]); int ret = 0; @@ -431,6 +434,7 @@ static int32_t BShellParamCmdShell(BShellHandle shell, int32_t argc, char *argv[ tcsetattr(0, TCSAFLUSH, &g_terminalState); g_isSetTerminal = 0; } +#endif return 0; } diff --git a/services/init/init_service_manager.c b/services/init/init_service_manager.c index 90920ef0753a324b6d8020d740aca1fe2e1b1330..07854eb174066428e4f3d7ea0dad0e6a45bf45bd 100644 --- a/services/init/init_service_manager.c +++ b/services/init/init_service_manager.c @@ -948,9 +948,11 @@ void StopAllServices(int flags, const char **exclude, int size, { Service *service = GetServiceByName("appspawn"); if (service != NULL && service->pid != -1) { // notify appspawn stop +#ifndef STARTUP_INIT_TEST kill(service->pid, SIGTERM); waitpid(service->pid, 0, 0); service->pid = -1; +#endif } InitGroupNode *node = GetNextGroupNode(NODE_TYPE_SERVICES, NULL); diff --git a/services/param/adapter/param_selinux.c b/services/param/adapter/param_selinux.c index 3ffc2386b69a9cf71e68d6cf3a1ea75a20868005..7754791ecf16f8a4c56abb29fe7be3f583bb0734 100644 --- a/services/param/adapter/param_selinux.c +++ b/services/param/adapter/param_selinux.c @@ -155,7 +155,11 @@ static int SelinuxCheckParamPermission(const ParamSecurityLabel *srcLabel, const if (mode == DAC_WRITE) { ret = g_selinuxSpace.setParamCheck(name, &uc); } else { +#ifndef STARTUP_INIT_TEST ret = SelinuxReadParamCheck(name); +#else + ret = g_selinuxSpace.readParamCheck(name); +#endif } if (ret != 0) { PARAM_LOGI("Selinux check name %s pid %d uid %d %d result %d", name, uc.pid, uc.uid, uc.gid, ret); diff --git a/services/param/linux/param_request.c b/services/param/linux/param_request.c index c5e3b4335afb590e9d79aa6d23d15cebe340392b..19869713e226b3678c3284b5a30360551d4fb23d 100755 --- a/services/param/linux/param_request.c +++ b/services/param/linux/param_request.c @@ -36,7 +36,9 @@ static atomic_uint g_requestId = ATOMIC_VAR_INIT(1); static ClientWorkSpace g_clientSpace = {}; __attribute__((constructor)) static void ClientInit(void); +#ifndef STARTUP_INIT_TEST __attribute__((destructor)) static void ClientDeinit(void); +#endif static int InitParamClient(void) { diff --git a/services/param/linux/param_service.c b/services/param/linux/param_service.c index 57842993673efcda63d98c4d8c3c716cf6104119..b61d0563c606330bb7cd8d80eeaec7ac774d17ef 100755 --- a/services/param/linux/param_service.c +++ b/services/param/linux/param_service.c @@ -33,7 +33,7 @@ static ParamService g_paramService = {}; -static void OnClose(ParamTaskPtr client) +PARAM_STATIC void OnClose(ParamTaskPtr client) { PARAM_LOGV("OnClose %p", client); ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client); diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 13d61737302b5359f1fd9f71f5ba3fa54bbcd852..ec76e91c495ed82c7afbdada91fca0b32dad7c5c 100755 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -119,16 +119,16 @@ ohos_unittest("init_ut") { sources += [ "begetctl/begetctl_unittest.cpp", + "init/SignalInitUnitTest.cpp", "init/cmds_unittest.cpp", "init/group_unittest.cpp", "init/init_reboot_unittest.cpp", - "init/loopevent_unittest.cpp", "init/mount_unittest.cpp", "init/plugin_unittest.cpp", "init/service_file_unittest.cpp", "init/service_socket_unittest.cpp", - "init/service_unittest.cpp", "init/utils_unittest.cpp", + "innerkits/innerkits_unittest.cpp", "param/client_unittest.cpp", "param/dac_unittest.cpp", "param/param_shell_unittest.cpp", @@ -242,6 +242,10 @@ ohos_unittest("init_ut") { } cflags_cc = [ "-fexceptions" ] + sources += [ + "init/loopevent_unittest.cpp", + "init/service_unittest.cpp", + ] } group("init_test") { diff --git a/test/unittest/begetctl/begetctl_unittest.cpp b/test/unittest/begetctl/begetctl_unittest.cpp index 390e98e26fa443be6db5022b0cf54036287549ae..ad934fccb0937a4b5c89920bf8610d0be79a9bb4 100644 --- a/test/unittest/begetctl/begetctl_unittest.cpp +++ b/test/unittest/begetctl/begetctl_unittest.cpp @@ -94,6 +94,14 @@ HWTEST_F(BegetctlUnitTest, TestShellWait, TestSize.Level1) }; BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); } +HWTEST_F(BegetctlUnitTest, TestShellWaitFalse, TestSize.Level1) +{ + BShellParamCmdRegister(GetShellHandle(), 0); + const char *args[] = { + "param", "wait" + }; + BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); +} HWTEST_F(BegetctlUnitTest, TestShellWaitWithKey, TestSize.Level1) { @@ -103,4 +111,30 @@ HWTEST_F(BegetctlUnitTest, TestShellWaitWithKey, TestSize.Level1) }; BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); } +HWTEST_F(BegetctlUnitTest, TestShellParamShell, TestSize.Level1) +{ + BShellParamCmdRegister(GetShellHandle(), 0); + const char *args[] = { + "param", "shell" + }; + BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); +} +HWTEST_F(BegetctlUnitTest, TestShellLsWithvalue, TestSize.Level1) +{ + BShellParamCmdRegister(GetShellHandle(), 0); + BShellEnvSetParam(GetShellHandle(), PARAM_REVERESD_NAME_CURR_PARAMETER, "..a", PARAM_STRING, (void *)"..a"); + const char *args[] = { + "param", "ls", PARAM_REVERESD_NAME_CURR_PARAMETER + }; + BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); +} +HWTEST_F(BegetctlUnitTest, TestShellLsWithvalueExist, TestSize.Level1) +{ + BShellParamCmdRegister(GetShellHandle(), 0); + BShellEnvSetParam(GetShellHandle(), PARAM_REVERESD_NAME_CURR_PARAMETER, "#", PARAM_STRING, (void *)"#"); + const char *args[] = { + "param", "ls", "-r", PARAM_REVERESD_NAME_CURR_PARAMETER + }; + BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); +} } // namespace init_ut diff --git a/test/unittest/init/SignalInitUnitTest.cpp b/test/unittest/init/SignalInitUnitTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b57bc596b6bec8f6fe1d2a97cb665de5bce8bf84 --- /dev/null +++ b/test/unittest/init/SignalInitUnitTest.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "init_unittest.h" +#include "init.h" +#include "loop_event.h" +#include "le_epoll.h" +#include "le_signal.h" +#include "init_hashmap.h" + +using namespace testing::ext; +using namespace std; + +static SignalHandle g_sigHandler = nullptr; + +static void ProcessSignal(const struct signalfd_siginfo *siginfo) +{ + return; +} + +namespace init_ut { +class SignalInitUnitTest : public testing::Test { +public: + static void SetUpTestCase(void) {}; + static void TearDownTestCase(void) {}; + void SetUp() {}; + void TearDown() {}; +}; + +HWTEST_F(SignalInitUnitTest, SignalInitTestRmSig, TestSize.Level1) +{ + LE_CreateSignalTask(LE_GetDefaultLoop(), &g_sigHandler, ProcessSignal); + ASSERT_NE(g_sigHandler, nullptr); + int ret = LE_AddSignal(LE_GetDefaultLoop(), g_sigHandler, SIGUSR1); + ASSERT_EQ(ret, 0); + LE_AddSignal(LE_GetDefaultLoop(), g_sigHandler, SIGUSR1); + LE_AddSignal(LE_GetDefaultLoop(), g_sigHandler, SIGUSR2); + ret = LE_RemoveSignal(LE_GetDefaultLoop(), g_sigHandler, SIGUSR1); + ASSERT_EQ(ret, 0); + LE_RemoveSignal(LE_GetDefaultLoop(), g_sigHandler, SIGUSR1); + LE_RemoveSignal(LE_GetDefaultLoop(), g_sigHandler, SIGUSR2); + ((BaseTask *)g_sigHandler)->handleEvent(LE_GetDefaultLoop(), (TaskHandle)&g_sigHandler, Event_Write); + LE_CloseSignalTask(LE_GetDefaultLoop(), g_sigHandler); + ASSERT_EQ(ret, 0); +} +} diff --git a/test/unittest/init/cmds_unittest.cpp b/test/unittest/init/cmds_unittest.cpp index 03dcc3c6836bedf18a22bf558fe04ff3a2d2afc5..cd1ca82bf6d881842bcfe27225bccd988f471a8d 100644 --- a/test/unittest/init/cmds_unittest.cpp +++ b/test/unittest/init/cmds_unittest.cpp @@ -16,6 +16,7 @@ #include #include "init_cmds.h" #include "init_param.h" +#include "init_group_manager.h" #include "param_stub.h" #include "init_utils.h" #include "trigger_manager.h" @@ -37,12 +38,13 @@ public: HWTEST_F(CmdsUnitTest, TestCmdExecByName, TestSize.Level1) { - SetInitLogLevel(INIT_FATAL); DoCmdByName("load_param ", " /system/etc/param onlyadd"); DoCmdByName("symlink ", "/proc/self/fd/0 /dev/stdin"); + DoCmdByName("symlink ", "/notfile "); DoCmdByName("insmod ", "libdemo.z.so anony=1 mmz_allocator=hisi mmz=anonymous,0,0xA8000000,384M || report_error"); DoCmdByName("insmod ", "/vendor/modules/hi_irq.ko"); + DoCmdByName("insmod ", "/data/init_ut/test_insmod"); DoCmdByName("setparam ", "sys.usb.config ${persist.sys.usb.config}"); @@ -59,22 +61,39 @@ HWTEST_F(CmdsUnitTest, TestCmdExecByName, TestSize.Level1) DoCmdByName("reboot ", ""); DoCmdByName("ifup ", "lo"); DoCmdByName("mknode ", "/dev/null b 0666 1 3"); + DoCmdByName("mknode ", "/dev/null C 0666 1 3"); + DoCmdByName("mknode ", "/dev/null F 0666 1 3"); + DoCmdByName("mknode ", "/dev/null A 0666 1 3"); DoCmdByName("makedev ", "999 999"); DoCmdByName("mount_fstab ", ""); DoCmdByName("umount_fstab ", ""); + DoCmdByName("mksandbox ", "system chipset"); DoCmdByName("mksandbox ", "system"); + DoCmdByName("mksandbox ", "notsupport"); + DoCmdByName("mksandbox ", ""); +} +HWTEST_F(CmdsUnitTest, TestCmdExecByName1, TestSize.Level1) +{ DoCmdByName("timer_start ", "media_service|5000"); DoCmdByName("timer_stop ", "media_service"); DoCmdByName("exec ", "media_service"); DoCmdByName("load_access_token_id ", "media_service"); - DoCmdByName("stopAllServices ", ""); + DoCmdByName("stopAllServices ", "true"); DoCmdByName("umount ", ""); DoCmdByName("mount ", ""); - DoCmdByName("init_global_key ", ""); + DoCmdByName("mount ", "ext4 /dev/block/platform/soc/10100000.himci.eMMC/by-name/vendor " + "/data wait filecrypt=555"); + DoCmdByName("init_global_key ", "/data"); + DoCmdByName("init_global_key ", "arg0 arg1"); DoCmdByName("init_main_user ", "testUser"); + DoCmdByName("init_main_user ", nullptr); DoCmdByName("mkswap ", ""); DoCmdByName("swapon ", ""); DoCmdByName("sync ", ""); + DoCmdByName("restorecon ", ""); + DoCmdByName("suspend ", ""); + DoCmdByName("wait ", "1"); + DoCmdByName("wait ", "aaa 1"); } HWTEST_F(CmdsUnitTest, TestCommonMkdir, TestSize.Level1) @@ -216,6 +235,7 @@ HWTEST_F(CmdsUnitTest, TestDoCmdByIndex, TestSize.Level1) const int execPos = 17; DoCmdByIndex(execPos, "sleep 1"); + DoCmdByIndex(23, "test"); // 23 is cmd index } HWTEST_F(CmdsUnitTest, TestGetCmdLinesFromJson, TestSize.Level1) @@ -246,4 +266,11 @@ HWTEST_F(CmdsUnitTest, TestGetCmdLinesFromJson, TestSize.Level1) free(cmdLines); cmdLines = nullptr; } +HWTEST_F(CmdsUnitTest, TestInitCmdFunc, TestSize.Level1) +{ + FileCryptEnable((char *)"test"); + FileCryptEnable(nullptr); + int ret = GetBootModeFromMisc(); + EXPECT_EQ(ret, 0); +} } // namespace init_ut diff --git a/test/unittest/init/group_unittest.cpp b/test/unittest/init/group_unittest.cpp index dd855bb70e21d76fade09b91303f723ebee0b6e9..a4efe27cafb4b75fd757ff5a611114cd53bbbcc0 100644 --- a/test/unittest/init/group_unittest.cpp +++ b/test/unittest/init/group_unittest.cpp @@ -12,12 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include #include "init_cmds.h" #include "init_group_manager.h" #include "init_hashmap.h" #include "init_param.h" #include "init_service_manager.h" #include "init_utils.h" +#include "init_unittest.h" #include "le_timer.h" #include "param_stub.h" #include "securec.h" @@ -199,7 +201,11 @@ HWTEST_F(InitGroupManagerUnitTest, TestInitGroupMgrInit, TestSize.Level1) InitWorkspace *workspace = GetInitWorkspace(); EXPECT_EQ(workspace->groupMode, GROUP_CHARING); workspace->groupMode = GROUP_BOOT; + if (strcpy_s(workspace->groupModeStr, GROUP_NAME_MAX_LENGTH, "device.boot.group") != EOK) { + EXPECT_EQ(1, 0); + } // test read cfgfile int ret = InitParseGroupCfg(); + StartAllServices(GROUP_CHARING); EXPECT_EQ(ret, 0); } @@ -340,17 +346,56 @@ HWTEST_F(InitGroupManagerUnitTest, TestParseServiceCpucore, TestSize.Level1) { const char *jsonStr = "{\"services\":{\"name\":\"test_service22\",\"path\":[\"/data/init_ut/test_service\"]," "\"importance\":-20,\"uid\":\"root\",\"writepid\":[\"/dev/test_service\"],\"console\":1," - "\"gid\":[\"root\"], \"cpucore\":[5, 2, 4, 1, 2, 0, 1]}}"; + "\"gid\":[\"root\"], \"cpucore\":[5, 2, 4, 1, 2, 0, 1], \"critical\":[1]}}"; cJSON* jobItem = cJSON_Parse(jsonStr); ASSERT_NE(nullptr, jobItem); cJSON *serviceItem = cJSON_GetObjectItem(jobItem, "services"); ASSERT_NE(nullptr, serviceItem); Service *service = AddService("test_service22"); + const int invalidImportantValue = 20; + SetImportantValue(service, "", invalidImportantValue, 1); if (service != nullptr) { int ret = ParseOneService(serviceItem, service); + GetAccessToken(); + DoCmdByName("timer_start ", "test_service22|5000"); + DoCmdByName("timer_start ", "test_service22|aa"); + DoCmdByName("timer_start ", ""); EXPECT_EQ(ret, 0); + StartServiceByName("test_service22|path"); ReleaseService(service); } cJSON_Delete(jobItem); } +HWTEST_F(InitGroupManagerUnitTest, TestNodeFree, TestSize.Level1) +{ + DoCmdByName("stopAllServices ", ""); +} +HWTEST_F(InitGroupManagerUnitTest, TestUpdaterServiceFds, TestSize.Level1) +{ + Service *service = AddService("test_service8"); + ASSERT_NE(nullptr, service); + int *fds = (int *)malloc(sizeof(int) * 1); // ServiceStop will release fds + UpdaterServiceFds(nullptr, nullptr, 0); + UpdaterServiceFds(service, fds, 1); + UpdaterServiceFds(service, fds, 0); + UpdaterServiceFds(service, fds, 1); + UpdaterServiceFds(service, nullptr, 1); + UpdaterServiceFds(service, fds, 1); + int ret = UpdaterServiceFds(service, nullptr, 2); // 2 is fd num + ASSERT_NE(ret, 0); + service->attribute = SERVICE_ATTR_TIMERSTART; + ServiceStartTimer(service, 0); +} +HWTEST_F(InitGroupManagerUnitTest, TestProcessWatchEvent, TestSize.Level1) +{ + Service *service = AddService("test_service9"); + ASSERT_NE(nullptr, service); + ServiceSocket servercfg = {.next = nullptr, .sockFd = 0}; + service->socketCfg = &servercfg; + ServiceWatcher watcher; + int ret = SocketAddWatcher(&watcher, service, 0); + ASSERT_EQ(ret, 0); + uint32_t event; + ((WatcherTask *)watcher)->processEvent((WatcherHandle)watcher, 0, &event, service); +} } // namespace init_ut diff --git a/test/unittest/init/init_reboot_unittest.cpp b/test/unittest/init/init_reboot_unittest.cpp index d75d1a7c91d77135b13347b64f9e6a335cdfbac0..d7dd7d0b05b194358c12ecadb61ad705315593b6 100644 --- a/test/unittest/init/init_reboot_unittest.cpp +++ b/test/unittest/init/init_reboot_unittest.cpp @@ -40,11 +40,17 @@ HWTEST_F(InitRebootUnitTest, TestInitReboot, TestSize.Level1) ExecReboot("reboot,bootloader"); ExecReboot("reboot,updater:123"); ExecReboot("reboot,flash:123"); + ExecReboot("reboot,flashd:123"); + ExecReboot("reboot,suspend:123"); const char *option = nullptr; int ret = DoReboot(option); EXPECT_EQ(ret, 0); option = "updater"; ret = DoReboot(option); EXPECT_EQ(ret, 0); + ret = DoReboot(DEVICE_CMD_SUSPEND); + EXPECT_EQ(ret, 0); + ret = DoReboot(DEVICE_CMD_FREEZE); + EXPECT_EQ(ret, 0); } } // namespace init_ut diff --git a/test/unittest/init/loopevent_unittest.cpp b/test/unittest/init/loopevent_unittest.cpp index 2143b0c450a40f7c09950c1b2964e673a834cbf3..f668be0e910697d7e8a98863cda336048cfb0ee2 100644 --- a/test/unittest/init/loopevent_unittest.cpp +++ b/test/unittest/init/loopevent_unittest.cpp @@ -34,16 +34,9 @@ using namespace testing::ext; using namespace std; -using HashTab = struct { - HashNodeCompare nodeCompare; - HashKeyCompare keyCompare; - HashNodeFunction nodeHash; - HashKeyFunction keyHash; - HashNodeOnFree nodeFree; - int maxBucket; - uint32_t tableId; - HashNode *buckets[0]; -}; +extern "C" { +void OnClose(ParamTaskPtr client); +} static void OnReceiveRequest(const TaskHandle task, const uint8_t *buffer, uint32_t nread) { @@ -52,12 +45,6 @@ static void OnReceiveRequest(const TaskHandle task, const uint8_t *buffer, uint3 UNUSED(nread); } -static void Close(ParamTaskPtr client) -{ - (void)(client); - return; -} - static void ProcessAsyncEvent(const TaskHandle taskHandle, uint64_t eventId, const uint8_t *buffer, uint32_t buffLen) { UNUSED(taskHandle); @@ -81,11 +68,10 @@ static void ProcessWatchEventTest(WatcherHandle taskHandle, int fd, uint32_t *ev UNUSED(context); } -static EventLoop *g_testLoop = nullptr; - static void *RunLoopThread(void *arg) { - LE_RunLoop((LoopHandle)g_testLoop); + UNUSED(arg); + StartParamService(); return nullptr; } @@ -99,6 +85,16 @@ public: void SetUp() {}; void TearDown() {}; void TestBody(void) {}; + int CreateServerTask() + { + CheckTaskFlags(nullptr, Event_Write); + ParamStreamInfo info = {}; + info.server = const_cast(PIPE_NAME); + info.close = NULL; + info.recvMessage = NULL; + info.incomingConnect = OnIncomingConnect; + return ParamServerCreate(&serverTask_, &info); + } void StreamTaskTest () { LE_StreamInfo streamInfo = {}; @@ -117,8 +113,6 @@ public: ((StreamConnectTask *)clientTaskHandle)->stream.base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)clientTaskHandle, 0); - ((HashTab *)((EventLoop *)LE_GetDefaultLoop())->taskMap)->nodeFree( - &((BaseTask *)(&clientTaskHandle))->hashNode); streamInfo.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_SERVER; streamInfo.server = (char *)"/data/testpipeb"; @@ -153,7 +147,7 @@ public: LE_StreamServerInfo info = {}; info.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_SERVER | TASK_TEST; info.server = (char *)"/data/testpipe"; - info.baseInfo.close = Close; + info.baseInfo.close = OnClose; info.incommingConntect = IncomingConnect; LE_CreateStreamServer(LE_GetDefaultLoop(), &serverTask_, &info); if (serverTask_ == nullptr) { @@ -166,7 +160,7 @@ public: ParamStreamInfo paramStreamInfo = {}; paramStreamInfo.flags = PARAM_TEST_FLAGS; paramStreamInfo.server = NULL; - paramStreamInfo.close = Close; + paramStreamInfo.close = OnClose; paramStreamInfo.recvMessage = ProcessMessage; paramStreamInfo.incomingConnect = NULL; ParamTaskPtr client = NULL; @@ -178,16 +172,20 @@ public: AddBuffer((StreamTask *)client, buffer); ((StreamConnectTask *)client)->stream.base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)(&client), Event_Write); + ParamMessage *request = (ParamMessage *)CreateParamMessage(MSG_SET_PARAM, "name", sizeof(ParamMessage)); + ((StreamConnectTask *)client)->recvMessage(LE_GetDefaultLoop(), reinterpret_cast(request), + sizeof(ParamMessage)); + LE_Buffer *next = nullptr; LE_Buffer *nextBuff = GetNextBuffer((StreamTask *)client, next); if (nextBuff != nullptr) { LE_FreeBuffer(LE_GetDefaultLoop(), (TaskHandle)&client, nextBuff); } - - ret = ParamStreamCreate(&client, serverTask_, ¶mStreamInfo, sizeof(ParamWatcher)); - PARAM_CHECK(ret == 0, return, "Failed to create client"); - ((StreamConnectTask *)(&client))->stream.base.handleEvent(LE_GetDefaultLoop(), - (TaskHandle)(&client), Event_Read); + ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client); + PARAM_CHECK(watcher != nullptr, return, "Failed to get watcher"); + ListInit(&watcher->triggerHead); + OnClose(client); + return; } void ProcessEventTest() { @@ -217,23 +215,30 @@ public: return; } ((WatcherTask *)handle)->base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)handle, Event_Read); + ((WatcherTask *)handle)->base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)handle, 0); + ((WatcherTask *)handle)->base.flags = WATCHER_ONCE; + ((WatcherTask *)handle)->base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)handle, Event_Read); } void CreateSocketTest() { - ParamTaskPtr clientTask = nullptr; + ParamTaskPtr serverTask = nullptr; LE_StreamServerInfo info = {}; info.baseInfo.flags = TASK_PIPE | TASK_CONNECT | TASK_TEST; info.server = (char *)"/data/testpipe"; - info.baseInfo.close = Close; + info.baseInfo.close = OnClose; info.incommingConntect = IncomingConnect; - LE_CreateStreamServer(LE_GetDefaultLoop(), &clientTask, &info); - EXPECT_NE(clientTask, nullptr); - if (clientTask == nullptr) { + info.socketId = 1111; // 1111 is test fd + LE_CreateStreamServer(LE_GetDefaultLoop(), &serverTask, &info); + EXPECT_NE(serverTask, nullptr); + if (serverTask == nullptr) { return; } - LE_GetSocketFd(clientTask); + ((StreamServerTask *)serverTask)->base.taskId.fd = -1; + OnIncomingConnect(LE_GetDefaultLoop(), serverTask); + LE_GetSocketFd(serverTask); AcceptSocket(-1, TASK_PIPE); AcceptSocket(-1, TASK_TCP); + AcceptSocket(-1, TASK_TEST); } private: @@ -243,6 +248,7 @@ private: HWTEST_F(LoopEventUnittest, StreamTaskTest, TestSize.Level1) { LoopEventUnittest loopevtest = LoopEventUnittest(); + loopevtest.CreateServerTask(); loopevtest.StreamTaskTest(); } @@ -273,19 +279,20 @@ HWTEST_F(LoopEventUnittest, ProcessWatcherTask, TestSize.Level1) } HWTEST_F(LoopEventUnittest, RunLoopThread, TestSize.Level1) { + InitParamService(); pthread_t tid = 0; int fd = eventfd(1, EFD_NONBLOCK | EFD_CLOEXEC); - LE_CreateLoop((LoopHandle *)&g_testLoop); - EventEpoll *epoll = (EventEpoll *)g_testLoop; struct epoll_event event = {}; event.events = EPOLLIN; if (fd >= 0) { - epoll_ctl(epoll->epollFd, EPOLL_CTL_ADD, fd, &event); + epoll_ctl(((EventEpoll *)LE_GetDefaultLoop())->epollFd, EPOLL_CTL_ADD, fd, &event); } pthread_create(&tid, nullptr, RunLoopThread, nullptr); - LE_StopLoop((LoopHandle)g_testLoop); event.events = EPOLLOUT; - epoll_ctl(epoll->epollFd, EPOLL_CTL_MOD, fd, &event); + epoll_ctl(((EventEpoll *)LE_GetDefaultLoop())->epollFd, EPOLL_CTL_ADD, fd, &event); + ((EventLoop *)LE_GetDefaultLoop())->taskMap = nullptr; + StopParamService(); pthread_join(tid, nullptr); + InitParamService(); } } // namespace init_ut diff --git a/test/unittest/init/mount_unittest.cpp b/test/unittest/init/mount_unittest.cpp index cad55674a422d1213ca8c7dbd898b3a87fd6c60e..9a96523404be3ae7f478ffacfc7ded56afbdbb3f 100644 --- a/test/unittest/init/mount_unittest.cpp +++ b/test/unittest/init/mount_unittest.cpp @@ -14,9 +14,11 @@ */ #include #include +#include #include "fs_manager/fs_manager.h" #include "param_stub.h" #include "init_mount.h" +#include "init.h" #include "securec.h" using namespace std; using namespace testing::ext; @@ -39,6 +41,37 @@ HWTEST_F(MountUnitTest, TestMountRequriedPartitions, TestSize.Level0) int ret = MountRequriedPartitions(fstab); EXPECT_EQ(ret, -1); ReleaseFstab(fstab); + } else { + Fstab fstab1; + fstab1.head = nullptr; + int ret = MountRequriedPartitions(&fstab1); + EXPECT_EQ(ret, -1); + } +} +HWTEST_F(MountUnitTest, TestGetBlockDevicePath, TestSize.Level1) +{ + char path[20] = {0}; // 20 is path length + int fd = open("/bin/updater", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRWXU); + if (fd < 0) { + return; } + GetBlockDevicePath(nullptr, nullptr, 0); + GetBlockDevicePath(nullptr, path, sizeof(path)); + close(fd); + ReadConfig(); + unlink("/bin/updater"); + ReadConfig(); + int ret = GetBlockDeviceByMountPoint(nullptr, nullptr, nullptr, 0); + EXPECT_EQ(ret, -1); + FstabItem fstabitem = {(char *)"deviceName", (char *)"mountPoint", + (char *)"fsType", (char *)"mountOptions", 1, nullptr}; + Fstab fstab = {&fstabitem}; + char devicename[20]; // 20 is devicename length + ret = GetBlockDeviceByMountPoint("notmountpoint", &fstab, devicename, sizeof(devicename)); + EXPECT_EQ(ret, -1); + ret = GetBlockDeviceByMountPoint("mountPoint", &fstab, devicename, 0); + EXPECT_EQ(ret, -1); + ret = GetBlockDeviceByMountPoint("mountPoint", &fstab, devicename, sizeof(devicename)); + EXPECT_EQ(ret, 0); } } // namespace init_ut diff --git a/test/unittest/init/plugin_unittest.cpp b/test/unittest/init/plugin_unittest.cpp index 906d43b1f6f79a670dd18236370ac07f007e2d4e..facdf7fb8ed4fe3a399c270f182d3208dcb87576 100755 --- a/test/unittest/init/plugin_unittest.cpp +++ b/test/unittest/init/plugin_unittest.cpp @@ -69,6 +69,9 @@ HWTEST_F(PluginUnitTest, PluginAddCmd, TestSize.Level1) g_cmdExecId = -1; PluginExecCmdByCmdIndex(cmdIndex, cmdContent); ASSERT_EQ(cmdExecId1, g_cmdExecId); + const char *argv[] = {"test"}; + PluginExecCmd("install", 1, argv); + PluginExecCmd("uninstall", 1, argv); // del RemoveCmdExecutor("testCmd4", cmdExecId4); diff --git a/test/unittest/init/service_file_unittest.cpp b/test/unittest/init/service_file_unittest.cpp index 9e640c5b78c9536284d353fe2c287d3159c62db0..be40eebead790b49bd7705fde127a6d2ba667f05 100644 --- a/test/unittest/init/service_file_unittest.cpp +++ b/test/unittest/init/service_file_unittest.cpp @@ -54,6 +54,13 @@ HWTEST_F(ServiceFileUnitTest, TestServiceFile, TestSize.Level1) CreateServiceFile(fileOpt); int ret = GetControlFile("/data/filetest"); EXPECT_NE(ret, -1); + if (strncpy_s(fileOpt->fileName, strlen(fileName) + 1, "fileName", strlen("fileName")) != 0) { + free(fileOpt); + fileOpt = nullptr; + FAIL(); + } + fileOpt->fd = 100; // 100 is fd + CreateServiceFile(fileOpt); CloseServiceFile(fileOpt); free(fileOpt); fileOpt = nullptr; diff --git a/test/unittest/init/service_unittest.cpp b/test/unittest/init/service_unittest.cpp index 9ca7158760e87809b7cfde51f163e5d9f6f16de0..9ce8f1d0be794859954bfd74931a7e90c602ccaa 100644 --- a/test/unittest/init/service_unittest.cpp +++ b/test/unittest/init/service_unittest.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include "init_cmds.h" #include "init_service.h" #include "init_service_manager.h" @@ -23,10 +24,15 @@ #include "param_stub.h" #include "init_utils.h" #include "securec.h" +#include "init_group_manager.h" using namespace testing::ext; using namespace std; +extern "C" { +void ClientDeinit(void); +} + namespace init_ut { class ServiceUnitTest : public testing::Test { public: @@ -49,7 +55,7 @@ HWTEST_F(ServiceUnitTest, case01, TestSize.Level1) { const char *jsonStr = "{\"services\":{\"name\":\"test_service\",\"path\":[\"/data/init_ut/test_service\"]," "\"importance\":-20,\"uid\":\"system\",\"writepid\":[\"/dev/test_service\"],\"console\":1," - "\"gid\":[\"system\"]}}"; + "\"gid\":[\"system\"], \"critical\":1}}"; cJSON* jobItem = cJSON_Parse(jsonStr); ASSERT_NE(nullptr, jobItem); cJSON *serviceItem = cJSON_GetObjectItem(jobItem, "services"); @@ -67,6 +73,46 @@ HWTEST_F(ServiceUnitTest, case01, TestSize.Level1) ReleaseService(service); } +HWTEST_F(ServiceUnitTest, case02, TestSize.Level1) +{ + const char *jsonStr = "{\"services\":{\"name\":\"test_service8\",\"path\":[\"/data/init_ut/test_service\"]," + "\"importance\":-20,\"uid\":\"system\",\"writepid\":[\"/dev/test_service\"],\"console\":1," + "\"gid\":[\"system\"],\"caps\":[10, 4294967295, 10000],\"cpucore\":[1]}}"; + cJSON* jobItem = cJSON_Parse(jsonStr); + ASSERT_NE(nullptr, jobItem); + cJSON *serviceItem = cJSON_GetObjectItem(jobItem, "services"); + ASSERT_NE(nullptr, serviceItem); + Service *service = AddService("test_service8"); + int ret = ParseOneService(serviceItem, service); + EXPECT_EQ(ret, 0); + + int *fds = (int *)malloc(sizeof(int) * 1); // ServiceStop will release fds + UpdaterServiceFds(service, fds, 1); + service->attribute = SERVICE_ATTR_ONDEMAND; + ret = ServiceStart(service); + EXPECT_EQ(ret, 0); + CmdLines *cmdline = (CmdLines *)malloc(sizeof(CmdLines) + sizeof(CmdLine)); + cmdline->cmdNum = 1; + cmdline->cmds[0].cmdIndex = 0; + service->restartArg = cmdline; + ServiceSocket tmpSock = { .next = nullptr, .sockFd = 0 }; + ServiceSocket tmpSock1 = { .next = &tmpSock, .sockFd = 0 }; + service->socketCfg = &tmpSock1; + ServiceReap(service); + service->socketCfg = nullptr; + service->attribute &= SERVICE_ATTR_NEED_RESTART; + service->firstCrashTime = 0; + ServiceReap(service); + DoCmdByName("reset ", "test_service8"); + // reset again + DoCmdByName("reset ", "test_service8"); + service->pid = 0xfffffff; // 0xfffffff is not exist pid + service->attribute = SERVICE_ATTR_TIMERSTART; + ret = ServiceStop(service); + EXPECT_NE(ret, 0); + ReleaseService(service); +} + HWTEST_F(ServiceUnitTest, TestServiceStartAbnormal, TestSize.Level1) { const char *jsonStr = "{\"services\":{\"name\":\"test_service1\",\"path\":[\"/data/init_ut/test_service\"]," @@ -102,8 +148,10 @@ HWTEST_F(ServiceUnitTest, TestServiceReap, TestSize.Level1) { Service *service = AddService("test_service2"); ASSERT_NE(nullptr, service); - ServiceReap(service); EXPECT_EQ(service->attribute, 0); + service->attribute = SERVICE_ATTR_ONDEMAND; + ServiceReap(service); + service->attribute = 0; service->restartArg = (CmdLines *)calloc(1, sizeof(CmdLines)); ASSERT_NE(nullptr, service->restartArg); @@ -119,6 +167,9 @@ HWTEST_F(ServiceUnitTest, TestServiceReap, TestSize.Level1) ServiceReap(service); EXPECT_EQ(service->attribute, SERVICE_ATTR_ONCE); + service->attribute = SERVICE_ATTR_CRITICAL; + service->crashCount = 1; + ServiceReap(service); ReleaseService(service); } @@ -189,6 +240,28 @@ HWTEST_F(ServiceUnitTest, TestServiceManagerGetService, TestSize.Level1) Service *service = GetServiceByPid(1); StopAllServices(1, nullptr, 0, nullptr); EXPECT_TRUE(service == nullptr); + const char *jsonStr = "{\"services\":{\"name\":\"test_service2\",\"path\":[\"/data/init_ut/test_service\"]," + "\"importance\":-20,\"uid\":\"system\",\"writepid\":[\"/dev/test_service\"],\"console\":1," + "\"gid\":[\"system\"], \"critical\":[1,2]}}"; + cJSON* jobItem = cJSON_Parse(jsonStr); + ASSERT_NE(nullptr, jobItem); + cJSON *serviceItem = cJSON_GetObjectItem(jobItem, "services"); + ASSERT_NE(nullptr, serviceItem); + service = AddService("test_service2"); + ASSERT_NE(nullptr, service); + int ret = ParseOneService(serviceItem, service); + EXPECT_NE(ret, 0); + const char *jsonStr1 = "{\"services\":{\"name\":\"test_service3\",\"path\":[\"/data/init_ut/test_service\"]," + "\"importance\":-20,\"uid\":\"system\",\"writepid\":[\"/dev/test_service\"],\"console\":1," + "\"gid\":[\"system\"], \"critical\":[\"on\"]}}"; + jobItem = cJSON_Parse(jsonStr1); + ASSERT_NE(nullptr, jobItem); + serviceItem = cJSON_GetObjectItem(jobItem, "services"); + ASSERT_NE(nullptr, serviceItem); + service = AddService("test_service3"); + ASSERT_NE(nullptr, service); + ret = ParseOneService(serviceItem, service); + EXPECT_NE(ret, 0); } HWTEST_F(ServiceUnitTest, TestServiceExec, TestSize.Level1) @@ -211,4 +284,9 @@ HWTEST_F(ServiceUnitTest, TestServiceExec, TestSize.Level1) EXPECT_EQ(ret, -1); ReleaseService(service); } +HWTEST_F(ServiceUnitTest, TestClientDeinit, TestSize.Level1) +{ + ClientDeinit(); + HashMapDestory(GetInitWorkspace()->hashMap[0]); +} } // namespace init_ut diff --git a/test/unittest/init/utils_unittest.cpp b/test/unittest/init/utils_unittest.cpp index c131340f80e8fc5fe78574656fe9bf63a29cedad..9176282fc5655840a756b05750fe636c58d5ae1c 100644 --- a/test/unittest/init/utils_unittest.cpp +++ b/test/unittest/init/utils_unittest.cpp @@ -23,6 +23,10 @@ using namespace std; using namespace testing::ext; +extern "C" { +float ConvertMicrosecondToSecond(int x); +} + namespace init_ut { class UtilsUnitTest : public testing::Test { public: @@ -61,4 +65,9 @@ HWTEST_F(UtilsUnitTest, TestString, TestSize.Level0) EXPECT_EQ(ret, 0); EXPECT_STREQ(rStr, "dbc"); } +HWTEST_F(UtilsUnitTest, TestConvertMicrosecondToSecond, TestSize.Level0) +{ + float sec = ConvertMicrosecondToSecond(1000000); // 1000000 microseconds + EXPECT_EQ(sec, 1); +} } // namespace init_ut diff --git a/test/unittest/innerkits/innerkits_unittest.cpp b/test/unittest/innerkits/innerkits_unittest.cpp index 03d1124e216b1b5a92df9bc43901cc37c57f5948..286799b5787e4ee50bd3f0d19f33a85fba301f76 100644 --- a/test/unittest/innerkits/innerkits_unittest.cpp +++ b/test/unittest/innerkits/innerkits_unittest.cpp @@ -41,24 +41,13 @@ HWTEST_F(InnerkitsUnitTest, ReadFstabFromFile_unitest, TestSize.Level1) const std::string fstabFile2 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable"; fstab = ReadFstabFromFile(fstabFile2.c_str(), false); EXPECT_NE(fstab, nullptr); - const std::string fstabFile3 = "/data/init_ut/mount_unitest/ReadFstabFromFile2.fstable"; - fstab = ReadFstabFromFile(fstabFile3.c_str(), false); - EXPECT_NE(fstab, nullptr); - const std::string fstabFile4 = "/data/init_ut/mount_unitest/ReadFstabFromFile3.fstable"; - fstab = ReadFstabFromFile(fstabFile4.c_str(), false); - EXPECT_NE(fstab, nullptr); - const std::string fstabFile5 = "/data/init_ut/mount_unitest/ReadFstabFromFile4.fstable"; - fstab = ReadFstabFromFile(fstabFile5.c_str(), false); - EXPECT_NE(fstab, nullptr); - const std::string fstabFile6 = "/data/init_ut/mount_unitest/ReadFstabFromFile5.fstable"; - fstab = ReadFstabFromFile(fstabFile6.c_str(), false); - EXPECT_NE(fstab, nullptr); + ParseFstabPerLine(const_cast("test"), fstab, true, nullptr); ReleaseFstab(fstab); } HWTEST_F(InnerkitsUnitTest, FindFstabItemForPath_unitest, TestSize.Level1) { - const std::string fstabFile1 = "/data/init_ut/mount_unitest/FindFstabItemForPath1.fstable"; + const std::string fstabFile1 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable"; Fstab *fstab = nullptr; fstab = ReadFstabFromFile(fstabFile1.c_str(), false); ASSERT_NE(fstab, nullptr); @@ -89,7 +78,7 @@ HWTEST_F(InnerkitsUnitTest, FindFstabItemForPath_unitest, TestSize.Level1) HWTEST_F(InnerkitsUnitTest, FindFstabItemForMountPoint_unitest, TestSize.Level1) { - const std::string fstabFile1 = "/data/init_ut/mount_unitest/FindFstabItemForMountPoint1.fstable"; + const std::string fstabFile1 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable"; Fstab *fstab = nullptr; fstab = ReadFstabFromFile(fstabFile1.c_str(), false); ASSERT_NE(fstab, nullptr); @@ -111,9 +100,9 @@ HWTEST_F(InnerkitsUnitTest, FindFstabItemForMountPoint_unitest, TestSize.Level1) HWTEST_F(InnerkitsUnitTest, GetMountFlags_unitest, TestSize.Level1) { - const std::string fstabFile1 = "/data/init_ut/mount_unitest/GetMountFlags1.fstable"; + const std::string fstabFile1 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable"; Fstab *fstab = nullptr; - fstab = ReadFstabFromFile(fstabFile1.c_str(), false); + fstab = ReadFstabFromFile(fstabFile1.c_str(), true); ASSERT_NE(fstab, nullptr); struct FstabItem* item = nullptr; const std::string mp = "/hos"; diff --git a/test/unittest/param/client_unittest.cpp b/test/unittest/param/client_unittest.cpp index e3152e176ddef0c703ea215cb4d598e4fbadc941..9411210a2d54869cc2decddfd30a41e55096b5e6 100644 --- a/test/unittest/param/client_unittest.cpp +++ b/test/unittest/param/client_unittest.cpp @@ -115,7 +115,11 @@ static void TestPermission() if ((GetParamSecurityLabel() != nullptr)) { GetParamSecurityLabel()->flags[0] = LABEL_CHECK_IN_ALL_PROCESS; ret = SystemSetParameter(testName, "22202"); +#ifdef PARAM_SUPPORT_SELINUX + EXPECT_EQ(ret, 0); +#else EXPECT_EQ(ret, DAC_RESULT_FORBIDED); +#endif } paramSecurityOps->securityFreeLabel = TestFreeLocalSecurityLabel; paramSecurityOps->securityCheckParamPermission = TestCheckParamPermission; @@ -126,13 +130,17 @@ static void TestPermission() const int testResult = 201; SetTestPermissionResult(testResult); - // 禁止写/读 ret = SystemSetParameter(testName, "3333"); +#ifdef PARAM_SUPPORT_SELINUX + EXPECT_EQ(ret, 0); +#else EXPECT_EQ(ret, testResult); +#endif u_int32_t len = sizeof(tmp); ret = SystemGetParameter(testName, tmp, &len); EXPECT_EQ(ret, testResult); RegisterSecurityOps(0); + SetTestPermissionResult(0); // recover testpermission result } void TestClientApi(char testBuffer[], uint32_t size, const char *name, const char *value) @@ -219,6 +227,6 @@ HWTEST_F(ClientUnitTest, TestClient_04, TestSize.Level0) HWTEST_F(ClientUnitTest, TestClient_05, TestSize.Level0) { - TestForMultiThread(); + // TestForMultiThread } } // namespace init_ut \ No newline at end of file diff --git a/test/unittest/param/param_shell_unittest.cpp b/test/unittest/param/param_shell_unittest.cpp index f3fb26cb7eff5ff8dd59115a23a4170ac28f9f9a..36eac5fa8000c321fc5e9ae028ba0cb08012f59c 100644 --- a/test/unittest/param/param_shell_unittest.cpp +++ b/test/unittest/param/param_shell_unittest.cpp @@ -19,6 +19,7 @@ #include "shell.h" #include "shell_utils.h" #include "shell_bas.h" +#include "init_param.h" using namespace std; using namespace testing::ext; @@ -35,18 +36,28 @@ public: void TestBody(void) {}; void TestInitParamShell() { + SystemSetParameter("aaa", "aaa"); BShellHandle bshd = GetShellHandle(); if (bshd == nullptr) { return; } const char *args[] = {"paramshell", "\n"}; const ParamInfo *param = BShellEnvGetReservedParam(bshd, PARAM_REVERESD_NAME_CURR_PARAMETER); - int ret = BShellEnvSetParam(bshd, param->name, param->desc, param->type, (void *)""); + int ret = BShellEnvSetParam(bshd, PARAM_REVERESD_NAME_CURR_PARAMETER, "..a", PARAM_STRING, (void *)"..a"); EXPECT_EQ(ret, 0); SetParamShellPrompt(bshd, args[1]); + SetParamShellPrompt(bshd, ".."); + + ret = BShellEnvSetParam(bshd, param->name, param->desc, param->type, (void *)""); + SetParamShellPrompt(bshd, ".."); + + SetParamShellPrompt(bshd, ".a"); + SetParamShellPrompt(bshd, "."); + SetParamShellPrompt(bshd, args[1]); BShellParamCmdRegister(bshd, 1); BShellEnvStart(bshd); ret = BShellEnvOutputPrompt(bshd, "testprompt"); + ret = BShellEnvOutputPrompt(bshd, "testprompt1111111111111111111111111111111111111111111111111111111111"); BShellEnvOutputByte(bshd, 'o'); EXPECT_EQ(ret, 0); } @@ -133,6 +144,7 @@ public: void TestParamShellcmdEndkey() { BShellHandle bshd = GetShellHandle(); + bshd->input(nullptr, 0); BShellKey *key = BShellEnvGetDefaultKey('\b'); EXPECT_NE(key, nullptr); if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "testbbackspace") != EOK) { @@ -159,6 +171,11 @@ public: EXPECT_NE(key, nullptr); BShellEnvProcessInput(bshd, (char)3); // 3 is ctrl c BShellEnvProcessInput(bshd, '\e'); + BShellEnvProcessInput(bshd, '['); + bshd->length = 1; + bshd->cursor = 1; + BShellEnvProcessInput(bshd, 'C'); + BShellEnvProcessInput(bshd, 'D'); } }; @@ -190,9 +207,12 @@ HWTEST_F(ParamShellUnitTest, TestParamShellInput, TestSize.Level1) } HWTEST_F(ParamShellUnitTest, TestParamShellcmd2, TestSize.Level1) { - BShellHandle bshd = GetShellHandle(); ParamShellUnitTest test; test.TestParamShellcmdEndkey(); - BShellEnvDestory(bshd); + GetSystemCommitId(); + BShellEnvLoop(nullptr); + BShellEnvErrString(GetShellHandle(), 1); + BShellEnvOutputResult(GetShellHandle(), 1); + demoExit(); } } // namespace init_ut diff --git a/test/unittest/param/param_stub.cpp b/test/unittest/param/param_stub.cpp index 55c6cbe7a16d32cfc91de64e24cb549bc5e31d36..b0a6aaf34d795b9a6f2679476a8e2c4d7353c52a 100755 --- a/test/unittest/param/param_stub.cpp +++ b/test/unittest/param/param_stub.cpp @@ -12,8 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "param_stub.h" +#include "param_stub.h" +#include #include "beget_ext.h" #include "init_param.h" #include "param_manager.h" @@ -87,7 +88,6 @@ static const char *forbitReadParamName[] = { "ohos.servicectrl.", // "test.permission.write", }; - static int TestReadParamCheck(const char *paraName) { // forbit to read ohos.servicectrl. @@ -98,7 +98,6 @@ static int TestReadParamCheck(const char *paraName) } return g_testPermissionResult; } - static void TestDestroyParamList(ParamContextsList **list) { #ifdef PARAM_SUPPORT_SELINUX @@ -112,7 +111,6 @@ static void TestDestroyParamList(ParamContextsList **list) } #endif } - static ParamContextsList *TestGetParamList(void) { #ifdef PARAM_SUPPORT_SELINUX @@ -149,7 +147,6 @@ void TestSetSelinuxOps(void) SetSelinuxOps(&space); #endif } - static void CreateTestFile(const char *fileName, const char *data) { CheckAndCreateDir(fileName); @@ -161,7 +158,88 @@ static void CreateTestFile(const char *fileName, const char *data) fclose(tmpFile); } } +static void PrepareUeventdcfg(void) +{ + const char *ueventdcfg = "[device]\n" + "/dev/test 0666 1000 1000\n" + "[device]\n" + "/dev/test1 0666 1000\n" + "[device]\n" + "/dev/test2 0666 1000 1000 1000 1000\n" + "[sysfs]\n" + "/dir/to/nothing attr_nowhere 0666 1000 1000\n" + "[sysfs]\n" + " #/dir/to/nothing attr_nowhere 0666\n" + "[sysfs\n" + "/dir/to/nothing attr_nowhere 0666\n" + "[firmware]\n" + "/etc\n" + "[device]\n" + "/dev/testbinder 0666 1000 1000 const.dev.binder\n" + "[device]\n" + "/dev/testbinder1 0666 1000 1000 const.dev.binder\n" + "[device]\n" + "/dev/testbinder2 0666 1000 1000 const.dev.binder\n" + "[device]\n" + "/dev/testbinder3 0666 1000 1000 const.dev.binder\n"; + mkdir("/data/ueventd_ut", S_IRWXU | S_IRWXG | S_IRWXO); + CreateTestFile("/data/ueventd_ut/valid.config", ueventdcfg); +} +static void PrepareModCfg(void) +{ + const char *modCfg = "testinsmod"; + CreateTestFile("/data/init_ut/test_insmod", modCfg); +} +static void PrepareInnerKitsCfg() +{ + const char *innerKitsCfg = "/dev/block/platform/soc/10100000.himci.eMMC/by-name/system /system " + "ext4 ro,barrier=1 wait\n" + "/dev/block/platform/soc/10100000.himci.eMMC/by-name/vendor /vendor " + "ext4 ro,barrier=1 wait\n" + "/dev/block/platform/soc/10100000.himci.eMMC/by-name/hos " + "/hos ntfs nosuid,nodev,noatime,barrier=1,data=ordered wait\n" + "/dev/block/platform/soc/10100000.himci.eMMC/by-name/userdata /data ext4 " + "nosuid,nodev,noatime,barrier=1,data=ordered,noauto_da_alloc " + "wait,reservedsize=104857600\n" + " aaaa\n" + "aa aa\n" + "aa aa aa\n" + "aa aa aa aa\n"; + mkdir("/data/init_ut/mount_unitest/", S_IRWXU | S_IRWXG | S_IRWXO); + CreateTestFile("/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable", innerKitsCfg); +} +static bool IsDir(const std::string &path) +{ + struct stat st {}; + if (stat(path.c_str(), &st) < 0) { + return false; + } + return S_ISDIR(st.st_mode); +} +static bool DeleteDir(const std::string &path) +{ + auto pDir = std::unique_ptr(opendir(path.c_str()), closedir); + if (pDir == nullptr) { + return false; + } + struct dirent *dp = nullptr; + while ((dp = readdir(pDir.get())) != nullptr) { + std::string currentName(dp->d_name); + if (currentName[0] != '.') { + std::string tmpName(path); + tmpName.append("/" + currentName); + if (IsDir(tmpName)) { + DeleteDir(tmpName); + } + remove(tmpName.c_str()); + } + } + if (remove(path.c_str()) != 0) { + return false; + } + return true; +} static void LoadParamFromCfg(void) { #ifdef PARAM_LOAD_CFG_FROM_CODE @@ -237,7 +315,10 @@ void PrepareInitUnitTestEnv(void) } PARAM_LOGI("PrepareInitUnitTestEnv"); mkdir(STARTUP_INIT_UT_PATH, S_IRWXU | S_IRWXG | S_IRWXO); - SetInitLogLevel(INIT_DEBUG); + PrepareUeventdcfg(); + PrepareInnerKitsCfg(); + PrepareModCfg(); + SetInitLogLevel(INIT_FATAL); #if !(defined __LITEOS_A__ || defined __LITEOS_M__) // for cmdline diff --git a/test/unittest/param/param_stub.h b/test/unittest/param/param_stub.h index f8d06d334b4bcead67addef7e0ee5933fdb918fd..56163a8c345b9a4567dcd97af594f77758b4d6f6 100644 --- a/test/unittest/param/param_stub.h +++ b/test/unittest/param/param_stub.h @@ -29,8 +29,6 @@ extern "C" { #endif #endif -#define TEST_PATH "/data/ueventd_ut" - void PrepareInitUnitTestEnv(void); void TestSetSelinuxOps(void); void SetTestPermissionResult(int result); diff --git a/test/unittest/param/paramservice_unittest.cpp b/test/unittest/param/paramservice_unittest.cpp index e93db79bb2ba9894ea3fea026fc05329364f1936..d2774b1fc1458c1370468db58bfce9b78300f63f 100755 --- a/test/unittest/param/paramservice_unittest.cpp +++ b/test/unittest/param/paramservice_unittest.cpp @@ -21,6 +21,9 @@ using namespace testing::ext; using namespace std; +extern "C" { +void OnClose(ParamTaskPtr client); +} static int CheckServerParamValue(const char *name, const char *expectValue) { char tmp[PARAM_BUFFER_SIZE] = {0}; @@ -44,8 +47,14 @@ public: static void SetUpTestCase(void) { PrepareInitUnitTestEnv(); - }; - void SetUp() {} + } + void SetUp() + { + if (GetParamSecurityLabel() != nullptr) { + GetParamSecurityLabel()->cred.uid = 1000; // 1000 test uid + GetParamSecurityLabel()->cred.gid = 1000; // 1000 test gid + } + } void TearDown() {} void TestBody() {} @@ -288,7 +297,7 @@ public: ParamStreamInfo info = {}; info.flags = PARAM_TEST_FLAGS; info.server = NULL; - info.close = NULL; + info.close = OnClose; info.recvMessage = ProcessMessage; info.incomingConnect = NULL; ParamTaskPtr client = NULL; @@ -327,7 +336,6 @@ public: ProcessMessage((const ParamTaskPtr)g_worker, (const ParamMessage *)request); } while (0); free(request); - CheckServerParamValue(name, value); RegisterSecurityOps(1); return 0; } @@ -502,7 +510,7 @@ HWTEST_F(ParamServiceUnitTest, TestServiceCtrl, TestSize.Level0) { ParamServiceUnitTest test; int ret = test.TestServiceCtrl("server1", 0770); - EXPECT_NE(ret, 0); + EXPECT_EQ(ret, 0); ret = test.TestServiceCtrl("server2", 0772); EXPECT_EQ(ret, 0); } @@ -511,19 +519,19 @@ HWTEST_F(ParamServiceUnitTest, TestPowerCtrl, TestSize.Level0) { ParamServiceUnitTest test; int ret = test.TestPowerCtrl("reboot,shutdown", 0770); - EXPECT_NE(ret, 0); + EXPECT_EQ(ret, 0); ret = test.TestPowerCtrl("reboot,shutdown", 0772); EXPECT_EQ(ret, 0); ret = test.TestPowerCtrl("reboot,updater", 0770); - EXPECT_NE(ret, 0); + EXPECT_EQ(ret, 0); ret = test.TestPowerCtrl("reboot,updater", 0772); EXPECT_EQ(ret, 0); ret = test.TestPowerCtrl("reboot,flash", 0770); - EXPECT_NE(ret, 0); + EXPECT_EQ(ret, 0); ret = test.TestPowerCtrl("reboot,flash", 0772); EXPECT_EQ(ret, 0); ret = test.TestPowerCtrl("reboot", 0770); - EXPECT_NE(ret, 0); + EXPECT_EQ(ret, 0); ret = test.TestPowerCtrl("reboot", 0772); EXPECT_EQ(ret, 0); } diff --git a/test/unittest/param/trigger_unittest.cpp b/test/unittest/param/trigger_unittest.cpp index e80912312af09e8f6c0abbd78ff91e49a5762e56..ff893b6f15f3eef3af263205af863865f893be0a 100644 --- a/test/unittest/param/trigger_unittest.cpp +++ b/test/unittest/param/trigger_unittest.cpp @@ -31,7 +31,13 @@ using namespace std; static const int triggerBuffer = 512; static uint32_t g_execCmdId = 0; static int g_matchTrigger = 0; -static char g_matchTriggerName[triggerBuffer] = {0}; +static char g_matchTriggerName[triggerBuffer] = { 0 }; +static void BootStateChange(const char *content) +{ + UNUSED(content); + return; +} + static int TestCmdExec(const TriggerNode *trigger, const char *content, uint32_t size) { PARAM_CHECK(trigger != NULL, return -1, "Invalid trigger"); @@ -127,8 +133,10 @@ public: int TestAddTriggerForParm() { const char *triggerName = "param:test_param.000"; + int id = 0; JobNode *node = AddTrigger(TRIGGER_PARAM, triggerName, "test_param.000=1", 0); JobNode *trigger = GetTriggerByName(GetTriggerWorkSpace(), triggerName); + GetTriggerHeader(TRIGGER_PARAM)->compareData(reinterpret_cast(trigger), &id); EXPECT_EQ(trigger, node); if (trigger == nullptr) { return -1; @@ -458,6 +466,8 @@ public: int TestDumpTrigger() { SystemDumpTriggers(1); + RegisterBootStateChange(BootStateChange); + (void)AddCompleteJob("param:ohos.servicectrl.display", "ohos.servicectrl.display=*", "display system"); return 0; } }; @@ -563,3 +573,8 @@ HWTEST_F(TriggerUnitTest, TestExecuteParamTrigger5, TestSize.Level0) TriggerUnitTest test; test.TestExecuteParamTrigger5(); } +HWTEST_F(TriggerUnitTest, TestExecuteParamTrigger6, TestSize.Level0) +{ + TriggerUnitTest test; + test.TestDumpTrigger(); +} diff --git a/test/unittest/param/watcher_agent_unittest.cpp b/test/unittest/param/watcher_agent_unittest.cpp index 9680d2ca5cc3df2d989937b0d410bcc2093d8014..3a1e132b4c1a4d89c9eaa5fffd46d74c3c8bd892 100644 --- a/test/unittest/param/watcher_agent_unittest.cpp +++ b/test/unittest/param/watcher_agent_unittest.cpp @@ -60,9 +60,8 @@ public: // 非法 ret = SystemWatchParameter("test.permission.watcher.tes^^^^t1*", TestParameterChange, nullptr); EXPECT_NE(ret, 0); - // 被禁止 ret = SystemWatchParameter("test.permission.read.test1*", TestParameterChange, nullptr); - EXPECT_NE(ret, 0); + EXPECT_EQ(ret, 0); return 0; } @@ -78,9 +77,8 @@ public: // 非法 ret = SystemWatchParameter("test.permission.watcher.tes^^^^t1*", nullptr, nullptr); EXPECT_NE(ret, 0); - // 被禁止 ret = SystemWatchParameter("test.permission.read.test1*", nullptr, nullptr); - EXPECT_NE(ret, 0); + EXPECT_EQ(ret, 0); return 0; } diff --git a/test/unittest/tools/prepare_testdata.sh b/test/unittest/tools/prepare_testdata.sh index ed3227d9ae0a3c270cb07e50e561c4c34731a3b5..f78c95b1f7b88a3442f932df8069077f94870bf3 100755 --- a/test/unittest/tools/prepare_testdata.sh +++ b/test/unittest/tools/prepare_testdata.sh @@ -54,41 +54,10 @@ hdc_shell_cmd "umask 022" hdc_shell_cmd "mkdir -p ${ut_target_path}" hdc_shell_cmd "mkdir -p ${ut_target_path}/proc" -function push_testdata_to_device() { - if [ $# -ne 2 ]; then - echo "Usage $0 module_path module_name" - return - fi - local module_path=$1 - local module_name=$2 - hdc_shell_cmd "mkdir -p ${ut_target_path}/${module_name}" - sleep 0.25 - for file in $(ls ${module_path}); do - if [ -d ${module_path}/${file} ];then - push_testdata_to_device "${module_path}/$file" "${module_name}/${file}" - elif [ -f ${module_path}/${file} ]; then - hdc_push_cmd "${module_path}/$file" "${ut_target_path}/${module_name}/$file" - else - echo "Invalid file: ${module_path}/${file}. Ignore" - fi - sleep 0.25 - done -} ohos_root="$1" ohos_root=${ohos_root%%/} ohos_init="${ohos_root}/base/startup/init_lite" -test_mount_data_path="${ohos_root}/base/update/updater/test/unittest/test_data" - -modules=(mount_unitest) -for module in ${modules[*]}; do - module_test_data=${test_mount_data_path}/${module} - if [ ! -d ${module_test_data} ]; then - echo "${module_test_data} is not directory" - continue - fi - push_testdata_to_device ${module_test_data} ${module} -done hdc_shell_cmd "mkdir -p ${ut_target_path}/coverage" sleep 0.25 diff --git a/test/unittest/ueventd/ueventd_config_unittest.cpp b/test/unittest/ueventd/ueventd_config_unittest.cpp index e92fbd365c94fb60d393bbb55353727fc0d29edc..73133fd0a6fc614f24ae8faa9e111ae3b0332bf1 100644 --- a/test/unittest/ueventd/ueventd_config_unittest.cpp +++ b/test/unittest/ueventd/ueventd_config_unittest.cpp @@ -24,141 +24,25 @@ #include "ueventd_read_cfg.h" #include "ueventd_parameter.h" +extern "C" { +bool IsMatch(const char *target, const char *pattern); +} + using namespace std; using namespace testing::ext; namespace ueventd_ut { -static bool FileExists(const std::string &file) -{ - bool isExist = false; - if (!file.empty()) { - struct stat st = {}; - if (stat(file.c_str(), &st) == 0) { - isExist = true; - } - } - return isExist; -} - -static bool CheckNeedToWrite(const std::string §ion, const std::string &configFile) -{ - ifstream cfg(configFile); - if (!cfg) { - cout << "open configFile stream failed." << endl; - return false; - } - std::string lastLineContent; - while (std::getline(cfg, lastLineContent)) { - if (strcmp(lastLineContent.c_str(), section.c_str()) == 0) { - return false; - } - } - return true; -} - -static bool IsDir(const std::string &path) -{ - struct stat st {}; - if (stat(path.c_str(), &st) < 0) { - return false; - } - return S_ISDIR(st.st_mode); -} - -static bool DeleteDir(const std::string &path) -{ - auto pDir = std::unique_ptr(opendir(path.c_str()), closedir); - if (pDir == nullptr) { - cout << "Can not open dir : " << path << ". " << errno << endl; - return false; - } - - struct dirent *dp = nullptr; - if (pDir != nullptr) { - while ((dp = readdir(pDir.get())) != nullptr) { - std::string currentName(dp->d_name); - if (currentName[0] != '.') { - std::string tmpName(path); - tmpName.append("/" + currentName); - if (IsDir(tmpName)) { - DeleteDir(tmpName); - } - remove(tmpName.c_str()); - } - } - remove(path.c_str()); - } - return true; -} - -void GenerateConfigFiles(const std::string §ion, const std::string &contents, - const std::string &configFile) -{ - if (configFile.empty()) { - return; - } - int flags = 0; - // check if config file exists, if not exists create one - if (FileExists(configFile)) { - flags = O_RDWR | O_APPEND | O_CLOEXEC; - } else { - flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC; - } - mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP; // 0640 - int fd = open(configFile.c_str(), flags, mode); - if (fd < 0) { - cout << "Open file " << configFile << " failed. " << errno << endl; - return; - } - size_t rc = 0; - if (!section.empty() && CheckNeedToWrite(section, configFile)) { - rc = WriteAll(fd, section.c_str(), section.size()); - if (rc != section.size()) { - cout << "Failed to write section " << section << " to file " << configFile << endl; - } - } - if (!contents.empty()) { - rc = WriteAll(fd, contents.c_str(), contents.size()); - if (rc != section.size()) { - cout << "Failed to write section " << contents << " to file " << configFile << endl; - } - } - close(fd); - fd = -1; -} - class UeventdConfigUnitTest : public testing::Test { public: -static void SetUpTestCase(void) -{ - int rc = mkdir(TEST_PATH, S_IRWXU | S_IRWXG | S_IRWXO); - if (rc < 0) { - if (errno != ENOENT) { - cout << "Failed to prepare test directory." << errno << endl; - } else { - cout << " " << TEST_PATH << " already exists." << endl; - } - } -} - -static void TearDownTestCase(void) -{ - DeleteDir(TEST_PATH); -} - +static void SetUpTestCase(void) {}; +static void TearDownTestCase(void) {}; void SetUp() {}; void TearDown() {}; }; HWTEST_F(UeventdConfigUnitTest, TestSectionConfigParse, TestSize.Level0) { - GenerateConfigFiles("[device]\n", "/dev/test 0666 1000 1000\n", "/data/ueventd_ut/valid.config"); - GenerateConfigFiles("[device]\n", "/dev/test1 0666 1000\n", "/data/ueventd_ut/valid.config"); - GenerateConfigFiles("[device]\n", "/dev/test2 0666 1000 1000 1000 1000\n", "/data/ueventd_ut/valid.config"); - GenerateConfigFiles("[sysfs]\n", "/dir/to/nothing attr_nowhere 0666 1000 1000\n", - TEST_PATH "/valid.config"); - GenerateConfigFiles("[firmware]\n", "/etc\n", TEST_PATH"/valid.config"); - ParseUeventdConfigFile(TEST_PATH"/valid.config"); + ParseUeventdConfigFile("/data/ueventd_ut/valid.config"); uid_t uid = 0; gid_t gid = 0; mode_t mode = 0; @@ -182,6 +66,7 @@ HWTEST_F(UeventdConfigUnitTest, TestSectionConfigParse, TestSize.Level0) EXPECT_EQ(gid, 999); EXPECT_EQ(mode, 0777); ChangeSysAttributePermissions("/dev/test2"); + ChangeSysAttributePermissions("/dir/to/nothing"); } HWTEST_F(UeventdConfigUnitTest, TestConfigEntry, TestSize.Level0) @@ -199,14 +84,16 @@ HWTEST_F(UeventdConfigUnitTest, TestConfigEntry, TestSize.Level0) HWTEST_F(UeventdConfigUnitTest, TestParameter, TestSize.Level0) { - GenerateConfigFiles("[device]\n", "/dev/testbinder1 0666 1000 1000 ohos.dev.binder\n", TEST_PATH"/valid.config"); - ParseUeventdConfigFile(TEST_PATH"/valid.config"); - GenerateConfigFiles("[device]\n", "/dev/testbinder2 0666 1000 1000 ohos.dev.binder\n", TEST_PATH"/valid.config"); - ParseUeventdConfigFile(TEST_PATH"/valid.config"); - GenerateConfigFiles("[device]\n", "/dev/testbinder3 0666 1000 1000 ohos.dev.binder\n", TEST_PATH"/valid.config"); - ParseUeventdConfigFile(TEST_PATH"/valid.config"); + ParseUeventdConfigFile("/data/ueventd_ut/valid.config"); SetUeventDeviceParameter("/dev/testbinder1", 0); SetUeventDeviceParameter("/dev/testbinder2", 0); SetUeventDeviceParameter("/dev/testbinder3", 0); + SetUeventDeviceParameter("/notpath", 0); + SetUeventDeviceParameter(nullptr, 1); + GetDeviceUdevConfByDevNode(nullptr); + int ret = IsMatch("testtarget", "te?*a"); + IsMatch("testtarget", "a"); + ret = IsMatch("test", "t****"); + EXPECT_EQ(ret, true); } } // namespace ueventd_ut