提交 8374a62e 编写于 作者: C cheng_jinsong

add init unittest

Signed-off-by: Ncheng_jinsong <chengjinsong2@huawei.com>
Change-Id: Ic3f2d0aab32592c472f17963e634fffced13d4cb
上级 e03ce132
......@@ -244,7 +244,9 @@ void CloseServiceSocket(Service *service)
sockopt->sockFd = -1;
}
if (GetSocketAddr(&addr, sockopt->name) == 0) {
#ifndef STARTUP_INIT_TEST
unlink(addr.sun_path);
#endif
}
sockopt = sockopt->next;
}
......
......@@ -21,6 +21,16 @@ config("utest_config") {
"-Wno-unused-function",
"-Dprivate=public",
"-Dprotected=public",
"-Dsprintf_s=SprintfStub",
"-Dmount=MountStub",
"-Dumount=UmountStub",
"-Dumount2=Umount2Stub",
"-Dsymlink=SymlinkStub",
"-Dprctl=PrctlStub",
"-Dexecv=ExecvStub",
"-Dlchown=LchownStub",
"-Dkill=KillStub",
"-Dexecve=ExecveStub",
]
cflags_cc = [
"-Wno-implicit-fallthrough",
......@@ -36,6 +46,10 @@ ohos_unittest("init_unittest") {
sources = [
"//base/startup/init/device_info/device_info.cpp",
"//base/startup/init/device_info/device_info_stub.cpp",
"//base/startup/init/interfaces/innerkits/control_fd/control_fd_client.c",
"//base/startup/init/interfaces/innerkits/control_fd/control_fd_service.c",
"//base/startup/init/interfaces/innerkits/fd_holder/fd_holder.c",
"//base/startup/init/interfaces/innerkits/fd_holder/fd_holder_internal.c",
"//base/startup/init/interfaces/innerkits/file/init_file.c",
"//base/startup/init/interfaces/innerkits/fs_manager/fstab.c",
"//base/startup/init/interfaces/innerkits/fs_manager/fstab_mount.c",
......@@ -44,7 +58,16 @@ ohos_unittest("init_unittest") {
"//base/startup/init/interfaces/innerkits/syspara/param_comm.c",
"//base/startup/init/interfaces/innerkits/syspara/parameter.c",
"//base/startup/init/interfaces/innerkits/syspara/sysversion.c",
"//base/startup/init/services/begetctl/begetctl_cmd.c",
"//base/startup/init/services/begetctl/bootchart_cmd.c",
"//base/startup/init/services/begetctl/dump_service.c",
"//base/startup/init/services/begetctl/init_cmd_reboot.c",
"//base/startup/init/services/begetctl/misc_daemon.cpp",
"//base/startup/init/services/begetctl/modulectl.c",
"//base/startup/init/services/begetctl/param_cmd.c",
"//base/startup/init/services/begetctl/sandbox.cpp",
"//base/startup/init/services/begetctl/service_control.c",
"//base/startup/init/services/begetctl/setloglevel.c",
"//base/startup/init/services/begetctl/shell/shell_bas.c",
"//base/startup/init/services/begetctl/shell/shell_main.c",
"//base/startup/init/services/init/adapter/init_adapter.c",
......@@ -57,6 +80,7 @@ ohos_unittest("init_unittest") {
"//base/startup/init/services/init/init_service_manager.c",
"//base/startup/init/services/init/init_service_socket.c",
"//base/startup/init/services/init/standard/device.c",
"//base/startup/init/services/init/standard/fd_holder_service.c",
"//base/startup/init/services/init/standard/init.c",
"//base/startup/init/services/init/standard/init_cmdexecutor.c",
"//base/startup/init/services/init/standard/init_cmds.c",
......@@ -78,6 +102,8 @@ ohos_unittest("init_unittest") {
"//base/startup/init/services/loopevent/task/le_watchtask.c",
"//base/startup/init/services/loopevent/timer/le_timer.c",
"//base/startup/init/services/loopevent/utils/le_utils.c",
"//base/startup/init/services/modules/bootchart/bootchart.c",
"//base/startup/init/services/modules/bootchart/bootchart_static.c",
"//base/startup/init/services/modules/bootevent/bootevent.c",
"//base/startup/init/services/modules/init_hook/init_hook.c",
"//base/startup/init/services/modules/init_hook/param_hook.c",
......@@ -139,16 +165,21 @@ ohos_unittest("init_unittest") {
sources += [
"begetctl/begetctl_unittest.cpp",
"deviceinfo/DeviceInfoUnittest.cpp",
"init/SignalInitUnitTest.cpp",
"init/cmds_unittest.cpp",
"init/group_unittest.cpp",
"init/init_reboot_unittest.cpp",
"init/init_unittest.cpp",
"init/mount_unittest.cpp",
"init/sandbox_unittest.cpp",
"init/service_file_unittest.cpp",
"init/service_socket_unittest.cpp",
"init/service_unittest.cpp",
"init/utils_unittest.cpp",
"innerkits/innerkits_unittest.cpp",
"loopevent/loopevent_unittest.cpp",
"loopevent/loopserver_unittest.cpp",
"loopevent/loopsignal_unittest.cpp",
"modules/modules_unittest.cpp",
"param/client_unittest.cpp",
"param/dac_unittest.cpp",
"param/param_shell_unittest.cpp",
......@@ -158,6 +189,7 @@ ohos_unittest("init_unittest") {
"param/trigger_unittest.cpp",
"syspara/syspara_unittest.cpp",
"ueventd/ueventd_config_unittest.cpp",
"ueventd/ueventd_event_unittest.cpp",
]
sources += [
......@@ -197,6 +229,7 @@ ohos_unittest("init_unittest") {
"//base/startup/init/services/loopevent/timer",
"//base/startup/init/services/loopevent/utils",
"//base/startup/init/services/modules",
"//base/startup/init/services/modules/bootchart",
"//base/startup/init/services/modules/init_hook",
"//base/startup/init/services/modules/selinux",
"//base/startup/init/services/modules/reboot",
......@@ -240,12 +273,17 @@ ohos_unittest("init_unittest") {
defines = [
"READ_CHECK",
"INIT_AGENT",
"INIT_DMESG",
"INIT_FILE",
"STARTUP_INIT_TEST",
"PARAM_SUPPORT_DAC",
"_GNU_SOURCE",
"PARAM_SUPPORT_TRIGGER",
"USE_MBEDTLS",
"PARAM_DECODE_GROUPID_FROM_FILE",
"WORKSPACE_AREA_NEED_MUTEX",
"PARAM_SUPPORT_REAL_CHECK",
"DISABLE_INIT_TWO_STAGES",
]
defines += [ "_GNU_SOURCE" ]
......@@ -262,6 +300,15 @@ ohos_unittest("init_unittest") {
"init:libinit_module_engine",
]
if (enable_ohos_startup_init_feature_ab_partition) {
include_dirs += [ "//drivers/hdf_core/adapter/uhdf2/include" ]
sources += [ "//base/startup/init/services/begetctl/partitionslot.cpp" ]
external_deps += [
"drivers_interface_partitionslot:libpartitionslot_proxy_1.0",
"hdf_core:libhdi",
]
}
if (!defined(ohos_lite) && enable_ohos_startup_init_feature_watcher) {
sources += [
"param/watcher_agent_unittest.cpp",
......@@ -287,11 +334,11 @@ ohos_unittest("init_unittest") {
"//third_party/selinux/libselinux/include/",
"//base/security/selinux/interfaces/policycoreutils/include/",
]
deps += [
"//base/security/selinux:libload_policy",
"//base/security/selinux:librestorecon",
"//third_party/selinux:libselinux",
sources += [
"//base/startup/init/services/modules/selinux/selinux_adp.c",
"//base/startup/init/services/modules/selinux/selinux_static.c",
]
defines += [
"WITH_SELINUX",
"PARAM_SUPPORT_SELINUX",
......@@ -303,12 +350,12 @@ ohos_unittest("init_unittest") {
"//base/startup/init/device_info/device_info_load.cpp",
"//base/startup/init/device_info/device_info_proxy.cpp",
]
include_dirs += [
"//third_party/selinux/libselinux/include/",
"//base/security/access_token/interfaces/innerkits/accesstoken/include",
]
defines += [ "PARAM_FEATURE_DEVICEINFO" ]
external_deps += [ "access_token:libaccesstoken_sdk" ]
}
cflags_cc = [ "-fexceptions" ]
sources += [
"init/loopevent_unittest.cpp",
"init/service_unittest.cpp",
]
}
......@@ -137,4 +137,456 @@ HWTEST_F(BegetctlUnitTest, TestShellLsWithvalueExist, TestSize.Level1)
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_1, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "getslot"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_2, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "getsuffix", "1"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_3, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "setactive", "1"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_4, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "setunboot", "2"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_5, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "setactive"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_6, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "setunboot"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestPartitionSlot_7, TestSize.Level1)
{
const char *args[] = {
"partitionslot", "getsuffix"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBegetctl_1, TestSize.Level1)
{
const char *args[] = {
"set", "log", "level", "1"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBegetctl_2, TestSize.Level1)
{
const char *args[] = {
"get", "log", "level"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBegetctl_3, TestSize.Level1)
{
const char *args[] = {
"set", "log", "level"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBegetctl_4, TestSize.Level1)
{
const char *args[] = {
"set", "log", "level", "1000"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBegetctl_5, TestSize.Level1)
{
const char *args[] = {
"set", "log", "level", "a"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBootChart_1, TestSize.Level1)
{
const char *args[] = {
"bootchart", "enable"
};
SystemWriteParam("persist.init.bootchart.enabled", "1");
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBootChart_2, TestSize.Level1)
{
const char *args[] = {
"bootchart", "start"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBootChart_3, TestSize.Level1)
{
const char *args[] = {
"bootchart", "stop"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBootChart_4, TestSize.Level1)
{
const char *args[] = {
"bootchart", "disable"
};
SystemWriteParam("persist.init.bootchart.enabled", "0");
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestBootChart_5, TestSize.Level1)
{
const char *args[] = {
"bootchart"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestDumpService_1, TestSize.Level1)
{
const char *args[] = {
"bootevent", "enable"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestDumpService_2, TestSize.Level1)
{
const char *args[] = {
"bootevent", "disable"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestDumpService_3, TestSize.Level1)
{
const char *args[] = {
"dump_service", "all"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestDumpService_4, TestSize.Level1)
{
const char *args[] = {
"dump_service", "param_watcher"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestDumpService_5, TestSize.Level1)
{
const char *args[] = {
"dump_service", "parameter-service", "trigger"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestMiscDaemon, TestSize.Level1)
{
const char *args[] = {
"misc_daemon", "--write_logo", BOOT_CMD_LINE
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestMiscDaemon_1, TestSize.Level1)
{
const char *args[] = {
"misc_daemon", "--write_logo1111", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestMiscDaemon_2, TestSize.Level1)
{
const char *args[] = {
"misc_daemon", "--write_logo", ""
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestMiscDaemon_3, TestSize.Level1)
{
const char *args[] = {
"misc_daemon", "--write_logo"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestMiscDaemon_4, TestSize.Level1)
{
// clear misc logo
const char *args[] = {
"misc_daemon", "--write_logo", "sssssssss"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestModulectl_1, TestSize.Level1)
{
const char *args[] = {
"modulectl", "install", "testModule"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestModulectl_2, TestSize.Level1)
{
const char *args[] = {
"modulectl", "uninstall", "testModule"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestModulectl_3, TestSize.Level1)
{
const char *args[] = {
"modulectl", "list", "testModule"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestModulectl_4, TestSize.Level1)
{
const char *args[] = {
"modulectl", "install"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestModulectl_5, TestSize.Level1)
{
const char *args[] = {
"modulectl", "list"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_1, TestSize.Level1)
{
const char *args[] = {
"service_control", "stop", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_2, TestSize.Level1)
{
const char *args[] = {
"service_control", "start", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_3, TestSize.Level1)
{
const char *args[] = {
"stop_service", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_4, TestSize.Level1)
{
const char *args[] = {
"start_service", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_5, TestSize.Level1)
{
const char *args[] = {
"timer_stop", "test"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_6, TestSize.Level1)
{
const char *args[] = {
"timer_stop"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_7, TestSize.Level1)
{
const char *args[] = {
"timer_start", "test-service", "10"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_8, TestSize.Level1)
{
const char *args[] = {
"timer_start", "test-service",
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_9, TestSize.Level1)
{
const char *args[] = {
"timer_start", "test-service", "ww"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestServiceControl_10, TestSize.Level1)
{
const char *args[] = {
"xxxxxxxxxxxxxx", "test-service", "ww"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestSetLogLevel_1, TestSize.Level1)
{
const char *args[] = {
"setloglevel", "1"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestSetLogLevel_2, TestSize.Level1)
{
const char *args[] = {
"getloglevel"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestSetLogLevel_3, TestSize.Level1)
{
const char *args[] = {
"setloglevel", "a"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestSetLogLevel_4, TestSize.Level1)
{
const char *args[] = {
"setloglevel"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestSandbox, TestSize.Level1)
{
const char *args[] = {
"sandbox", "-s", "test", "-n", "test2", "-p", "test3", "-h", "?"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_1, TestSize.Level1)
{
const char *args[] = {
"reboot"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_2, TestSize.Level1)
{
const char *args[] = {
"reboot", "shutdown"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_3, TestSize.Level1)
{
const char *args[] = {
"reboot", "charge"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_4, TestSize.Level1)
{
const char *args[] = {
"reboot", "updater"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_5, TestSize.Level1)
{
const char *args[] = {
"reboot", "updater:aaaaaaa"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_6, TestSize.Level1)
{
const char *args[] = {
"reboot", "flashd:aaaaaaa"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_7, TestSize.Level1)
{
const char *args[] = {
"reboot", "flashd"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_8, TestSize.Level1)
{
const char *args[] = {
"reboot", "suspend"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
HWTEST_F(BegetctlUnitTest, TestReboot_9, TestSize.Level1)
{
const char *args[] = {
"reboot", "222222222"
};
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), const_cast<char **>(args));
}
} // namespace init_ut
......@@ -15,6 +15,8 @@
#include <string>
#include <iostream>
#include <gtest/gtest.h>
#include "accesstoken_kit.h"
#include "parameter.h"
#include "system_ability_definition.h"
#include "if_system_ability_manager.h"
......@@ -22,16 +24,36 @@
#include "parcel.h"
#include "string_ex.h"
#include "device_info_kits.h"
#include "device_info_load.h"
#include "device_info_proxy.h"
#include "idevice_info.h"
#include "device_info_stub.h"
#include "sysparam_errno.h"
using namespace testing::ext;
using namespace std;
using namespace OHOS;
using namespace OHOS::device_info;
int g_tokenType = OHOS::Security::AccessToken::TOKEN_HAP;
int g_tokenVerifyResult = 0;
namespace OHOS {
namespace Security {
namespace AccessToken {
ATokenTypeEnum AccessTokenKit::GetTokenTypeFlag(AccessTokenID tokenID)
{
return static_cast<ATokenTypeEnum>(g_tokenType);
}
int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName)
{
return g_tokenVerifyResult;
}
} // namespace AccessToken
} // namespace Security
} // namespace OHOS
const int UDID_LEN = 65;
namespace init_ut {
using DeviceInfoServicePtr = DeviceInfoService *;
using DeviceInfoServicePtr = OHOS::device_info::DeviceInfoService *;
class DeviceInfoUnittest : public testing::Test {
public:
DeviceInfoUnittest() {};
......@@ -45,7 +67,7 @@ public:
{
static DeviceInfoServicePtr deviceInfoServicePtr = nullptr;
if (deviceInfoServicePtr == nullptr) {
deviceInfoServicePtr = new DeviceInfoService(0, true);
deviceInfoServicePtr = new OHOS::device_info::DeviceInfoService(0, true);
if (deviceInfoServicePtr == nullptr) {
return nullptr;
}
......@@ -55,19 +77,28 @@ public:
}
};
HWTEST_F(DeviceInfoUnittest, GetDevUdidTest, TestSize.Level1)
HWTEST_F(DeviceInfoUnittest, DevInfoAgentTest, TestSize.Level1)
{
char localDeviceId[UDID_LEN] = {0};
AclGetDevUdid(localDeviceId, UDID_LEN);
const char *serialNumber = AclGetSerial();
EXPECT_NE(nullptr, serialNumber);
OHOS::device_info::DeviceInfoKits &kits = OHOS::device_info::DeviceInfoKits::GetInstance();
std::string serial = {};
int ret = kits.GetSerialID(serial);
EXPECT_EQ(ret, SYSPARAM_PERMISSION_DENIED);
ret = kits.GetUdid(serial);
EXPECT_EQ(ret, SYSPARAM_PERMISSION_DENIED);
}
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
ASSERT_NE(nullptr, samgr);
sptr<IRemoteObject> object = samgr->GetSystemAbility(SYSPARAM_DEVICE_SERVICE_ID);
ASSERT_NE(nullptr, samgr);
HWTEST_F(DeviceInfoUnittest, DevInfoAgentFail, TestSize.Level1)
{
sptr<OHOS::device_info::DeviceInfoLoad> deviceInfoLoad = new (std::nothrow) OHOS::device_info::DeviceInfoLoad();
ASSERT_NE(deviceInfoLoad, nullptr);
deviceInfoLoad->OnLoadSystemAbilityFail(SYSPARAM_DEVICE_SERVICE_ID);
deviceInfoLoad->OnLoadSystemAbilityFail(SYSPARAM_DEVICE_SERVICE_ID + 1);
OHOS::device_info::DeviceInfoKits &kits = OHOS::device_info::DeviceInfoKits::GetInstance();
kits.FinishStartSAFailed();
}
HWTEST_F(DeviceInfoUnittest, StubTest, TestSize.Level1)
HWTEST_F(DeviceInfoUnittest, DeviceInfoServiceInvalidTokenTest, TestSize.Level1)
{
string result;
DeviceInfoServicePtr deviceInfoService = GetDeviceInfoService();
......@@ -75,13 +106,97 @@ HWTEST_F(DeviceInfoUnittest, StubTest, TestSize.Level1)
MessageParcel data;
MessageParcel reply;
MessageOption option;
data.WriteInterfaceToken(DeviceInfoStub::GetDescriptor());
deviceInfoService->OnRemoteRequest(IDeviceInfo::COMMAND_GET_UDID, data, reply, option);
data.WriteInterfaceToken(DeviceInfoStub::GetDescriptor());
deviceInfoService->OnRemoteRequest(IDeviceInfo::COMMAND_GET_SERIAL_ID, data, reply, option);
g_tokenType = OHOS::Security::AccessToken::TOKEN_INVALID;
data.WriteInterfaceToken(OHOS::device_info::DeviceInfoStub::GetDescriptor());
deviceInfoService->OnRemoteRequest(OHOS::device_info::IDeviceInfo::COMMAND_GET_UDID, data, reply, option);
}
HWTEST_F(DeviceInfoUnittest, DeviceInfoServiceFailTest, TestSize.Level1)
{
string result;
DeviceInfoServicePtr deviceInfoService = GetDeviceInfoService();
ASSERT_NE(deviceInfoService, nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
g_tokenType = OHOS::Security::AccessToken::TOKEN_HAP;
g_tokenVerifyResult = OHOS::Security::AccessToken::TypePermissionState::PERMISSION_DENIED;
// udid
data.WriteInterfaceToken(OHOS::device_info::DeviceInfoStub::GetDescriptor());
deviceInfoService->OnRemoteRequest(OHOS::device_info::IDeviceInfo::COMMAND_GET_UDID, data, reply, option);
// serial
data.WriteInterfaceToken(OHOS::device_info::DeviceInfoStub::GetDescriptor());
deviceInfoService->OnRemoteRequest(OHOS::device_info::IDeviceInfo::COMMAND_GET_SERIAL_ID, data, reply, option);
}
HWTEST_F(DeviceInfoUnittest, DeviceInfoServiceTest, TestSize.Level1)
{
string result;
DeviceInfoServicePtr deviceInfoService = GetDeviceInfoService();
ASSERT_NE(deviceInfoService, nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
g_tokenType = OHOS::Security::AccessToken::TOKEN_HAP;
g_tokenVerifyResult = OHOS::Security::AccessToken::TypePermissionState::PERMISSION_GRANTED;
data.WriteInterfaceToken(OHOS::device_info::DeviceInfoStub::GetDescriptor());
deviceInfoService->OnRemoteRequest(OHOS::device_info::IDeviceInfo::COMMAND_GET_UDID, data, reply, option);
data.WriteInterfaceToken(OHOS::device_info::DeviceInfoStub::GetDescriptor());
deviceInfoService->OnRemoteRequest(OHOS::device_info::IDeviceInfo::COMMAND_GET_SERIAL_ID, data, reply, option);
data.WriteInterfaceToken(OHOS::device_info::DeviceInfoStub::GetDescriptor());
deviceInfoService->OnRemoteRequest(OHOS::device_info::IDeviceInfo::COMMAND_GET_SERIAL_ID + 1, data, reply, option);
deviceInfoService->OnRemoteRequest(OHOS::device_info::IDeviceInfo::COMMAND_GET_SERIAL_ID + 1, data, reply, option);
deviceInfoService->GetUdid(result);
deviceInfoService->GetSerialID(result);
deviceInfoService->OnStop();
std::vector<std::u16string> args = {};
deviceInfoService->Dump(STDOUT_FILENO, args);
deviceInfoService->Dump(-1, args);
delete deviceInfoService;
}
HWTEST_F(DeviceInfoUnittest, TestInterface, TestSize.Level1)
{
char localDeviceId[UDID_LEN] = {0};
int ret = AclGetDevUdid(nullptr, UDID_LEN);
ASSERT_NE(ret, 0);
ret = AclGetDevUdid(localDeviceId, 2); // 2 test
ASSERT_NE(ret, 0);
ret = AclGetDevUdid(localDeviceId, UDID_LEN);
const char *serialNumber = AclGetSerial();
EXPECT_NE(nullptr, serialNumber);
}
HWTEST_F(DeviceInfoUnittest, TestDeviceInfoProxy1, TestSize.Level1)
{
auto remote = device_info::DeviceInfoKits::GetInstance().GetService()->AsObject();
sptr<device_info::DeviceInfoProxy> proxy = new(std::nothrow) device_info::DeviceInfoProxy(remote);
ASSERT_NE(proxy, nullptr);
device_info::DeviceInfoKits::GetInstance().FinishStartSASuccess(proxy->AsObject());
std::string udid;
std::string serialId;
proxy->GetUdid(udid);
proxy->GetSerialID(serialId);
char localDeviceId[UDID_LEN] = {0};
int ret = AclGetDevUdid(localDeviceId, UDID_LEN);
ASSERT_NE(ret, 0);
const char *serialNumber = AclGetSerial();
EXPECT_NE(nullptr, serialNumber);
}
HWTEST_F(DeviceInfoUnittest, TestDeviceInfoProxy2, TestSize.Level1)
{
sptr<device_info::DeviceInfoProxy> proxy = new(std::nothrow) device_info::DeviceInfoProxy(nullptr);
ASSERT_NE(proxy, nullptr);
std::string udid;
std::string serialId;
proxy->GetUdid(udid);
proxy->GetSerialID(serialId);
}
} // namespace init_ut
......@@ -44,7 +44,7 @@ HWTEST_F(CmdsUnitTest, TestCmdExecByName, TestSize.Level1)
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("insmod ", STARTUP_INIT_UT_PATH"/test_insmod");
DoCmdByName("setparam ", "sys.usb.config ${persist.sys.usb.config}");
......@@ -54,6 +54,7 @@ HWTEST_F(CmdsUnitTest, TestCmdExecByName, TestSize.Level1)
DoCmdByName("hostname ", "localhost");
DoCmdByName("sleep ", "1");
DoCmdByName("setrlimit ", "RLIMIT_NICE 40 40");
DoCmdByName("setrlimit ", "RLIMIT_NICE unlimited unlimited");
DoCmdByName("setrlimit ", "RLIMIT_NICE2 40 40");
DoCmdByName("start ", "init_ut");
DoCmdByName("stop ", "init_ut");
......@@ -65,12 +66,13 @@ HWTEST_F(CmdsUnitTest, TestCmdExecByName, TestSize.Level1)
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("mount_fstab ", "/wwwwwww");
DoCmdByName("umount_fstab ", "/wwwwwww");
DoCmdByName("mksandbox ", "system chipset");
DoCmdByName("mksandbox ", "system");
DoCmdByName("mksandbox ", "notsupport");
DoCmdByName("mksandbox ", "");
DoCmdByName("mksandbox ", nullptr);
}
HWTEST_F(CmdsUnitTest, TestCmdExecByName1, TestSize.Level1)
{
......@@ -79,19 +81,20 @@ HWTEST_F(CmdsUnitTest, TestCmdExecByName1, TestSize.Level1)
DoCmdByName("exec ", "media_service");
DoCmdByName("syncexec ", "/system/bin/toybox");
DoCmdByName("load_access_token_id ", "media_service");
DoCmdByName("load_access_token_id ", "");
DoCmdByName("stopAllServices ", "true");
DoCmdByName("umount ", "");
DoCmdByName("mount ", "");
DoCmdByName("mount ", "ext4 /dev/block/platform/soc/10100000.himci.eMMC/by-name/vendor "
"/data wait filecrypt=555");
DoCmdByName("umount ", "/2222222");
DoCmdByName("mount ", "/2222222");
DoCmdByName("mount ", "ext4 /2222222 /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("mkswap ", "/data/init_ut");
DoCmdByName("swapon ", "/data/init_ut");
DoCmdByName("sync ", "");
DoCmdByName("restorecon ", "");
DoCmdByName("restorecon ", "/data /data");
DoCmdByName("suspend ", "");
DoCmdByName("wait ", "1");
DoCmdByName("wait ", "aaa 1");
......@@ -169,6 +172,14 @@ HWTEST_F(CmdsUnitTest, TestCommonCopy, TestSize.Level1)
DoCmdByName("copy ", "/data/init_ut/test_dir0/test_file_copy1 /data/init_ut/test_dir0/test_file_copy1");
DoCmdByName("copy ", "/data/init_ut/test_dir0/test_file_copy11 /data/init_ut/test_dir0/test_file_copy1");
DoCmdByName("copy ", "a");
DoCmdByName("chmod ", "111 /data/init_ut/test_dir0/test_file_copy1");
DoCmdByName("copy ", "/data/init_ut/test_dir0/test_file_copy1 /data/init_ut/test_dir0/test_file_copy2");
DoCmdByName("chmod ", "777 /data/init_ut/test_dir0/test_file_copy1");
DoCmdByName("chmod ", "111 /data/init_ut/test_dir0/test_file_copy2");
DoCmdByName("copy ", "/data/init_ut/test_dir0/test_file_copy1 /data/init_ut/test_dir0/test_file_copy2");
DoCmdByName("chmod ", "777 /data/init_ut/test_dir0/test_file_copy2");
}
HWTEST_F(CmdsUnitTest, TestCommonWrite, TestSize.Level1)
......@@ -241,7 +252,7 @@ HWTEST_F(CmdsUnitTest, TestDoCmdByIndex, TestSize.Level1)
HWTEST_F(CmdsUnitTest, TestGetCmdLinesFromJson, TestSize.Level1)
{
const char *jsonStr = "{\"jobs\":[{\"name\":\"init\",\"cmds\":[\"sleep 1\"]}]}";
const char *jsonStr = "{\"jobs\":[{\"name\":\"init\",\"cmds\":[\"sleep 1\",100,\"test321 123\"]}]}";
cJSON* jobItem = cJSON_Parse(jsonStr);
ASSERT_NE(nullptr, jobItem);
cJSON *cmdsItem = cJSON_GetObjectItem(jobItem, "jobs");
......@@ -272,5 +283,39 @@ HWTEST_F(CmdsUnitTest, TestInitCmdFunc, TestSize.Level1)
{
int ret = GetBootModeFromMisc();
EXPECT_EQ(ret, 0);
ret = SetFileCryptPolicy(nullptr);
EXPECT_NE(ret, 0);
}
HWTEST_F(CmdsUnitTest, TestBuildStringFromCmdArg, TestSize.Level1)
{
int strNum = 3;
struct CmdArgs *ctx = (struct CmdArgs *)calloc(1, sizeof(struct CmdArgs) + sizeof(char *) * (strNum));
ctx->argc = strNum;
ctx->argv[0] = strdup("123456789012345678901234567890123456789012345678901234567890 \
1234567890123456789012345678901234567890123456789012345678901234567");
ctx->argv[1] = strdup("test");
ctx->argv[2] = nullptr;
char *options = BuildStringFromCmdArg(ctx, 0);
EXPECT_EQ(options[0], '\0');
free(options);
options = BuildStringFromCmdArg(ctx, 1);
EXPECT_STREQ(options, "test");
free(options);
FreeCmdArg(ctx);
}
HWTEST_F(CmdsUnitTest, TestInitDiffTime, TestSize.Level1)
{
INIT_TIMING_STAT stat;
stat.startTime.tv_sec = 2; // 2 is test sec
stat.startTime.tv_nsec = 1000; // 1000 is test nsec
stat.endTime.tv_sec = 3; // 3 is test sec
stat.endTime.tv_nsec = 0;
long long diff = InitDiffTime(&stat);
EXPECT_TRUE(diff > 0);
}
} // namespace init_ut
......@@ -165,7 +165,7 @@ HWTEST_F(InitGroupManagerUnitTest, TestInitGroupMgrInit, TestSize.Level1)
{
InitServiceSpace();
InitWorkspace *workspace = GetInitWorkspace();
EXPECT_EQ(workspace->groupMode, GROUP_CHARGE);
EXPECT_EQ(workspace->groupMode, GROUP_BOOT);
workspace->groupMode = GROUP_BOOT;
if (strcpy_s(workspace->groupModeStr, GROUP_NAME_MAX_LENGTH, "device.boot.group") != EOK) {
EXPECT_EQ(1, 0);
......@@ -338,10 +338,7 @@ HWTEST_F(InitGroupManagerUnitTest, TestParseServiceCpucore, TestSize.Level1)
}
cJSON_Delete(jobItem);
}
HWTEST_F(InitGroupManagerUnitTest, TestNodeFree, TestSize.Level1)
{
DoCmdByName("stopAllServices ", "");
}
HWTEST_F(InitGroupManagerUnitTest, TestUpdaterServiceFds, TestSize.Level1)
{
Service *service = AddService("test_service8");
......@@ -370,4 +367,18 @@ HWTEST_F(InitGroupManagerUnitTest, TestProcessWatchEvent, TestSize.Level1)
uint32_t event;
((WatcherTask *)watcher)->processEvent((WatcherHandle)watcher, 0, &event, service);
}
HWTEST_F(InitGroupManagerUnitTest, TestCheckNodeValid, TestSize.Level1)
{
int ret = CheckNodeValid(NODE_TYPE_MAX, "charger");
EXPECT_EQ(ret, -1);
ret = CheckNodeValid(NODE_TYPE_PLUGINS, "charger");
EXPECT_EQ(ret, -1);
}
HWTEST_F(InitGroupManagerUnitTest, TestGetGroupHashMap, TestSize.Level1)
{
HashMapHandle handle = GetGroupHashMap(NODE_TYPE_GROUPS);
EXPECT_TRUE(handle == nullptr);
}
} // namespace init_ut
......@@ -22,6 +22,7 @@
#include "trigger_manager.h"
#include "init_group_manager.h"
#include "init_cmdexecutor.h"
#include "reboot_adp.h"
using namespace testing::ext;
using namespace std;
......@@ -37,7 +38,7 @@ public:
#ifndef OHOS_LITE
static int g_result = 0;
HWTEST_F(InitRebootUnitTest, TestAddRebootCmd, TestSize.Level1)
HWTEST_F(InitRebootUnitTest, TestAddRebootCmdExt, TestSize.Level1)
{
auto rebootCallback = [](int id, const char *name, int argc, const char **argv) -> int {
return 0;
......@@ -86,6 +87,18 @@ HWTEST_F(InitRebootUnitTest, TestAddRebootCmd, TestSize.Level1)
ret = AddRebootCmdExecutor(nullptr, nullptr);
EXPECT_NE(ret, 0);
}
HWTEST_F(InitRebootUnitTest, TestAddRebootCmdNormal, TestSize.Level1)
{
SystemWriteParam("ohos.startup.powerctrl", "reboot");
SystemWriteParam("ohos.startup.powerctrl", "reboot,shutdown");
SystemWriteParam("ohos.startup.powerctrl", "reboot,suspend");
SystemWriteParam("ohos.startup.powerctrl", "reboot,charge");
SystemWriteParam("ohos.startup.powerctrl", "reboot,updater");
SystemWriteParam("ohos.startup.powerctrl", "reboot,updater:2222222");
SystemWriteParam("ohos.startup.powerctrl", "reboot,flashd");
SystemWriteParam("ohos.startup.powerctrl", "reboot,flashd:1000000");
}
#endif
HWTEST_F(InitRebootUnitTest, TestInitReboot, TestSize.Level1)
......@@ -107,6 +120,12 @@ HWTEST_F(InitRebootUnitTest, TestInitReboot, TestSize.Level1)
EXPECT_EQ(ret, 0);
ret = DoReboot(DEVICE_CMD_FREEZE);
EXPECT_EQ(ret, 0);
clearMisc();
ret = UpdateMiscMessage("charge:wwwwwwwwwww", "charge", "charge:", "boot_charge");
if (ret == 0) {
ret = GetBootModeFromMisc();
EXPECT_EQ(ret, GROUP_CHARGE);
clearMisc();
}
}
} // namespace init_ut
/*
* Copyright (c) 2022 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 <cerrno>
#include <cstdio>
#include <ctime>
#include <sys/types.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include "init.h"
#include "device.h"
#include "init_cmds.h"
#include "init_log.h"
#include "init_service.h"
#include "init_unittest.h"
#include "init_utils.h"
#include "loop_event.h"
#include "param_stub.h"
#include "fs_manager/fs_manager.h"
#include "fd_holder.h"
#include "fd_holder_service.h"
#include "bootstage.h"
#include "parameter.h"
using namespace testing::ext;
using namespace std;
extern "C" {
INIT_STATIC void ProcessSignal(const struct signalfd_siginfo *siginfo);
int SwitchRoot(const char *newRoot)
{
return 0;
}
}
namespace init_ut {
class InitUnitTest : public testing::Test {
public:
static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {};
void SetUp() {};
void TearDown() {};
};
HWTEST_F(InitUnitTest, TestSignalHandle, TestSize.Level1)
{
SignalInit();
struct signalfd_siginfo siginfo;
siginfo.ssi_signo = SIGCHLD;
ProcessSignal(&siginfo);
siginfo.ssi_signo = SIGTERM;
ProcessSignal(&siginfo);
siginfo.ssi_signo = SIGUSR1;
ProcessSignal(&siginfo);
SUCCEED();
}
HWTEST_F(InitUnitTest, TestSystemPrepare, TestSize.Level1)
{
SetStubResult(STUB_MOUNT, -1);
SetStubResult(STUB_MKNODE, -1);
MountBasicFs();
CreateDeviceNode();
SetStubResult(STUB_MOUNT, 0);
SetStubResult(STUB_MKNODE, 0);
MountBasicFs();
CreateDeviceNode();
}
HWTEST_F(InitUnitTest, TestSystemExecRcs, TestSize.Level1)
{
SystemExecuteRcs();
}
static void TestProcessTimer(const TimerHandle taskHandle, void *context)
{
static int count = 0;
printf("ProcessTimer %d\n", count);
if (count == 0) { // 2 stop
// set service pid for test
Service *service = GetServiceByName("param_watcher");
if (service != nullptr) {
service->pid = getpid();
}
int fds1[] = {1, 0};
ServiceSaveFd("param_watcher", fds1, ARRAY_LENGTH(fds1));
ServiceSaveFdWithPoll("param_watcher", fds1, 0);
ServiceSaveFdWithPoll("param_watcher", fds1, ARRAY_LENGTH(fds1));
EXPECT_EQ(setenv("OHOS_FD_HOLD_param_watcher", "1 0", 0), 0);
size_t fdCount = 0;
int *fds = ServiceGetFd("param_watcher", &fdCount);
EXPECT_TRUE(fds != nullptr);
ServiceSaveFd("testservice", fds1, ARRAY_LENGTH(fds1));
ServiceSaveFd("deviceinfoservice", fds1, ARRAY_LENGTH(fds1));
}
if (count == 1) {
LE_StopTimer(LE_GetDefaultLoop(), taskHandle);
LE_StopLoop(LE_GetDefaultLoop());
}
count++;
}
HWTEST_F(InitUnitTest, TestFdHoldService, TestSize.Level1)
{
RegisterFdHoldWatcher(-1);
TimerHandle timer = nullptr;
int ret = LE_CreateTimer(LE_GetDefaultLoop(), &timer, TestProcessTimer, nullptr);
EXPECT_EQ(ret, 0);
ret = LE_StartTimer(LE_GetDefaultLoop(), timer, 500, 2);
EXPECT_EQ(ret, 0);
SystemRun();
}
HWTEST_F(InitUnitTest, TestInitLog, TestSize.Level1)
{
EnableInitLogFromCmdline();
// test log
CheckAndCreateDir(INIT_LOG_PATH);
SetInitLogLevel(INIT_DEBUG);
INIT_LOGI("TestInitLog");
INIT_LOGV("TestInitLog");
INIT_LOGE("TestInitLog");
INIT_LOGW("TestInitLog");
INIT_LOGF("TestInitLog");
// restore log level
int32_t loglevel = GetIntParameter("persist.init.debug.loglevel", INIT_ERROR);
SetInitLogLevel((InitLogLevel)loglevel);
}
}
......@@ -32,25 +32,6 @@ public:
void TearDown() {};
};
HWTEST_F(MountUnitTest, TestMountRequriedPartitions, TestSize.Level0)
{
const char *fstabFiles = "/data/init_ut/etc/fstab.required";
Fstab *fstab = NULL;
fstab = ReadFstabFromFile(fstabFiles, false);
if (fstab != NULL) {
#ifdef __MUSL__
int ret = MountRequriedPartitions(fstab);
EXPECT_EQ(ret, -1);
#endif
ReleaseFstab(fstab);
} else {
Fstab fstab1;
fstab1.head = nullptr;
int ret = MountRequriedPartitions(&fstab1);
EXPECT_EQ(ret, -1);
}
ReleaseFstab(LoadRequiredFstab());
}
HWTEST_F(MountUnitTest, TestGetBlockDevicePath, TestSize.Level1)
{
char path[20] = {0}; // 20 is path length
......@@ -76,4 +57,9 @@ HWTEST_F(MountUnitTest, TestGetBlockDevicePath, TestSize.Level1)
ret = GetBlockDeviceByMountPoint("mountPoint", &fstab, devicename, sizeof(devicename));
EXPECT_EQ(ret, 0);
}
HWTEST_F(MountUnitTest, TestInvalidParam, TestSize.Level1)
{
int ret = MountRequriedPartitions(nullptr);
EXPECT_NE(ret, 0);
}
} // namespace init_ut
......@@ -59,7 +59,7 @@ int RestartSandbox(const char *sandbox)
DumpSandboxByName(sandbox);
std::cout << "dump sandbox" << std::endl;
if (PrepareSandbox(sandbox) != 0) {
std::cout << "Failed to prepare sandbox %s" << sandbox << std::endl;
std::cout << "Failed to prepare sandbox " << sandbox << std::endl;
DestroySandbox(sandbox);
CloseDefaultNamespace();
return 0;
......@@ -179,7 +179,7 @@ HWTEST_F(SandboxUnitTest, TestCreateNormalSandbox, TestSize.Level1) {
}
MakeFileByJson(mJson, SANDBOX_JSON_NAME);
int ret = RestartSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, 1);
ASSERT_EQ(ret, 0);
}
HWTEST_F(SandboxUnitTest, TestEnterErrorSandbox, TestSize.Level1) {
......@@ -269,6 +269,7 @@ HWTEST_F(SandboxUnitTest, TestSetNamespace, TestSize.Level1) {
HWTEST_F(SandboxUnitTest, TestGetNamespaceFd, TestSize.Level1) {
int ret1 = GetNamespaceFd("");
GetNamespaceFd(nullptr);
ASSERT_EQ(ret1, -1);
const std::string sandboxJsonPth = std::string("/mnt/sandbox/") + std::string(TEST_SANDBOX_NAME);
const char* cSandboxJsonPth = sandboxJsonPth.c_str();
......
......@@ -62,7 +62,29 @@ HWTEST_F(ServiceFileUnitTest, TestServiceFile, TestSize.Level1)
fileOpt->fd = 100; // 100 is fd
CreateServiceFile(fileOpt);
CloseServiceFile(fileOpt);
if (strncpy_s(fileOpt->fileName, strlen(fileName) + 1, "/dev/filetest", strlen("/dev/filetest")) != 0) {
free(fileOpt);
fileOpt = nullptr;
FAIL();
}
char *wrongName = (char *)malloc(PATH_MAX);
ASSERT_NE(wrongName, nullptr);
EXPECT_EQ(memset_s(wrongName, PATH_MAX, 1, PATH_MAX), 0);
ret = GetControlFile(wrongName);
EXPECT_NE(ret, 0);
GetControlFile("notExist");
GetControlFile(nullptr);
EXPECT_EQ(setenv("OHOS_FILE_ENV_PREFIX_testPath", "5", 0), 0);
GetControlFile("testPath");
EXPECT_EQ(setenv("OHOS_FILE_ENV_PREFIX_testPath1", "aaaaaaaa", 0), 0);
GetControlFile("testPath1");
fileOpt->fd = -1;
CreateServiceFile(fileOpt);
CloseServiceFile(fileOpt);
free(fileOpt);
free(wrongName);
fileOpt = nullptr;
wrongName = nullptr;
}
}
......@@ -60,9 +60,12 @@ HWTEST_F(ServiceSocketUnitTest, TestCreateSocket, TestSize.Level0)
service->socketCfg->next = sockopt;
}
int ret1 = CreateServiceSocket(service);
((WatcherTask *)((ServiceSocket *)service->socketCfg)->watcher)->processEvent(
LE_GetDefaultLoop(), 0, &eventid, service);
if (((ServiceSocket *)service->socketCfg)->watcher != nullptr) {
((WatcherTask *)((ServiceSocket *)service->socketCfg)->watcher)->processEvent(
LE_GetDefaultLoop(), 0, &eventid, service);
}
EXPECT_EQ(ret1, 0);
GetControlSocket(nullptr);
ret1 = GetControlSocket(testSocName);
EXPECT_GE(ret1, 0);
CloseServiceSocket(service);
......
......@@ -54,6 +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,"
"\"caps\":[\"TEST_ERR\"],"
"\"gid\":[\"system\"], \"critical\":1}}";
cJSON* jobItem = cJSON_Parse(jsonStr);
ASSERT_NE(nullptr, jobItem);
......@@ -76,7 +77,7 @@ 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]}}";
"\"gid\":[\"system\", \"shell\", \"root\"],\"caps\":[10, 4294967295, 10000],\"cpucore\":[1]}}";
cJSON* jobItem = cJSON_Parse(jsonStr);
ASSERT_NE(nullptr, jobItem);
cJSON *serviceItem = cJSON_GetObjectItem(jobItem, "services");
......@@ -111,7 +112,7 @@ HWTEST_F(ServiceUnitTest, case02, TestSize.Level1)
service->pid = 0xfffffff; // 0xfffffff is not exist pid
service->attribute = SERVICE_ATTR_TIMERSTART;
ret = ServiceStop(service);
EXPECT_NE(ret, 0);
EXPECT_EQ(ret, 0);
ReleaseService(service);
}
......@@ -119,7 +120,7 @@ HWTEST_F(ServiceUnitTest, TestServiceStartAbnormal, TestSize.Level1)
{
const char *jsonStr = "{\"services\":{\"name\":\"test_service1\",\"path\":[\"/data/init_ut/test_service\"],"
"\"importance\":-20,\"uid\":\"system\",\"writepid\":[\"/dev/test_service\"],\"console\":1,"
"\"gid\":[\"system\"]}}";
"\"gid\":[\"system\"],\"caps\":[\"\"]}}";
cJSON* jobItem = cJSON_Parse(jsonStr);
ASSERT_NE(nullptr, jobItem);
cJSON *serviceItem = cJSON_GetObjectItem(jobItem, "services");
......@@ -329,6 +330,20 @@ HWTEST_F(ServiceUnitTest, TestServiceBootEventHook, TestSize.Level1)
cJSON_Delete(fileRoot);
}
HWTEST_F(ServiceUnitTest, TestSetServiceContent, TestSize.Level1)
{
(void)WatchConsoleDevice(NULL);
Service service;
(void)WatchConsoleDevice(&service);
int fd = open("/dev/console", O_RDWR);
if (fd >= 0) {
(void)write(fd, "0", 1);
(void)close(fd);
}
PluginExecCmdByName("setServiceContent", "netmanager");
StopServiceByName("netmanager");
}
HWTEST_F(ServiceUnitTest, TestServiceExec, TestSize.Level1)
{
Service *service = AddService("test_service7");
......
......@@ -17,15 +17,39 @@
#include <sys/mount.h>
#include "fs_manager/fs_manager.h"
#include "init_log.h"
#include "init_param.h"
#include "param_stub.h"
#include "securec.h"
#include "systemcapability.h"
#include "service_control.h"
#include "control_fd.h"
#include "loop_event.h"
#include "fd_holder.h"
#include "fd_holder_internal.h"
using namespace testing::ext;
using namespace std;
namespace init_ut {
extern "C" {
void CmdDisConnectComplete(const TaskHandle client);
void CmdOnSendMessageComplete(const TaskHandle task, const BufferHandle handle);
void CmdOnClose(const TaskHandle task);
void CmdOnConnectComplete(const TaskHandle client);
void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint32_t buffLen);
int InitPtyInterface(CmdAgent *agent, uint16_t type, const char *cmd);
void ProcessPtyRead(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context);
void ProcessPtyWrite(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context);
int CmdOnIncommingConnect(const LoopHandle loop, const TaskHandle server);
CmdAgent *CmdAgentCreate(const char *server);
void CmdClientOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint32_t buffLen);
int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd, const char *ptyName);
int SendMessage(LoopHandle loop, TaskHandle task, const char *message);
int *GetFdsFromMsg(size_t *outFdCount, pid_t *requestPid, struct msghdr msghdr);
int BuildSendData(char *buffer, size_t size, const char *serviceName, bool hold, bool poll);
}
class InnerkitsUnitTest : public testing::Test {
public:
static void SetUpTestCase(void) {};
......@@ -47,7 +71,7 @@ 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 = STARTUP_INIT_UT_PATH"/mount_unitest/ReadFstabFromFile1.fstable";
fstab = ReadFstabFromFile(fstabFile2.c_str(), false);
EXPECT_NE(fstab, nullptr);
ParseFstabPerLine(const_cast<char *>("test"), fstab, true, nullptr);
......@@ -63,7 +87,7 @@ HWTEST_F(InnerkitsUnitTest, ReadFstabFromFile_unitest, TestSize.Level1)
*/
HWTEST_F(InnerkitsUnitTest, FindFstabItemForPath_unitest, TestSize.Level1)
{
const std::string fstabFile1 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable";
const std::string fstabFile1 = STARTUP_INIT_UT_PATH"/mount_unitest/ReadFstabFromFile1.fstable";
Fstab *fstab = nullptr;
fstab = ReadFstabFromFile(fstabFile1.c_str(), false);
ASSERT_NE(fstab, nullptr);
......@@ -101,7 +125,7 @@ HWTEST_F(InnerkitsUnitTest, FindFstabItemForPath_unitest, TestSize.Level1)
*/
HWTEST_F(InnerkitsUnitTest, FindFstabItemForMountPoint_unitest, TestSize.Level1)
{
const std::string fstabFile1 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable";
const std::string fstabFile1 = STARTUP_INIT_UT_PATH"/mount_unitest/ReadFstabFromFile1.fstable";
Fstab *fstab = nullptr;
fstab = ReadFstabFromFile(fstabFile1.c_str(), false);
ASSERT_NE(fstab, nullptr);
......@@ -130,7 +154,7 @@ HWTEST_F(InnerkitsUnitTest, FindFstabItemForMountPoint_unitest, TestSize.Level1)
*/
HWTEST_F(InnerkitsUnitTest, GetMountFlags_unitest, TestSize.Level1)
{
const std::string fstabFile1 = "/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable";
const std::string fstabFile1 = STARTUP_INIT_UT_PATH"/mount_unitest/ReadFstabFromFile1.fstable";
Fstab *fstab = nullptr;
fstab = ReadFstabFromFile(fstabFile1.c_str(), true);
ASSERT_NE(fstab, nullptr);
......@@ -186,6 +210,11 @@ HWTEST_F(InnerkitsUnitTest, GetBlockDevicePath_unittest, TestSize.Level1)
EXPECT_EQ(GetBlockDevicePath("/vendor", devicePath, MAX_BUFFER_LEN), 0);
EXPECT_EQ(GetBlockDevicePath("/misc", devicePath, MAX_BUFFER_LEN), 0);
EXPECT_EQ(GetBlockDevicePath("/invalid", devicePath, MAX_BUFFER_LEN), -1);
unlink(BOOT_CMD_LINE);
EXPECT_EQ(GetBlockDevicePath("/invalid", devicePath, MAX_BUFFER_LEN), -1);
EXPECT_NE(GetCurrentSlot(), 0);
// restore cmdline
PrepareCmdLineData();
}
/**
......@@ -199,6 +228,8 @@ HWTEST_F(InnerkitsUnitTest, DoFormat_unittest, TestSize.Level1)
{
EXPECT_NE(DoFormat("/testpath", "ext4"), -1);
EXPECT_NE(DoFormat("/testpath", "f2fs"), -1);
EXPECT_EQ(DoFormat("/testpath", "notFs"), -1);
EXPECT_EQ(DoFormat(nullptr, nullptr), -1);
}
/**
......@@ -210,9 +241,23 @@ HWTEST_F(InnerkitsUnitTest, DoFormat_unittest, TestSize.Level1)
*/
HWTEST_F(InnerkitsUnitTest, MountAllWithFstabFile_unittest, TestSize.Level1)
{
EXPECT_NE(MountAllWithFstabFile("/data/init_ut/etc/fstab.required", 0), 1);
EXPECT_NE(MountAllWithFstabFile(STARTUP_INIT_UT_PATH"/etc/fstab.required", 0), 1);
EXPECT_NE(UmountAllWithFstabFile(STARTUP_INIT_UT_PATH"/etc/fstab.required"), 1);
EXPECT_EQ(MountAllWithFstabFile("/testErrorFile", 0), -1);
EXPECT_EQ(MountAllWithFstabFile(nullptr, 0), -1);
EXPECT_EQ(GetMountStatusForMountPoint(nullptr), -1);
FstabItem fstabItem;
fstabItem.fsType = strdup("notSupport");
EXPECT_EQ(MountOneItem(nullptr), -1);
EXPECT_EQ(MountOneItem(&fstabItem), 0);
if (fstabItem.fsType != nullptr) {
free(fstabItem.fsType);
fstabItem.fsType = nullptr;
}
}
#define SYSCAP_MAX_SIZE 100
// TestSysCap
HWTEST_F(InnerkitsUnitTest, TestSysCap, TestSize.Level1)
{
......@@ -224,14 +269,22 @@ HWTEST_F(InnerkitsUnitTest, TestSysCap, TestSize.Level1)
EXPECT_EQ(ret, true);
ret = HasSystemCapability("SystemCapability.ArkUI.ArkUI.Napi");
EXPECT_EQ(ret, true);
char *wrongName = (char *)malloc(SYSCAP_MAX_SIZE);
ASSERT_NE(wrongName, nullptr);
EXPECT_EQ(memset_s(wrongName, SYSCAP_MAX_SIZE, 1, SYSCAP_MAX_SIZE), 0);
HasSystemCapability(wrongName);
free(wrongName);
}
// TestControlService
HWTEST_F(InnerkitsUnitTest, TestControlService, TestSize.Level1)
{
TestSetParamCheckResult("startup.service.ctl.", 0777, 0);
ServiceControl("deviceinfoservice", START);
ServiceControl("deviceinfoservice", STOP);
SystemWriteParam("startup.service.ctl.deviceinfoservice", "2");
ServiceControl("deviceinfoservice", RESTART);
ServiceControl("deviceinfoservice", STOP);
SystemWriteParam("startup.service.ctl.deviceinfoservice", "0");
ServiceControl("param_watcher", RESTART);
EXPECT_EQ(ServiceControl(nullptr, RESTART), -1);
const char *argv[] = {"testArg"};
......@@ -239,6 +292,7 @@ HWTEST_F(InnerkitsUnitTest, TestControlService, TestSize.Level1)
ServiceControlWithExtra(nullptr, RESTART, argv, 1);
ServiceControlWithExtra(nullptr, 3, argv, 1); // 3 is action
ServiceControlWithExtra("notservie", RESTART, argv, 1);
ServiceControlWithExtra("deviceinfoservice", 3, argv, 1); // 3 is action
ServiceSetReady("deviceinfoservice");
ServiceSetReady(nullptr);
ServiceWaitForStatus("deviceinfoservice", SERVICE_READY, 1);
......@@ -250,4 +304,168 @@ HWTEST_F(InnerkitsUnitTest, TestControlService, TestSize.Level1)
StopServiceTimer("deviceinfoservice");
}
static int TestIncommingConnect(const LoopHandle loop, const TaskHandle server)
{
UNUSED(loop);
UNUSED(server);
return 0;
}
// TestControlFd
HWTEST_F(InnerkitsUnitTest, TestControlFd, TestSize.Level1)
{
CmdClientInit("/data/testSock1", ACTION_DUMP, "cmd");
CmdClientInit("/data/testSock1", ACTION_DUMP, "cmd");
CmdClientInit(INIT_CONTROL_FD_SOCKET_PATH, ACTION_DUMP, nullptr);
CmdClientInit(nullptr, ACTION_DUMP, "cmd");
CmdDisConnectComplete(nullptr);
CmdOnSendMessageComplete(nullptr, nullptr);
CmdOnConnectComplete(nullptr);
CmdClientOnRecvMessage(nullptr, nullptr, 0);
CmdAgentCreate(nullptr);
CmdAgent *agent = CmdAgentCreate(INIT_CONTROL_FD_SOCKET_PATH);
EXPECT_NE(agent, nullptr);
SendCmdMessage(agent, ACTION_DUMP, "cmd", "test");
SendCmdMessage(agent, ACTION_DUMP, "cmd", nullptr);
SendMessage(nullptr, nullptr, nullptr);
uint32_t events = 0;
InitPtyInterface(agent, 0, "cmd");
InitPtyInterface(agent, 0, nullptr);
InitPtyInterface(nullptr, 0, nullptr);
mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
CheckAndCreatFile("/data/init_ut/testInput", mode);
int fd = open("/data/init_ut/testInput", O_RDWR);
perror("write failed");
EXPECT_GT(fd, 0);
EXPECT_GT(write(fd, "test", strlen("test")), 0);
perror("write failed");
lseek(fd, 0, SEEK_SET);
ProcessPtyRead(nullptr, fd, &events, (void *)agent);
ProcessPtyRead(nullptr, fd, &events, (void *)agent);
ProcessPtyRead(nullptr, STDERR_FILENO, &events, nullptr);
lseek(fd, 0, SEEK_SET);
ProcessPtyWrite(nullptr, fd, &events, (void *)agent);
ProcessPtyWrite(nullptr, fd, &events, (void *)agent);
ProcessPtyWrite(nullptr, STDERR_FILENO, &events, nullptr);
close(fd);
CmdOnClose(agent->task);
}
HWTEST_F(InnerkitsUnitTest, TestControlFdServer, TestSize.Level1)
{
CmdServiceInit(nullptr, nullptr);
CmdServiceInit("/data/testSock1", [](uint16_t type, const char *serviceCmd, const void *context) {
UNUSED(type);
UNUSED(serviceCmd);
UNUSED(context);
});
TaskHandle testServer;
LE_StreamServerInfo info = {};
info.baseInfo.flags = TASK_STREAM | TASK_SERVER | TASK_PIPE | TASK_TEST;
info.server = (char *)"/data/testSock1";
info.socketId = -1;
info.baseInfo.close = NULL;
info.disConnectComplete = NULL;
info.incommingConnect = TestIncommingConnect;
info.sendMessageComplete = NULL;
info.recvMessage = NULL;
(void)LE_CreateStreamServer(LE_GetDefaultLoop(), &testServer, &info);
CmdOnIncommingConnect(LE_GetDefaultLoop(), testServer);
CmdOnRecvMessage(testServer, nullptr, 0);
CmdMessage *cmdMsg = (CmdMessage *)malloc(sizeof(CmdMessage) + strlen("test"));
cmdMsg->type = ACTION_DUMP;
cmdMsg->ptyName[0] = '\0';;
CmdOnRecvMessage(testServer, (uint8_t *)(&cmdMsg), 0);
cmdMsg->type = ACTION_DUMP;
cmdMsg->cmd[0] = 'a';
cmdMsg->ptyName[0] = 'a';
CmdOnRecvMessage(testServer, (uint8_t *)(&cmdMsg), 0);
CmdServiceProcessDelClient(0);
CmdServiceProcessDelClient(0);
free(cmdMsg);
}
HWTEST_F(InnerkitsUnitTest, TestHoldFd, TestSize.Level1)
{
int fds1[] = {1, 0};
ServiceSaveFd("testServiceName", fds1, ARRAY_LENGTH(fds1));
ServiceSaveFd(nullptr, fds1, ARRAY_LENGTH(fds1));
ServiceSaveFdWithPoll("testServiceName", fds1, 0);
ServiceSaveFdWithPoll(nullptr, fds1, 0);
ServiceSaveFdWithPoll("testServiceName", fds1, ARRAY_LENGTH(fds1));
EXPECT_EQ(setenv("OHOS_FD_HOLD_testServiceName", "1 0", 0), 0);
size_t fdCount = 0;
int *fds = nullptr;
ServiceGetFd("testService", nullptr);
ServiceGetFd("testService", &fdCount);
char *wrongName = (char *)malloc(MAX_FD_HOLDER_BUFFER + 1);
ASSERT_NE(wrongName, nullptr);
EXPECT_EQ(memset_s(wrongName, MAX_FD_HOLDER_BUFFER + 1, 1, MAX_FD_HOLDER_BUFFER + 1), 0);
ServiceGetFd(wrongName, &fdCount);
BuildSendData(wrongName, 1, "testService", 0, 1);
BuildSendData(wrongName, 1, "testService", 0, 0);
BuildSendData(nullptr, 1, "testService", 0, 0);
free(wrongName);
fds = ServiceGetFd("testServiceName", &fdCount);
EXPECT_NE(fds, nullptr);
struct msghdr msghdr;
BuildControlMessage(nullptr, nullptr, 1, 0);
BuildControlMessage(&msghdr, nullptr, 1, 0);
BuildControlMessage(&msghdr, fds, -1, 0);
BuildControlMessage(&msghdr, fds, -1, 1);
if (fds != nullptr)
{
free(fds);
fds = nullptr;
}
}
HWTEST_F(InnerkitsUnitTest, TestHoldFd2, TestSize.Level1)
{
size_t fdCount = 0;
int *fds = nullptr;
char buffer[MAX_FD_HOLDER_BUFFER + 1] = {};
pid_t requestPid = -1;
struct msghdr msghdr;
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
msghdr.msg_flags = MSG_TRUNC;
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
msghdr.msg_flags = 0;
msghdr.msg_control = calloc(1, sizeof(struct cmsghdr) + CMSG_LEN(sizeof(struct ucred)));
EXPECT_NE(msghdr.msg_control, nullptr);
msghdr.msg_controllen = sizeof(struct cmsghdr);
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
struct iovec iovec = {
.iov_base = buffer,
.iov_len = MAX_FD_HOLDER_BUFFER,
};
((struct cmsghdr *)msghdr.msg_control)->cmsg_level = 1;
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
((struct cmsghdr *)msghdr.msg_control)->cmsg_level = 0;
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
((struct cmsghdr *)msghdr.msg_control)->cmsg_level = 1;
((struct cmsghdr *)msghdr.msg_control)->cmsg_type = 1;
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
((struct cmsghdr *)msghdr.msg_control)->cmsg_level = 1;
((struct cmsghdr *)msghdr.msg_control)->cmsg_type = SCM_CREDENTIALS;
((struct cmsghdr *)msghdr.msg_control)->cmsg_len = CMSG_LEN(sizeof(struct ucred));
GetFdsFromMsg(&fdCount, &requestPid, msghdr);
ReceiveFds(0, iovec, &fdCount, false, &requestPid);
fds = ReceiveFds(0, iovec, &fdCount, true, &requestPid);
if (fds != nullptr)
{
free(fds);
fds = nullptr;
}
if (msghdr.msg_control != nullptr) {
free(msghdr.msg_control);
}
}
} // namespace init_ut
......@@ -12,6 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bootstage.h"
#include "init_cmds.h"
#include "init_group_manager.h"
#include "init_hashmap.h"
......@@ -62,6 +63,7 @@ HWTEST_F(ModuleMgrUnitTest, PluginAddCmd, TestSize.Level1)
const char *cmdName = PluginGetCmdIndex(cmdContent, &cmdIndex);
ASSERT_EQ(strcmp(cmdName, testName), 0);
printf("TestCmdExecutor cmdIndex 0x%04x, name %s \n", cmdIndex, cmdName);
ASSERT_NE(GetPluginCmdNameByIndex(cmdIndex), nullptr);
// exec
g_cmdExecId = -1;
......@@ -72,9 +74,10 @@ HWTEST_F(ModuleMgrUnitTest, PluginAddCmd, TestSize.Level1)
g_cmdExecId = -1;
PluginExecCmdByCmdIndex(cmdIndex, cmdContent);
ASSERT_EQ(cmdExecId1, g_cmdExecId);
const char *argv[] = {"test"};
const char *argv[] = {"test.value"};
PluginExecCmd("install", 1, argv);
PluginExecCmd("uninstall", 1, argv);
PluginExecCmd("setloglevel", 1, argv);
// del
RemoveCmdExecutor("testCmd4", cmdExecId4);
......@@ -86,6 +89,8 @@ HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1)
int cnt;
// Create module manager
ASSERT_EQ(ModuleMgrCreate(nullptr), nullptr);
ModuleMgrDestroy(nullptr);
MODULE_MGR *moduleMgr = ModuleMgrCreate("init");
ASSERT_NE(moduleMgr, nullptr);
cnt = ModuleMgrGetCnt(moduleMgr);
......@@ -99,6 +104,7 @@ HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1)
// Uninstall the module
ModuleMgrUninstall(moduleMgr, "bootchart");
InitModuleMgrUnInstall("bootchart");
cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0);
......@@ -123,6 +129,15 @@ HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1)
ModuleMgrDestroy(moduleMgr);
// Scan all modules
ModuleMgrScan(nullptr);
// test updater mode
int fd = open("/bin/updater", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRWXU);
ASSERT_NE(fd, 0);
ModuleMgrScan("init/autorun");
unlink("/bin/updater");
close(fd);
moduleMgr = ModuleMgrScan("init/autorun");
ASSERT_NE(moduleMgr, nullptr);
cnt = ModuleMgrGetCnt(moduleMgr);
......@@ -152,7 +167,9 @@ HWTEST_F(ModuleMgrUnitTest, ModuleTraversalTest, TestSize.Level1)
ASSERT_EQ(ret, 0);
cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 1);
ModuleMgrTraversal(nullptr, nullptr, nullptr);
ModuleMgrTraversal(moduleMgr, NULL, TestModuleDump);
InitModuleMgrDump();
ModuleMgrDestroy(moduleMgr);
}
......@@ -164,6 +181,7 @@ HWTEST_F(ModuleMgrUnitTest, ModuleScanTest, TestSize.Level1)
int cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_GE(cnt, 1);
ModuleMgrUninstall(nullptr, nullptr);
ModuleMgrUninstall(moduleMgr, NULL);
cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0);
......@@ -172,8 +190,10 @@ HWTEST_F(ModuleMgrUnitTest, ModuleScanTest, TestSize.Level1)
// scan /lib/init/
moduleMgr = ModuleMgrScan("/lib/init");
ASSERT_NE(moduleMgr, nullptr);
ModuleMgrGetCnt(nullptr);
cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_GE(cnt, 1);
ModuleMgrDestroy(moduleMgr);
EXPECT_EQ(InitModuleMgrInstall(nullptr), -1);
}
} // namespace init_ut
......@@ -73,7 +73,6 @@ if (defined(ohos_lite)) {
"STARTUP_INIT_TEST",
"PARAM_SUPPORT_DAC",
"USE_MBEDTLS",
"STARTUP_INIT_UT_PATH =\"/userdata/init_ut\"",
]
if (storage_type == "emmc") {
defines += [ "USE_EMMC_STORAGE" ]
......@@ -115,9 +114,15 @@ if (defined(ohos_lite)) {
sources += param_common_sources
sources += base_sources
deps = [ "//third_party/bounds_checking_function:libsec_static" ]
if (enable_ohos_startup_init_feature_begetctl_liteos) {
defines += [ "LITEOS_SUPPORT" ]
}
if (ohos_kernel_type == "liteos_a") {
defines += [ "__LITEOS_A__" ]
defines += [
"__LITEOS_A__",
"STARTUP_INIT_UT_PATH =\"/userdata/init_ut\"",
]
include_dirs += [
"//kernel/liteos_a/syscall",
"//base/startup/init/interfaces/kits/syscap",
......@@ -168,7 +173,10 @@ if (defined(ohos_lite)) {
}
if (ohos_kernel_type == "liteos_m") {
defines += [ "__LITEOS_M__" ]
defines += [
"__LITEOS_M__",
"STARTUP_INIT_UT_PATH =\"/\"",
]
sources += [
"//base/startup/init/services/param/liteos/param_client.c",
"//base/startup/init/services/param/liteos/param_hal.c",
......@@ -199,7 +207,10 @@ if (defined(ohos_lite)) {
]
}
if (ohos_kernel_type == "linux") {
defines += [ "__LINUX__" ]
defines += [
"__LINUX__",
"STARTUP_INIT_UT_PATH =\"/data/init_ut\"",
]
sources += init_common_sources
sources += [
......
......@@ -103,6 +103,7 @@ public:
info.incomingConnect = OnIncomingConnect;
return ParamServerCreate(&serverTask_, &info);
}
void StreamTaskTest ()
{
LE_StreamInfo streamInfo = {};
......@@ -114,26 +115,10 @@ public:
if (clientTaskHandle == nullptr) {
return;
}
((StreamConnectTask *)clientTaskHandle)->stream.base.handleEvent(LE_GetDefaultLoop(),
(TaskHandle)clientTaskHandle, Event_Read);
((StreamConnectTask *)clientTaskHandle)->stream.base.handleEvent(LE_GetDefaultLoop(),
(TaskHandle)clientTaskHandle, Event_Write);
((StreamConnectTask *)clientTaskHandle)->stream.base.handleEvent(LE_GetDefaultLoop(),
(TaskHandle)clientTaskHandle, 0);
streamInfo.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_SERVER;
streamInfo.server = (char *)"/data/testpipeb";
TaskHandle clientTaskHandleb = nullptr;
LE_CreateStreamClient(LE_GetDefaultLoop(), &clientTaskHandleb, &streamInfo);
if (clientTaskHandleb == nullptr) {
return;
}
((StreamClientTask *)clientTaskHandleb)->stream.base.handleEvent(LE_GetDefaultLoop(),
clientTaskHandleb, Event_Read);
((StreamClientTask *)clientTaskHandleb)->stream.base.handleEvent(LE_GetDefaultLoop(),
clientTaskHandleb, Event_Write);
((StreamClientTask *)clientTaskHandleb)->stream.base.innerClose(LE_GetDefaultLoop(), clientTaskHandleb);
((StreamConnectTask *)clientTaskHandle)->stream.base.handleEvent(LE_GetDefaultLoop(),
(TaskHandle)clientTaskHandle, Event_Read);
TaskHandle clientTaskHandlec = nullptr;
streamInfo.baseInfo.flags = TASK_STREAM | TASK_TCP | TASK_SERVER;
......@@ -178,6 +163,7 @@ public:
LE_Buffer *buffer = (LE_Buffer *)handle;
AddBuffer((StreamTask *)client, buffer);
((StreamConnectTask *)client)->stream.base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)(client), Event_Write);
EXPECT_NE(LE_GetSendResult(handle), 0);
ParamMessage *request = (ParamMessage *)CreateParamMessage(MSG_SET_PARAM, "name", sizeof(ParamMessage));
((StreamConnectTask *)client)->recvMessage(LE_GetDefaultLoop(), reinterpret_cast<uint8_t *>(request),
......@@ -201,8 +187,8 @@ public:
if (task != nullptr) {
task->handleEvent = TestHandleTaskEvent;
ProcessEvent((EventLoop *)LE_GetDefaultLoop(), testfd, Event_Read);
((HashTab *)(((EventLoop *)LE_GetDefaultLoop())->taskMap))->nodeFree(&task->hashNode);
}
((HashTab *)(((EventLoop *)LE_GetDefaultLoop())->taskMap))->nodeFree(&task->hashNode);
}
void ProcessasynEvent()
{
......@@ -317,6 +303,22 @@ HWTEST_F(LoopEventUnittest, LoopRunTest, TestSize.Level1)
ASSERT_EQ(ret, 0);
ret = LE_StartTimer(g_loop, timer, 500, 2);
ASSERT_EQ(ret, 0);
// test invalid
ret = LE_CreateTimer(nullptr, &timer, Test_ProcessTimer, nullptr);
ASSERT_NE(ret, 0);
ret = LE_CreateTimer(g_loop, nullptr, Test_ProcessTimer, nullptr);
ASSERT_NE(ret, 0);
ret = LE_CreateTimer(g_loop, &timer, nullptr, nullptr);
ASSERT_NE(ret, 0);
ret = LE_StartTimer(nullptr, timer, 500, 2);
ASSERT_NE(ret, 0);
ret = LE_StartTimer(g_loop, nullptr, 500, 2);
ASSERT_NE(ret, 0);
LE_StopTimer(nullptr, timer);
LE_StopTimer(g_loop, nullptr);
LE_CloseLoop(g_loop);
LE_RunLoop(g_loop);
LE_CloseLoop(g_loop);
......
/*
* 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 <gtest/gtest.h>
#include <thread>
#include <sys/eventfd.h>
#include "begetctl.h"
#include "cJSON.h"
#include "init.h"
#include "init_hashmap.h"
#include "init_param.h"
#include "init_utils.h"
#include "le_epoll.h"
#include "le_loop.h"
#include "le_socket.h"
#include "le_task.h"
#include "loop_event.h"
#include "param_manager.h"
#include "param_message.h"
#include "param_utils.h"
#include "trigger_manager.h"
using namespace testing::ext;
using namespace std;
namespace init_ut {
const std::string TCP_SERVER = "127.0.0.1:7777";
const std::string PIPE_SERVER = STARTUP_INIT_UT_PATH "/dev/unix/socket/testsocket";
const std::string WATCHER_FILE = STARTUP_INIT_UT_PATH "/test_watcher_file";
const std::string FORMAT_STR = "{ \"cmd\":%d, \"message\":\"%s\" }";
static LoopHandle g_loopClient_ = nullptr;
static LoopHandle g_loopServer_ = nullptr;
static int g_maxCount = 0;
static int g_timeCount = 0;
static int g_cmd = 2;
static void DecodeMessage(const char *buffer, size_t nread, uint32_t &cmd)
{
cJSON *root = cJSON_ParseWithLength(buffer, nread);
if (root == nullptr) {
EXPECT_NE(root, nullptr);
printf("Invalid message %s \n", buffer);
return;
}
printf("Message: %s \n", cJSON_GetStringValue(cJSON_GetObjectItem(root, "message")));
cmd = cJSON_GetNumberValue(cJSON_GetObjectItem(root, "cmd"));
printf("cmd: %d \n", cmd);
cJSON_Delete(root);
return;
}
static void SendMessage(const LoopHandle loopHandle, const TaskHandle taskHandle, const char *message, ...)
{
uint32_t bufferSize = 1024; // 1024 buffer size
BufferHandle handle = LE_CreateBuffer(loopHandle, bufferSize);
char *buffer = (char *)LE_GetBufferInfo(handle, nullptr, &bufferSize);
va_list vargs;
va_start(vargs, message);
if (vsnprintf_s(buffer, bufferSize, bufferSize - 1, message, vargs) == -1) {
LE_FreeBuffer(loopHandle, taskHandle, handle);
va_end(vargs);
EXPECT_EQ(1, 0);
return;
}
va_end(vargs);
int ret = LE_Send(loopHandle, taskHandle, handle, bufferSize);
EXPECT_EQ(ret, 0);
}
static void TestOnClose(const TaskHandle taskHandle)
{
}
static LE_STATUS TestHandleTaskEvent(const LoopHandle loop, const TaskHandle task, uint32_t oper)
{
return LE_SUCCESS;
}
static void TestOnReceiveRequest(const TaskHandle task, const uint8_t *buffer, uint32_t nread)
{
EXPECT_NE(buffer, nullptr);
if (buffer == nullptr) {
return;
}
printf("Server receive message %s \n", reinterpret_cast<const char *>(buffer));
uint32_t cmd = 0;
DecodeMessage(reinterpret_cast<const char *>(buffer), nread, cmd);
SendMessage(g_loopServer_, task, reinterpret_cast<const char *>(buffer));
}
static void TestClientOnReceiveRequest(const TaskHandle task, const uint8_t *buffer, uint32_t nread)
{
printf("Client receive message %s \n", reinterpret_cast<const char *>(buffer));
EXPECT_NE(buffer, nullptr);
if (buffer == nullptr) {
return;
}
uint32_t cmd = 0;
DecodeMessage(reinterpret_cast<const char *>(buffer), nread, cmd);
if (cmd == 5 || cmd == 2) { // 2 5 close server
LE_StopLoop(g_loopClient_);
}
}
static void ProcessAsyncEvent(const TaskHandle taskHandle, uint64_t eventId, const uint8_t *buffer, uint32_t buffLen)
{
UNUSED(taskHandle);
UNUSED(eventId);
UNUSED(buffer);
UNUSED(buffLen);
}
static void TestSendMessageComplete(const TaskHandle taskHandle, BufferHandle handle)
{
printf("SendMessage result %d \n", LE_GetSendResult(handle));
uint32_t bufferSize = 1024; // 1024 buffer size
char *buffer = (char *)LE_GetBufferInfo(handle, nullptr, &bufferSize);
uint32_t cmd = 0;
DecodeMessage(reinterpret_cast<const char *>(buffer), bufferSize, cmd);
if (cmd == 5) { // 5 close server
LE_StopLoop(g_loopServer_);
}
}
static int TestTcpIncomingConnect(LoopHandle loop, TaskHandle server)
{
PARAM_CHECK(server != nullptr, return -1, "Error server");
printf("Tcp connect incoming \n");
TaskHandle stream;
LE_StreamInfo info = {};
info.baseInfo.flags = TASK_STREAM | TASK_TCP | TASK_CONNECT;
info.baseInfo.close = TestOnClose;
info.baseInfo.userDataSize = 0;
info.disConnectComplete = nullptr;
info.sendMessageComplete = TestSendMessageComplete;
info.recvMessage = TestOnReceiveRequest;
LE_STATUS ret = LE_AcceptStreamClient(loop, server, &stream, &info);
EXPECT_EQ(ret, 0);
return 0;
}
static int TestPipIncomingConnect(LoopHandle loop, TaskHandle server)
{
PARAM_CHECK(server != nullptr, return -1, "Error server");
printf("Pipe connect incoming \n");
TaskHandle stream;
LE_StreamInfo info = {};
info.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_CONNECT;
info.baseInfo.close = TestOnClose;
info.baseInfo.userDataSize = 0;
info.disConnectComplete = nullptr;
info.sendMessageComplete = TestSendMessageComplete;
info.recvMessage = TestOnReceiveRequest;
LE_STATUS ret = LE_AcceptStreamClient(loop, server, &stream, &info);
EXPECT_EQ(ret, 0);
return 0;
}
static void TestConnectComplete(const TaskHandle client)
{
printf("Connect complete \n");
}
static void TestDisConnectComplete(const TaskHandle client)
{
printf("DisConnect complete \n");
LE_StopLoop(g_loopClient_);
}
static void TestProcessTimer(const TimerHandle taskHandle, void *context)
{
g_timeCount++;
printf("ProcessTimer %d\n", g_timeCount);
if (g_maxCount == 2) { // 2 stop
if (g_timeCount >= g_maxCount) {
LE_StopLoop(g_loopClient_);
}
}
if (g_maxCount == 3) { // 3 stop timer
if (g_timeCount >= g_maxCount) {
LE_StopTimer(g_loopClient_, taskHandle);
LE_StopLoop(g_loopClient_);
}
}
if (g_maxCount == 10) { // 10 write watcher file
FILE *tmpFile = fopen(WATCHER_FILE.c_str(), "wr");
if (tmpFile != nullptr) {
fprintf(tmpFile, "%s", "test watcher file 22222222222");
(void)fflush(tmpFile);
fclose(tmpFile);
}
LE_StopTimer(g_loopClient_, taskHandle);
LE_StopLoop(g_loopClient_);
}
}
static void ProcessWatchEventTest(WatcherHandle taskHandle, int fd, uint32_t *events, const void *context)
{
UNUSED(taskHandle);
UNUSED(fd);
UNUSED(events);
UNUSED(context);
printf("Process watcher event \n");
LE_StopLoop(g_loopClient_);
}
class LoopServerUnitTest : public testing::Test {
public:
LoopServerUnitTest() {};
virtual ~LoopServerUnitTest() {};
static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {};
void SetUp() {};
void TearDown() {};
void TestBody(void) {};
// for thread to create tcp\pipe server
void RunServer(void)
{
TaskHandle tcpServer = nullptr;
TaskHandle pipeServer = nullptr;
LE_STATUS ret = LE_CreateLoop(&g_loopServer_);
EXPECT_EQ(ret, 0);
// create server for tcp
LE_StreamServerInfo info = {};
info.baseInfo.flags = TASK_STREAM | TASK_TCP | TASK_SERVER;
info.socketId = -1;
info.server = const_cast<char *>(TCP_SERVER.c_str());
info.baseInfo.close = TestOnClose;
info.incommingConnect = TestTcpIncomingConnect;
ret = LE_CreateStreamServer(g_loopServer_, &tcpServer, &info);
EXPECT_EQ(ret, 0);
info.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_SERVER;
info.socketId = -1;
info.server = const_cast<char *>(PIPE_SERVER.c_str());
info.baseInfo.close = TestOnClose;
info.incommingConnect = TestPipIncomingConnect;
ret = LE_CreateStreamServer(g_loopServer_, &pipeServer, &info);
EXPECT_EQ(ret, 0);
printf("Run server pipeServer_ %p \n", pipeServer);
// run loop for server
LE_RunLoop(g_loopServer_);
printf("Run server pipeServer_ %p \n", pipeServer);
LE_CloseStreamTask(g_loopServer_, pipeServer);
pipeServer = nullptr;
LE_CloseStreamTask(g_loopServer_, tcpServer);
tcpServer = nullptr;
LE_CloseLoop(g_loopServer_);
g_loopServer_ = nullptr;
}
void StartServer()
{
serverThread_ = new (std::nothrow)std::thread(&LoopServerUnitTest::RunServer, this);
sleep(1);
}
TaskHandle CreateConnect(const char *tcpServer, uint32_t flags)
{
if (g_loopClient_ == nullptr) {
LE_STATUS ret = LE_CreateLoop(&g_loopClient_);
EXPECT_EQ(ret, 0);
}
TaskHandle task = nullptr;
LE_StreamInfo info = {};
info.baseInfo.flags = TASK_STREAM | flags | TASK_CONNECT;
info.server = const_cast<char *>(tcpServer);
info.baseInfo.userDataSize = 0;
info.baseInfo.close = TestOnClose;
info.disConnectComplete = TestDisConnectComplete;
info.connectComplete = TestConnectComplete;
info.sendMessageComplete = nullptr;
info.recvMessage = TestClientOnReceiveRequest;
LE_STATUS status = LE_CreateStreamClient(g_loopClient_, &task, &info);
EXPECT_EQ(status, 0);
return task;
}
WatcherHandle CreateWatcherTask(int fd, const char *fileName)
{
if (g_loopClient_ == nullptr) {
LE_STATUS ret = LE_CreateLoop(&g_loopClient_);
EXPECT_EQ(ret, 0);
}
WatcherHandle handle = nullptr;
LE_WatchInfo info = {};
info.fd = fd;
info.flags = WATCHER_ONCE;
info.events = Event_Read | Event_Write;
info.processEvent = ProcessWatchEventTest;
LE_STATUS status = LE_StartWatcher(g_loopClient_, &handle, &info, nullptr);
EXPECT_EQ(status, 0);
return handle;
}
TimerHandle CreateTimerTask(int repeat)
{
if (g_loopClient_ == nullptr) {
LE_STATUS ret = LE_CreateLoop(&g_loopClient_);
EXPECT_EQ(ret, 0);
}
TimerHandle timer = nullptr;
int ret = LE_CreateTimer(g_loopClient_, &timer, TestProcessTimer, nullptr);
EXPECT_EQ(ret, 0);
ret = LE_StartTimer(g_loopClient_, timer, 500, repeat); // 500 ms
EXPECT_EQ(ret, 0);
return timer;
}
private:
std::thread *serverThread_ = nullptr;
};
HWTEST_F(LoopServerUnitTest, TestRunServer, TestSize.Level1)
{
LoopServerUnitTest test;
test.StartServer();
}
HWTEST_F(LoopServerUnitTest, TestPipConnect, TestSize.Level1)
{
g_cmd = 2; // 2 only close client
LoopServerUnitTest test;
TaskHandle pipe = test.CreateConnect(PIPE_SERVER.c_str(), TASK_PIPE);
EXPECT_NE(pipe, nullptr);
SendMessage(g_loopClient_, pipe, FORMAT_STR.c_str(), g_cmd, "connect success");
LE_RunLoop(g_loopClient_);
LE_CloseStreamTask(g_loopClient_, pipe);
LE_CloseLoop(g_loopClient_);
g_loopClient_ = nullptr;
}
HWTEST_F(LoopServerUnitTest, TestTcpConnect, TestSize.Level1)
{
g_cmd = 2; // 2 only close client
LoopServerUnitTest test;
TaskHandle tcp = test.CreateConnect(TCP_SERVER.c_str(), TASK_TCP);
EXPECT_NE(tcp, nullptr);
SendMessage(g_loopClient_, tcp, FORMAT_STR.c_str(), g_cmd, "connect success");
LE_RunLoop(g_loopClient_);
LE_CloseStreamTask(g_loopClient_, tcp);
LE_CloseLoop(g_loopClient_);
g_loopClient_ = nullptr;
}
HWTEST_F(LoopServerUnitTest, TestTimer, TestSize.Level1)
{
LoopServerUnitTest test;
g_maxCount = 2; // 2 stop
TimerHandle timer = test.CreateTimerTask(2);
EXPECT_NE(timer, nullptr);
LE_RunLoop(g_loopClient_);
LE_CloseLoop(g_loopClient_);
g_loopClient_ = nullptr;
}
HWTEST_F(LoopServerUnitTest, TestTimer2, TestSize.Level1)
{
LoopServerUnitTest test;
g_maxCount = 3; // 3 stop timer
TimerHandle timer = test.CreateTimerTask(3);
EXPECT_NE(timer, nullptr);
LE_RunLoop(g_loopClient_);
LE_CloseLoop(g_loopClient_);
g_loopClient_ = nullptr;
}
HWTEST_F(LoopServerUnitTest, TestWatcher, TestSize.Level1)
{
int fd = open(WATCHER_FILE.c_str(), O_RDWR | O_CREAT);
if (fd >= 0) {
write(fd, WATCHER_FILE.c_str(), WATCHER_FILE.size());
}
EXPECT_GE(fd, 0);
printf("Watcher fd %d \n", fd);
LoopServerUnitTest test;
WatcherHandle watcher = test.CreateWatcherTask(3, WATCHER_FILE.c_str());
EXPECT_NE(watcher, nullptr);
g_maxCount = 10; // 10 write watcher file
TimerHandle timer = test.CreateTimerTask(1);
EXPECT_NE(timer, nullptr);
LE_RunLoop(g_loopClient_);
LE_RemoveWatcher(g_loopClient_, watcher);
close(fd);
LE_CloseLoop(g_loopClient_);
g_loopClient_ = nullptr;
}
HWTEST_F(LoopServerUnitTest, TestStopServer, TestSize.Level1)
{
g_cmd = 5; // 5 close server
LoopServerUnitTest test;
TaskHandle pip = test.CreateConnect(PIPE_SERVER.c_str(), TASK_PIPE);
EXPECT_NE(pip, nullptr);
SendMessage(g_loopClient_, pip, FORMAT_STR.c_str(), g_cmd, "connect success");
LE_RunLoop(g_loopClient_);
LE_CloseStreamTask(g_loopClient_, pip);
LE_CloseLoop(g_loopClient_);
g_loopClient_ = nullptr;
}
} // namespace init_ut
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Copyright (c) 2022 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
* 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,
......@@ -27,13 +27,13 @@ using namespace std;
static SignalHandle g_sigHandler = nullptr;
static void ProcessSignal(const struct signalfd_siginfo *siginfo)
static void TestProcessSignal(const struct signalfd_siginfo *siginfo)
{
return;
}
namespace init_ut {
class SignalInitUnitTest : public testing::Test {
class LoopSignalUnitTest : public testing::Test {
public:
static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {};
......@@ -41,20 +41,25 @@ public:
void TearDown() {};
};
HWTEST_F(SignalInitUnitTest, SignalInitTestRmSig, TestSize.Level1)
HWTEST_F(LoopSignalUnitTest, SignalInitTestRmSig, TestSize.Level1)
{
LE_CreateSignalTask(LE_GetDefaultLoop(), &g_sigHandler, ProcessSignal);
static LoopHandle loopClient = nullptr;
LE_STATUS status = LE_CreateLoop(&loopClient);
EXPECT_EQ(status, 0);
LE_CreateSignalTask(loopClient, &g_sigHandler, TestProcessSignal);
ASSERT_NE(g_sigHandler, nullptr);
int ret = LE_AddSignal(LE_GetDefaultLoop(), g_sigHandler, SIGUSR1);
int ret = LE_AddSignal(loopClient, 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);
LE_AddSignal(loopClient, g_sigHandler, SIGUSR1);
LE_AddSignal(loopClient, g_sigHandler, SIGUSR2);
ret = LE_RemoveSignal(loopClient, 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);
LE_RemoveSignal(loopClient, g_sigHandler, SIGUSR1);
LE_RemoveSignal(loopClient, g_sigHandler, SIGUSR2);
((BaseTask *)g_sigHandler)->handleEvent(loopClient, (TaskHandle)&g_sigHandler, Event_Write);
LE_CloseSignalTask(loopClient, g_sigHandler);
ASSERT_EQ(ret, 0);
LE_CloseLoop(loopClient);
loopClient = nullptr;
}
}
/*
* Copyright (c) 2022 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 "bootchart.h"
#include "bootstage.h"
#include "init_utils.h"
#include "param_stub.h"
#include "securec.h"
using namespace std;
using namespace testing::ext;
namespace init_ut {
extern "C" {
long long GetJiffies(void);
char *ReadFileToBuffer(const char *fileName, char *buffer, uint32_t bufferSize);
void BootchartLogHeader(void);
void BootchartLogFile(FILE *log, const char *procfile);
void BootchartLogProcessStat(FILE *log, pid_t pid);
void bootchartLogProcess(FILE *log);
void *BootchartThreadMain(void *data);
void BootchartDestory(void);
int DoBootchartStart(void);
int DoBootchartStop(void);
int DoBootchartCmd(int id, const char *name, int argc, const char **argv);
int BootchartInit(void);
void BootchartExit(void);
}
class ModulesUnitTest : public testing::Test {
public:
static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {};
void SetUp() {};
void TearDown() {};
};
HWTEST_F(ModulesUnitTest, TestBootchartInit, TestSize.Level1)
{
EXPECT_EQ(BootchartInit(), 0);
EXPECT_NE(GetJiffies(), -1);
EXPECT_NE(DoBootchartStart(), 1);
EXPECT_EQ(DoBootchartStop(), 0);
BootchartExit();
}
HWTEST_F(ModulesUnitTest, TestReadFileToBuffer, TestSize.Level1)
{
const char *fileName = "ModulesTest";
char buffer[MAX_BUFFER_LEN] = {0};
EXPECT_EQ(ReadFileToBuffer(fileName, buffer, MAX_BUFFER_LEN), nullptr);
}
HWTEST_F(ModulesUnitTest, TestBootchartLogFile, TestSize.Level1)
{
DoBootchartStart();
FILE *log = fopen("/data/init_ut/ModulesTest.log", "w");
BootchartLogFile(log, "/proc/stat");
if (log != NULL) {
(void)fflush(log);
(void)fclose(log);
}
}
HWTEST_F(ModulesUnitTest, TestBootchartLogProcessStat, TestSize.Level1)
{
FILE *log = fopen("/data/init_ut/ModulesTest.log", "w");
pid_t selfPid = getpid();
BootchartLogProcessStat(log, selfPid);
if (log != NULL) {
(void)fflush(log);
(void)fclose(log);
}
}
HWTEST_F(ModulesUnitTest, TestbootchartLogProcess, TestSize.Level1)
{
FILE *log = fopen("/data/init_ut/ModulesTest.log", "w");
bootchartLogProcess(log);
if (log != NULL) {
(void)fflush(log);
(void)fclose(log);
}
}
HWTEST_F(ModulesUnitTest, TestDoBootchartCmd, TestSize.Level1)
{
const char *argv1[] = { "start" };
const char *argv2[] = { "stop" };
EXPECT_NE(DoBootchartCmd(0, "bootchart", 1, argv1), 1);
EXPECT_NE(DoBootchartCmd(0, "bootchart", 1, argv2), 1);
}
HWTEST_F(ModulesUnitTest, TestDoBootchartInsall, TestSize.Level1)
{
TestSetParamCheckResult("ohos.servicectrl.", 0777, 0);
SystemWriteParam("persist.init.bootchart.enabled", "1");
SystemWriteParam("persist.init.debug.dump.trigger", "1");
SystemWriteParam("persist.init.debug.loglevel", "6");
SystemWriteParam("ohos.servicectrl.cmd", "setloglevel 10");
HookMgrExecute(GetBootStageHookMgr(), INIT_POST_PERSIST_PARAM_LOAD, NULL, NULL);
}
} // namespace init_ut
......@@ -35,42 +35,56 @@ public:
int TestDacInitLocalLabel()
{
int ret = RegisterSecurityDacOps(&initParamSercurityOps, LABEL_INIT_FOR_INIT);
int ret = RegisterSecurityDacOps(nullptr, LABEL_INIT_FOR_INIT);
EXPECT_NE(ret, 0);
ret = RegisterSecurityDacOps(&initParamSecurityOps, LABEL_INIT_FOR_INIT);
EXPECT_EQ(ret, 0);
if (initParamSercurityOps.securityInitLabel == nullptr || initParamSercurityOps.securityFreeLabel == nullptr) {
if (initParamSecurityOps.securityInitLabel == nullptr || initParamSecurityOps.securityFreeLabel == nullptr) {
return -1;
}
ParamSecurityLabel label = {};
ret = initParamSercurityOps.securityInitLabel(&label, LABEL_INIT_FOR_INIT);
ret = initParamSecurityOps.securityInitLabel(&label, LABEL_INIT_FOR_INIT);
EXPECT_EQ(ret, 0);
ret = initParamSercurityOps.securityFreeLabel(&label);
ret = initParamSecurityOps.securityFreeLabel(&label);
EXPECT_EQ(ret, 0);
return 0;
}
int TestDacGetLabel()
{
int ret = RegisterSecurityDacOps(&initParamSecurityOps, LABEL_INIT_FOR_INIT);
EXPECT_EQ(ret, 0);
if (initParamSecurityOps.securityGetLabel == nullptr) {
return -1;
}
// get label from file
ret = initParamSecurityOps.securityGetLabel(STARTUP_INIT_UT_PATH "/system/etc/param/ohos.para.dac");
return ret;
}
int TestDacCheckFilePermission(const char *fileName)
{
int ret = RegisterSecurityDacOps(&initParamSercurityOps, LABEL_INIT_FOR_INIT);
int ret = RegisterSecurityDacOps(&initParamSecurityOps, LABEL_INIT_FOR_INIT);
EXPECT_EQ(ret, 0);
if (initParamSercurityOps.securityCheckFilePermission == nullptr) {
if (initParamSecurityOps.securityCheckFilePermission == nullptr) {
return -1;
}
ParamSecurityLabel label = {};
ret = initParamSercurityOps.securityInitLabel(&label, LABEL_INIT_FOR_INIT);
ret = initParamSecurityOps.securityInitLabel(&label, LABEL_INIT_FOR_INIT);
EXPECT_EQ(ret, 0);
ret = initParamSercurityOps.securityCheckFilePermission(&label, fileName, DAC_WRITE);
ret = initParamSecurityOps.securityCheckFilePermission(&label, fileName, DAC_WRITE);
EXPECT_EQ(ret, 0);
ret = initParamSercurityOps.securityFreeLabel(&label);
ret = initParamSecurityOps.securityFreeLabel(&label);
EXPECT_EQ(ret, 0);
return 0;
}
int TestDacCheckParaPermission(const char *name, ParamDacData *dacData, int mode)
{
int ret = RegisterSecurityDacOps(&initParamSercurityOps, LABEL_INIT_FOR_INIT);
int ret = RegisterSecurityDacOps(&initParamSecurityOps, LABEL_INIT_FOR_INIT);
EXPECT_EQ(ret, 0);
if (initParamSercurityOps.securityCheckFilePermission == nullptr) {
if (initParamSecurityOps.securityCheckFilePermission == nullptr) {
return -1;
}
ParamAuditData auditData = {};
......@@ -80,10 +94,10 @@ public:
ret = AddSecurityLabel(&auditData);
EXPECT_EQ(ret, 0);
ParamSecurityLabel srclabel = {};
ret = initParamSercurityOps.securityInitLabel(&srclabel, LABEL_INIT_FOR_INIT);
ret = initParamSecurityOps.securityInitLabel(&srclabel, LABEL_INIT_FOR_INIT);
EXPECT_EQ(ret, 0);
ret = initParamSercurityOps.securityCheckParamPermission(&srclabel, name, mode);
initParamSercurityOps.securityFreeLabel(&srclabel);
ret = initParamSecurityOps.securityCheckParamPermission(&srclabel, name, mode);
initParamSecurityOps.securityFreeLabel(&srclabel);
return ret;
}
......@@ -109,7 +123,7 @@ public:
}
private:
ParamSecurityOps initParamSercurityOps {};
ParamSecurityOps initParamSecurityOps {};
ParamSecurityOps clientParamSercurityOps {};
};
......
......@@ -15,13 +15,23 @@
#include "param_stub.h"
#include <dirent.h>
#include <sys/prctl.h>
#include <unistd.h>
#include "bootstage.h"
#include "init.h"
#include "init_log.h"
#include "init_param.h"
#ifndef OHOS_LITE
#include "init_mount.h"
#endif
#include "hookmgr.h"
#include "parameter.h"
#include "param_manager.h"
#include "param_security.h"
#include "param_utils.h"
#include "init_group_manager.h"
#include "beget_ext.h"
#include "init_module_engine.h"
#ifdef PARAM_LOAD_CFG_FROM_CODE
#include "param_cfg.h"
#endif
......@@ -31,7 +41,10 @@
extern "C" {
#endif
#endif
int LoadParamFromCmdLine(void);
static int g_stubResult[STUB_MAX] = { 0 };
static int g_testRandom = 2; // 2 is test random
static int g_testPermissionResult = DAC_RESULT_PERMISSION;
void SetTestPermissionResult(int result)
{
......@@ -39,9 +52,9 @@ void SetTestPermissionResult(int result)
}
static const char *selinuxLabels[][2] = {
{"test.permission.read", "test.persmission.read"},
{"test.permission.write", "test.persmission.write"},
{"test.permission.watch", "test.persmission.watch"}
{"test.permission.read", "u:object_r:test_read:s0"},
{"test.permission.write", "u:object_r:test_write:s0"},
{"test.permission.watch", "u:object_r:test_watch:s0"},
};
static int TestGenHashCode(const char *buff)
......@@ -119,6 +132,32 @@ static ParamContextsList *TestGetParamList(void)
node->next = head->next;
head->next = node;
}
// test error, no node paraName
ParamContextsList *node = (ParamContextsList *)malloc(sizeof(ParamContextsList));
BEGET_ERROR_CHECK(node != nullptr, TestDestroyParamList(&head);
return nullptr, "Failed to alloc ParamContextsList");
node->info.paraName = nullptr;
node->info.paraContext = strdup(selinuxLabels[0][1]);
node->next = head->next;
head->next = node;
// test error, no node paraContext
node = (ParamContextsList *)malloc(sizeof(ParamContextsList));
BEGET_ERROR_CHECK(node != nullptr, TestDestroyParamList(&head);
return nullptr, "Failed to alloc ParamContextsList");
node->info.paraName = strdup(selinuxLabels[0][0]);
node->info.paraContext = nullptr;
node->next = head->next;
head->next = node;
// test error, repeat
node = (ParamContextsList *)malloc(sizeof(ParamContextsList));
BEGET_ERROR_CHECK(node != nullptr, TestDestroyParamList(&head);
return nullptr, "Failed to alloc ParamContextsList");
node->info.paraName = strdup(selinuxLabels[0][0]);
node->info.paraContext = strdup(selinuxLabels[0][1]);
node->next = head->next;
head->next = node;
return head;
#else
return nullptr;
......@@ -149,7 +188,7 @@ void TestSetParamCheckResult(const char *prefix, uint16_t mode, int result)
SetTestPermissionResult(result);
}
static void CreateTestFile(const char *fileName, const char *data)
void CreateTestFile(const char *fileName, const char *data)
{
CheckAndCreateDir(fileName);
PARAM_LOGV("PrepareParamTestData for %s", fileName);
......@@ -185,12 +224,12 @@ static void PrepareUeventdcfg(void)
"[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);
CreateTestFile(STARTUP_INIT_UT_PATH"/ueventd_ut/valid.config", ueventdcfg);
}
static void PrepareModCfg(void)
{
const char *modCfg = "testinsmod";
CreateTestFile("/data/init_ut/test_insmod", modCfg);
CreateTestFile(STARTUP_INIT_UT_PATH"/test_insmod", modCfg);
}
static void PrepareInnerKitsCfg()
{
......@@ -215,8 +254,9 @@ static void PrepareInnerKitsCfg()
"/dev/block/platform/fe310000.sdhci/by-name/testuserdata2 /data ext4 noatime,fscrypt=xxx wait,check,quota\n"
"/dev/block/platform/fe310000.sdhci/by-name/testmisc /misc none none wait,required";
mkdir("/data/init_ut/mount_unitest/", S_IRWXU | S_IRWXG | S_IRWXO);
CreateTestFile("/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable", innerKitsCfg);
CreateTestFile("/data/init_ut/etc/fstab.required", fstabRequired);
CreateTestFile(STARTUP_INIT_UT_PATH"/mount_unitest/ReadFstabFromFile1.fstable", innerKitsCfg);
CreateTestFile(STARTUP_INIT_UT_PATH"/etc/fstab.required", fstabRequired);
CreateTestFile(STARTUP_INIT_UT_PATH"/system/etc/fstab.required", fstabRequired);
}
static void PrepareGroupTestCfg()
{
......@@ -291,7 +331,7 @@ static void LoadParamFromCfg(void)
}
#endif
}
#if !(defined __LITEOS_A__ || defined __LITEOS_M__)
static const char *g_triggerData = "{"
"\"jobs\" : [{"
" \"name\" : \"early-init\","
......@@ -344,81 +384,124 @@ static const char *g_triggerData = "{"
" }"
"]"
"}";
#endif
void PrepareCmdLineHasSn()
void PrepareCmdLineData()
{
// for cmdline
const char *cmdLineHasSnroot = "bootgroup=device.charge.group earlycon=uart8250,mmio32,0xfe660000 "
"root=PARTUUID=614e0000-0000 rw rootwait rootfstype=ext4 console=ttyFIQ0 hardware=rk3568"
" BOOT_IMAGE=/kernel ohos.boot.sn=/test init=/init";
CreateTestFile(BOOT_CMD_LINE, cmdLineHasSnroot);
LoadParamFromCmdLine();
const char *cmdLineHasntSn = "bootgroup=device.charge.group earlycon=uart8250,mmio32,0xfe660000 "
const char *cmdLine = "bootgroup=device.boot.group earlycon=uart8250,mmio32,0xfe660000 "
"root=PARTUUID=614e0000-0000 rw rootwait rootfstype=ext4 console=ttyFIQ0 hardware=rk3568 "
"BOOT_IMAGE=/kernel init=/init default_boot_device=fe310000.sdhci bootslots=2 currentslot=1 "
"BOOT_IMAGE=/kernel init=/init default_boot_device=fe310000.sdhci bootslots=2 currentslot=1 initloglevel=2 "
"ohos.required_mount.system="
"/dev/block/platform/fe310000.sdhci/by-name/system@/usr@ext4@ro,barrier=1@wait,required "
"ohos.required_mount.vendor="
"/dev/block/platform/fe310000.sdhci/by-name/vendor@/vendor@ext4@ro,barrier=1@wait,required "
"ohos.required_mount.misc="
"/dev/block/platform/fe310000.sdhci/by-name/misc@none@none@none@wait,required";
CreateTestFile(BOOT_CMD_LINE, cmdLineHasntSn);
"/dev/block/platform/fe310000.sdhci/by-name/misc@none@none@none@wait,required ";
CreateTestFile(BOOT_CMD_LINE, cmdLine);
}
void PrepareAreaSizeFile()
static void PrepareAreaSizeFile(void)
{
// for cmdline
const char *ohosParamSize = "default_param=1024"
"hilog_param=2048"
"const_product_param=2048"
"startup_param=20480"
"persist_param=2048"
"const_param=20480"
"persist_sys_param=2048";
const char *ohosParamSize = "default_param=1024\n"
"hilog_param=2048\n"
"const_product_param=2048\n"
"startup_param=20480\n"
"persist_param=2048\n"
"const_param=20480\n"
"test_watch=40960\n"
"test_read=40960\n"
"const_param***=20480\n"
"persist_sys_param=2048\n";
CreateTestFile(PARAM_AREA_SIZE_CFG, ohosParamSize);
}
void PrepareInitUnitTestEnv(void)
static void PrepareTestGroupFile(void)
{
static int evnOk = 0;
if (evnOk) {
return;
}
PARAM_LOGI("PrepareInitUnitTestEnv");
mkdir(STARTUP_INIT_UT_PATH, S_IRWXU | S_IRWXG | S_IRWXO);
PrepareUeventdcfg();
PrepareInnerKitsCfg();
PrepareModCfg();
PrepareGroupTestCfg();
std::string groupData = "root:x:0:\n"
"bin:x:2:\n"
"system:x:1000:\n"
"log:x:1007:\n"
"deviceinfo:x:1102:\n"
"samgr:x:5555:\n"
"hdf_devmgr:x:3044:\n\n"
"power_host:x:3025:\n"
"servicectrl:x:1050:root, shell,system, samgr, hdf_devmgr \n"
"powerctrl:x:1051:root, shell,system, update,power_host\r\n"
"bootctrl:x:1052:root,shell,system\n"
"deviceprivate:x:1053:root,shell,system,samgr,hdf_devmgr,deviceinfo,"
"dsoftbus,dms,account,useriam,access_token,device_manager,foundation,dbms,deviceauth,huks_server\n"
"hiview:x:1201:\n"
"hidumper_service:x:1212:\n"
"shell:x:2000:\n"
"cache:x:2001:\n"
"net_bw_stats:x:3006:\n";
CreateTestFile(STARTUP_INIT_UT_PATH "/etc/group", groupData.c_str());
}
#if !(defined __LITEOS_A__ || defined __LITEOS_M__)
static void PrepareDacData()
{
// for dac
std::string dacData = "ohos.servicectrl. = system:servicectrl:0775 \n";
dacData += "startup.service.ctl. = system:servicectrl:0775:int\n";
dacData += "test.permission. = root:root:0770\n";
dacData += "test.permission.read. = root:root:0774\n";
dacData += "test.permission.write.= root:root:0772\n";
dacData += "test.permission.watcher. = root:root:0771\n";
dacData += "test.test1. = system:test1:0771\n";
dacData += "test.test2.watcher. = test2:root:0771\n";
dacData += "test.type.int. = root:root:0777:int\n";
dacData += "test.type.bool. = root:root:0777:bool\n";
dacData += "test.type.string. = root:root:0777\n";
dacData += "test.invalid.int. = root:root:\n";
dacData += "test.invalid.int. = root::\n";
dacData += "test.invalid.int. = ::\n";
dacData += "test.invalid.int. = \n";
dacData += "test.invalid.int. \n";
CreateTestFile(STARTUP_INIT_UT_PATH "/system/etc/param/ohos.para.dac", dacData.c_str());
CreateTestFile(STARTUP_INIT_UT_PATH"/trigger_test.cfg", g_triggerData);
PrepareAreaSizeFile();
#endif
InitParamService();
CreateTestFile(STARTUP_INIT_UT_PATH "/system/etc/param/ohos.para.dac_1", dacData.c_str());
}
#if !(defined __LITEOS_A__ || defined __LITEOS_M__)
PrepareCmdLineHasSn();
TestSetSelinuxOps();
LoadSpecialParam();
static int TestHook(const HOOK_INFO *hookInfo, void *cookie)
{
return 0;
}
void PrepareInitUnitTestEnv(void)
{
static int evnOk = 0;
if (evnOk) {
return;
}
printf("PrepareInitUnitTestEnv \n");
#ifdef PARAM_SUPPORT_SELINUX
RegisterSecuritySelinuxOps(nullptr, 0);
#endif
// read system parameters
int32_t loglevel = GetIntParameter("persist.init.debug.loglevel", INIT_ERROR);
SetInitLogLevel((InitLogLevel)loglevel);
#ifndef OHOS_LITE
InitAddGlobalInitHook(0, TestHook);
InitAddPreParamServiceHook(0, TestHook);
InitAddPreParamLoadHook(0, TestHook);
InitAddPreCfgLoadHook(0, TestHook);
InitAddPostCfgLoadHook(0, TestHook);
InitAddPostPersistParamLoadHook(0, TestHook);
// ini system
SystemInit();
SystemPrepare();
SystemConfig();
#else
// read default parameter from system
LoadDefaultParams("/system/etc/param/ohos_const", LOAD_PARAM_NORMAL);
LoadDefaultParams("/vendor/etc/param", LOAD_PARAM_NORMAL);
LoadDefaultParams("/system/etc/param", LOAD_PARAM_ONLY_ADD);
#endif
// read ut parameters
LoadDefaultParams(STARTUP_INIT_UT_PATH "/system/etc/param/ohos_const", LOAD_PARAM_NORMAL);
LoadDefaultParams(STARTUP_INIT_UT_PATH "/vendor/etc/param", LOAD_PARAM_NORMAL);
LoadDefaultParams(STARTUP_INIT_UT_PATH "/system/etc/param", LOAD_PARAM_ONLY_ADD);
LoadParamsFile(STARTUP_INIT_UT_PATH "/system/etc/param", LOAD_PARAM_ONLY_ADD);
LoadParamFromCfg();
// for test int get
......@@ -427,6 +510,7 @@ void PrepareInitUnitTestEnv(void)
SystemWriteParam("test.string.get", "101");
SystemWriteParam("test.bool.get.true", "true");
SystemWriteParam("test.bool.get.false", "false");
evnOk = 1;
}
......@@ -441,12 +525,176 @@ int TestFreeLocalSecurityLabel(ParamSecurityLabel *srcLabel)
return 0;
}
void SetStubResult(STUB_TYPE type, int result)
{
g_stubResult[type] = result;
}
#ifndef OHOS_LITE
static void TestBeforeInit(void)
{
ParamWorkSpace *paramSpace = GetParamWorkSpace();
EXPECT_EQ(paramSpace, nullptr);
InitParamService();
CloseParamWorkSpace();
paramSpace = GetParamWorkSpace();
EXPECT_EQ(paramSpace, nullptr);
EnableInitLogFromCmdline();
// test read cmdline
Fstab *stab = LoadRequiredFstab();
ReleaseFstab(stab);
}
#endif
static __attribute__((constructor(101))) void ParamTestStubInit(void)
{
EnableInitLog(INIT_DEBUG);
SetInitLogLevel(INIT_DEBUG);
PARAM_LOGI("ParamTestStubInit");
PrepareInitUnitTestEnv();
printf("Init unit test start \n");
EnableInitLog(INIT_ERROR);
// prepare data
mkdir(STARTUP_INIT_UT_PATH, S_IRWXU | S_IRWXG | S_IRWXO);
PrepareUeventdcfg();
PrepareInnerKitsCfg();
PrepareModCfg();
PrepareGroupTestCfg();
PrepareDacData();
CreateTestFile(STARTUP_INIT_UT_PATH"/trigger_test.cfg", g_triggerData);
PrepareAreaSizeFile();
PrepareTestGroupFile();
#ifndef OHOS_LITE
TestBeforeInit();
#endif
PrepareCmdLineData();
// init service open
InitServiceSpace();
// param service open
InitParamService();
TestSetSelinuxOps();
}
__attribute__((destructor)) static void ParamTestStubExit(void)
{
PARAM_LOGI("ParamTestStubExit");
#ifndef OHOS_LITE
HookMgrExecute(GetBootStageHookMgr(), INIT_BOOT_COMPLETE, NULL, NULL);
#endif
StopParamService();
}
#ifdef OHOS_LITE
void __attribute__((weak))LE_DoAsyncEvent(const LoopHandle loopHandle, const TaskHandle taskHandle)
{
}
const char* HalGetSerial(void)
{
static const char *serial = "1234567890";
return serial;
}
#endif
int __attribute__((weak))SprintfStub(char *buffer, size_t size, const char *fmt, ...)
{
int len = -1;
va_list vargs;
va_start(vargs, fmt);
len = vsnprintf_s(buffer, size, size - 1, fmt, vargs);
va_end(vargs);
return len;
}
int __attribute__((weak))MountStub(const char* source, const char* target,
const char* filesystemtype, unsigned long mountflags, const void * data)
{
return g_stubResult[STUB_MOUNT];
}
int __attribute__((weak))UmountStub(const char *target)
{
return 0;
}
int __attribute__((weak))Umount2Stub(const char *target, int flags)
{
return 0;
}
int __attribute__((weak))SymlinkStub(const char * oldpath, const char * newpath)
{
return 0;
}
int PrctlStub(int option, ...)
{
static int count = 0;
static int count1 = 0;
if (option == PR_SET_SECUREBITS) {
count++;
return (count % g_testRandom == 1) ? 0 : -1;
}
if (option == PR_CAP_AMBIENT) {
count1++;
return (count1 % g_testRandom == 1) ? 0 : -1;
}
return 0;
}
int ExecvStub(const char *pathname, char *const argv[])
{
printf("ExecvStub %s \n", pathname);
return 0;
}
int LchownStub(const char *pathname, uid_t owner, gid_t group)
{
return 0;
}
int KillStub(pid_t pid, int signal)
{
return 0;
}
int ExecveStub(const char *pathname, char *const argv[], char *const envp[])
{
printf("ExecveStub %s \n", pathname);
return 0;
}
int LoadPolicy()
{
return 0;
}
static int g_selinuxOptResult = 0;
int setcon(const char *name)
{
g_selinuxOptResult++;
return g_selinuxOptResult % g_testRandom;
}
int RestoreconRecurse(const char *name)
{
g_selinuxOptResult++;
return g_selinuxOptResult % g_testRandom;
}
int setexeccon(const char *name)
{
g_selinuxOptResult++;
return g_selinuxOptResult % g_testRandom;
}
int setsockcreatecon(const char *name)
{
g_selinuxOptResult++;
return g_selinuxOptResult % g_testRandom;
}
int setfilecon(const char *name, const char *content)
{
g_selinuxOptResult++;
return g_selinuxOptResult % g_testRandom;
}
#ifdef __cplusplus
#if __cplusplus
......
......@@ -32,6 +32,8 @@ extern "C" {
#endif
#endif
#define DEFAULT_ERROR (-65535)
#ifndef PARAM_SUPPORT_SELINUX
typedef struct ParameterNode {
const char *paraName;
......@@ -49,6 +51,7 @@ typedef struct SrcInfo {
} SrcInfo;
#endif
void CreateTestFile(const char *fileName, const char *data);
void PrepareInitUnitTestEnv(void);
void TestSetSelinuxOps(void);
void SetTestPermissionResult(int result);
......@@ -56,6 +59,14 @@ void TestSetParamCheckResult(const char *prefix, uint16_t mode, int result);
int TestCheckParamPermission(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode);
int TestFreeLocalSecurityLabel(ParamSecurityLabel *srcLabel);
typedef enum {
STUB_SPRINTF,
STUB_MOUNT,
STUB_MKNODE,
STUB_MAX
} STUB_TYPE;
void SetStubResult(STUB_TYPE type, int result);
void PrepareCmdLineData();
#ifdef __cplusplus
#if __cplusplus
}
......
......@@ -26,12 +26,10 @@ using namespace testing::ext;
using namespace std;
extern "C" {
int WorkSpaceNodeCompare(const HashNode *node1, const HashNode *node2);
}
static void OnClose(ParamTaskPtr client)
void ParamWorBaseLog(InitLogLevel logLevel, uint32_t domain, const char *tag, const char *fmt, ...);
static void OnClose(const TaskHandle taskHandle)
{
UNUSED(client);
}
}
static int CheckServerParamValue(const char *name, const char *expectValue)
......@@ -396,6 +394,7 @@ HWTEST_F(ParamUnitTest, TestDumpParamMemory, TestSize.Level0)
ParamUnitTest test;
test.TestDumpParamMemory();
}
HWTEST_F(ParamUnitTest, TestLinuxRWLock, TestSize.Level0)
{
ParamRWMutexCreate(nullptr);
......@@ -404,21 +403,96 @@ HWTEST_F(ParamUnitTest, TestLinuxRWLock, TestSize.Level0)
ParamRWMutexUnlock(nullptr);
ParamRWMutexDelete(nullptr);
ParamMutexDelete(nullptr);
WorkSpace *workspace1 = (WorkSpace *)malloc(sizeof(WorkSpace) + strlen("testfilename1"));
ASSERT_NE(nullptr, workspace1);
WorkSpace *workspace2 = (WorkSpace *)malloc(sizeof(WorkSpace) + strlen("testfilename1"));
ASSERT_NE(nullptr, workspace2);
if (strcpy_s(workspace1->fileName, strlen("testfilename1"), "testfilename") != EOK) {
EXPECT_EQ(0, 1);
}
if (strcpy_s(workspace2->fileName, strlen("testfilename1"), "testfilename") != EOK) {
EXPECT_EQ(0, 1);
}
HWTEST_F(ParamUnitTest, TestWorkSpace1, TestSize.Level0)
{
int ret = AddWorkSpace("test.workspace.1", 0, PARAM_WORKSPACE_DEF);
EXPECT_EQ(ret, 0);
ret = AddWorkSpace("test.workspace.2", 0, PARAM_WORKSPACE_DEF);
EXPECT_EQ(ret, 0);
ret = AddWorkSpace("test.workspace.3", 0, PARAM_WORKSPACE_DEF);
EXPECT_EQ(ret, 0);
WorkSpace *space = GetWorkSpace("test.workspace.1");
EXPECT_NE(space, nullptr);
CloseWorkSpace(nullptr);
}
HWTEST_F(ParamUnitTest, TestWorkSpace2, TestSize.Level0)
{
const char *spaceName = "test.workspace2";
const size_t size = strlen(spaceName) + 1;
WorkSpace *workSpace = (WorkSpace *)malloc(sizeof(WorkSpace) + size);
if (workSpace == nullptr) {
EXPECT_NE(workSpace, nullptr);
return;
}
EXPECT_EQ(WorkSpaceNodeCompare(&(workspace1->hashNode), &(workspace2->hashNode)), 0);
free(workspace1);
free(workspace2);
workSpace->flags = 0;
workSpace->area = NULL;
OH_ListInit(&workSpace->node);
int ret = ParamStrCpy(workSpace->fileName, size, spaceName);
EXPECT_EQ(ret, 0);
HASHMAPInitNode(&workSpace->hashNode);
CloseWorkSpace(workSpace);
}
HWTEST_F(ParamUnitTest, TestWorkSpace3, TestSize.Level0)
{
const char *spaceName = "test.workspace3";
int ret = AddWorkSpace(spaceName, 1, PARAM_WORKSPACE_DEF);
#ifndef OHOS_LITE
EXPECT_NE(ret, 0);
#else
EXPECT_EQ(ret, 0);
#endif
HashNode *node = OH_HashMapGet(GetParamWorkSpace()->workSpaceHashHandle, (const void *)spaceName);
EXPECT_EQ(node, nullptr);
}
#if !(defined __LITEOS_A__ || defined __LITEOS_M__) // can not support parameter type
HWTEST_F(ParamUnitTest, TestParamValueType1, TestSize.Level0)
{
int ret = SystemWriteParam("test.type.int.1000", "10000");
EXPECT_EQ(ret, 0);
ret = SystemWriteParam("test.type.int.1001", "-1111111144444444444441111111666666661");
EXPECT_EQ(ret, PARAM_CODE_INVALID_VALUE);
ret = SystemWriteParam("test.type.int.1001", "1111111111444444444444411111166666666");
EXPECT_EQ(ret, PARAM_CODE_INVALID_VALUE);
}
HWTEST_F(ParamUnitTest, TestParamValueType2, TestSize.Level0)
{
int ret = SystemWriteParam("test.type.bool.1000", "10000");
EXPECT_EQ(ret, PARAM_CODE_INVALID_VALUE);
ret = SystemWriteParam("test.type.bool.1001", "-1111111111111111");
EXPECT_EQ(ret, PARAM_CODE_INVALID_VALUE);
ret = SystemWriteParam("test.type.bool.1001", "1111111111111111");
EXPECT_EQ(ret, PARAM_CODE_INVALID_VALUE);
ret = SystemWriteParam("test.type.bool.1001", "true");
EXPECT_EQ(ret, 0);
ret = SystemWriteParam("test.type.bool.1001", "false");
EXPECT_EQ(ret, 0);
ret = SystemWriteParam("test.type.bool.1001", "1");
EXPECT_EQ(ret, 0);
ret = SystemWriteParam("test.type.bool.1001", "0");
EXPECT_EQ(ret, 0);
ret = SystemWriteParam("test.type.bool.1001", "on");
EXPECT_EQ(ret, 0);
ret = SystemWriteParam("test.type.bool.1001", "off");
EXPECT_EQ(ret, 0);
ret = SystemWriteParam("test.type.bool.1001", "yes");
EXPECT_EQ(ret, 0);
ret = SystemWriteParam("test.type.bool.1001", "no");
EXPECT_EQ(ret, 0);
ret = SystemWriteParam("test.type.bool.1001", "y");
EXPECT_EQ(ret, 0);
ret = SystemWriteParam("test.type.bool.1001", "n");
EXPECT_EQ(ret, 0);
}
#endif
HWTEST_F(ParamUnitTest, TestGetServiceCtlName, TestSize.Level0)
{
ServiceCtrlInfo *serviceInfo = NULL;
......@@ -437,5 +511,127 @@ HWTEST_F(ParamUnitTest, TestGetServiceCtlName, TestSize.Level0)
EXPECT_STREQ(serviceInfo->realKey, "ohos.servicectrl.stop.test");
free(serviceInfo);
}
ParamWorBaseLog(INIT_DEBUG, PARAN_DOMAIN, "PARAM", "%s", "ParamWorBaseLog");
}
HWTEST_F(ParamUnitTest, TestFindTrieNode, TestSize.Level0)
{
int ret = AddWorkSpace("test.workspace.1", 0, PARAM_WORKSPACE_DEF);
EXPECT_EQ(ret, 0);
WorkSpace *space = GetWorkSpace("test.workspace.1");
ASSERT_NE(space, nullptr);
ParamTrieNode *node = FindTrieNode(nullptr, nullptr, 0, nullptr);
ASSERT_EQ(node, nullptr);
node = FindTrieNode(space, nullptr, 0, nullptr);
ASSERT_EQ(node, nullptr);
node = FindTrieNode(space, "111111", 0, nullptr);
ASSERT_EQ(node, nullptr);
node = FindTrieNode(space, "find.test.111111", strlen("find.test.111111"), nullptr);
ASSERT_EQ(node, nullptr);
}
#ifndef OHOS_LITE
HWTEST_F(ParamUnitTest, TestConnectServer, TestSize.Level0)
{
int ret = ConnectServer(-1, CLIENT_PIPE_NAME);
EXPECT_NE(ret, 0);
int fd = socket(PF_UNIX, SOCK_STREAM, 0);
ret = ConnectServer(fd, "");
EXPECT_NE(ret, 0);
ret = ConnectServer(fd, CLIENT_PIPE_NAME);
EXPECT_EQ(ret, 0);
close(fd);
}
HWTEST_F(ParamUnitTest, TestRequestMessage, TestSize.Level0)
{
const int maxSize = 1024 * 64 + 10;
const int msgSize = sizeof(ParamMessage) + 128; // 128 TEST
ParamMessage *msg = CreateParamMessage(0, nullptr, msgSize);
EXPECT_EQ(msg, nullptr);
msg = CreateParamMessage(0, "nullptr", maxSize);
EXPECT_EQ(msg, nullptr);
msg = CreateParamMessage(0, "22222222222222222222222222222222222222222"
"333333333333333333333333333333333333333333333333333333333333333333333"
"555555555555555555555555555555555555555555555555555555555555555555555", msgSize);
EXPECT_EQ(msg, nullptr);
// success
msg = CreateParamMessage(0, "22222222222222222222222222222222222222222", msgSize);
EXPECT_NE(msg, nullptr);
uint32_t start = 0;
int ret = FillParamMsgContent(nullptr, &start, 0, nullptr, 0);
EXPECT_NE(ret, 0);
ret = FillParamMsgContent(msg, nullptr, 0, nullptr, 0);
EXPECT_NE(ret, 0);
ret = FillParamMsgContent(msg, &start, 0, nullptr, 0);
EXPECT_NE(ret, 0);
ret = FillParamMsgContent(msg, &start, 0, "22222", 0);
EXPECT_NE(ret, 0);
ret = FillParamMsgContent(msg, &start, 0, "22222", msgSize);
EXPECT_NE(ret, 0);
// fill success
ret = FillParamMsgContent(msg, &start, 0, "22222", strlen("22222"));
EXPECT_EQ(ret, 0);
msg->msgSize = start + sizeof(ParamMessage);
uint32_t offset = 0;
ParamMsgContent *content = GetNextContent(nullptr, &offset);
EXPECT_EQ(content, nullptr);
content = GetNextContent(msg, nullptr);
EXPECT_EQ(content, nullptr);
offset = 0;
content = GetNextContent(msg, &offset);
EXPECT_NE(content, nullptr);
content = GetNextContent(msg, &offset);
EXPECT_EQ(content, nullptr);
free(msg);
}
HWTEST_F(ParamUnitTest, TestServerTaskFail, TestSize.Level0)
{
ParamTaskPtr serverTask = nullptr;
ParamStreamInfo info = {};
info.server = const_cast<char *>(PIPE_NAME);
info.close = nullptr;
info.recvMessage = nullptr;
info.incomingConnect = nullptr;
int ret = ParamServerCreate(nullptr, &info);
EXPECT_NE(ret, 0);
ret = ParamServerCreate(&serverTask, nullptr);
EXPECT_NE(ret, 0);
ret = ParamServerCreate(&serverTask, &info);
EXPECT_NE(ret, 0);
}
HWTEST_F(ParamUnitTest, TestStreamTaskFail, TestSize.Level0)
{
ParamTaskPtr client = nullptr;
ParamStreamInfo info = {};
info.flags = PARAM_TEST_FLAGS;
info.server = NULL;
info.close = OnClose;
info.recvMessage = ProcessMessage;
info.incomingConnect = NULL;
int ret = ParamStreamCreate(&client, nullptr, &info, sizeof(ParamWatcher));
EXPECT_NE(ret, 0);
ret = ParamStreamCreate(&client, GetParamService()->serverTask, nullptr, sizeof(ParamWatcher));
EXPECT_NE(ret, 0);
info.close = nullptr;
ret = ParamStreamCreate(&client, GetParamService()->serverTask, &info, sizeof(ParamWatcher));
EXPECT_NE(ret, 0);
info.close = OnClose;
info.recvMessage = nullptr;
ret = ParamStreamCreate(&client, GetParamService()->serverTask, &info, sizeof(ParamWatcher));
EXPECT_NE(ret, 0);
void *data = ParamGetTaskUserData(client);
EXPECT_EQ(data, nullptr);
ret = ParamTaskSendMsg(nullptr, nullptr);
EXPECT_NE(ret, 0);
ret = ParamTaskSendMsg(GetParamService()->serverTask, nullptr);
EXPECT_NE(ret, 0);
}
#endif
}
......@@ -28,9 +28,6 @@ static int TestTriggerExecute(TriggerNode *trigger, const char *content, uint32_
return 0;
}
extern "C" {
void OnClose(ParamTaskPtr client);
}
static int CheckServerParamValue(const char *name, const char *expectValue)
{
char tmp[PARAM_BUFFER_SIZE] = {0};
......@@ -210,6 +207,15 @@ public:
ret = SystemWriteParam(buffer, "1111");
EXPECT_NE(ret, 0);
ret = SystemWriteParam(" ", "1111");
EXPECT_NE(ret, 0);
ret = SystemWriteParam("__.__..", "1111");
EXPECT_NE(ret, 0);
ret = SystemWriteParam(".__..", "1111");
EXPECT_NE(ret, 0);
ret = SystemWriteParam("test.-@:_", "1111");
EXPECT_EQ(ret, 0);
// 保存一个只读的属性,大于最大值
TestBufferValue(buffer, PARAM_VALUE_LEN_MAX - 1);
ret = SystemWriteParam("const.test_readonly.dddddddddddddddddd.fffffffffffffffffff", buffer);
......@@ -270,13 +276,7 @@ public:
int TestPersistParam()
{
ParamAuditData auditData = {};
auditData.name = "persist.";
auditData.dacData.gid = 0;
auditData.dacData.uid = 0;
auditData.dacData.mode = 0777; // 0777 test mode
AddSecurityLabel(&auditData);
RegisterPersistParamOps(nullptr);
LoadPersistParams();
SystemWriteParam("persist.111.ffff.bbbb.cccc.dddd.eeee", "1101");
SystemWriteParam("persist.111.aaaa.bbbb.cccc.dddd.eeee", "1102");
......@@ -287,11 +287,11 @@ public:
CheckServerParamValue("persist.111.ffff.bbbb.cccc.dddd.eeee", "1101");
SystemWriteParam("persist.111.ffff.bbbb.cccc.dddd.eeee", "1106");
CheckServerParamValue("persist.111.ffff.bbbb.cccc.dddd.eeee", "1106");
sleep(1);
SystemWriteParam("persist.111.bbbb.cccc.dddd.1107", "1107");
SystemWriteParam("persist.111.bbbb.cccc.dddd.1108", "1108");
SystemWriteParam("persist.111.bbbb.cccc.dddd.1109", "1108");
sleep(1);
SystemWriteParam("persist.111.bbbb.cccc.dddd.1110", "1108");
SystemWriteParam("persist.111.bbbb.cccc.dddd.1111", "1108");
TimerCallbackForSave(nullptr, nullptr);
......@@ -301,21 +301,8 @@ public:
ParamTaskPtr CreateAndGetStreamTask()
{
ParamStreamInfo info = {};
info.flags = PARAM_TEST_FLAGS;
info.server = NULL;
info.close = OnClose;
info.recvMessage = ProcessMessage;
info.incomingConnect = NULL;
ParamTaskPtr client = NULL;
int ret = ParamStreamCreate(&client, GetParamService()->serverTask, &info, sizeof(ParamWatcher));
PARAM_CHECK(ret == 0, return NULL, "Failed to create client");
ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client);
PARAM_CHECK(watcher != NULL, return NULL, "Failed to get watcher");
OH_ListInit(&watcher->triggerHead);
watcher->stream = client;
GetParamService()->watcherTask = client;
OnIncomingConnect(LE_GetDefaultLoop(), GetParamService()->serverTask);
EXPECT_NE(GetParamService()->watcherTask, nullptr);
return GetParamService()->watcherTask;
}
......@@ -355,13 +342,22 @@ public:
if (g_worker == nullptr) {
return 0;
}
uint32_t msgSize = sizeof(ParamMessage) + sizeof(ParamMsgContent) + PARAM_ALIGN(strlen(value) + 1);
uint32_t msgSize = sizeof(ParamMessage) + sizeof(ParamMsgContent) + sizeof(ParamMsgContent)
+ PARAM_ALIGN(strlen(value) + 1) + sizeof(uint32_t);
ParamMessage *request = (ParamMessage *)(ParamMessage *)CreateParamMessage(type, name, msgSize);
PARAM_CHECK(request != nullptr, return -1, "Failed to malloc for connect");
do {
uint32_t offset = 0;
int ret = FillParamMsgContent(request, &offset, PARAM_VALUE, value, strlen(value));
PARAM_CHECK(ret == 0, break, "Failed to fill value");
ParamMsgContent *content = (ParamMsgContent *)(request->data + offset);
content->type = PARAM_WAIT_TIMEOUT;
content->contentSize = sizeof(uint32_t);
*((uint32_t *)(content->content)) = 100; // 100 is test value
offset += sizeof(ParamMsgContent) + sizeof(uint32_t);
request->msgSize = offset + sizeof(ParamMessage);
ProcessMessage((const ParamTaskPtr)g_worker, (const ParamMessage *)request);
} while (0);
free(request);
......@@ -375,6 +371,8 @@ public:
const char *value = "wait1";
AddWatch(MSG_WAIT_PARAM, name, value);
SystemWriteParam(name, value);
// execute trigger
LE_DoAsyncEvent(LE_GetDefaultLoop(), GetTriggerWorkSpace()->eventHandle);
return 0;
}
......@@ -385,6 +383,8 @@ public:
const char *value = "wait2";
AddWatch(MSG_WAIT_PARAM, name, "*");
SystemWriteParam(name, value);
// execute trigger
LE_DoAsyncEvent(LE_GetDefaultLoop(), GetTriggerWorkSpace()->eventHandle);
return 0;
}
......@@ -395,6 +395,8 @@ public:
const char *value = "wait3";
SystemWriteParam(name, value);
AddWatch(MSG_WAIT_PARAM, name, value);
// execute trigger
LE_DoAsyncEvent(LE_GetDefaultLoop(), GetTriggerWorkSpace()->eventHandle);
return 0;
}
......@@ -406,6 +408,8 @@ public:
std::string newName = name;
newName += ".test.test.test";
SystemWriteParam(newName.c_str(), value);
// execute trigger
LE_DoAsyncEvent(LE_GetDefaultLoop(), GetTriggerWorkSpace()->eventHandle);
return 0;
}
......@@ -415,6 +419,8 @@ public:
const char *value = "watch2";
AddWatch(MSG_ADD_WATCHER, name, "*");
SystemWriteParam(name, value);
// execute trigger
LE_DoAsyncEvent(LE_GetDefaultLoop(), GetTriggerWorkSpace()->eventHandle);
return 0;
}
......@@ -428,15 +434,15 @@ public:
AddWatch(MSG_ADD_WATCHER, name, value);
char buffer[] = "testbuff";
CheckTrigger(GetTriggerWorkSpace(), TRIGGER_PARAM_WATCH, buffer, strlen(buffer), TestTriggerExecute);
#ifdef PARAM_SUPPORT_TRIGGER
SystemDumpTriggers(1, NULL);
#endif
AddWatch(MSG_DEL_WATCHER, name, value);
return 0;
}
int TestCloseTriggerWatch()
{
#ifdef PARAM_SUPPORT_TRIGGER
SystemDumpTriggers(1, NULL);
#endif
ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(g_worker);
ClearWatchTrigger(watcher, TRIGGER_PARAM_WAIT);
ParamTaskClose(g_worker);
......@@ -460,6 +466,30 @@ public:
}
};
HWTEST_F(ParamServiceUnitTest, TestPersistParam, TestSize.Level0)
{
ParamServiceUnitTest test;
test.TestPersistParam();
}
HWTEST_F(ParamServiceUnitTest, TestReadCmdline, TestSize.Level0)
{
const char *snData = "222222222222222222222";
CreateTestFile(STARTUP_INIT_UT_PATH "/system/etc/sn", snData);
// for cmdline
std::string cmdLineForSn = "bootgroup=device.charge.group earlycon=uart8250,mmio32,0xfe660000 "
"root=PARTUUID=614e0000-0000 rw rootwait rootfstype=ext4 console=ttyFIQ0 hardware=rk3568"
" BOOT_IMAGE=/kernel init=/init";
std::string snWithPath = cmdLineForSn + "ohos.boot.sn=" + STARTUP_INIT_UT_PATH "/system/etc/sn";
CreateTestFile(BOOT_CMD_LINE, snWithPath.c_str());
LoadParamFromCmdLine();
std::string snWithSN = cmdLineForSn + "ohos.boot.sn=" + snData;
CreateTestFile(BOOT_CMD_LINE, snWithSN.c_str());
LoadParamFromCmdLine();
CreateTestFile(BOOT_CMD_LINE, cmdLineForSn.c_str());
LoadParamFromCmdLine();
}
HWTEST_F(ParamServiceUnitTest, TestServiceProcessMessage, TestSize.Level0)
{
ParamServiceUnitTest test;
......@@ -497,6 +527,7 @@ HWTEST_F(ParamServiceUnitTest, TestAddParamWatch2, TestSize.Level0)
test.TestAddParamWatch2();
}
#ifndef OHOS_LITE
HWTEST_F(ParamServiceUnitTest, TestAddParamWatch3, TestSize.Level0)
{
ParamServiceUnitTest test;
......@@ -519,11 +550,9 @@ HWTEST_F(ParamServiceUnitTest, TestServiceCtrl, TestSize.Level0)
ParamServiceUnitTest test;
int ret = test.TestServiceCtrl("server1", 0770);
EXPECT_NE(ret, 0);
#ifdef PARAM_SUPPORT_SELINUX
// selinux forbid
ret = test.TestServiceCtrl("server2", 0772);
EXPECT_NE(ret, 0);
#endif
ret = 0;
}
......@@ -532,32 +561,27 @@ HWTEST_F(ParamServiceUnitTest, TestPowerCtrl, TestSize.Level0)
ParamServiceUnitTest test;
int ret = test.TestPowerCtrl("reboot,shutdown", 0770);
EXPECT_NE(ret, 0);
#ifdef PARAM_SUPPORT_SELINUX
ret = test.TestPowerCtrl("reboot,shutdown", 0772);
// selinux forbid
EXPECT_NE(ret, 0);
#endif
ret = test.TestPowerCtrl("reboot,updater", 0770);
EXPECT_NE(ret, 0);
#ifdef PARAM_SUPPORT_SELINUX
ret = test.TestPowerCtrl("reboot,updater", 0772);
// selinux forbid
EXPECT_NE(ret, 0);
#endif
ret = test.TestPowerCtrl("reboot,flashd", 0770);
EXPECT_NE(ret, 0);
#ifdef PARAM_SUPPORT_SELINUX
ret = test.TestPowerCtrl("reboot,flashd", 0772);
// selinux forbid
EXPECT_NE(ret, 0);
#endif
ret = test.TestPowerCtrl("reboot", 0770);
EXPECT_NE(ret, 0);
#ifdef PARAM_SUPPORT_SELINUX
ret = test.TestPowerCtrl("reboot", 0772);
// selinux forbid
EXPECT_NE(ret, 0);
#endif
ParamServiceStop();
}
#endif
} // namespace init_ut
......@@ -38,7 +38,10 @@ public:
int TestSelinuxInitLocalLabel()
{
int ret = RegisterSecuritySelinuxOps(&initParamSercurityOps, LABEL_INIT_FOR_INIT);
int ret = RegisterSecuritySelinuxOps(nullptr, 0);
EXPECT_NE(ret, 0);
ret = RegisterSecuritySelinuxOps(&initParamSercurityOps, LABEL_INIT_FOR_INIT);
EXPECT_EQ(ret, 0);
if (initParamSercurityOps.securityInitLabel == nullptr || initParamSercurityOps.securityFreeLabel == nullptr) {
......
......@@ -27,6 +27,7 @@
#include "system_ability_definition.h"
#include "watcher.h"
#include "watcher_manager_kits.h"
#include "watcher_manager_proxy.h"
#include "service_watcher.h"
using namespace testing::ext;
......@@ -62,6 +63,31 @@ public:
void TearDown() {}
void TestBody() {}
int TestAddWatcher0(size_t index)
{
int ret = 0;
// has beed deleted
ret = RemoveParameterWatcher("test.permission.watcher.test1",
TestParameterChange, reinterpret_cast<void *>(index));
EXPECT_NE(ret, 0);
// delete all
ret = SystemWatchParameter("test.permission.watcher.test1",
TestParameterChange, reinterpret_cast<void *>(index));
EXPECT_EQ(ret, 0);
index++;
ret = SystemWatchParameter("test.permission.watcher.test1",
TestParameterChange, reinterpret_cast<void *>(index));
EXPECT_EQ(ret, 0);
ret = RemoveParameterWatcher("test.permission.watcher.test1", nullptr, nullptr);
EXPECT_EQ(ret, 0);
// 非法
ret = SystemWatchParameter("test.permission.watcher.tes^^^^t1*", TestParameterChange, nullptr);
EXPECT_NE(ret, 0);
ret = SystemWatchParameter("test.permission.read.test1*", TestParameterChange, nullptr);
EXPECT_EQ(ret, DAC_RESULT_FORBIDED);
return ret;
}
int TestAddWatcher()
{
size_t index = 1;
......@@ -88,7 +114,6 @@ public:
ret = RemoveParameterWatcher("test.permission.watcher.test1",
TestParameterChange, reinterpret_cast<void *>(index));
EXPECT_EQ(ret, 0);
index--;
ret = RemoveParameterWatcher("test.permission.watcher.test1",
TestParameterChange, reinterpret_cast<void *>(index));
EXPECT_EQ(ret, 0);
......@@ -96,17 +121,11 @@ public:
ret = RemoveParameterWatcher("test.permission.watcher.test1",
TestParameterChange, reinterpret_cast<void *>(index));
EXPECT_EQ(ret, 0);
// has beed deleted
index--;
ret = RemoveParameterWatcher("test.permission.watcher.test1",
TestParameterChange, reinterpret_cast<void *>(index));
EXPECT_NE(ret, 0);
// 非法
ret = SystemWatchParameter("test.permission.watcher.tes^^^^t1*", TestParameterChange, nullptr);
EXPECT_NE(ret, 0);
ret = SystemWatchParameter("test.permission.read.test1*", TestParameterChange, nullptr);
EXPECT_EQ(ret, DAC_RESULT_FORBIDED);
return 0;
EXPECT_EQ(ret, 0);
return TestAddWatcher0(index);
}
int TestDelWatcher()
......@@ -158,6 +177,9 @@ public:
EXPECT_EQ(g_callbackCount, 3);
instance.remoteWatcher_->OnParameterChange(name.c_str(), "testname.2", "testvalue");
EXPECT_EQ(g_callbackCount, 3);
// prefix not exit
instance.remoteWatcher_->OnParameterChange("44444444444444444444", "testname.2", "testvalue");
}
EXPECT_EQ(g_callbackCount, 3);
return 0;
......@@ -175,6 +197,55 @@ public:
}
return 0;
}
void TestWatcherProxy()
{
sptr<WatcherManagerProxy> watcherManager = new(std::nothrow) WatcherManagerProxy(nullptr);
ASSERT_NE(watcherManager, nullptr);
WatcherManagerKits &instance = OHOS::init_param::WatcherManagerKits::GetInstance();
sptr<Watcher> remoteWatcher = new OHOS::init_param::WatcherManagerKits::RemoteWatcher(&instance);
ASSERT_NE(remoteWatcher, nullptr);
MessageParcel data;
MessageParcel reply;
MessageOption option;
data.WriteInterfaceToken(IWatcher::GetDescriptor());
data.WriteString("name");
data.WriteString("name");
data.WriteString("watcherId");
remoteWatcher->OnRemoteRequest(IWatcher::PARAM_CHANGE, data, reply, option);
// invalid parameter
data.WriteInterfaceToken(IWatcher::GetDescriptor());
data.WriteString("name");
data.WriteString("watcherId");
remoteWatcher->OnRemoteRequest(IWatcher::PARAM_CHANGE, data, reply, option);
data.WriteInterfaceToken(IWatcher::GetDescriptor());
data.WriteString("name");
remoteWatcher->OnRemoteRequest(IWatcher::PARAM_CHANGE, data, reply, option);
data.WriteInterfaceToken(IWatcher::GetDescriptor());
remoteWatcher->OnRemoteRequest(IWatcher::PARAM_CHANGE, data, reply, option);
data.WriteInterfaceToken(IWatcher::GetDescriptor());
data.WriteString("name");
data.WriteString("name");
data.WriteString("watcherId");
remoteWatcher->OnRemoteRequest(IWatcher::PARAM_CHANGE + 1, data, reply, option);
remoteWatcher->OnRemoteRequest(IWatcher::PARAM_CHANGE + 1, data, reply, option);
uint32_t watcherId = watcherManager->AddRemoteWatcher(1000, remoteWatcher);
// add watcher
int ret = watcherManager->AddWatcher("test.watcher.proxy", watcherId);
ASSERT_EQ(ret, 0);
ret = watcherManager->DelWatcher("test.watcher.proxy", watcherId);
ASSERT_EQ(ret, 0);
ret = watcherManager->RefreshWatcher("test.watcher.proxy", watcherId);
ASSERT_EQ(ret, 0);
watcherManager->DelRemoteWatcher(watcherId);
}
};
HWTEST_F(WatcherAgentUnitTest, TestAddWatcher, TestSize.Level0)
......@@ -209,4 +280,19 @@ HWTEST_F(WatcherAgentUnitTest, TestWatcherService, TestSize.Level0)
EXPECT_EQ(ServiceWatchForStatus(errstr, TestWatcherCallBack), -1);
EXPECT_EQ(ServiceWatchForStatus(NULL, TestWatcherCallBack), -1);
WatchParameter("testParam", nullptr, nullptr);
}
\ No newline at end of file
WatchParameter(nullptr, nullptr, nullptr);
}
HWTEST_F(WatcherAgentUnitTest, TestInvalidWatcher, TestSize.Level0)
{
int ret = SystemWatchParameter(nullptr, TestParameterChange, nullptr);
ASSERT_NE(ret, 0);
ret = RemoveParameterWatcher(nullptr, nullptr, nullptr);
ASSERT_NE(ret, 0);
}
HWTEST_F(WatcherAgentUnitTest, TestWatcherProxy, TestSize.Level0)
{
WatcherAgentUnitTest test;
test.TestWatcherProxy();
}
......@@ -54,7 +54,14 @@ public:
WatcherProxyUnitTest() {}
virtual ~WatcherProxyUnitTest() {}
void SetUp() {}
void SetUp()
{
if (GetParamSecurityLabel() != nullptr) {
GetParamSecurityLabel()->cred.uid = 0;
GetParamSecurityLabel()->cred.gid = 0;
}
SetTestPermissionResult(0);
}
void TearDown() {}
void TestBody() {}
......@@ -112,8 +119,24 @@ public:
data.WriteString(keyPrefix);
data.WriteUint32(watcherId);
watcherManager->OnRemoteRequest(IWatcherManager::ADD_WATCHER, data, reply, option);
int ret = reply.ReadInt32();
EXPECT_EQ(ret, 0);
EXPECT_EQ(reply.ReadInt32(), 0);
EXPECT_EQ(watcherManager->GetWatcherGroup(keyPrefix) != nullptr, 1);
return 0;
}
int TestRefreshWatcher(const std::string &keyPrefix, uint32_t watcherId)
{
WatcherManagerPtr watcherManager = GetWatcherManager();
WATCHER_CHECK(watcherManager != nullptr, return -1, "Failed to create manager");
MessageParcel data;
MessageParcel reply;
MessageOption option;
data.WriteInterfaceToken(IWatcherManager::GetDescriptor());
data.WriteString(keyPrefix);
data.WriteUint32(watcherId);
watcherManager->OnRemoteRequest(IWatcherManager::REFRESH_WATCHER, data, reply, option);
EXPECT_EQ(reply.ReadInt32(), 0);
EXPECT_EQ(watcherManager->GetWatcherGroup(keyPrefix) != nullptr, 1);
return 0;
}
......@@ -205,7 +228,9 @@ public:
MessageParcel data;
MessageParcel reply;
MessageOption option;
data.WriteInterfaceToken(IWatcherManager::GetDescriptor());
data.WriteString(keyPrefix);
data.WriteUint32(0);
watcherManager->OnRemoteRequest(IWatcherManager::REFRESH_WATCHER + 1, data, reply, option);
data.WriteInterfaceToken(IWatcherManager::GetDescriptor());
......@@ -219,20 +244,21 @@ public:
WatcherManagerPtr watcherManager = GetWatcherManager();
WATCHER_CHECK(watcherManager != nullptr, return -1, "Failed to get manager");
watcherManager->OnStop();
watcherManager->Clear();
return 0;
}
WatcherManagerPtr GetWatcherManager()
{
static WatcherManagerPtr watcherManager = nullptr;
if (watcherManager == nullptr) {
watcherManager = new WatcherManager(0, true);
if (watcherManager == nullptr) {
static WatcherManagerPtr watcherManager_ = nullptr;
if (watcherManager_ == nullptr) {
watcherManager_ = new WatcherManager(0, true);
if (watcherManager_ == nullptr) {
return nullptr;
}
watcherManager->OnStart();
watcherManager_->OnStart();
}
return watcherManager;
return watcherManager_;
}
};
......@@ -242,6 +268,7 @@ HWTEST_F(WatcherProxyUnitTest, TestAddWatcher, TestSize.Level0)
uint32_t watcherId = 0;
test.TestAddRemoteWatcher(1000, watcherId); // 1000 test agent
test.TestAddWatcher("test.permission.watcher.test1", watcherId);
test.TestRefreshWatcher("test.permission.watcher.test1", watcherId);
test.TestProcessWatcherMessage("test.permission.watcher.test1", watcherId);
test.TestWatchAgentDump("test.permission.watcher.test1");
}
......@@ -254,6 +281,7 @@ HWTEST_F(WatcherProxyUnitTest, TestAddWatcher2, TestSize.Level0)
test.TestAddWatcher("test.permission.watcher.test2", watcherId);
test.TestAddWatcher("test.permission.watcher.test2", watcherId);
test.TestAddWatcher("test.permission.watcher.test2", watcherId);
test.TestRefreshWatcher("test.permission.watcher.test2", watcherId);
test.TestWatchAgentDump("test.permission.watcher.test2");
}
......@@ -271,8 +299,8 @@ HWTEST_F(WatcherProxyUnitTest, TestAddWatcher4, TestSize.Level0)
WatcherProxyUnitTest test;
uint32_t watcherId = 0;
test.TestAddRemoteWatcher(1004, watcherId); // 1004 test agent
SystemSetParameter("test.watcher.test4", "1101");
SystemSetParameter("test.watcher.test4.test", "1102");
SystemWriteParam("test.watcher.test4", "1101");
SystemWriteParam("test.watcher.test4.test", "1102");
test.TestAddWatcher("test.watcher.test4*", watcherId);
test.TestWatchAgentDump("test.watcher.test4*");
}
......@@ -283,7 +311,7 @@ HWTEST_F(WatcherProxyUnitTest, TestAddWatcher5, TestSize.Level0)
uint32_t watcherId = 0;
test.TestAddRemoteWatcher(1005, watcherId); // 1005 test agent
test.TestAddWatcher("test.permission.watcher.test5", watcherId);
SystemSetParameter("test.permission.watcher.test5", "1101");
SystemWriteParam("test.permission.watcher.test5", "1101");
test.TestWatchAgentDump("test.permission.watcher.test5");
}
......@@ -309,6 +337,16 @@ HWTEST_F(WatcherProxyUnitTest, TestDiedWatcher, TestSize.Level0)
test.TestWatchAgentDump("test.permission.watcher.testdied");
}
HWTEST_F(WatcherProxyUnitTest, TestSendLocalChange, TestSize.Level0)
{
WatcherProxyUnitTest test;
uint32_t watcherId = 0;
test.TestAddRemoteWatcher(2006, watcherId); // 2006 test agent
test.TestAddWatcher("test.watcher*", watcherId);
test.TestAddWatcher("test.watcher.", watcherId);
test.TestWatchAgentDump("test.watcher.");
}
HWTEST_F(WatcherProxyUnitTest, TestWatchProxy, TestSize.Level0)
{
WatcherProxyUnitTest test;
......@@ -324,5 +362,8 @@ HWTEST_F(WatcherProxyUnitTest, TestInvalid, TestSize.Level0)
HWTEST_F(WatcherProxyUnitTest, TestStop, TestSize.Level0)
{
WatcherProxyUnitTest test;
uint32_t watcherId = 0;
test.TestAddRemoteWatcher(1007, watcherId); // 1005 test agent
test.TestAddWatcher("test.permission.watcher.stop", watcherId);
test.TestStop();
}
\ No newline at end of file
......@@ -303,6 +303,7 @@ HWTEST_F(SysparaUnitTest, parameterTest0013, TestSize.Level0)
HWTEST_F(SysparaUnitTest, parameterTest0014, TestSize.Level0)
{
const std::string key1 = "test.int.get";
OHOS::system::SetParameter(std::string("testKey"), std::string("testValue"));
int v = OHOS::system::GetIntParameter(key1, 0);
EXPECT_EQ(v, -TEST_VALUE);
int8_t v1 = OHOS::system::GetIntParameter(key1, 0, -127, 128); // -127, 128 range
......
......@@ -31,7 +31,7 @@ bool IsMatch(const char *target, const char *pattern);
using namespace std;
using namespace testing::ext;
namespace ueventd_ut {
namespace UeventdUt {
class UeventdConfigUnitTest : public testing::Test {
public:
static void SetUpTestCase(void) {};
......@@ -42,7 +42,7 @@ void TearDown() {};
HWTEST_F(UeventdConfigUnitTest, TestSectionConfigParse, TestSize.Level0)
{
ParseUeventdConfigFile("/data/ueventd_ut/valid.config");
ParseUeventdConfigFile(STARTUP_INIT_UT_PATH"/ueventd_ut/valid.config");
uid_t uid = 0;
gid_t gid = 0;
mode_t mode = 0;
......@@ -84,7 +84,7 @@ HWTEST_F(UeventdConfigUnitTest, TestConfigEntry, TestSize.Level0)
HWTEST_F(UeventdConfigUnitTest, TestParameter, TestSize.Level0)
{
ParseUeventdConfigFile("/data/ueventd_ut/valid.config");
ParseUeventdConfigFile(STARTUP_INIT_UT_PATH"/ueventd_ut/valid.config");
SetUeventDeviceParameter("/dev/testbinder1", 0);
SetUeventDeviceParameter("/dev/testbinder2", 0);
SetUeventDeviceParameter("/dev/testbinder3", 0);
......@@ -96,4 +96,4 @@ HWTEST_F(UeventdConfigUnitTest, TestParameter, TestSize.Level0)
ret = IsMatch("test", "t****");
EXPECT_EQ(ret, true);
}
} // namespace ueventd_ut
} // namespace UeventdUt
/*
* Copyright (c) 2022 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 <cerrno>
#include <string>
#include <vector>
#include <iostream>
#include <memory>
#include <gtest/gtest.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include "ueventd.h"
#include "ueventd_device_handler.h"
#include "ueventd_socket.h"
using namespace testing::ext;
namespace UeventdUt {
namespace {
std::string g_testRoot{"/data/ueventd"};
int g_oldRootFd = -1;
}
class UeventdEventUnitTest : public testing::Test {
public:
static void SetUpTestCase(void)
{
struct stat st{};
bool isExist = true;
if (stat(g_testRoot.c_str(), &st) < 0) {
if (errno != ENOENT) {
std::cout << "Cannot get stat of " << g_testRoot << std::endl;
// If we cannot get root for ueventd tests
// There is no reason to continue.
ASSERT_TRUE(false);
}
isExist = false;
}
if (isExist) {
RemoveDir(g_testRoot);
}
int ret = mkdir(g_testRoot.c_str(), S_IRWXU | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (ret < 0) {
std::cout << "Cannot create directory " << g_testRoot << " err = " << errno << std::endl;
ASSERT_TRUE(0);
}
if (SwitchRoot() < 0) {
// If we cannot do this, there is not reason to continue
ASSERT_TRUE(0);
}
}
static void TearDownTestCase(void)
{
// Switch back to old root
if (g_oldRootFd < 0) {
std::cout << "Old root directory is not valid\n";
return;
}
if (fchdir(g_oldRootFd) < 0) {
std::cout << "Failed to change working directory to '/', err = " << errno << std::endl;
}
if (chroot(".") < 0) {
std::cout << "Failed to change root directory to '/', err = " << errno << std::endl;
}
close(g_oldRootFd);
g_oldRootFd = -1;
std::cout << "Change root back done\n";
// Remove test data
if (RemoveDir(g_testRoot) < 0) {
std::cout << "Failed to remove " << g_testRoot << ", err = " << errno << std::endl;
}
}
static int RemoveDir(const std::string &path)
{
if (path.empty()) {
// Treat it as OK
return 0;
}
auto dir = std::unique_ptr<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir);
if (dir == nullptr) {
std::cout << "Cannot open dir " << path << ", err = " << errno << std::endl;
return -1;
}
struct dirent *dp = nullptr;
while ((dp = readdir(dir.get())) != nullptr) {
// Skip hidden files
if (dp->d_name[0] == '.') {
continue;
}
bool endsWithSlash = (path.find_last_of("/") == path.size() - 1);
std::string fullPath {};
if (endsWithSlash) {
fullPath = path + dp->d_name;
} else {
fullPath = path + "/" + dp->d_name;
}
struct stat st {};
if (stat(fullPath.c_str(), &st) < 0) {
std::cout << "Failed to get stat of " << fullPath << std::endl;
continue; // Should we continue?
}
if (S_ISDIR(st.st_mode)) {
if (RemoveDir(fullPath) < 0) {
std::cout << "Failed to remove directory " << fullPath << std::endl;
return -1;
}
} else {
if (unlink(fullPath.c_str()) < 0) {
std::cout << "Failed to unlink file " << fullPath << std::endl;
return -1;
}
}
}
return rmdir(path.c_str());
}
static int SwitchRoot()
{
if (g_oldRootFd >= 0) {
close(g_oldRootFd);
g_oldRootFd = -1;
}
// Save old root
DIR *dir = opendir("/");
if (dir == nullptr) {
std::cout << "Failed to open root directory\n";
return -1;
}
g_oldRootFd = dirfd(dir);
if (g_oldRootFd < 0) {
std::cout << "Failed to pen root directory, err = " << errno << std::endl;
return -1;
}
// Changing working directory to "/data/ueventd"
if (chdir(g_testRoot.c_str()) < 0) {
std::cout << "Failed to change working directory to " << g_testRoot << ", err = " << errno << std::endl;
close(g_oldRootFd);
g_oldRootFd = -1;
}
if (chroot(g_testRoot.c_str()) < 0) {
std::cout << "Failed to change root directory to " << g_testRoot << ", err = " << errno << std::endl;
close(g_oldRootFd);
g_oldRootFd = -1;
}
std::cout << "Change root to " << g_testRoot << " done\n";
return 0;
}
void SetUp() {};
void TearDown() {};
};
// Generate uevent buffer from struct uevent.
// extra data used to break uevent buffer to check
// if ueventd will handle this situation correctly
std::string GenerateUeventBuffer(struct Uevent &uevent, std::vector<std::string> &extraData)
{
std::string ueventdBuffer{};
if (uevent.syspath != nullptr) {
ueventdBuffer.append(std::string("DEVPATH=") + uevent.syspath + '\000');
}
if (uevent.subsystem != nullptr) {
ueventdBuffer.append(std::string("SUBSYSTEM=") + uevent.subsystem + '\000');
}
ueventdBuffer.append(std::string("ACTION=") + ActionString(uevent.action) + '\000');
if (uevent.deviceName != nullptr) {
ueventdBuffer.append(std::string("DEVNAME=") + uevent.deviceName + '\000');
}
if (uevent.partitionName != nullptr) {
ueventdBuffer.append(std::string("PARTNAME=") + uevent.partitionName + '\000');
}
ueventdBuffer.append(std::string("PARTN=") + std::to_string(uevent.partitionNum) + '\000');
ueventdBuffer.append(std::string("MAJOR=") + std::to_string(uevent.major) + '\000');
ueventdBuffer.append(std::string("MINOR=") + std::to_string(uevent.minor) + '\000');
ueventdBuffer.append(std::string("DEVUID=") + std::to_string(uevent.ug.uid) + '\000');
ueventdBuffer.append(std::string("DEVGID=") + std::to_string(uevent.ug.gid) + '\000');
if (uevent.firmware != nullptr) {
ueventdBuffer.append(std::string("FIRMWARE=") + uevent.firmware + '\000');
}
ueventdBuffer.append(std::string("BUSNUM=") + std::to_string(uevent.busNum) + '\000');
ueventdBuffer.append(std::string("DEVNUM=") + std::to_string(uevent.devNum) + '\000');
if (!extraData.empty()) {
for (const auto &data : extraData) {
ueventdBuffer.append(data);
}
}
return ueventdBuffer;
}
bool IsFileExist(const std::string &file)
{
struct stat st{};
if (file.empty()) {
return false;
}
if (stat(file.c_str(), &st) < 0) {
if (errno == ENOENT) {
std::cout << "File " << file << " is not exist\n";
}
return false;
}
return true;
}
HWTEST_F(UeventdEventUnitTest, TestParseUeventdEvent, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "block",
.syspath = "/block/mmc/test",
.deviceName = "test",
.partitionName = "userdata",
.firmware = "",
.action = ACTION_ADD,
.partitionNum = 3,
.major = 1,
.minor = 2,
.ug = {
.uid = 0,
.gid = 0,
},
.busNum = 1,
.devNum = 2,
};
std::vector<std::string> extraData{};
auto ueventBuffer = GenerateUeventBuffer(uevent, extraData);
std::cout << "ueventBuffer = [" << ueventBuffer << "]. size = " << ueventBuffer.length() << std::endl;
struct Uevent outEvent;
ParseUeventMessage(ueventBuffer.data(), ueventBuffer.length(), &outEvent);
EXPECT_EQ(outEvent.action, ACTION_ADD);
EXPECT_EQ(outEvent.busNum, 1);
EXPECT_STREQ(outEvent.subsystem, "block");
EXPECT_STREQ(outEvent.deviceName, "test");
EXPECT_EQ(outEvent.devNum, 2);
EXPECT_EQ(outEvent.major, 1);
EXPECT_EQ(outEvent.minor, 2);
EXPECT_EQ(outEvent.partitionNum, 3);
EXPECT_STREQ(outEvent.partitionName, "userdata");
EXPECT_STREQ(outEvent.syspath, "/block/mmc/test");
EXPECT_EQ(outEvent.ug.gid, 0);
EXPECT_EQ(outEvent.ug.uid, 0);
}
HWTEST_F(UeventdEventUnitTest, TestUeventActions, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "block",
.syspath = "/block/mmc/test",
.deviceName = "test",
.partitionName = "userdata",
.action = ACTION_UNKNOWN,
};
std::vector<std::string> extraData {};
auto ueventBuffer = GenerateUeventBuffer(uevent, extraData);
std::cout << "ueventBuffer = [" << ueventBuffer << "]. size = " << ueventBuffer.length() << std::endl;
struct Uevent outEvent;
ParseUeventMessage(ueventBuffer.data(), ueventBuffer.length(), &outEvent);
EXPECT_EQ(outEvent.action, ACTION_UNKNOWN);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleBlockDevicesInvalidParameters, TestSize.Level1)
{
HandleBlockDeviceEvent(nullptr);
// Not block device
struct Uevent noBlockUevent = {
.subsystem = "char",
};
HandleBlockDeviceEvent(&noBlockUevent);
struct Uevent invalidDevNoUevent = {
.subsystem = "block",
.major = -1,
.minor = -1,
};
HandleBlockDeviceEvent(&invalidDevNoUevent);
struct Uevent invalidSysPathUevent = {
.subsystem = "block",
.syspath = nullptr,
.major = 1,
.minor = 1,
};
HandleBlockDeviceEvent(&invalidSysPathUevent);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleBlockDevicesValidParameters, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "block",
.syspath = "/block/mmc/block_device_test",
.deviceName = "block_device_test",
.partitionName = "block_device_test",
.firmware = "",
.action = ACTION_ADD,
.partitionNum = 3,
.major = 5,
.minor = 15,
.ug = {
.uid = 0,
.gid = 0,
},
.busNum = 1,
.devNum = 2,
};
HandleBlockDeviceEvent(&uevent);
// Check results
std::string blockDevice = "/dev/block/block_device_test";
struct stat st{};
int ret = stat(blockDevice.c_str(), &st);
EXPECT_EQ(ret, 0);
bool isBlock = S_ISBLK(st.st_mode);
EXPECT_TRUE(isBlock);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleBlockDevicesRemoved, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "block",
.syspath = "/block/mmc/block_device_test",
.deviceName = "block_device_test",
.partitionName = "block_device_test",
.firmware = "",
.action = ACTION_REMOVE,
.partitionNum = 3,
.major = 5,
.minor = 15,
.ug = {
.uid = 0,
.gid = 0,
},
.busNum = 1,
.devNum = 2,
};
std::string blockDevice = "/dev/block/block_device_test";
struct stat st{};
int ret = stat(blockDevice.c_str(), &st);
if (ret < 0) {
// This should not happen actually, because we've created the device node before.
std::cout << "Warning. Block device " << blockDevice << " is not exist.\n";
}
HandleBlockDeviceEvent(&uevent);
ret = stat(blockDevice.c_str(), &st);
EXPECT_EQ(ret, -1);
EXPECT_EQ(errno, ENOENT);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleBlockDevicesChanged, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "block",
.syspath = "/block/mmc/block_device_test",
.deviceName = "block_device_test",
.partitionName = "block_device_test",
.firmware = "",
.action = ACTION_REMOVE,
.partitionNum = 3,
.major = 5,
.minor = 15,
.ug = {
.uid = 0,
.gid = 0,
},
.busNum = 1,
.devNum = 2,
};
HandleBlockDeviceEvent(&uevent);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleOtherDevicesInvalidParameters, TestSize.Level1)
{
HandleOtherDeviceEvent(nullptr);
// Not Character device
struct Uevent invalidDevNoUevent = {
.subsystem = "test",
.major = -1,
.minor = -1,
};
HandleOtherDeviceEvent(&invalidDevNoUevent);
struct Uevent invalidSysPathUevent = {
.subsystem = "test",
.syspath = nullptr,
.major = 5,
.minor = 9,
};
HandleOtherDeviceEvent(&invalidSysPathUevent);
struct Uevent invalidSubsystemUevent = {
.subsystem = "",
.syspath = "/devices/test/char",
.major = 5,
.minor = 9,
};
HandleOtherDeviceEvent(&invalidSubsystemUevent);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleOtherDevicesValidParameters, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "extcon3",
.syspath = "/devices/platform/headset/extcon/extcon3",
.deviceName = "extcon3-1",
.major = 5,
.minor = 9,
};
HandleOtherDeviceEvent(&uevent);
auto exist = IsFileExist("/dev/extcon3-1");
EXPECT_TRUE(exist);
exist = IsFileExist("/dev/extcon3");
EXPECT_FALSE(exist);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleUsbDevicesWithDeviceName, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "usb",
.syspath = "/devices/platform/headset/extcon/usb-dev",
.deviceName = "usb-dev",
.major = 8,
.minor = 9,
};
HandleOtherDeviceEvent(&uevent);
auto exist = IsFileExist("/dev/usb-dev");
EXPECT_TRUE(exist);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleInvalidUsbDevices, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "usb",
.syspath = "/devices/platform/headset/extcon/usb-dev-1",
.major = 8,
.minor = 10,
.busNum = -1,
.devNum = -1,
};
HandleOtherDeviceEvent(&uevent);
auto exist = IsFileExist("/dev/usb-dev-1");
EXPECT_FALSE(exist);
}
HWTEST_F(UeventdEventUnitTest, TestUeventHandleUsbDevicesWithBusNo, TestSize.Level1)
{
struct Uevent uevent = {
.subsystem = "usb",
.syspath = "/devices/platform/headset/extcon/usb-dev",
.major = 8,
.minor = 9,
.busNum = 3,
.devNum = 4,
};
HandleOtherDeviceEvent(&uevent);
auto exist = IsFileExist("/dev/bus/usb/003/004");
EXPECT_TRUE(exist);
}
} // UeventdUt
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册