提交 4278d9b4 编写于 作者: L laiguizhong

add unittest cases

Signed-off-by: Nlaiguizhong <laiguizhong@huawei.com>
Change-Id: I9408b1109b66d0ec54fea0cb772439f4911fb56a
上级 b0aae888
......@@ -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);
......@@ -383,6 +385,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;
......@@ -423,6 +426,7 @@ static int32_t BShellParamCmdShell(BShellHandle shell, int32_t argc, char *argv[
tcsetattr(0, TCSAFLUSH, &g_terminalState);
g_isSetTerminal = 0;
}
#endif
return 0;
}
......
......@@ -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);
......
......@@ -135,7 +135,11 @@ static int SelinuxCheckParamPermission(const ParamSecurityLabel *srcLabel, const
if (mode == DAC_WRITE) {
ret = g_selinuxSpace.setParamCheck(name, &uc);
} else {
#ifndef STARTUP_INIT_TEST
ret = 0;
#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);
......
......@@ -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)
{
......
......@@ -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);
......
......@@ -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") {
......
......@@ -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
/*
* 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 <errno.h>
#include <stdio.h>
#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);
}
}
......@@ -16,6 +16,7 @@
#include <sys/statvfs.h>
#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,36 @@ 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 ", "");
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 +232,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 +263,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
......@@ -12,12 +12,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#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,57 @@ 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
......@@ -40,11 +40,18 @@ 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
......@@ -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<char *>(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<uint8_t *>(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_, &paramStreamInfo, 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
......@@ -14,9 +14,11 @@
*/
#include <cerrno>
#include <unistd.h>
#include <fcntl.h>
#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,38 @@ 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
......@@ -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);
......
......@@ -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;
......
......@@ -16,6 +16,7 @@
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include "init_cmds.h"
#include "init_service.h"
#include "init_service_manager.h"
......@@ -27,6 +28,10 @@
using namespace testing::ext;
using namespace std;
extern "C" {
void ClientDeinit(void);
}
namespace init_ut {
class ServiceUnitTest : public testing::Test {
public:
......@@ -49,7 +54,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 +72,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 +147,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 +166,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 +239,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 +283,8 @@ HWTEST_F(ServiceUnitTest, TestServiceExec, TestSize.Level1)
EXPECT_EQ(ret, -1);
ReleaseService(service);
}
HWTEST_F(ServiceUnitTest, TestClientDeinit, TestSize.Level1)
{
ClientDeinit();
}
} // namespace init_ut
......@@ -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
......@@ -20,6 +20,7 @@
#include "param_stub.h"
#include "securec.h"
#define TEST_PATH_MOUNTCFG "/data/init_ut/mount_unitest/"
using namespace testing::ext;
using namespace std;
......@@ -38,27 +39,16 @@ HWTEST_F(InnerkitsUnitTest, ReadFstabFromFile_unitest, TestSize.Level1)
const std::string fstabFile1 = "/data/fstab.updater1";
fstab = ReadFstabFromFile(fstabFile1.c_str(), false);
EXPECT_EQ(fstab, nullptr);
const std::string fstabFile2 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable";
const std::string fstabFile2 = TEST_PATH_MOUNTCFG"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<char *>("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 = TEST_PATH_MOUNTCFG"ReadFstabFromFile1.fstable";
Fstab *fstab = nullptr;
fstab = ReadFstabFromFile(fstabFile1.c_str(), false);
ASSERT_NE(fstab, nullptr);
......@@ -89,7 +79,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 = TEST_PATH_MOUNTCFG"ReadFstabFromFile1.fstable";
Fstab *fstab = nullptr;
fstab = ReadFstabFromFile(fstabFile1.c_str(), false);
ASSERT_NE(fstab, nullptr);
......@@ -111,9 +101,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 = TEST_PATH_MOUNTCFG"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";
......
......@@ -133,6 +133,7 @@ static void TestPermission()
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)
......
......@@ -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
......@@ -12,8 +12,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "param_stub.h"
#include <dirent.h>
#include "param_stub.h"
#include "beget_ext.h"
#include "init_param.h"
#include "param_manager.h"
......@@ -23,6 +24,9 @@
#include "param_cfg.h"
#endif
#define TEST_PATH_UEVENT "/data/ueventd_ut"
#define TEST_PATH_MOUNTCFG "/data/init_ut/mount_unitest/"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
......@@ -87,7 +91,6 @@ static const char *forbitReadParamName[] = {
"ohos.servicectrl.",
// "test.permission.write",
};
static int TestReadParamCheck(const char *paraName)
{
// forbit to read ohos.servicectrl.
......@@ -98,7 +101,6 @@ static int TestReadParamCheck(const char *paraName)
}
return g_testPermissionResult;
}
static void TestDestroyParamList(ParamContextsList **list)
{
#ifdef PARAM_SUPPORT_SELINUX
......@@ -112,7 +114,6 @@ static void TestDestroyParamList(ParamContextsList **list)
}
#endif
}
static ParamContextsList *TestGetParamList(void)
{
#ifdef PARAM_SUPPORT_SELINUX
......@@ -149,7 +150,6 @@ void TestSetSelinuxOps(void)
SetSelinuxOps(&space);
#endif
}
static void CreateTestFile(const char *fileName, const char *data)
{
CheckAndCreateDir(fileName);
......@@ -161,7 +161,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(TEST_PATH_UEVENT, S_IRWXU | S_IRWXG | S_IRWXO);
CreateTestFile(TEST_PATH_UEVENT"/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(TEST_PATH_MOUNTCFG"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<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir);
if (pDir == nullptr) {
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;
}
static void LoadParamFromCfg(void)
{
#ifdef PARAM_LOAD_CFG_FROM_CODE
......@@ -237,6 +318,9 @@ void PrepareInitUnitTestEnv(void)
}
PARAM_LOGI("PrepareInitUnitTestEnv");
mkdir(STARTUP_INIT_UT_PATH, S_IRWXU | S_IRWXG | S_IRWXO);
PrepareUeventdcfg();
PrepareInnerKitsCfg();
PrepareModCfg();
SetInitLogLevel(INIT_DEBUG);
#if !(defined __LITEOS_A__ || defined __LITEOS_M__)
......
......@@ -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;
}
......
......@@ -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<struct tagTriggerNode_ *>(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();
}
......@@ -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;
}
......
......@@ -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
......
......@@ -24,140 +24,26 @@
#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;
#define TEST_PATH "/data/ueventd_ut"
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 &section, 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<DIR, decltype(&closedir)>(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 &section, 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");
uid_t uid = 0;
gid_t gid = 0;
......@@ -182,6 +68,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 +86,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");
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
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册