提交 df26e0e2 编写于 作者: W William Dean

去掉cpp文件中的windows ^M 换行符

Signed-off-by: NWilliam Dean <williamsukatube@gmail.com>
上级 864bd0dc
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "beget_ext.h" #include "beget_ext.h"
#ifdef PARAM_FEATURE_DEVICEINFO #ifdef PARAM_FEATURE_DEVICEINFO
#include "device_info_kits.h" #include "device_info_kits.h"
#endif #endif
#include "param_comm.h" #include "param_comm.h"
#include "securec.h" #include "securec.h"
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
extern "C" { extern "C" {
#endif #endif
#endif /* __cplusplus */ #endif /* __cplusplus */
int AclGetDevUdid(char *udid, int size) int AclGetDevUdid(char *udid, int size)
{ {
if (udid == nullptr || size < UDID_LEN) { if (udid == nullptr || size < UDID_LEN) {
return -1; return -1;
} }
#ifdef PARAM_FEATURE_DEVICEINFO #ifdef PARAM_FEATURE_DEVICEINFO
std::string result = {}; std::string result = {};
OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance(); OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance();
int ret = instance.GetUdid(result); int ret = instance.GetUdid(result);
if (ret == 0) { if (ret == 0) {
ret = strcpy_s(udid, size, result.c_str()); ret = strcpy_s(udid, size, result.c_str());
} }
#else #else
int ret = GetDevUdid_(udid, size); int ret = GetDevUdid_(udid, size);
#endif #endif
BEGET_LOGI("AclGetDevUdid %s", udid); BEGET_LOGI("AclGetDevUdid %s", udid);
return ret; return ret;
} }
const char *AclGetSerial(void) const char *AclGetSerial(void)
{ {
static char serialNumber[MAX_SERIAL_LEN] = {"1234567890"}; static char serialNumber[MAX_SERIAL_LEN] = {"1234567890"};
#ifdef PARAM_FEATURE_DEVICEINFO #ifdef PARAM_FEATURE_DEVICEINFO
std::string result = {}; std::string result = {};
OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance(); OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance();
int ret = instance.GetSerialID(result); int ret = instance.GetSerialID(result);
if (ret == 0) { if (ret == 0) {
ret = strcpy_s(serialNumber, sizeof(serialNumber), result.c_str()); ret = strcpy_s(serialNumber, sizeof(serialNumber), result.c_str());
BEGET_ERROR_CHECK(ret == 0, return nullptr, "Failed to copy"); BEGET_ERROR_CHECK(ret == 0, return nullptr, "Failed to copy");
} }
#else #else
const char *tmpSerial = GetSerial_(); const char *tmpSerial = GetSerial_();
if (tmpSerial != nullptr) { if (tmpSerial != nullptr) {
int ret = strcpy_s(serialNumber, sizeof(serialNumber), tmpSerial); int ret = strcpy_s(serialNumber, sizeof(serialNumber), tmpSerial);
BEGET_ERROR_CHECK(ret == 0, return nullptr, "Failed to copy"); BEGET_ERROR_CHECK(ret == 0, return nullptr, "Failed to copy");
} }
#endif #endif
BEGET_LOGI("AclGetSerial %s", serialNumber); BEGET_LOGI("AclGetSerial %s", serialNumber);
return serialNumber; return serialNumber;
} }
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
} }
#endif #endif
#endif /* __cplusplus */ #endif /* __cplusplus */
\ No newline at end of file
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "device_info_kits.h" #include "device_info_kits.h"
#include "beget_ext.h" #include "beget_ext.h"
#include "device_info_proxy.h" #include "device_info_proxy.h"
#include "idevice_info.h" #include "idevice_info.h"
#include "if_system_ability_manager.h" #include "if_system_ability_manager.h"
#include "iservice_registry.h" #include "iservice_registry.h"
#include "system_ability_definition.h" #include "system_ability_definition.h"
#include "securec.h" #include "securec.h"
namespace OHOS { namespace OHOS {
namespace device_info { namespace device_info {
DeviceInfoKits::DeviceInfoKits() {} DeviceInfoKits::DeviceInfoKits() {}
DeviceInfoKits::~DeviceInfoKits() {} DeviceInfoKits::~DeviceInfoKits() {}
DeviceInfoKits &DeviceInfoKits::GetInstance() DeviceInfoKits &DeviceInfoKits::GetInstance()
{ {
return DelayedRefSingleton<DeviceInfoKits>::GetInstance(); return DelayedRefSingleton<DeviceInfoKits>::GetInstance();
} }
void DeviceInfoKits::ResetService(const wptr<IRemoteObject> &remote) void DeviceInfoKits::ResetService(const wptr<IRemoteObject> &remote)
{ {
std::lock_guard<std::mutex> lock(lock_); std::lock_guard<std::mutex> lock(lock_);
if (deviceInfoService_ != nullptr) { if (deviceInfoService_ != nullptr) {
sptr<IRemoteObject> object = deviceInfoService_->AsObject(); sptr<IRemoteObject> object = deviceInfoService_->AsObject();
if ((object != nullptr) && (remote == object)) { if ((object != nullptr) && (remote == object)) {
object->RemoveDeathRecipient(deathRecipient_); object->RemoveDeathRecipient(deathRecipient_);
deviceInfoService_ = nullptr; deviceInfoService_ = nullptr;
} }
} }
} }
sptr<IDeviceInfo> DeviceInfoKits::GetService() sptr<IDeviceInfo> DeviceInfoKits::GetService()
{ {
std::lock_guard<std::mutex> lock(lock_); std::lock_guard<std::mutex> lock(lock_);
if (deviceInfoService_ != nullptr) { if (deviceInfoService_ != nullptr) {
return deviceInfoService_; return deviceInfoService_;
} }
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
DINFO_CHECK(samgr != nullptr, return nullptr, "Get samgr failed"); DINFO_CHECK(samgr != nullptr, return nullptr, "Get samgr failed");
sptr<IRemoteObject> object = samgr->GetSystemAbility(SYSPARAM_DEVICE_SERVICE_ID); sptr<IRemoteObject> object = samgr->GetSystemAbility(SYSPARAM_DEVICE_SERVICE_ID);
DINFO_CHECK(object != nullptr, return nullptr, "Get device service object from samgr failed"); DINFO_CHECK(object != nullptr, return nullptr, "Get device service object from samgr failed");
if (deathRecipient_ == nullptr) { if (deathRecipient_ == nullptr) {
deathRecipient_ = new DeathRecipient(); deathRecipient_ = new DeathRecipient();
} }
if ((object->IsProxyObject()) && (!object->AddDeathRecipient(deathRecipient_))) { if ((object->IsProxyObject()) && (!object->AddDeathRecipient(deathRecipient_))) {
DINFO_LOGE("Failed to add death recipient"); DINFO_LOGE("Failed to add death recipient");
} }
deviceInfoService_ = iface_cast<IDeviceInfo>(object); deviceInfoService_ = iface_cast<IDeviceInfo>(object);
if (deviceInfoService_ == nullptr) { if (deviceInfoService_ == nullptr) {
DINFO_LOGE("device service iface_cast failed"); DINFO_LOGE("device service iface_cast failed");
} }
return deviceInfoService_; return deviceInfoService_;
} }
void DeviceInfoKits::DeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote) void DeviceInfoKits::DeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
{ {
DelayedRefSingleton<DeviceInfoKits>::GetInstance().ResetService(remote); DelayedRefSingleton<DeviceInfoKits>::GetInstance().ResetService(remote);
} }
int32_t DeviceInfoKits::GetUdid(std::string& result) int32_t DeviceInfoKits::GetUdid(std::string& result)
{ {
auto deviceService = GetService(); auto deviceService = GetService();
DINFO_CHECK(deviceService != nullptr, return -1, "Failed to get watcher manager"); DINFO_CHECK(deviceService != nullptr, return -1, "Failed to get watcher manager");
return deviceService->GetUdid(result); return deviceService->GetUdid(result);
} }
int32_t DeviceInfoKits::GetSerialID(std::string& result) int32_t DeviceInfoKits::GetSerialID(std::string& result)
{ {
auto deviceService = GetService(); auto deviceService = GetService();
DINFO_CHECK(deviceService != nullptr, return -1, "Failed to get watcher manager"); DINFO_CHECK(deviceService != nullptr, return -1, "Failed to get watcher manager");
return deviceService->GetSerialID(result); return deviceService->GetSerialID(result);
} }
} // namespace device_info } // namespace device_info
} // namespace OHOS } // namespace OHOS
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "device_info_proxy.h" #include "device_info_proxy.h"
#include "beget_ext.h" #include "beget_ext.h"
#include "idevice_info.h" #include "idevice_info.h"
#include "parcel.h" #include "parcel.h"
#include "string_ex.h" #include "string_ex.h"
namespace OHOS { namespace OHOS {
namespace device_info { namespace device_info {
int32_t DeviceInfoProxy::GetUdid(std::string& result) int32_t DeviceInfoProxy::GetUdid(std::string& result)
{ {
MessageParcel data; MessageParcel data;
MessageParcel reply; MessageParcel reply;
MessageOption option { MessageOption::TF_SYNC }; MessageOption option { MessageOption::TF_SYNC };
data.WriteInterfaceToken(DeviceInfoProxy::GetDescriptor()); data.WriteInterfaceToken(DeviceInfoProxy::GetDescriptor());
int32_t ret = Remote()->SendRequest(COMMAND_GET_UDID, data, reply, option); int32_t ret = Remote()->SendRequest(COMMAND_GET_UDID, data, reply, option);
DINFO_CHECK(ret == ERR_NONE, return ret, "getUdid failed, error code is %d", ret); DINFO_CHECK(ret == ERR_NONE, return ret, "getUdid failed, error code is %d", ret);
result = Str16ToStr8(reply.ReadString16()); result = Str16ToStr8(reply.ReadString16());
return ERR_OK; return ERR_OK;
} }
int32_t DeviceInfoProxy::GetSerialID(std::string& result) int32_t DeviceInfoProxy::GetSerialID(std::string& result)
{ {
MessageParcel data; MessageParcel data;
MessageParcel reply; MessageParcel reply;
MessageOption option { MessageOption::TF_SYNC }; MessageOption option { MessageOption::TF_SYNC };
data.WriteInterfaceToken(DeviceInfoProxy::GetDescriptor()); data.WriteInterfaceToken(DeviceInfoProxy::GetDescriptor());
int32_t ret = Remote()->SendRequest(COMMAND_GET_SERIAL_ID, data, reply, option); int32_t ret = Remote()->SendRequest(COMMAND_GET_SERIAL_ID, data, reply, option);
DINFO_CHECK(ret == ERR_NONE, return ret, "GetSerial failed, error code is %d", ret); DINFO_CHECK(ret == ERR_NONE, return ret, "GetSerial failed, error code is %d", ret);
result = Str16ToStr8(reply.ReadString16()); result = Str16ToStr8(reply.ReadString16());
return ERR_OK; return ERR_OK;
} }
} // namespace device_info } // namespace device_info
} // namespace OHOS } // namespace OHOS
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "device_info_stub.h" #include "device_info_stub.h"
#include "beget_ext.h" #include "beget_ext.h"
#include "idevice_info.h" #include "idevice_info.h"
#include "ipc_skeleton.h" #include "ipc_skeleton.h"
#include "accesstoken_kit.h" #include "accesstoken_kit.h"
#include "parcel.h" #include "parcel.h"
#include "string_ex.h" #include "string_ex.h"
#include "system_ability_definition.h" #include "system_ability_definition.h"
#include "param_comm.h" #include "param_comm.h"
using std::u16string; using std::u16string;
namespace OHOS { namespace OHOS {
using namespace Security; using namespace Security;
using namespace Security::AccessToken; using namespace Security::AccessToken;
namespace device_info { namespace device_info {
REGISTER_SYSTEM_ABILITY_BY_ID(DeviceInfoService, SYSPARAM_DEVICE_SERVICE_ID, true) REGISTER_SYSTEM_ABILITY_BY_ID(DeviceInfoService, SYSPARAM_DEVICE_SERVICE_ID, true)
int32_t DeviceInfoStub::OnRemoteRequest(uint32_t code, int32_t DeviceInfoStub::OnRemoteRequest(uint32_t code,
MessageParcel &data, MessageParcel &reply, MessageOption &option) MessageParcel &data, MessageParcel &reply, MessageOption &option)
{ {
std::u16string myDescripter = IDeviceInfo::GetDescriptor(); std::u16string myDescripter = IDeviceInfo::GetDescriptor();
std::u16string remoteDescripter = data.ReadInterfaceToken(); std::u16string remoteDescripter = data.ReadInterfaceToken();
DINFO_CHECK(myDescripter == remoteDescripter, return ERR_INVALD_DESC, "Invalid remoteDescripter"); DINFO_CHECK(myDescripter == remoteDescripter, return ERR_INVALD_DESC, "Invalid remoteDescripter");
int ret = ERR_FAIL; int ret = ERR_FAIL;
switch (code) { switch (code) {
case COMMAND_GET_UDID: { case COMMAND_GET_UDID: {
if (!CheckPermission(data, PERMISSION_UDID)) { if (!CheckPermission(data, PERMISSION_UDID)) {
return ERR_FAIL; return ERR_FAIL;
} }
char localDeviceInfo[UDID_LEN] = {0}; char localDeviceInfo[UDID_LEN] = {0};
ret = GetDevUdid_(localDeviceInfo, UDID_LEN); ret = GetDevUdid_(localDeviceInfo, UDID_LEN);
DINFO_CHECK(ret == 0, break, "Failed to get dev udid"); DINFO_CHECK(ret == 0, break, "Failed to get dev udid");
reply.WriteString16(Str8ToStr16(localDeviceInfo)); reply.WriteString16(Str8ToStr16(localDeviceInfo));
break; break;
} }
case COMMAND_GET_SERIAL_ID: { case COMMAND_GET_SERIAL_ID: {
if (!CheckPermission(data, PERMISSION_UDID)) { if (!CheckPermission(data, PERMISSION_UDID)) {
return ERR_FAIL; return ERR_FAIL;
} }
const char *serialNumber = GetSerial_(); const char *serialNumber = GetSerial_();
DINFO_CHECK(serialNumber != nullptr, break, "Failed to get serialNumber"); DINFO_CHECK(serialNumber != nullptr, break, "Failed to get serialNumber");
reply.WriteString16(Str8ToStr16(serialNumber)); reply.WriteString16(Str8ToStr16(serialNumber));
break; break;
} }
default: { default: {
return IPCObjectStub::OnRemoteRequest(code, data, reply, option); return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
} }
} }
return ret; return ret;
} }
bool DeviceInfoStub::CheckPermission(MessageParcel &data, const std::string &permission) bool DeviceInfoStub::CheckPermission(MessageParcel &data, const std::string &permission)
{ {
AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
int32_t result = TypePermissionState::PERMISSION_GRANTED; int32_t result = TypePermissionState::PERMISSION_GRANTED;
int32_t tokenType = AccessTokenKit::GetTokenTypeFlag(callerToken); int32_t tokenType = AccessTokenKit::GetTokenTypeFlag(callerToken);
if (tokenType == TOKEN_NATIVE) { if (tokenType == TOKEN_NATIVE) {
result = AccessTokenKit::VerifyNativeToken(callerToken, permission); result = AccessTokenKit::VerifyNativeToken(callerToken, permission);
} else if (tokenType == TOKEN_HAP) { } else if (tokenType == TOKEN_HAP) {
result = AccessTokenKit::VerifyAccessToken(callerToken, permission); result = AccessTokenKit::VerifyAccessToken(callerToken, permission);
} else { } else {
DINFO_LOGE("AccessToken type:%d, permission:%d denied!", tokenType, callerToken); DINFO_LOGE("AccessToken type:%d, permission:%d denied!", tokenType, callerToken);
return false; return false;
} }
if (result == TypePermissionState::PERMISSION_DENIED) { if (result == TypePermissionState::PERMISSION_DENIED) {
DINFO_LOGE("AccessTokenID:%d, permission:%s denied!", callerToken, permission.c_str()); DINFO_LOGE("AccessTokenID:%d, permission:%s denied!", callerToken, permission.c_str());
return false; return false;
} }
DINFO_LOGI("tokenType %d dAccessTokenID:%d, permission:%s matched!", tokenType, callerToken, permission.c_str()); DINFO_LOGI("tokenType %d dAccessTokenID:%d, permission:%s matched!", tokenType, callerToken, permission.c_str());
return true; return true;
} }
int32_t DeviceInfoService::GetUdid(std::string& result) int32_t DeviceInfoService::GetUdid(std::string& result)
{ {
return 0; return 0;
} }
int32_t DeviceInfoService::GetSerialID(std::string& result) int32_t DeviceInfoService::GetSerialID(std::string& result)
{ {
return 0; return 0;
} }
void DeviceInfoService::OnStart(void) void DeviceInfoService::OnStart(void)
{ {
DINFO_LOGI("WatcherManager OnStart"); DINFO_LOGI("WatcherManager OnStart");
bool res = Publish(this); bool res = Publish(this);
if (!res) { if (!res) {
DINFO_LOGE("WatcherManager Publish failed"); DINFO_LOGE("WatcherManager Publish failed");
} }
return; return;
} }
void DeviceInfoService::OnStop() void DeviceInfoService::OnStop()
{ {
} }
} // namespace device_info } // namespace device_info
} // namespace OHOS } // namespace OHOS
/* /*
* Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "param_wrapper.h" #include "param_wrapper.h"
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include <climits> #include <climits>
#include "beget_ext.h" #include "beget_ext.h"
#include "param_comm.h" #include "param_comm.h"
#include "init_param.h" #include "init_param.h"
#include "sysparam_errno.h" #include "sysparam_errno.h"
#include "securec.h" #include "securec.h"
#include "parameter.h" #include "parameter.h"
#include "parameters.h" #include "parameters.h"
namespace OHOS { namespace OHOS {
namespace system { namespace system {
bool SetParameter(const std::string& key, const std::string& value) bool SetParameter(const std::string& key, const std::string& value)
{ {
int ret = SystemSetParameter(key.c_str(), value.c_str()); int ret = SystemSetParameter(key.c_str(), value.c_str());
return (ret == 0) ? true : false; return (ret == 0) ? true : false;
} }
template<typename T> template<typename T>
bool StringToInt(const std::string& str, T min, T max, T& out) bool StringToInt(const std::string& str, T min, T max, T& out)
{ {
long long int result = 0; long long int result = 0;
if (StringToLL(str.c_str(), &result) != 0) { if (StringToLL(str.c_str(), &result) != 0) {
return false; return false;
} }
if (result < min || max < result) { if (result < min || max < result) {
return false; return false;
} }
out = static_cast<T>(result); out = static_cast<T>(result);
return true; return true;
} }
template<typename T> template<typename T>
bool StringToUint(const std::string& str, T max, T& out) bool StringToUint(const std::string& str, T max, T& out)
{ {
unsigned long long int result = 0; unsigned long long int result = 0;
if (StringToULL(str.c_str(), &result) != 0) { if (StringToULL(str.c_str(), &result) != 0) {
return false; return false;
} }
if (max < result) { if (max < result) {
return false; return false;
} }
out = static_cast<T>(result); out = static_cast<T>(result);
return true; return true;
} }
std::string GetParameter(const std::string& key, const std::string& def) std::string GetParameter(const std::string& key, const std::string& def)
{ {
uint32_t size = 0; uint32_t size = 0;
int ret = SystemReadParam(key.c_str(), NULL, &size); int ret = SystemReadParam(key.c_str(), NULL, &size);
if (ret == 0) { if (ret == 0) {
std::vector<char> value(size + 1); std::vector<char> value(size + 1);
ret = SystemReadParam(key.c_str(), value.data(), &size); ret = SystemReadParam(key.c_str(), value.data(), &size);
if (ret == 0) { if (ret == 0) {
return std::string(value.data()); return std::string(value.data());
} }
} }
if (IsValidParamValue(def.c_str(), MAX_VALUE_LEN) == 1) { if (IsValidParamValue(def.c_str(), MAX_VALUE_LEN) == 1) {
return std::string(def); return std::string(def);
} }
return ""; return "";
} }
bool GetBoolParameter(const std::string& key, bool def) bool GetBoolParameter(const std::string& key, bool def)
{ {
static const std::string trueMap[] = { "1", "y", "yes", "on", "true" }; static const std::string trueMap[] = { "1", "y", "yes", "on", "true" };
static const std::string falseMap[] = { "0", "off", "n", "no", "false" }; static const std::string falseMap[] = { "0", "off", "n", "no", "false" };
std::string value = GetParameter(key, ""); std::string value = GetParameter(key, "");
for (size_t i = 0; i < sizeof(trueMap) / sizeof(trueMap[0]); i++) { for (size_t i = 0; i < sizeof(trueMap) / sizeof(trueMap[0]); i++) {
if (trueMap[i] == value) { if (trueMap[i] == value) {
return true; return true;
} }
} }
for (size_t i = 0; i < sizeof(falseMap) / sizeof(falseMap[0]); i++) { for (size_t i = 0; i < sizeof(falseMap) / sizeof(falseMap[0]); i++) {
if (falseMap[i] == value) { if (falseMap[i] == value) {
return false; return false;
} }
} }
return def; return def;
} }
int GetStringParameter(const std::string key, std::string &value, const std::string def) int GetStringParameter(const std::string key, std::string &value, const std::string def)
{ {
uint32_t size = 0; uint32_t size = 0;
int ret = SystemReadParam(key.c_str(), NULL, &size); int ret = SystemReadParam(key.c_str(), NULL, &size);
if (ret == 0) { if (ret == 0) {
std::vector<char> data(size + 1); std::vector<char> data(size + 1);
ret = SystemReadParam(key.c_str(), data.data(), &size); ret = SystemReadParam(key.c_str(), data.data(), &size);
if (ret == 0) { if (ret == 0) {
value = std::string(data.data()); value = std::string(data.data());
return EC_SUCCESS; return EC_SUCCESS;
} }
} }
if (IsValidParamValue(def.c_str(), MAX_VALUE_LEN) == 1) { if (IsValidParamValue(def.c_str(), MAX_VALUE_LEN) == 1) {
value = std::string(def); value = std::string(def);
return EC_SUCCESS; return EC_SUCCESS;
} }
return EC_FAILURE; return EC_FAILURE;
} }
template<typename T> template<typename T>
T GetIntParameter(const std::string& key, T def, T min, T max) T GetIntParameter(const std::string& key, T def, T min, T max)
{ {
if (!std::is_signed<T>::value) { if (!std::is_signed<T>::value) {
return def; return def;
} }
T result; T result;
std::string value = GetParameter(key, ""); std::string value = GetParameter(key, "");
if (!value.empty() && StringToInt(value, min, max, result)) { if (!value.empty() && StringToInt(value, min, max, result)) {
return result; return result;
} }
return def; return def;
} }
template int8_t GetIntParameter(const std::string&, int8_t, int8_t, int8_t); template int8_t GetIntParameter(const std::string&, int8_t, int8_t, int8_t);
template int16_t GetIntParameter(const std::string&, int16_t, int16_t, int16_t); template int16_t GetIntParameter(const std::string&, int16_t, int16_t, int16_t);
template int32_t GetIntParameter(const std::string&, int32_t, int32_t, int32_t); template int32_t GetIntParameter(const std::string&, int32_t, int32_t, int32_t);
template int64_t GetIntParameter(const std::string&, int64_t, int64_t, int64_t); template int64_t GetIntParameter(const std::string&, int64_t, int64_t, int64_t);
template<typename T> template<typename T>
T GetUintParameter(const std::string& key, T def, T max) T GetUintParameter(const std::string& key, T def, T max)
{ {
if (!std::is_unsigned<T>::value) { if (!std::is_unsigned<T>::value) {
return def; return def;
} }
T result; T result;
std::string value = GetParameter(key, ""); std::string value = GetParameter(key, "");
if (!value.empty() && StringToUint(value, max, result)) { if (!value.empty() && StringToUint(value, max, result)) {
return result; return result;
} }
return def; return def;
} }
template uint8_t GetUintParameter(const std::string&, uint8_t, uint8_t); template uint8_t GetUintParameter(const std::string&, uint8_t, uint8_t);
template uint16_t GetUintParameter(const std::string&, uint16_t, uint16_t); template uint16_t GetUintParameter(const std::string&, uint16_t, uint16_t);
template uint32_t GetUintParameter(const std::string&, uint32_t, uint32_t); template uint32_t GetUintParameter(const std::string&, uint32_t, uint32_t);
template uint64_t GetUintParameter(const std::string&, uint64_t, uint64_t); template uint64_t GetUintParameter(const std::string&, uint64_t, uint64_t);
std::string GetDeviceType(void) std::string GetDeviceType(void)
{ {
std::unordered_map<std::string, std::string> deviceTypeMap = { std::unordered_map<std::string, std::string> deviceTypeMap = {
{"watch", "wearable"}, {"watch", "wearable"},
{"fitnessWatch", "liteWearable"}, {"fitnessWatch", "liteWearable"},
}; };
static const char *productType = nullptr; static const char *productType = nullptr;
const char *type = GetProperty("const.build.characteristics", &productType); const char *type = GetProperty("const.build.characteristics", &productType);
if (deviceTypeMap.count(type) != 0) { if (deviceTypeMap.count(type) != 0) {
return deviceTypeMap[type]; return deviceTypeMap[type];
} }
return std::string(type); return std::string(type);
} }
int GetIntParameter(const std::string key, int def) int GetIntParameter(const std::string key, int def)
{ {
return GetIntParameter(key, def, INT_MIN, INT_MAX); return GetIntParameter(key, def, INT_MIN, INT_MAX);
} }
} // namespace system } // namespace system
} // namespace OHOS } // namespace OHOS
\ No newline at end of file
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "begetctl.h" #include "begetctl.h"
#include "param_stub.h" #include "param_stub.h"
#include "securec.h" #include "securec.h"
#include "shell.h" #include "shell.h"
using namespace std; using namespace std;
using namespace testing::ext; using namespace testing::ext;
namespace init_ut { namespace init_ut {
class BegetctlUnitTest : public testing::Test { class BegetctlUnitTest : public testing::Test {
public: public:
static void SetUpTestCase(void) static void SetUpTestCase(void)
{ {
PrepareInitUnitTestEnv(); PrepareInitUnitTestEnv();
}; };
static void TearDownTestCase(void) {}; static void TearDownTestCase(void) {};
void SetUp(void) {}; void SetUp(void) {};
void TearDown(void) {}; void TearDown(void) {};
}; };
HWTEST_F(BegetctlUnitTest, TestShellInit, TestSize.Level0) HWTEST_F(BegetctlUnitTest, TestShellInit, TestSize.Level0)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param" "param"
}; };
BShellEnvDirectExecute(GetShellHandle(), 1, (char **)args); BShellEnvDirectExecute(GetShellHandle(), 1, (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellLs, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellLs, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "ls" "param", "ls"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellLsWithR, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellLsWithR, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "ls", "-r" "param", "ls", "-r"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellLsGet, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellLsGet, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "get" "param", "get"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellSet, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellSet, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "set", "aaaaa", "1234567" "param", "set", "aaaaa", "1234567"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellGetWithKey, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellGetWithKey, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "get", "aaaaa" "param", "get", "aaaaa"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellWait, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellWait, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "wait", "aaaaa" "param", "wait", "aaaaa"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellWaitFalse, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellWaitFalse, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "wait" "param", "wait"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellWaitWithKey, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellWaitWithKey, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "wait", "aaaaa", "12*", "30" "param", "wait", "aaaaa", "12*", "30"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellParamShell, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellParamShell, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "shell" "param", "shell"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellLsWithvalue, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellLsWithvalue, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
BShellEnvSetParam(GetShellHandle(), PARAM_REVERESD_NAME_CURR_PARAMETER, "..a", PARAM_STRING, (void *)"..a"); BShellEnvSetParam(GetShellHandle(), PARAM_REVERESD_NAME_CURR_PARAMETER, "..a", PARAM_STRING, (void *)"..a");
const char *args[] = { const char *args[] = {
"param", "ls", PARAM_REVERESD_NAME_CURR_PARAMETER "param", "ls", PARAM_REVERESD_NAME_CURR_PARAMETER
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellLsWithvalueExist, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellLsWithvalueExist, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
BShellEnvSetParam(GetShellHandle(), PARAM_REVERESD_NAME_CURR_PARAMETER, "#", PARAM_STRING, (void *)"#"); BShellEnvSetParam(GetShellHandle(), PARAM_REVERESD_NAME_CURR_PARAMETER, "#", PARAM_STRING, (void *)"#");
const char *args[] = { const char *args[] = {
"param", "ls", "-r", PARAM_REVERESD_NAME_CURR_PARAMETER "param", "ls", "-r", PARAM_REVERESD_NAME_CURR_PARAMETER
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
} // namespace init_ut } // namespace init_ut
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include <cstdlib> #include <cstdlib>
#include "init_cmds.h" #include "init_cmds.h"
#include "init_group_manager.h" #include "init_group_manager.h"
#include "init_hashmap.h" #include "init_hashmap.h"
#include "init_param.h" #include "init_param.h"
#include "init_service_manager.h" #include "init_service_manager.h"
#include "init_utils.h" #include "init_utils.h"
#include "init_unittest.h" #include "init_unittest.h"
#include "le_timer.h" #include "le_timer.h"
#include "param_stub.h" #include "param_stub.h"
#include "securec.h" #include "securec.h"
using namespace testing::ext; using namespace testing::ext;
using namespace std; using namespace std;
typedef struct { typedef struct {
HashNode node; HashNode node;
char name[0]; char name[0];
} TestHashNode; } TestHashNode;
static int TestHashNodeCompare(const HashNode *node1, const HashNode *node2) static int TestHashNodeCompare(const HashNode *node1, const HashNode *node2)
{ {
TestHashNode *testNode1 = HASHMAP_ENTRY(node1, TestHashNode, node); TestHashNode *testNode1 = HASHMAP_ENTRY(node1, TestHashNode, node);
TestHashNode *testNode2 = HASHMAP_ENTRY(node2, TestHashNode, node); TestHashNode *testNode2 = HASHMAP_ENTRY(node2, TestHashNode, node);
return strcmp(testNode1->name, testNode2->name); return strcmp(testNode1->name, testNode2->name);
} }
static int TestHashKeyCompare(const HashNode *node1, const void *key) static int TestHashKeyCompare(const HashNode *node1, const void *key)
{ {
TestHashNode *testNode1 = HASHMAP_ENTRY(node1, TestHashNode, node); TestHashNode *testNode1 = HASHMAP_ENTRY(node1, TestHashNode, node);
return strcmp(testNode1->name, (char *)key); return strcmp(testNode1->name, (char *)key);
} }
static int TestHashNodeFunction(const HashNode *node) static int TestHashNodeFunction(const HashNode *node)
{ {
TestHashNode *testNode = HASHMAP_ENTRY(node, TestHashNode, node); TestHashNode *testNode = HASHMAP_ENTRY(node, TestHashNode, node);
int code = 0; int code = 0;
for (int i = 0; i < (int)strlen(testNode->name); i++) { for (int i = 0; i < (int)strlen(testNode->name); i++) {
code += testNode->name[i] - 'A'; code += testNode->name[i] - 'A';
} }
return code; return code;
} }
static int TestHashKeyFunction(const void *key) static int TestHashKeyFunction(const void *key)
{ {
int code = 0; int code = 0;
char *buff = const_cast<char *>(static_cast<const char *>(key)); char *buff = const_cast<char *>(static_cast<const char *>(key));
for (int i = 0; i < (int)strlen(buff); i++) { for (int i = 0; i < (int)strlen(buff); i++) {
code += buff[i] - 'A'; code += buff[i] - 'A';
} }
return code; return code;
} }
static void TestHashNodeFree(const HashNode *node) static void TestHashNodeFree(const HashNode *node)
{ {
TestHashNode *testNode = HASHMAP_ENTRY(node, TestHashNode, node); TestHashNode *testNode = HASHMAP_ENTRY(node, TestHashNode, node);
printf("TestHashNodeFree %s\n", testNode->name); printf("TestHashNodeFree %s\n", testNode->name);
free(testNode); free(testNode);
} }
static TestHashNode *TestCreateHashNode(const char *value) static TestHashNode *TestCreateHashNode(const char *value)
{ {
TestHashNode *node = (TestHashNode *)malloc(sizeof(TestHashNode) + strlen(value) + 1); TestHashNode *node = (TestHashNode *)malloc(sizeof(TestHashNode) + strlen(value) + 1);
if (node == nullptr) { if (node == nullptr) {
return nullptr; return nullptr;
} }
int ret = strcpy_s(node->name, strlen(value) + 1, value); int ret = strcpy_s(node->name, strlen(value) + 1, value);
if (ret != 0) { if (ret != 0) {
free(node); free(node);
return nullptr; return nullptr;
} }
HASHMAPInitNode(&node->node); HASHMAPInitNode(&node->node);
return node; return node;
} }
namespace init_ut { namespace init_ut {
class InitGroupManagerUnitTest : public testing::Test { class InitGroupManagerUnitTest : public testing::Test {
public: public:
static void SetUpTestCase(void) {}; static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {}; static void TearDownTestCase(void) {};
void SetUp(void) {}; void SetUp(void) {};
void TearDown(void) {}; void TearDown(void) {};
}; };
HashInfo g_info = { HashInfo g_info = {
TestHashNodeCompare, TestHashNodeCompare,
TestHashKeyCompare, TestHashKeyCompare,
TestHashNodeFunction, TestHashNodeFunction,
TestHashKeyFunction, TestHashKeyFunction,
TestHashNodeFree, TestHashNodeFree,
2 2
}; };
HWTEST_F(InitGroupManagerUnitTest, TestHashMap, TestSize.Level1) HWTEST_F(InitGroupManagerUnitTest, TestHashMap, TestSize.Level1)
{ {
HashMapHandle handle; HashMapHandle handle;
HashMapCreate(&handle, &g_info); HashMapCreate(&handle, &g_info);
const char *str1 = "Test hash map node 1"; const char *str1 = "Test hash map node 1";
const char *str2 = "Test hash map node 2"; const char *str2 = "Test hash map node 2";
const char *str3 = "Test hash map node 3"; const char *str3 = "Test hash map node 3";
TestHashNode *node1 = TestCreateHashNode(str1); TestHashNode *node1 = TestCreateHashNode(str1);
TestHashNode *node2 = TestCreateHashNode(str2); TestHashNode *node2 = TestCreateHashNode(str2);
HashMapAdd(handle, &node1->node); HashMapAdd(handle, &node1->node);
HashMapAdd(handle, &node2->node); HashMapAdd(handle, &node2->node);
HashNode *node = HashMapGet(handle, (const void *)str1); HashNode *node = HashMapGet(handle, (const void *)str1);
EXPECT_NE(node != nullptr, 0); EXPECT_NE(node != nullptr, 0);
if (node) { if (node) {
TestHashNode *tmp = HASHMAP_ENTRY(node, TestHashNode, node); TestHashNode *tmp = HASHMAP_ENTRY(node, TestHashNode, node);
EXPECT_EQ(strcmp(tmp->name, str1), 0); EXPECT_EQ(strcmp(tmp->name, str1), 0);
} }
node = HashMapGet(handle, (const void *)str2); node = HashMapGet(handle, (const void *)str2);
EXPECT_NE(node != nullptr, 0); EXPECT_NE(node != nullptr, 0);
if (node) { if (node) {
TestHashNode *tmp = HASHMAP_ENTRY(node, TestHashNode, node); TestHashNode *tmp = HASHMAP_ENTRY(node, TestHashNode, node);
EXPECT_EQ(strcmp(tmp->name, str2), 0); EXPECT_EQ(strcmp(tmp->name, str2), 0);
} }
TestHashNode *node3 = TestCreateHashNode(str3); TestHashNode *node3 = TestCreateHashNode(str3);
HashMapAdd(handle, &node3->node); HashMapAdd(handle, &node3->node);
node3 = TestCreateHashNode("Test hash map node 4"); node3 = TestCreateHashNode("Test hash map node 4");
HashMapAdd(handle, &node3->node); HashMapAdd(handle, &node3->node);
node3 = TestCreateHashNode("Test hash map node 5"); node3 = TestCreateHashNode("Test hash map node 5");
HashMapAdd(handle, &node3->node); HashMapAdd(handle, &node3->node);
node = HashMapGet(handle, (const void *)str3); node = HashMapGet(handle, (const void *)str3);
EXPECT_NE(node != nullptr, 0); EXPECT_NE(node != nullptr, 0);
if (node) { if (node) {
TestHashNode *tmp = HASHMAP_ENTRY(node, TestHashNode, node); TestHashNode *tmp = HASHMAP_ENTRY(node, TestHashNode, node);
EXPECT_EQ(strcmp(tmp->name, str3), 0); EXPECT_EQ(strcmp(tmp->name, str3), 0);
} }
TestHashNode *node4 = TestCreateHashNode("pre-init"); TestHashNode *node4 = TestCreateHashNode("pre-init");
HashMapAdd(handle, &node4->node); HashMapAdd(handle, &node4->node);
const char *act = "load_persist_props_action"; const char *act = "load_persist_props_action";
TestHashNode *node5 = TestCreateHashNode(act); TestHashNode *node5 = TestCreateHashNode(act);
HashMapAdd(handle, &node5->node); HashMapAdd(handle, &node5->node);
HashMapRemove(handle, "pre-init"); HashMapRemove(handle, "pre-init");
node = HashMapGet(handle, (const void *)act); node = HashMapGet(handle, (const void *)act);
EXPECT_NE(node != nullptr, 0); EXPECT_NE(node != nullptr, 0);
if (node) { if (node) {
TestHashNode *tmp = HASHMAP_ENTRY(node, TestHashNode, node); TestHashNode *tmp = HASHMAP_ENTRY(node, TestHashNode, node);
EXPECT_EQ(strcmp(tmp->name, act), 0); EXPECT_EQ(strcmp(tmp->name, act), 0);
} }
HashMapIsEmpty(handle); HashMapIsEmpty(handle);
HashMapTraverse(handle, [](const HashNode *node, const void *context) {return;}, nullptr); HashMapTraverse(handle, [](const HashNode *node, const void *context) {return;}, nullptr);
HashMapDestory(handle); HashMapDestory(handle);
} }
HWTEST_F(InitGroupManagerUnitTest, TestInitGroupMgrInit, TestSize.Level1) HWTEST_F(InitGroupManagerUnitTest, TestInitGroupMgrInit, TestSize.Level1)
{ {
InitServiceSpace(); InitServiceSpace();
InitWorkspace *workspace = GetInitWorkspace(); InitWorkspace *workspace = GetInitWorkspace();
EXPECT_EQ(workspace->groupMode, GROUP_CHARGE); EXPECT_EQ(workspace->groupMode, GROUP_CHARGE);
workspace->groupMode = GROUP_BOOT; workspace->groupMode = GROUP_BOOT;
if (strcpy_s(workspace->groupModeStr, GROUP_NAME_MAX_LENGTH, "device.boot.group") != EOK) { if (strcpy_s(workspace->groupModeStr, GROUP_NAME_MAX_LENGTH, "device.boot.group") != EOK) {
EXPECT_EQ(1, 0); EXPECT_EQ(1, 0);
} // test read cfgfile } // test read cfgfile
int ret = InitParseGroupCfg(); int ret = InitParseGroupCfg();
StartAllServices(GROUP_CHARGE); StartAllServices(GROUP_CHARGE);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
} }
HWTEST_F(InitGroupManagerUnitTest, TestAddService, TestSize.Level1) HWTEST_F(InitGroupManagerUnitTest, TestAddService, TestSize.Level1)
{ {
const char *serviceStr = "{" const char *serviceStr = "{"
"\"services\": [{" "\"services\": [{"
"\"name\" : \"test-service\"," "\"name\" : \"test-service\","
"\"path\" : [\"/dev/test_service\"]," "\"path\" : [\"/dev/test_service\"],"
"\"start-mode\" : \"condition\"," "\"start-mode\" : \"condition\","
"\"end-mode\" : \"after-exec\"," "\"end-mode\" : \"after-exec\","
"\"console\":1," "\"console\":1,"
"\"writepid\":[\"/dev/test_service\"]," "\"writepid\":[\"/dev/test_service\"],"
"\"jobs\" : {" "\"jobs\" : {"
"\"on-boot\" : \"boot:bootjob1\"," "\"on-boot\" : \"boot:bootjob1\","
"\"on-start\" : \"service:startjob\"," "\"on-start\" : \"service:startjob\","
"\"on-stop\" : \"service:stopjob\"," "\"on-stop\" : \"service:stopjob\","
"\"on-restart\" : \"service:restartjob\"" "\"on-restart\" : \"service:restartjob\""
"}" "}"
"},{" "},{"
"\"name\" : \"test-service2\"," "\"name\" : \"test-service2\","
"\"path\" : [\"/dev/test_service\"]," "\"path\" : [\"/dev/test_service\"],"
"\"console\":1," "\"console\":1,"
"\"start-mode\" : \"boot\"," "\"start-mode\" : \"boot\","
"\"writepid\":[\"/dev/test_service\"]," "\"writepid\":[\"/dev/test_service\"],"
"\"jobs\" : {" "\"jobs\" : {"
"\"on-boot\" : \"boot:bootjob1\"," "\"on-boot\" : \"boot:bootjob1\","
"\"on-start\" : \"service:startjob\"," "\"on-start\" : \"service:startjob\","
"\"on-stop\" : \"service:stopjob\"," "\"on-stop\" : \"service:stopjob\","
"\"on-restart\" : \"service:restartjob\"" "\"on-restart\" : \"service:restartjob\""
"}" "}"
"}]" "}]"
"}"; "}";
cJSON *fileRoot = cJSON_Parse(serviceStr); cJSON *fileRoot = cJSON_Parse(serviceStr);
ASSERT_NE(nullptr, fileRoot); ASSERT_NE(nullptr, fileRoot);
ParseAllServices(fileRoot); ParseAllServices(fileRoot);
cJSON_Delete(fileRoot); cJSON_Delete(fileRoot);
Service *service = GetServiceByName("test-service"); Service *service = GetServiceByName("test-service");
ServiceStartTimer(service, 1); ServiceStartTimer(service, 1);
((TimerTask *)service->timer)->base.handleEvent(LE_GetDefaultLoop(), (LoopBase *)service->timer, Event_Read); ((TimerTask *)service->timer)->base.handleEvent(LE_GetDefaultLoop(), (LoopBase *)service->timer, Event_Read);
ServiceStopTimer(service); ServiceStopTimer(service);
ASSERT_NE(service != nullptr, 0); ASSERT_NE(service != nullptr, 0);
EXPECT_EQ(service->startMode, START_MODE_CONDITION); EXPECT_EQ(service->startMode, START_MODE_CONDITION);
ReleaseService(service); ReleaseService(service);
service = GetServiceByName("test-service2"); service = GetServiceByName("test-service2");
ASSERT_NE(service != nullptr, 0); ASSERT_NE(service != nullptr, 0);
EXPECT_EQ(service->startMode, START_MODE_BOOT); EXPECT_EQ(service->startMode, START_MODE_BOOT);
ReleaseService(service); ReleaseService(service);
} }
/** /**
* @brief * @brief
* *
"socket" : [{ "socket" : [{
"name" : "ueventd", "name" : "ueventd",
"family" : "AF_INET", // AF_INET,AF_INET6,AF_UNIX(AF_LOCAL),AF_NETLINK "family" : "AF_INET", // AF_INET,AF_INET6,AF_UNIX(AF_LOCAL),AF_NETLINK
"type" : : "SOCK_STREAM", // SOCK_STREAM,SOCK_DGRAM,SOCK_RAW,SOCK_PACKET,SOCK_SEQPACKET "type" : : "SOCK_STREAM", // SOCK_STREAM,SOCK_DGRAM,SOCK_RAW,SOCK_PACKET,SOCK_SEQPACKET
"protocol" : "IPPROTO_TCP", // IPPROTO_TCP,IPPTOTO_UDP,IPPROTO_SCTP,PPROTO_TIPC "protocol" : "IPPROTO_TCP", // IPPROTO_TCP,IPPTOTO_UDP,IPPROTO_SCTP,PPROTO_TIPC
"permissions" : "0660", "permissions" : "0660",
"uid" : "system", "uid" : "system",
"gid" : "system", "gid" : "system",
"option" : { "option" : {
"passcred" : "true", "passcred" : "true",
"rcvbufforce" : "", "rcvbufforce" : "",
"cloexec" : "", "cloexec" : "",
"nonblock : "" "nonblock : ""
} }
}], }],
*/ */
HWTEST_F(InitGroupManagerUnitTest, TestAddServiceDeny, TestSize.Level1) HWTEST_F(InitGroupManagerUnitTest, TestAddServiceDeny, TestSize.Level1)
{ {
const char *serviceStr = "{" const char *serviceStr = "{"
"\"services\": [{" "\"services\": [{"
"\"name\" : \"test-service5\"," "\"name\" : \"test-service5\","
"\"path\" : [\"/dev/test_service\"]," "\"path\" : [\"/dev/test_service\"],"
"\"start-mode\" : \"by-condition\"," "\"start-mode\" : \"by-condition\","
"\"end-mode\" : \"ready\"," "\"end-mode\" : \"ready\","
"\"console\":1," "\"console\":1,"
"\"writepid\":[\"/dev/test_service\"]," "\"writepid\":[\"/dev/test_service\"],"
"\"jobs\" : {" "\"jobs\" : {"
"\"on-boot\" : \"boot:bootjob1\"," "\"on-boot\" : \"boot:bootjob1\","
"\"on-start\" : \"service:startjob\"," "\"on-start\" : \"service:startjob\","
"\"on-stop\" : \"service:stopjob\"," "\"on-stop\" : \"service:stopjob\","
"\"on-restart\" : \"service:restartjob\"" "\"on-restart\" : \"service:restartjob\""
"}" "}"
"}]" "}]"
"}"; "}";
InitWorkspace *workspace = GetInitWorkspace(); InitWorkspace *workspace = GetInitWorkspace();
workspace->groupMode = GROUP_CHARGE; workspace->groupMode = GROUP_CHARGE;
cJSON *fileRoot = cJSON_Parse(serviceStr); cJSON *fileRoot = cJSON_Parse(serviceStr);
ASSERT_NE(nullptr, fileRoot); ASSERT_NE(nullptr, fileRoot);
ParseAllServices(fileRoot); ParseAllServices(fileRoot);
cJSON_Delete(fileRoot); cJSON_Delete(fileRoot);
Service *service = GetServiceByName("test-service5"); Service *service = GetServiceByName("test-service5");
ASSERT_EQ(service, nullptr); ASSERT_EQ(service, nullptr);
workspace->groupMode = GROUP_BOOT; workspace->groupMode = GROUP_BOOT;
} }
HWTEST_F(InitGroupManagerUnitTest, TestAddService2, TestSize.Level1) HWTEST_F(InitGroupManagerUnitTest, TestAddService2, TestSize.Level1)
{ {
const char *serviceStr = "{" const char *serviceStr = "{"
"\"services\": [{" "\"services\": [{"
"\"name\" : \"test-service6\"," "\"name\" : \"test-service6\","
"\"path\" : [\"/dev/test_service\"]," "\"path\" : [\"/dev/test_service\"],"
"\"console\":1," "\"console\":1,"
"\"writepid\":[\"/dev/test_service\"]," "\"writepid\":[\"/dev/test_service\"],"
"\"jobs\" : {" "\"jobs\" : {"
"\"on-boot\" : \"boot:bootjob1\"," "\"on-boot\" : \"boot:bootjob1\","
"\"on-start\" : \"service:startjob\"," "\"on-start\" : \"service:startjob\","
"\"on-stop\" : \"service:stopjob\"," "\"on-stop\" : \"service:stopjob\","
"\"on-restart\" : \"service:restartjob\"" "\"on-restart\" : \"service:restartjob\""
"}" "}"
"}]" "}]"
"}"; "}";
InitWorkspace *workspace = GetInitWorkspace(); InitWorkspace *workspace = GetInitWorkspace();
workspace->groupMode = GROUP_CHARGE; workspace->groupMode = GROUP_CHARGE;
InitGroupNode *node = AddGroupNode(NODE_TYPE_SERVICES, "test-service6"); InitGroupNode *node = AddGroupNode(NODE_TYPE_SERVICES, "test-service6");
ASSERT_NE(nullptr, node); ASSERT_NE(nullptr, node);
cJSON *fileRoot = cJSON_Parse(serviceStr); cJSON *fileRoot = cJSON_Parse(serviceStr);
ASSERT_NE(nullptr, fileRoot); ASSERT_NE(nullptr, fileRoot);
ParseAllServices(fileRoot); ParseAllServices(fileRoot);
cJSON_Delete(fileRoot); cJSON_Delete(fileRoot);
DumpAllServices(); DumpAllServices();
Service *service = GetServiceByName("test-service6"); Service *service = GetServiceByName("test-service6");
ASSERT_NE(service, nullptr); ASSERT_NE(service, nullptr);
workspace->groupMode = GROUP_BOOT; workspace->groupMode = GROUP_BOOT;
} }
HWTEST_F(InitGroupManagerUnitTest, TestParseServiceCpucore, TestSize.Level1) HWTEST_F(InitGroupManagerUnitTest, TestParseServiceCpucore, TestSize.Level1)
{ {
const char *jsonStr = "{\"services\":{\"name\":\"test_service22\",\"path\":[\"/data/init_ut/test_service\"]," const char *jsonStr = "{\"services\":{\"name\":\"test_service22\",\"path\":[\"/data/init_ut/test_service\"],"
"\"importance\":-20,\"uid\":\"root\",\"writepid\":[\"/dev/test_service\"],\"console\":1," "\"importance\":-20,\"uid\":\"root\",\"writepid\":[\"/dev/test_service\"],\"console\":1,"
"\"gid\":[\"root\"], \"cpucore\":[5, 2, 4, 1, 2, 0, 1], \"critical\":[1]}}"; "\"gid\":[\"root\"], \"cpucore\":[5, 2, 4, 1, 2, 0, 1], \"critical\":[1]}}";
cJSON* jobItem = cJSON_Parse(jsonStr); cJSON* jobItem = cJSON_Parse(jsonStr);
ASSERT_NE(nullptr, jobItem); ASSERT_NE(nullptr, jobItem);
cJSON *serviceItem = cJSON_GetObjectItem(jobItem, "services"); cJSON *serviceItem = cJSON_GetObjectItem(jobItem, "services");
ASSERT_NE(nullptr, serviceItem); ASSERT_NE(nullptr, serviceItem);
Service *service = AddService("test_service22"); Service *service = AddService("test_service22");
const int invalidImportantValue = 20; const int invalidImportantValue = 20;
SetImportantValue(service, "", invalidImportantValue, 1); SetImportantValue(service, "", invalidImportantValue, 1);
if (service != nullptr) { if (service != nullptr) {
int ret = ParseOneService(serviceItem, service); int ret = ParseOneService(serviceItem, service);
GetAccessToken(); GetAccessToken();
DoCmdByName("timer_start ", "test_service22|5000"); DoCmdByName("timer_start ", "test_service22|5000");
DoCmdByName("timer_start ", "test_service22|aa"); DoCmdByName("timer_start ", "test_service22|aa");
DoCmdByName("timer_start ", ""); DoCmdByName("timer_start ", "");
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
StartServiceByName("test_service22|path"); StartServiceByName("test_service22|path");
ReleaseService(service); ReleaseService(service);
} }
cJSON_Delete(jobItem); cJSON_Delete(jobItem);
} }
HWTEST_F(InitGroupManagerUnitTest, TestNodeFree, TestSize.Level1) HWTEST_F(InitGroupManagerUnitTest, TestNodeFree, TestSize.Level1)
{ {
DoCmdByName("stopAllServices ", ""); DoCmdByName("stopAllServices ", "");
} }
HWTEST_F(InitGroupManagerUnitTest, TestUpdaterServiceFds, TestSize.Level1) HWTEST_F(InitGroupManagerUnitTest, TestUpdaterServiceFds, TestSize.Level1)
{ {
Service *service = AddService("test_service8"); Service *service = AddService("test_service8");
ASSERT_NE(nullptr, service); ASSERT_NE(nullptr, service);
int *fds = (int *)malloc(sizeof(int) * 1); // ServiceStop will release fds int *fds = (int *)malloc(sizeof(int) * 1); // ServiceStop will release fds
UpdaterServiceFds(nullptr, nullptr, 0); UpdaterServiceFds(nullptr, nullptr, 0);
UpdaterServiceFds(service, fds, 1); UpdaterServiceFds(service, fds, 1);
UpdaterServiceFds(service, fds, 0); UpdaterServiceFds(service, fds, 0);
UpdaterServiceFds(service, fds, 1); UpdaterServiceFds(service, fds, 1);
UpdaterServiceFds(service, nullptr, 1); UpdaterServiceFds(service, nullptr, 1);
UpdaterServiceFds(service, fds, 1); UpdaterServiceFds(service, fds, 1);
int ret = UpdaterServiceFds(service, nullptr, 2); // 2 is fd num int ret = UpdaterServiceFds(service, nullptr, 2); // 2 is fd num
ASSERT_NE(ret, 0); ASSERT_NE(ret, 0);
service->attribute = SERVICE_ATTR_TIMERSTART; service->attribute = SERVICE_ATTR_TIMERSTART;
ServiceStartTimer(service, 0); ServiceStartTimer(service, 0);
} }
HWTEST_F(InitGroupManagerUnitTest, TestProcessWatchEvent, TestSize.Level1) HWTEST_F(InitGroupManagerUnitTest, TestProcessWatchEvent, TestSize.Level1)
{ {
Service *service = AddService("test_service9"); Service *service = AddService("test_service9");
ASSERT_NE(nullptr, service); ASSERT_NE(nullptr, service);
ServiceSocket servercfg = {.next = nullptr, .sockFd = 0}; ServiceSocket servercfg = {.next = nullptr, .sockFd = 0};
service->socketCfg = &servercfg; service->socketCfg = &servercfg;
ServiceWatcher watcher; ServiceWatcher watcher;
int ret = SocketAddWatcher(&watcher, service, 0); int ret = SocketAddWatcher(&watcher, service, 0);
ASSERT_EQ(ret, 0); ASSERT_EQ(ret, 0);
uint32_t event; uint32_t event;
((WatcherTask *)watcher)->processEvent((WatcherHandle)watcher, 0, &event, service); ((WatcherTask *)watcher)->processEvent((WatcherHandle)watcher, 0, &event, service);
} }
} // namespace init_ut } // namespace init_ut
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include <sys/statvfs.h> #include <sys/statvfs.h>
#include "init_cmds.h" #include "init_cmds.h"
#include "init_reboot.h" #include "init_reboot.h"
#include "init_param.h" #include "init_param.h"
#include "param_stub.h" #include "param_stub.h"
#include "init_utils.h" #include "init_utils.h"
#include "trigger_manager.h" #include "trigger_manager.h"
#include "init_group_manager.h" #include "init_group_manager.h"
using namespace testing::ext; using namespace testing::ext;
using namespace std; using namespace std;
namespace init_ut { namespace init_ut {
class InitRebootUnitTest : public testing::Test { class InitRebootUnitTest : public testing::Test {
public: public:
static void SetUpTestCase(void) {}; static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {}; static void TearDownTestCase(void) {};
void SetUp() {}; void SetUp() {};
void TearDown() {}; void TearDown() {};
}; };
HWTEST_F(InitRebootUnitTest, TestInitReboot, TestSize.Level1) HWTEST_F(InitRebootUnitTest, TestInitReboot, TestSize.Level1)
{ {
ExecReboot("reboot"); ExecReboot("reboot");
ExecReboot("reboot,shutdown"); ExecReboot("reboot,shutdown");
ExecReboot("reboot,bootloader"); ExecReboot("reboot,bootloader");
ExecReboot("reboot,updater:123"); ExecReboot("reboot,updater:123");
ExecReboot("reboot,flash:123"); ExecReboot("reboot,flash:123");
ExecReboot("reboot,flashd:123"); ExecReboot("reboot,flashd:123");
ExecReboot("reboot,suspend:123"); ExecReboot("reboot,suspend:123");
const char *option = nullptr; const char *option = nullptr;
int ret = DoReboot(option); int ret = DoReboot(option);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
option = "updater"; option = "updater";
ret = DoReboot(option); ret = DoReboot(option);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = DoReboot(DEVICE_CMD_SUSPEND); ret = DoReboot(DEVICE_CMD_SUSPEND);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = DoReboot(DEVICE_CMD_FREEZE); ret = DoReboot(DEVICE_CMD_FREEZE);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
clearMisc(); clearMisc();
} }
} // namespace init_ut } // namespace init_ut
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <pthread.h> #include <pthread.h>
#include <sys/eventfd.h> #include <sys/eventfd.h>
#include "begetctl.h" #include "begetctl.h"
#include "init.h" #include "init.h"
#include "init_hashmap.h" #include "init_hashmap.h"
#include "init_param.h" #include "init_param.h"
#include "init_utils.h" #include "init_utils.h"
#include "le_epoll.h" #include "le_epoll.h"
#include "le_loop.h" #include "le_loop.h"
#include "le_socket.h" #include "le_socket.h"
#include "le_task.h" #include "le_task.h"
#include "loop_event.h" #include "loop_event.h"
#include "param_manager.h" #include "param_manager.h"
#include "param_message.h" #include "param_message.h"
#include "param_utils.h" #include "param_utils.h"
#include "trigger_manager.h" #include "trigger_manager.h"
using namespace testing::ext; using namespace testing::ext;
using namespace std; using namespace std;
using HashTab = struct { using HashTab = struct {
HashNodeCompare nodeCompare; HashNodeCompare nodeCompare;
HashKeyCompare keyCompare; HashKeyCompare keyCompare;
HashNodeFunction nodeHash; HashNodeFunction nodeHash;
HashKeyFunction keyHash; HashKeyFunction keyHash;
HashNodeOnFree nodeFree; HashNodeOnFree nodeFree;
int maxBucket; int maxBucket;
uint32_t tableId; uint32_t tableId;
HashNode *buckets[0]; HashNode *buckets[0];
}; };
extern "C" { extern "C" {
void OnClose(ParamTaskPtr client); void OnClose(ParamTaskPtr client);
} }
static LE_STATUS TestHandleTaskEvent(const LoopHandle loop, const TaskHandle task, uint32_t oper) static LE_STATUS TestHandleTaskEvent(const LoopHandle loop, const TaskHandle task, uint32_t oper)
{ {
return LE_SUCCESS; return LE_SUCCESS;
} }
static void OnReceiveRequest(const TaskHandle task, const uint8_t *buffer, uint32_t nread) static void OnReceiveRequest(const TaskHandle task, const uint8_t *buffer, uint32_t nread)
{ {
UNUSED(task); UNUSED(task);
UNUSED(buffer); UNUSED(buffer);
UNUSED(nread); UNUSED(nread);
} }
static void ProcessAsyncEvent(const TaskHandle taskHandle, uint64_t eventId, const uint8_t *buffer, uint32_t buffLen) static void ProcessAsyncEvent(const TaskHandle taskHandle, uint64_t eventId, const uint8_t *buffer, uint32_t buffLen)
{ {
UNUSED(taskHandle); UNUSED(taskHandle);
UNUSED(eventId); UNUSED(eventId);
UNUSED(buffer); UNUSED(buffer);
UNUSED(buffLen); UNUSED(buffLen);
} }
static int IncomingConnect(LoopHandle loop, TaskHandle server) static int IncomingConnect(LoopHandle loop, TaskHandle server)
{ {
UNUSED(loop); UNUSED(loop);
UNUSED(server); UNUSED(server);
return 0; return 0;
} }
static void ProcessWatchEventTest(WatcherHandle taskHandle, int fd, uint32_t *events, const void *context) static void ProcessWatchEventTest(WatcherHandle taskHandle, int fd, uint32_t *events, const void *context)
{ {
UNUSED(taskHandle); UNUSED(taskHandle);
UNUSED(fd); UNUSED(fd);
UNUSED(events); UNUSED(events);
UNUSED(context); UNUSED(context);
} }
static void *RunLoopThread(void *arg) static void *RunLoopThread(void *arg)
{ {
UNUSED(arg); UNUSED(arg);
StartParamService(); StartParamService();
return nullptr; return nullptr;
} }
namespace init_ut { namespace init_ut {
class LoopEventUnittest : public testing::Test { class LoopEventUnittest : public testing::Test {
public: public:
LoopEventUnittest() {}; LoopEventUnittest() {};
virtual ~LoopEventUnittest() {}; virtual ~LoopEventUnittest() {};
static void SetUpTestCase(void) {}; static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {}; static void TearDownTestCase(void) {};
void SetUp() {}; void SetUp() {};
void TearDown() {}; void TearDown() {};
void TestBody(void) {}; void TestBody(void) {};
int CreateServerTask() int CreateServerTask()
{ {
CheckTaskFlags(nullptr, Event_Write); CheckTaskFlags(nullptr, Event_Write);
ParamStreamInfo info = {}; ParamStreamInfo info = {};
info.server = const_cast<char *>(PIPE_NAME); info.server = const_cast<char *>(PIPE_NAME);
info.close = NULL; info.close = NULL;
info.recvMessage = NULL; info.recvMessage = NULL;
info.incomingConnect = OnIncomingConnect; info.incomingConnect = OnIncomingConnect;
return ParamServerCreate(&serverTask_, &info); return ParamServerCreate(&serverTask_, &info);
} }
void StreamTaskTest () void StreamTaskTest ()
{ {
LE_StreamInfo streamInfo = {}; LE_StreamInfo streamInfo = {};
streamInfo.recvMessage = OnReceiveRequest; streamInfo.recvMessage = OnReceiveRequest;
streamInfo.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_CONNECT | TASK_TEST; streamInfo.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_CONNECT | TASK_TEST;
streamInfo.server = (char *)"/data/testpipea"; streamInfo.server = (char *)"/data/testpipea";
TaskHandle clientTaskHandle = nullptr; TaskHandle clientTaskHandle = nullptr;
LE_AcceptStreamClient(LE_GetDefaultLoop(), (TaskHandle)serverTask_, &clientTaskHandle, &streamInfo); LE_AcceptStreamClient(LE_GetDefaultLoop(), (TaskHandle)serverTask_, &clientTaskHandle, &streamInfo);
if (clientTaskHandle == nullptr) { if (clientTaskHandle == nullptr) {
return; return;
} }
((StreamConnectTask *)clientTaskHandle)->stream.base.handleEvent(LE_GetDefaultLoop(), ((StreamConnectTask *)clientTaskHandle)->stream.base.handleEvent(LE_GetDefaultLoop(),
(TaskHandle)clientTaskHandle, Event_Read); (TaskHandle)clientTaskHandle, Event_Read);
((StreamConnectTask *)clientTaskHandle)->stream.base.handleEvent(LE_GetDefaultLoop(), ((StreamConnectTask *)clientTaskHandle)->stream.base.handleEvent(LE_GetDefaultLoop(),
(TaskHandle)clientTaskHandle, Event_Write); (TaskHandle)clientTaskHandle, Event_Write);
((StreamConnectTask *)clientTaskHandle)->stream.base.handleEvent(LE_GetDefaultLoop(), ((StreamConnectTask *)clientTaskHandle)->stream.base.handleEvent(LE_GetDefaultLoop(),
(TaskHandle)clientTaskHandle, 0); (TaskHandle)clientTaskHandle, 0);
streamInfo.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_SERVER; streamInfo.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_SERVER;
streamInfo.server = (char *)"/data/testpipeb"; streamInfo.server = (char *)"/data/testpipeb";
TaskHandle clientTaskHandleb = nullptr; TaskHandle clientTaskHandleb = nullptr;
LE_CreateStreamClient(LE_GetDefaultLoop(), &clientTaskHandleb, &streamInfo); LE_CreateStreamClient(LE_GetDefaultLoop(), &clientTaskHandleb, &streamInfo);
if (clientTaskHandleb == nullptr) { if (clientTaskHandleb == nullptr) {
return; return;
} }
((StreamClientTask *)clientTaskHandleb)->stream.base.handleEvent(LE_GetDefaultLoop(), ((StreamClientTask *)clientTaskHandleb)->stream.base.handleEvent(LE_GetDefaultLoop(),
clientTaskHandleb, Event_Read); clientTaskHandleb, Event_Read);
((StreamClientTask *)clientTaskHandleb)->stream.base.handleEvent(LE_GetDefaultLoop(), ((StreamClientTask *)clientTaskHandleb)->stream.base.handleEvent(LE_GetDefaultLoop(),
clientTaskHandleb, Event_Write); clientTaskHandleb, Event_Write);
((StreamClientTask *)clientTaskHandleb)->stream.base.innerClose(LE_GetDefaultLoop(), clientTaskHandleb); ((StreamClientTask *)clientTaskHandleb)->stream.base.innerClose(LE_GetDefaultLoop(), clientTaskHandleb);
TaskHandle clientTaskHandlec = nullptr; TaskHandle clientTaskHandlec = nullptr;
streamInfo.baseInfo.flags = TASK_STREAM | TASK_TCP | TASK_SERVER; streamInfo.baseInfo.flags = TASK_STREAM | TASK_TCP | TASK_SERVER;
streamInfo.server = (char *)"0.0.0.0:10110"; streamInfo.server = (char *)"0.0.0.0:10110";
LE_CreateStreamClient(LE_GetDefaultLoop(), &clientTaskHandlec, &streamInfo); LE_CreateStreamClient(LE_GetDefaultLoop(), &clientTaskHandlec, &streamInfo);
if (clientTaskHandlec == nullptr) { if (clientTaskHandlec == nullptr) {
return; return;
} }
TaskHandle clientTaskHandled = nullptr; TaskHandle clientTaskHandled = nullptr;
streamInfo.baseInfo.flags = TASK_STREAM | TASK_TCP | TASK_CONNECT; streamInfo.baseInfo.flags = TASK_STREAM | TASK_TCP | TASK_CONNECT;
streamInfo.server = (char *)"127.0.0.1:10111"; streamInfo.server = (char *)"127.0.0.1:10111";
LE_CreateStreamClient(LE_GetDefaultLoop(), &clientTaskHandled, &streamInfo); LE_CreateStreamClient(LE_GetDefaultLoop(), &clientTaskHandled, &streamInfo);
if (clientTaskHandled == nullptr) { if (clientTaskHandled == nullptr) {
return; return;
} }
} }
void LeTaskTest() void LeTaskTest()
{ {
LE_StreamServerInfo info = {}; LE_StreamServerInfo info = {};
info.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_SERVER | TASK_TEST; info.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_SERVER | TASK_TEST;
info.server = (char *)"/data/testpipe"; info.server = (char *)"/data/testpipe";
info.baseInfo.close = OnClose; info.baseInfo.close = OnClose;
info.incommingConntect = IncomingConnect; info.incommingConntect = IncomingConnect;
LE_CreateStreamServer(LE_GetDefaultLoop(), &serverTask_, &info); LE_CreateStreamServer(LE_GetDefaultLoop(), &serverTask_, &info);
if (serverTask_ == nullptr) { if (serverTask_ == nullptr) {
return; return;
} }
((StreamServerTask *)serverTask_)->base.handleEvent(LE_GetDefaultLoop(), serverTask_, Event_Read); ((StreamServerTask *)serverTask_)->base.handleEvent(LE_GetDefaultLoop(), serverTask_, Event_Read);
uint64_t eventId = 0; uint64_t eventId = 0;
ParamStreamInfo paramStreamInfo = {}; ParamStreamInfo paramStreamInfo = {};
paramStreamInfo.flags = PARAM_TEST_FLAGS; paramStreamInfo.flags = PARAM_TEST_FLAGS;
paramStreamInfo.server = NULL; paramStreamInfo.server = NULL;
paramStreamInfo.close = OnClose; paramStreamInfo.close = OnClose;
paramStreamInfo.recvMessage = ProcessMessage; paramStreamInfo.recvMessage = ProcessMessage;
paramStreamInfo.incomingConnect = NULL; paramStreamInfo.incomingConnect = NULL;
ParamTaskPtr client = NULL; ParamTaskPtr client = NULL;
int ret = ParamStreamCreate(&client, serverTask_, &paramStreamInfo, sizeof(ParamWatcher)); int ret = ParamStreamCreate(&client, serverTask_, &paramStreamInfo, sizeof(ParamWatcher));
PARAM_CHECK(ret == 0, return, "Failed to create client"); PARAM_CHECK(ret == 0, return, "Failed to create client");
BufferHandle handle = LE_CreateBuffer(LE_GetDefaultLoop(), 1 + sizeof(eventId)); BufferHandle handle = LE_CreateBuffer(LE_GetDefaultLoop(), 1 + sizeof(eventId));
LE_Buffer *buffer = (LE_Buffer *)handle; LE_Buffer *buffer = (LE_Buffer *)handle;
AddBuffer((StreamTask *)client, buffer); AddBuffer((StreamTask *)client, buffer);
((StreamConnectTask *)client)->stream.base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)(client), Event_Write); ((StreamConnectTask *)client)->stream.base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)(client), Event_Write);
ParamMessage *request = (ParamMessage *)CreateParamMessage(MSG_SET_PARAM, "name", sizeof(ParamMessage)); ParamMessage *request = (ParamMessage *)CreateParamMessage(MSG_SET_PARAM, "name", sizeof(ParamMessage));
((StreamConnectTask *)client)->recvMessage(LE_GetDefaultLoop(), reinterpret_cast<uint8_t *>(request), ((StreamConnectTask *)client)->recvMessage(LE_GetDefaultLoop(), reinterpret_cast<uint8_t *>(request),
sizeof(ParamMessage)); sizeof(ParamMessage));
LE_Buffer *next = nullptr; LE_Buffer *next = nullptr;
EXPECT_EQ(GetNextBuffer((StreamTask *)client, next), nullptr); EXPECT_EQ(GetNextBuffer((StreamTask *)client, next), nullptr);
ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client); ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client);
PARAM_CHECK(watcher != nullptr, return, "Failed to get watcher"); PARAM_CHECK(watcher != nullptr, return, "Failed to get watcher");
ListInit(&watcher->triggerHead); ListInit(&watcher->triggerHead);
OnClose(client); OnClose(client);
LE_FreeBuffer(LE_GetDefaultLoop(), (TaskHandle)client, nullptr); LE_FreeBuffer(LE_GetDefaultLoop(), (TaskHandle)client, nullptr);
return; return;
} }
void ProcessEventTest() void ProcessEventTest()
{ {
ProcessEvent((EventLoop *)LE_GetDefaultLoop(), 1, Event_Read); ProcessEvent((EventLoop *)LE_GetDefaultLoop(), 1, Event_Read);
LE_BaseInfo info = {TASK_EVENT, NULL}; LE_BaseInfo info = {TASK_EVENT, NULL};
int testfd = 65535; // 65535 is not exist fd int testfd = 65535; // 65535 is not exist fd
BaseTask *task = CreateTask(LE_GetDefaultLoop(), testfd, &info, sizeof(StreamClientTask)); BaseTask *task = CreateTask(LE_GetDefaultLoop(), testfd, &info, sizeof(StreamClientTask));
task->handleEvent = TestHandleTaskEvent; task->handleEvent = TestHandleTaskEvent;
if (task != nullptr) { if (task != nullptr) {
ProcessEvent((EventLoop *)LE_GetDefaultLoop(), testfd, Event_Read); 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() void ProcessasynEvent()
{ {
TaskHandle asynHandle = nullptr; TaskHandle asynHandle = nullptr;
LE_CreateAsyncTask(LE_GetDefaultLoop(), &asynHandle, ProcessAsyncEvent); LE_CreateAsyncTask(LE_GetDefaultLoop(), &asynHandle, ProcessAsyncEvent);
if (asynHandle == nullptr) { if (asynHandle == nullptr) {
return; return;
} }
((AsyncEventTask *)asynHandle)->stream.base.handleEvent(LE_GetDefaultLoop(), asynHandle, Event_Read); ((AsyncEventTask *)asynHandle)->stream.base.handleEvent(LE_GetDefaultLoop(), asynHandle, Event_Read);
((AsyncEventTask *)asynHandle)->stream.base.handleEvent(LE_GetDefaultLoop(), asynHandle, Event_Write); ((AsyncEventTask *)asynHandle)->stream.base.handleEvent(LE_GetDefaultLoop(), asynHandle, Event_Write);
LE_StopAsyncTask(LE_GetDefaultLoop(), asynHandle); LE_StopAsyncTask(LE_GetDefaultLoop(), asynHandle);
} }
void ProcessWatcherTask() void ProcessWatcherTask()
{ {
WatcherHandle handle = nullptr; WatcherHandle handle = nullptr;
LE_WatchInfo info = {}; LE_WatchInfo info = {};
info.fd = -1; info.fd = -1;
info.flags = WATCHER_ONCE; info.flags = WATCHER_ONCE;
info.events = Event_Read; info.events = Event_Read;
info.processEvent = ProcessWatchEventTest; info.processEvent = ProcessWatchEventTest;
LE_StartWatcher(LE_GetDefaultLoop(), &handle, &info, nullptr); LE_StartWatcher(LE_GetDefaultLoop(), &handle, &info, nullptr);
if (handle == nullptr) { if (handle == nullptr) {
return; return;
} }
((WatcherTask *)handle)->base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)handle, Event_Read); ((WatcherTask *)handle)->base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)handle, Event_Read);
((WatcherTask *)handle)->base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)handle, 0); ((WatcherTask *)handle)->base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)handle, 0);
((WatcherTask *)handle)->base.flags = WATCHER_ONCE; ((WatcherTask *)handle)->base.flags = WATCHER_ONCE;
((WatcherTask *)handle)->base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)handle, Event_Read); ((WatcherTask *)handle)->base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)handle, Event_Read);
} }
void CreateSocketTest() void CreateSocketTest()
{ {
ParamTaskPtr serverTask = nullptr; ParamTaskPtr serverTask = nullptr;
LE_StreamServerInfo info = {}; LE_StreamServerInfo info = {};
info.baseInfo.flags = TASK_PIPE | TASK_CONNECT | TASK_TEST; info.baseInfo.flags = TASK_PIPE | TASK_CONNECT | TASK_TEST;
info.server = (char *)"/data/testpipe"; info.server = (char *)"/data/testpipe";
info.baseInfo.close = OnClose; info.baseInfo.close = OnClose;
info.incommingConntect = IncomingConnect; info.incommingConntect = IncomingConnect;
info.socketId = 1111; // 1111 is test fd info.socketId = 1111; // 1111 is test fd
LE_CreateStreamServer(LE_GetDefaultLoop(), &serverTask, &info); LE_CreateStreamServer(LE_GetDefaultLoop(), &serverTask, &info);
EXPECT_NE(serverTask, nullptr); EXPECT_NE(serverTask, nullptr);
if (serverTask == nullptr) { if (serverTask == nullptr) {
return; return;
} }
((StreamServerTask *)serverTask)->base.taskId.fd = -1; ((StreamServerTask *)serverTask)->base.taskId.fd = -1;
OnIncomingConnect(LE_GetDefaultLoop(), serverTask); OnIncomingConnect(LE_GetDefaultLoop(), serverTask);
LE_GetSocketFd(serverTask); LE_GetSocketFd(serverTask);
AcceptSocket(-1, TASK_PIPE); AcceptSocket(-1, TASK_PIPE);
AcceptSocket(-1, TASK_TCP); AcceptSocket(-1, TASK_TCP);
AcceptSocket(-1, TASK_TEST); AcceptSocket(-1, TASK_TEST);
} }
private: private:
ParamTaskPtr serverTask_ = NULL; ParamTaskPtr serverTask_ = NULL;
}; };
HWTEST_F(LoopEventUnittest, StreamTaskTest, TestSize.Level1) HWTEST_F(LoopEventUnittest, StreamTaskTest, TestSize.Level1)
{ {
LoopEventUnittest loopevtest = LoopEventUnittest(); LoopEventUnittest loopevtest = LoopEventUnittest();
loopevtest.CreateServerTask(); loopevtest.CreateServerTask();
loopevtest.StreamTaskTest(); loopevtest.StreamTaskTest();
LE_StreamInfo streamInfo = {}; LE_StreamInfo streamInfo = {};
streamInfo.recvMessage = OnReceiveRequest; streamInfo.recvMessage = OnReceiveRequest;
streamInfo.baseInfo.flags = TASK_PIPE | TASK_CONNECT; streamInfo.baseInfo.flags = TASK_PIPE | TASK_CONNECT;
streamInfo.server = (char *)PIPE_NAME; streamInfo.server = (char *)PIPE_NAME;
TaskHandle clientTaskHandlec = nullptr; TaskHandle clientTaskHandlec = nullptr;
LE_CreateStreamClient(LE_GetDefaultLoop(), &clientTaskHandlec, &streamInfo); LE_CreateStreamClient(LE_GetDefaultLoop(), &clientTaskHandlec, &streamInfo);
EXPECT_NE(clientTaskHandlec, nullptr); EXPECT_NE(clientTaskHandlec, nullptr);
} }
HWTEST_F(LoopEventUnittest, LeTaskTest, TestSize.Level1) HWTEST_F(LoopEventUnittest, LeTaskTest, TestSize.Level1)
{ {
LoopEventUnittest loopevtest = LoopEventUnittest(); LoopEventUnittest loopevtest = LoopEventUnittest();
loopevtest.LeTaskTest(); loopevtest.LeTaskTest();
} }
HWTEST_F(LoopEventUnittest, runServerTest, TestSize.Level1) HWTEST_F(LoopEventUnittest, runServerTest, TestSize.Level1)
{ {
LoopEventUnittest loopevtest = LoopEventUnittest(); LoopEventUnittest loopevtest = LoopEventUnittest();
loopevtest.ProcessEventTest(); loopevtest.ProcessEventTest();
} }
HWTEST_F(LoopEventUnittest, ProcessasynEvent, TestSize.Level1) HWTEST_F(LoopEventUnittest, ProcessasynEvent, TestSize.Level1)
{ {
LoopEventUnittest loopevtest = LoopEventUnittest(); LoopEventUnittest loopevtest = LoopEventUnittest();
loopevtest.ProcessasynEvent(); loopevtest.ProcessasynEvent();
} }
HWTEST_F(LoopEventUnittest, CreateSocketTest, TestSize.Level1) HWTEST_F(LoopEventUnittest, CreateSocketTest, TestSize.Level1)
{ {
LoopEventUnittest loopevtest = LoopEventUnittest(); LoopEventUnittest loopevtest = LoopEventUnittest();
loopevtest.CreateSocketTest(); loopevtest.CreateSocketTest();
} }
HWTEST_F(LoopEventUnittest, ProcessWatcherTask, TestSize.Level1) HWTEST_F(LoopEventUnittest, ProcessWatcherTask, TestSize.Level1)
{ {
LoopEventUnittest loopevtest = LoopEventUnittest(); LoopEventUnittest loopevtest = LoopEventUnittest();
loopevtest.ProcessWatcherTask(); loopevtest.ProcessWatcherTask();
} }
HWTEST_F(LoopEventUnittest, RunLoopThread, TestSize.Level1) HWTEST_F(LoopEventUnittest, RunLoopThread, TestSize.Level1)
{ {
InitParamService(); InitParamService();
pthread_t tid = 0; pthread_t tid = 0;
int fd = eventfd(1, EFD_NONBLOCK | EFD_CLOEXEC); int fd = eventfd(1, EFD_NONBLOCK | EFD_CLOEXEC);
struct epoll_event event = {}; struct epoll_event event = {};
event.events = EPOLLIN; event.events = EPOLLIN;
if (fd >= 0) { if (fd >= 0) {
epoll_ctl(((EventEpoll *)LE_GetDefaultLoop())->epollFd, EPOLL_CTL_ADD, fd, &event); epoll_ctl(((EventEpoll *)LE_GetDefaultLoop())->epollFd, EPOLL_CTL_ADD, fd, &event);
} }
pthread_create(&tid, nullptr, RunLoopThread, nullptr); pthread_create(&tid, nullptr, RunLoopThread, nullptr);
event.events = EPOLLOUT; event.events = EPOLLOUT;
epoll_ctl(((EventEpoll *)LE_GetDefaultLoop())->epollFd, EPOLL_CTL_ADD, fd, &event); epoll_ctl(((EventEpoll *)LE_GetDefaultLoop())->epollFd, EPOLL_CTL_ADD, fd, &event);
HashMapHandle taskMap = ((EventLoop *)LE_GetDefaultLoop())->taskMap; HashMapHandle taskMap = ((EventLoop *)LE_GetDefaultLoop())->taskMap;
((EventLoop *)LE_GetDefaultLoop())->taskMap = nullptr; ((EventLoop *)LE_GetDefaultLoop())->taskMap = nullptr;
StopParamService(); StopParamService();
pthread_join(tid, nullptr); pthread_join(tid, nullptr);
InitParamService(); InitParamService();
((EventLoop *)LE_GetDefaultLoop())->taskMap = taskMap; ((EventLoop *)LE_GetDefaultLoop())->taskMap = taskMap;
} }
} // namespace init_ut } // namespace init_ut
/* /*
* Copyright (c) 2022 Huawei Device Co., Ltd. * Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include <cerrno> #include <cerrno>
#include <unistd.h> #include <unistd.h>
#include <sys/stat.h> #include <sys/stat.h>
#include "init_unittest.h" #include "init_unittest.h"
#include "cJSON.h" #include "cJSON.h"
#include "sandbox.h" #include "sandbox.h"
#include "sandbox_namespace.h" #include "sandbox_namespace.h"
#include "securec.h" #include "securec.h"
using namespace testing::ext; using namespace testing::ext;
namespace init_ut { namespace init_ut {
const int NULL_ROOT_PATH = 1; const int NULL_ROOT_PATH = 1;
const int NULL_MOUNT_FLAGS = 2; const int NULL_MOUNT_FLAGS = 2;
const int NULL_MOUNT = 3; const int NULL_MOUNT = 3;
const int NULL_MOUNT_ITEM = 13; const int NULL_MOUNT_ITEM = 13;
const int LINK_ARRARY_START = 5; const int LINK_ARRARY_START = 5;
const int LINK_ARRARY_END = 8; const int LINK_ARRARY_END = 8;
const int FLAGS_NUMBER = 3; const int FLAGS_NUMBER = 3;
const char *TEST_SANDBOX_NAME = "test"; const char *TEST_SANDBOX_NAME = "test";
const char *SANDBOX_JSON_NAME = "test-sandbox.json"; const char *SANDBOX_JSON_NAME = "test-sandbox.json";
const char *SANDBOX_CONFIG[] = {"sandbox-root", "mount-bind-paths", "mount-bind-files", "symbol-links"}; const char *SANDBOX_CONFIG[] = {"sandbox-root", "mount-bind-paths", "mount-bind-files", "symbol-links"};
const char *SANDBOX_ROOT[] = { "/mnt/sandbox/test", "/mnt/sandbox/chipset", "/mnt/error"}; const char *SANDBOX_ROOT[] = { "/mnt/sandbox/test", "/mnt/sandbox/chipset", "/mnt/error"};
const char *SANDBOX_FLAGS[] = {"bind", "rec", "private"}; const char *SANDBOX_FLAGS[] = {"bind", "rec", "private"};
const char *MOUNT_BIND_PATHS[] = {"src-path", "sandbox-path", "sandbox-flags"}; const char *MOUNT_BIND_PATHS[] = {"src-path", "sandbox-path", "sandbox-flags"};
const char *SYMBOL_LINKS[] = {"target-name", "link-name"}; const char *SYMBOL_LINKS[] = {"target-name", "link-name"};
const char *APP_PATHS[] = {"/mnt", "/sys", "/proc", "/dev", "/data", const char *APP_PATHS[] = {"/mnt", "/sys", "/proc", "/dev", "/data",
"/system/bin", "/system/lib", "/system/etc", "/system"}; "/system/bin", "/system/lib", "/system/etc", "/system"};
int RestartSandbox(const char *sandbox) int RestartSandbox(const char *sandbox)
{ {
if (sandbox == nullptr) { if (sandbox == nullptr) {
std::cout << "invalid parameters" << std::endl; std::cout << "invalid parameters" << std::endl;
return 0; return 0;
} }
InitDefaultNamespace(); InitDefaultNamespace();
std::cout << "init namespace" << std::endl; std::cout << "init namespace" << std::endl;
if (!InitSandboxWithName(sandbox)) { if (!InitSandboxWithName(sandbox)) {
CloseDefaultNamespace(); CloseDefaultNamespace();
std::cout << "Failed to init sandbox with name " << sandbox << std::endl; std::cout << "Failed to init sandbox with name " << sandbox << std::endl;
return 0; return 0;
} }
std::cout << "init sandbox with name" << std::endl; std::cout << "init sandbox with name" << std::endl;
DumpSandboxByName(sandbox); DumpSandboxByName(sandbox);
std::cout << "dump sandbox" << std::endl; std::cout << "dump sandbox" << std::endl;
if (PrepareSandbox(sandbox) != 0) { if (PrepareSandbox(sandbox) != 0) {
std::cout << "Failed to prepare sandbox %s" << sandbox << std::endl; std::cout << "Failed to prepare sandbox %s" << sandbox << std::endl;
DestroySandbox(sandbox); DestroySandbox(sandbox);
CloseDefaultNamespace(); CloseDefaultNamespace();
return 0; return 0;
} }
std::cout << "prepare sandbox" << std::endl; std::cout << "prepare sandbox" << std::endl;
if (EnterDefaultNamespace() < 0) { if (EnterDefaultNamespace() < 0) {
std::cout << "Failed to set default namespace" << std::endl; std::cout << "Failed to set default namespace" << std::endl;
DestroySandbox(sandbox); DestroySandbox(sandbox);
CloseDefaultNamespace(); CloseDefaultNamespace();
return 0; return 0;
} }
std::cout << "enter default namespace" << std::endl; std::cout << "enter default namespace" << std::endl;
CloseDefaultNamespace(); CloseDefaultNamespace();
std::cout << "close namespace" << std::endl; std::cout << "close namespace" << std::endl;
return 1; return 1;
} }
cJSON *MakeSandboxJson(const char *sandboxFileName, const int MODE) cJSON *MakeSandboxJson(const char *sandboxFileName, const int MODE)
{ {
cJSON *mJsonSandbox = cJSON_CreateObject(); // json file object cJSON *mJsonSandbox = cJSON_CreateObject(); // json file object
cJSON *mJsonMtBdPth = cJSON_CreateArray(); // mount-bind-paths cJSON *mJsonMtBdPth = cJSON_CreateArray(); // mount-bind-paths
cJSON *mJsonMtBdFl = cJSON_CreateArray(); // mount-bind-files cJSON *mJsonMtBdFl = cJSON_CreateArray(); // mount-bind-files
cJSON *mJsonSymLk = cJSON_CreateArray(); // symbol-links cJSON *mJsonSymLk = cJSON_CreateArray(); // symbol-links
cJSON *mJsonMtBdPthItmSdxFlg = cJSON_CreateArray(); // mount-bind-paths items sandbox-flags cJSON *mJsonMtBdPthItmSdxFlg = cJSON_CreateArray(); // mount-bind-paths items sandbox-flags
cJSON *mJsonMtBdFlItm = cJSON_CreateObject(); // mount-bind-files items cJSON *mJsonMtBdFlItm = cJSON_CreateObject(); // mount-bind-files items
if (mJsonSandbox == nullptr || mJsonMtBdPth == nullptr || mJsonMtBdFl == nullptr || if (mJsonSandbox == nullptr || mJsonMtBdPth == nullptr || mJsonMtBdFl == nullptr ||
mJsonSymLk == nullptr || mJsonMtBdPthItmSdxFlg == nullptr || mJsonMtBdFlItm == nullptr) { mJsonSymLk == nullptr || mJsonMtBdPthItmSdxFlg == nullptr || mJsonMtBdFlItm == nullptr) {
std::cout << "create json object error" << std::endl; std::cout << "create json object error" << std::endl;
return nullptr; return nullptr;
} }
cJSON *mJsonMtBdPth_Itm; // point to mount-bind-paths items cJSON *mJsonMtBdPth_Itm; // point to mount-bind-paths items
cJSON *mJsonSymLk_Itm; // point to symbol-links items cJSON *mJsonSymLk_Itm; // point to symbol-links items
// drop root path // drop root path
if (MODE != NULL_ROOT_PATH) { if (MODE != NULL_ROOT_PATH) {
cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[0], cJSON_CreateString(SANDBOX_ROOT[0])); cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[0], cJSON_CreateString(SANDBOX_ROOT[0]));
} }
// assemble SANDBOX_FLAGS // assemble SANDBOX_FLAGS
if (MODE != NULL_MOUNT_FLAGS) { if (MODE != NULL_MOUNT_FLAGS) {
for (int i = 0; i < FLAGS_NUMBER; i++) { for (int i = 0; i < FLAGS_NUMBER; i++) {
cJSON_AddItemToArray(mJsonMtBdPthItmSdxFlg, cJSON_CreateString(SANDBOX_FLAGS[i])); cJSON_AddItemToArray(mJsonMtBdPthItmSdxFlg, cJSON_CreateString(SANDBOX_FLAGS[i]));
} }
} }
// assemble mount-bind-paths items // assemble mount-bind-paths items
// Append items to mount-bind-paths // Append items to mount-bind-paths
for (int i = 0; i < (sizeof(APP_PATHS) / sizeof(char *)); i++) { for (int i = 0; i < (sizeof(APP_PATHS) / sizeof(char *)); i++) {
cJSON_AddItemToArray(mJsonMtBdPth, mJsonMtBdPth_Itm = cJSON_CreateObject()); cJSON_AddItemToArray(mJsonMtBdPth, mJsonMtBdPth_Itm = cJSON_CreateObject());
int MOUNT_FLAG_COUNT = 2; int MOUNT_FLAG_COUNT = 2;
if (MODE != NULL_MOUNT_ITEM) { if (MODE != NULL_MOUNT_ITEM) {
cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[0], cJSON_CreateString(APP_PATHS[i])); cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[0], cJSON_CreateString(APP_PATHS[i]));
cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[1], cJSON_CreateString(APP_PATHS[i])); cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[1], cJSON_CreateString(APP_PATHS[i]));
} else { } else {
cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[0], nullptr); cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[0], nullptr);
cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[1], nullptr); cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[1], nullptr);
} }
cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[MOUNT_FLAG_COUNT], mJsonMtBdPthItmSdxFlg); cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[MOUNT_FLAG_COUNT], mJsonMtBdPthItmSdxFlg);
} }
if (MODE != NULL_MOUNT) { if (MODE != NULL_MOUNT) {
cJSON_AddItemToObject(mJsonMtBdFlItm, SANDBOX_CONFIG[1], cJSON_CreateString("/data/init_ut/testsandboxfile")); cJSON_AddItemToObject(mJsonMtBdFlItm, SANDBOX_CONFIG[1], cJSON_CreateString("/data/init_ut/testsandboxfile"));
// Append items to mount-bind-files // Append items to mount-bind-files
cJSON_AddItemToArray(mJsonMtBdFl, mJsonMtBdFlItm); cJSON_AddItemToArray(mJsonMtBdFl, mJsonMtBdFlItm);
// assemble symbol-links items // assemble symbol-links items
for (int i = LINK_ARRARY_START; i < LINK_ARRARY_END; i++) { for (int i = LINK_ARRARY_START; i < LINK_ARRARY_END; i++) {
// Append items to symbol-links // Append items to symbol-links
cJSON_AddItemToArray(mJsonSymLk, mJsonSymLk_Itm = cJSON_CreateObject()); cJSON_AddItemToArray(mJsonSymLk, mJsonSymLk_Itm = cJSON_CreateObject());
cJSON_AddItemToObject(mJsonSymLk_Itm, SYMBOL_LINKS[0], cJSON_CreateString(APP_PATHS[i])); cJSON_AddItemToObject(mJsonSymLk_Itm, SYMBOL_LINKS[0], cJSON_CreateString(APP_PATHS[i]));
cJSON_AddItemToObject(mJsonSymLk_Itm, SYMBOL_LINKS[1], cJSON_CreateString(APP_PATHS[i])); cJSON_AddItemToObject(mJsonSymLk_Itm, SYMBOL_LINKS[1], cJSON_CreateString(APP_PATHS[i]));
} }
} }
// at last, assemble the json file // at last, assemble the json file
int count = 1; int count = 1;
cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[count++], mJsonMtBdPth); cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[count++], mJsonMtBdPth);
cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[count++], mJsonMtBdFl); cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[count++], mJsonMtBdFl);
cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[count], mJsonSymLk); cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[count], mJsonSymLk);
return mJsonSandbox; return mJsonSandbox;
} }
bool MakeFileByJson(cJSON * mJson, const char *sandboxFileName) bool MakeFileByJson(cJSON * mJson, const char *sandboxFileName)
{ {
const std::string sandboxJsonPth = std::string("/data/init_ut/") + std::string(sandboxFileName); const std::string sandboxJsonPth = std::string("/data/init_ut/") + std::string(sandboxFileName);
const char* cSandboxJsonPth = sandboxJsonPth.c_str(); const char* cSandboxJsonPth = sandboxJsonPth.c_str();
int fd = open(cSandboxJsonPth, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); int fd = open(cSandboxJsonPth, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd < 0) { if (fd < 0) {
std::cout << "open sandbox json file failed" << std::endl; std::cout << "open sandbox json file failed" << std::endl;
return false; return false;
} }
char *cjValue1 = cJSON_Print(mJson); char *cjValue1 = cJSON_Print(mJson);
int ret1 = write(fd, cjValue1, strlen(cjValue1)); int ret1 = write(fd, cjValue1, strlen(cjValue1));
if (-1 == ret1) { if (-1 == ret1) {
std::cout << "Write file ERROR" << errno << " fd is :" << fd << std::endl; std::cout << "Write file ERROR" << errno << " fd is :" << fd << std::endl;
return false; return false;
} }
free(cjValue1); free(cjValue1);
close(fd); close(fd);
return true; return true;
} }
class SandboxUnitTest : public testing::Test { class SandboxUnitTest : public testing::Test {
public: public:
static void SetUpTestCase(void) {} static void SetUpTestCase(void) {}
static void TearDownTestCase(void) {} static void TearDownTestCase(void) {}
void SetUp() {}; void SetUp() {};
void TearDown() {}; void TearDown() {};
}; };
HWTEST_F(SandboxUnitTest, TestCreateNormalSandbox, TestSize.Level1) { HWTEST_F(SandboxUnitTest, TestCreateNormalSandbox, TestSize.Level1) {
cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, 0); cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, 0);
if (mJson == nullptr) { if (mJson == nullptr) {
std::cout << "created mJson error, mJson is null." << std::endl; std::cout << "created mJson error, mJson is null." << std::endl;
return; return;
} }
MakeFileByJson(mJson, SANDBOX_JSON_NAME); MakeFileByJson(mJson, SANDBOX_JSON_NAME);
int ret = RestartSandbox(TEST_SANDBOX_NAME); int ret = RestartSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, 1); ASSERT_EQ(ret, 1);
} }
HWTEST_F(SandboxUnitTest, TestEnterErrorSandbox, TestSize.Level1) { HWTEST_F(SandboxUnitTest, TestEnterErrorSandbox, TestSize.Level1) {
int ret1 = EnterSandbox("error_system"); int ret1 = EnterSandbox("error_system");
ASSERT_EQ(ret1, -1); ASSERT_EQ(ret1, -1);
const char *pname = nullptr; const char *pname = nullptr;
int ret2 = EnterSandbox(pname); int ret2 = EnterSandbox(pname);
ASSERT_EQ(ret2, -1); ASSERT_EQ(ret2, -1);
DestroySandbox(TEST_SANDBOX_NAME); DestroySandbox(TEST_SANDBOX_NAME);
int ret3 = EnterSandbox(TEST_SANDBOX_NAME); int ret3 = EnterSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret3, -1); ASSERT_EQ(ret3, -1);
} }
HWTEST_F(SandboxUnitTest, TestCreateErrorSandbox1, TestSize.Level1) { HWTEST_F(SandboxUnitTest, TestCreateErrorSandbox1, TestSize.Level1) {
const char *pname = nullptr; const char *pname = nullptr;
std::cout << "test destroy nullptr" << std::endl; std::cout << "test destroy nullptr" << std::endl;
DestroySandbox(pname); DestroySandbox(pname);
std::cout << "test destroy xapp" << std::endl; std::cout << "test destroy xapp" << std::endl;
DestroySandbox("xapp"); DestroySandbox("xapp");
std::cout << "test enter xapp" << std::endl; std::cout << "test enter xapp" << std::endl;
int ret1 = EnterSandbox("xapp"); int ret1 = EnterSandbox("xapp");
ASSERT_EQ(ret1, -1); ASSERT_EQ(ret1, -1);
bool result = InitSandboxWithName(pname); bool result = InitSandboxWithName(pname);
ASSERT_FALSE(result); ASSERT_FALSE(result);
DumpSandboxByName(pname); DumpSandboxByName(pname);
DumpSandboxByName("xpp"); DumpSandboxByName("xpp");
result = InitSandboxWithName("xapp"); result = InitSandboxWithName("xapp");
ASSERT_FALSE(result); ASSERT_FALSE(result);
} }
HWTEST_F(SandboxUnitTest, TestCreateErrorSandbox2, TestSize.Level1) { HWTEST_F(SandboxUnitTest, TestCreateErrorSandbox2, TestSize.Level1) {
cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, NULL_ROOT_PATH); cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, NULL_ROOT_PATH);
if (mJson == nullptr) { if (mJson == nullptr) {
std::cout << "created mJson error, mJson is null." << std::endl; std::cout << "created mJson error, mJson is null." << std::endl;
return; return;
} }
bool ret1 = MakeFileByJson(mJson, SANDBOX_JSON_NAME); bool ret1 = MakeFileByJson(mJson, SANDBOX_JSON_NAME);
ASSERT_TRUE(ret1); ASSERT_TRUE(ret1);
InitSandboxWithName(TEST_SANDBOX_NAME); InitSandboxWithName(TEST_SANDBOX_NAME);
int ret = PrepareSandbox(TEST_SANDBOX_NAME); int ret = PrepareSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, -1); ASSERT_EQ(ret, -1);
ret = PrepareSandbox("xapp"); ret = PrepareSandbox("xapp");
ASSERT_EQ(ret, -1); ASSERT_EQ(ret, -1);
} }
HWTEST_F(SandboxUnitTest, TestCreateSandboxNoneJsonError, TestSize.Level1) { HWTEST_F(SandboxUnitTest, TestCreateSandboxNoneJsonError, TestSize.Level1) {
unlink("/etc/sandbox/test-sandbox.json"); unlink("/etc/sandbox/test-sandbox.json");
int ret = PrepareSandbox(TEST_SANDBOX_NAME); int ret = PrepareSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, -1); ASSERT_EQ(ret, -1);
} }
HWTEST_F(SandboxUnitTest, TestCreateSandboxMountFlagsError, TestSize.Level1) { HWTEST_F(SandboxUnitTest, TestCreateSandboxMountFlagsError, TestSize.Level1) {
cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, NULL_MOUNT_FLAGS); cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, NULL_MOUNT_FLAGS);
if (mJson == nullptr) { if (mJson == nullptr) {
std::cout << "created mJson error, mJson is null." << std::endl; std::cout << "created mJson error, mJson is null." << std::endl;
return; return;
} }
MakeFileByJson(mJson, SANDBOX_JSON_NAME); MakeFileByJson(mJson, SANDBOX_JSON_NAME);
int ret = PrepareSandbox(TEST_SANDBOX_NAME); int ret = PrepareSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, -1); ASSERT_EQ(ret, -1);
} }
HWTEST_F(SandboxUnitTest, TestCreateSandboxMountNULLError, TestSize.Level1) { HWTEST_F(SandboxUnitTest, TestCreateSandboxMountNULLError, TestSize.Level1) {
cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, NULL_MOUNT_ITEM); cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, NULL_MOUNT_ITEM);
if (mJson == nullptr) { if (mJson == nullptr) {
std::cout << "created mJson error, mJson is null." << std::endl; std::cout << "created mJson error, mJson is null." << std::endl;
return; return;
} }
MakeFileByJson(mJson, SANDBOX_JSON_NAME); MakeFileByJson(mJson, SANDBOX_JSON_NAME);
int ret = PrepareSandbox(TEST_SANDBOX_NAME); int ret = PrepareSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, -1); ASSERT_EQ(ret, -1);
InitSandboxWithName(TEST_SANDBOX_NAME); InitSandboxWithName(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, -1); ASSERT_EQ(ret, -1);
} }
HWTEST_F(SandboxUnitTest, TestUnshareNamespace, TestSize.Level1) { HWTEST_F(SandboxUnitTest, TestUnshareNamespace, TestSize.Level1) {
int ret1 = UnshareNamespace(-1); int ret1 = UnshareNamespace(-1);
ASSERT_EQ(ret1, -1); ASSERT_EQ(ret1, -1);
} }
HWTEST_F(SandboxUnitTest, TestSetNamespace, TestSize.Level1) { HWTEST_F(SandboxUnitTest, TestSetNamespace, TestSize.Level1) {
int ret1 = SetNamespace(-1, 1); int ret1 = SetNamespace(-1, 1);
ASSERT_EQ(ret1, -1); ASSERT_EQ(ret1, -1);
ret1 = SetNamespace(1, -1); ret1 = SetNamespace(1, -1);
ASSERT_EQ(ret1, -1); ASSERT_EQ(ret1, -1);
} }
HWTEST_F(SandboxUnitTest, TestGetNamespaceFd, TestSize.Level1) { HWTEST_F(SandboxUnitTest, TestGetNamespaceFd, TestSize.Level1) {
int ret1 = GetNamespaceFd(""); int ret1 = GetNamespaceFd("");
ASSERT_EQ(ret1, -1); ASSERT_EQ(ret1, -1);
const std::string sandboxJsonPth = std::string("/mnt/sandbox/") + std::string(TEST_SANDBOX_NAME); const std::string sandboxJsonPth = std::string("/mnt/sandbox/") + std::string(TEST_SANDBOX_NAME);
const char* cSandboxJsonPth = sandboxJsonPth.c_str(); const char* cSandboxJsonPth = sandboxJsonPth.c_str();
ret1 = GetNamespaceFd(cSandboxJsonPth); ret1 = GetNamespaceFd(cSandboxJsonPth);
EXPECT_GT(ret1, 1); EXPECT_GT(ret1, 1);
} }
} }
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "init_cmds.h" #include "init_cmds.h"
#include "init_group_manager.h" #include "init_group_manager.h"
#include "init_hashmap.h" #include "init_hashmap.h"
#include "init_param.h" #include "init_param.h"
#include "init_module_engine.h" #include "init_module_engine.h"
#include "init_cmdexecutor.h" #include "init_cmdexecutor.h"
#include "param_stub.h" #include "param_stub.h"
#include "init_utils.h" #include "init_utils.h"
#include "securec.h" #include "securec.h"
using namespace testing::ext; using namespace testing::ext;
using namespace std; using namespace std;
namespace init_ut { namespace init_ut {
class ModuleMgrUnitTest : public testing::Test { class ModuleMgrUnitTest : public testing::Test {
public: public:
static void SetUpTestCase(void) {}; static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {}; static void TearDownTestCase(void) {};
void SetUp(void) {}; void SetUp(void) {};
void TearDown(void) {}; void TearDown(void) {};
}; };
int g_cmdExecId = 0; int g_cmdExecId = 0;
int TestCmdExecutor(int id, const char *name, int argc, const char **argv) int TestCmdExecutor(int id, const char *name, int argc, const char **argv)
{ {
printf("TestCmdExecutor id %d, name %s \n", id, name); printf("TestCmdExecutor id %d, name %s \n", id, name);
g_cmdExecId = id; g_cmdExecId = id;
return 0; return 0;
} }
HWTEST_F(ModuleMgrUnitTest, PluginAddCmd, TestSize.Level1) HWTEST_F(ModuleMgrUnitTest, PluginAddCmd, TestSize.Level1)
{ {
InitServiceSpace(); InitServiceSpace();
const char *testName = "testCmd1"; const char *testName = "testCmd1";
const char *cmdContent = "testCmd1 test1 test2 test3"; const char *cmdContent = "testCmd1 test1 test2 test3";
const char *cmdContentNotValid = "testCmd1 t e s t 1 t e s t 2 t"; const char *cmdContentNotValid = "testCmd1 t e s t 1 t e s t 2 t";
int cmdExecId1 = AddCmdExecutor(testName, TestCmdExecutor); int cmdExecId1 = AddCmdExecutor(testName, TestCmdExecutor);
ASSERT_NE(cmdExecId1 > 0, 0); ASSERT_NE(cmdExecId1 > 0, 0);
int cmdExecId2 = AddCmdExecutor("testCmd2", TestCmdExecutor); int cmdExecId2 = AddCmdExecutor("testCmd2", TestCmdExecutor);
ASSERT_NE(cmdExecId2 > 0, 0); ASSERT_NE(cmdExecId2 > 0, 0);
cmdExecId2 = AddCmdExecutor("testCmd3", TestCmdExecutor); cmdExecId2 = AddCmdExecutor("testCmd3", TestCmdExecutor);
ASSERT_NE(cmdExecId2 > 0, 0); ASSERT_NE(cmdExecId2 > 0, 0);
int cmdExecId4 = AddCmdExecutor("testCmd4", TestCmdExecutor); int cmdExecId4 = AddCmdExecutor("testCmd4", TestCmdExecutor);
ASSERT_NE(cmdExecId4 > 0, 0); ASSERT_NE(cmdExecId4 > 0, 0);
PluginExecCmd("testCmd4", 0, nullptr); PluginExecCmd("testCmd4", 0, nullptr);
int cmdIndex = 0; int cmdIndex = 0;
const char *cmdName = PluginGetCmdIndex(cmdContent, &cmdIndex); const char *cmdName = PluginGetCmdIndex(cmdContent, &cmdIndex);
ASSERT_EQ(strcmp(cmdName, testName), 0); ASSERT_EQ(strcmp(cmdName, testName), 0);
printf("TestCmdExecutor cmdIndex 0x%04x, name %s \n", cmdIndex, cmdName); printf("TestCmdExecutor cmdIndex 0x%04x, name %s \n", cmdIndex, cmdName);
// exec // exec
g_cmdExecId = -1; g_cmdExecId = -1;
PluginExecCmdByName(cmdName, cmdContent); PluginExecCmdByName(cmdName, cmdContent);
ASSERT_EQ(cmdExecId1, g_cmdExecId); ASSERT_EQ(cmdExecId1, g_cmdExecId);
PluginExecCmdByName(cmdName, nullptr); PluginExecCmdByName(cmdName, nullptr);
PluginExecCmdByName(cmdName, cmdContentNotValid); PluginExecCmdByName(cmdName, cmdContentNotValid);
g_cmdExecId = -1; g_cmdExecId = -1;
PluginExecCmdByCmdIndex(cmdIndex, cmdContent); PluginExecCmdByCmdIndex(cmdIndex, cmdContent);
ASSERT_EQ(cmdExecId1, g_cmdExecId); ASSERT_EQ(cmdExecId1, g_cmdExecId);
const char *argv[] = {"test"}; const char *argv[] = {"test"};
PluginExecCmd("install", 1, argv); PluginExecCmd("install", 1, argv);
PluginExecCmd("uninstall", 1, argv); PluginExecCmd("uninstall", 1, argv);
// del // del
RemoveCmdExecutor("testCmd4", cmdExecId4); RemoveCmdExecutor("testCmd4", cmdExecId4);
} }
HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1) HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1)
{ {
int ret; int ret;
int cnt; int cnt;
// Create module manager // Create module manager
MODULE_MGR *moduleMgr = ModuleMgrCreate("init"); MODULE_MGR *moduleMgr = ModuleMgrCreate("init");
ASSERT_NE(moduleMgr, nullptr); ASSERT_NE(moduleMgr, nullptr);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
// Install one module // Install one module
ret = ModuleMgrInstall(moduleMgr, "libbootchart", 0, NULL); ret = ModuleMgrInstall(moduleMgr, "libbootchart", 0, NULL);
ASSERT_EQ(ret, 0); ASSERT_EQ(ret, 0);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 1); ASSERT_EQ(cnt, 1);
// Uninstall the module // Uninstall the module
ModuleMgrUninstall(moduleMgr, "libbootchart"); ModuleMgrUninstall(moduleMgr, "libbootchart");
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
// Install two module // Install two module
ret = ModuleMgrInstall(moduleMgr, "libbootchart", 0, NULL); ret = ModuleMgrInstall(moduleMgr, "libbootchart", 0, NULL);
ASSERT_EQ(ret, 0); ASSERT_EQ(ret, 0);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 1); ASSERT_EQ(cnt, 1);
ret = ModuleMgrInstall(moduleMgr, "notexist", 0, NULL); ret = ModuleMgrInstall(moduleMgr, "notexist", 0, NULL);
ASSERT_NE(ret, 0); ASSERT_NE(ret, 0);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 1); ASSERT_EQ(cnt, 1);
// Uninstall the module // Uninstall the module
ModuleMgrUninstall(moduleMgr, "libbootchart"); ModuleMgrUninstall(moduleMgr, "libbootchart");
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
ModuleMgrUninstall(moduleMgr, "notexist"); ModuleMgrUninstall(moduleMgr, "notexist");
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
ModuleMgrDestroy(moduleMgr); ModuleMgrDestroy(moduleMgr);
// Scan all modules // Scan all modules
moduleMgr = ModuleMgrScan("init"); moduleMgr = ModuleMgrScan("init");
ASSERT_NE(moduleMgr, nullptr); ASSERT_NE(moduleMgr, nullptr);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_NE(cnt, 0); ASSERT_NE(cnt, 0);
ModuleMgrUninstall(moduleMgr, NULL); ModuleMgrUninstall(moduleMgr, NULL);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
ModuleMgrGetArgs(); ModuleMgrGetArgs();
ModuleMgrDestroy(moduleMgr); ModuleMgrDestroy(moduleMgr);
} }
} // namespace init_ut } // namespace init_ut
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include "begetctl.h" #include "begetctl.h"
#include "securec.h" #include "securec.h"
#include "shell.h" #include "shell.h"
#include "shell_utils.h" #include "shell_utils.h"
#include "shell_bas.h" #include "shell_bas.h"
#include "init_param.h" #include "init_param.h"
using namespace std; using namespace std;
using namespace testing::ext; using namespace testing::ext;
namespace init_ut { namespace init_ut {
class ParamShellUnitTest : public testing::Test { class ParamShellUnitTest : public testing::Test {
public: public:
ParamShellUnitTest() {}; ParamShellUnitTest() {};
virtual ~ParamShellUnitTest() {}; virtual ~ParamShellUnitTest() {};
static void SetUpTestCase(void) {}; static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {}; static void TearDownTestCase(void) {};
void SetUp(void) {}; void SetUp(void) {};
void TearDown(void) {}; void TearDown(void) {};
void TestBody(void) {}; void TestBody(void) {};
void TestInitParamShell() void TestInitParamShell()
{ {
SystemSetParameter("aaa", "aaa"); SystemSetParameter("aaa", "aaa");
BShellHandle bshd = GetShellHandle(); BShellHandle bshd = GetShellHandle();
if (bshd == nullptr) { if (bshd == nullptr) {
return; return;
} }
const char *args[] = {"paramshell", "\n"}; const char *args[] = {"paramshell", "\n"};
const ParamInfo *param = BShellEnvGetReservedParam(bshd, PARAM_REVERESD_NAME_CURR_PARAMETER); const ParamInfo *param = BShellEnvGetReservedParam(bshd, PARAM_REVERESD_NAME_CURR_PARAMETER);
int ret = BShellEnvSetParam(bshd, PARAM_REVERESD_NAME_CURR_PARAMETER, "..a", PARAM_STRING, (void *)"..a"); int ret = BShellEnvSetParam(bshd, PARAM_REVERESD_NAME_CURR_PARAMETER, "..a", PARAM_STRING, (void *)"..a");
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
SetParamShellPrompt(bshd, args[1]); SetParamShellPrompt(bshd, args[1]);
SetParamShellPrompt(bshd, ".."); SetParamShellPrompt(bshd, "..");
ret = BShellEnvSetParam(bshd, param->name, param->desc, param->type, (void *)""); ret = BShellEnvSetParam(bshd, param->name, param->desc, param->type, (void *)"");
SetParamShellPrompt(bshd, ".."); SetParamShellPrompt(bshd, "..");
SetParamShellPrompt(bshd, ".a"); SetParamShellPrompt(bshd, ".a");
SetParamShellPrompt(bshd, "."); SetParamShellPrompt(bshd, ".");
SetParamShellPrompt(bshd, args[1]); SetParamShellPrompt(bshd, args[1]);
BShellParamCmdRegister(bshd, 1); BShellParamCmdRegister(bshd, 1);
BShellEnvStart(bshd); BShellEnvStart(bshd);
ret = BShellEnvOutputPrompt(bshd, "testprompt"); ret = BShellEnvOutputPrompt(bshd, "testprompt");
ret = BShellEnvOutputPrompt(bshd, "testprompt1111111111111111111111111111111111111111111111111111111111"); ret = BShellEnvOutputPrompt(bshd, "testprompt1111111111111111111111111111111111111111111111111111111111");
BShellEnvOutputByte(bshd, 'o'); BShellEnvOutputByte(bshd, 'o');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
} }
void TestParamShellCmd() void TestParamShellCmd()
{ {
BShellHandle bshd = GetShellHandle(); BShellHandle bshd = GetShellHandle();
BShellKey *key = BShellEnvGetDefaultKey('\n'); BShellKey *key = BShellEnvGetDefaultKey('\n');
EXPECT_NE(key, nullptr); EXPECT_NE(key, nullptr);
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "cd const") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "cd const") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
int ret = key->keyHandle(bshd, '\n'); int ret = key->keyHandle(bshd, '\n');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "cat aaa") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "cat aaa") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
ret = key->keyHandle(bshd, '\n'); ret = key->keyHandle(bshd, '\n');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "testnotcmd") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "testnotcmd") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
ret = key->keyHandle(bshd, '\n'); ret = key->keyHandle(bshd, '\n');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
// test param start with " // test param start with "
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "\"ls") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "\"ls") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
ret = key->keyHandle(bshd, '\n'); ret = key->keyHandle(bshd, '\n');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
// test argc is 0 // test argc is 0
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), ",ls") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), ",ls") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
ret = key->keyHandle(bshd, '\n'); ret = key->keyHandle(bshd, '\n');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "$test$") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "$test$") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
ret = key->keyHandle(bshd, '\n'); ret = key->keyHandle(bshd, '\n');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "exit") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "exit") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
ret = key->keyHandle(bshd, '\n'); ret = key->keyHandle(bshd, '\n');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
} }
void TestParamShellCmd1() void TestParamShellCmd1()
{ {
BShellHandle bshd = GetShellHandle(); BShellHandle bshd = GetShellHandle();
BShellKey *key = BShellEnvGetDefaultKey('\n'); BShellKey *key = BShellEnvGetDefaultKey('\n');
EXPECT_NE(key, nullptr); EXPECT_NE(key, nullptr);
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "pwd") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "pwd") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
int ret = key->keyHandle(bshd, '\n'); int ret = key->keyHandle(bshd, '\n');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "help") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "help") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
ret = key->keyHandle(bshd, '\n'); ret = key->keyHandle(bshd, '\n');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "dump") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "dump") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
ret = key->keyHandle(bshd, '\n'); ret = key->keyHandle(bshd, '\n');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "dump verbose") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "dump verbose") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
ret = key->keyHandle(bshd, '\n'); ret = key->keyHandle(bshd, '\n');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
} }
void TestParamShellcmdEndkey() void TestParamShellcmdEndkey()
{ {
BShellHandle bshd = GetShellHandle(); BShellHandle bshd = GetShellHandle();
bshd->input(nullptr, 0); bshd->input(nullptr, 0);
BShellKey *key = BShellEnvGetDefaultKey('\b'); BShellKey *key = BShellEnvGetDefaultKey('\b');
EXPECT_NE(key, nullptr); EXPECT_NE(key, nullptr);
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "testbbackspace") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "testbbackspace") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
bshd->cursor = strlen("testb"); bshd->cursor = strlen("testb");
int ret = key->keyHandle(bshd, '\b'); int ret = key->keyHandle(bshd, '\b');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "testbbackspace") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "testbbackspace") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
bshd->cursor = strlen(bshd->buffer); bshd->cursor = strlen(bshd->buffer);
ret = key->keyHandle(bshd, '\b'); ret = key->keyHandle(bshd, '\b');
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
key = BShellEnvGetDefaultKey('\t'); key = BShellEnvGetDefaultKey('\t');
if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "testtab") != EOK) { if (strcpy_s(bshd->buffer, sizeof(bshd->buffer), "testtab") != EOK) {
return; return;
} }
bshd->length = strlen(bshd->buffer); bshd->length = strlen(bshd->buffer);
ret = key->keyHandle(bshd, '\t'); ret = key->keyHandle(bshd, '\t');
EXPECT_NE(key, nullptr); EXPECT_NE(key, nullptr);
BShellEnvProcessInput(bshd, (char)3); // 3 is ctrl c BShellEnvProcessInput(bshd, (char)3); // 3 is ctrl c
BShellEnvProcessInput(bshd, '\e'); BShellEnvProcessInput(bshd, '\e');
BShellEnvProcessInput(bshd, '['); BShellEnvProcessInput(bshd, '[');
bshd->length = 1; bshd->length = 1;
bshd->cursor = 1; bshd->cursor = 1;
BShellEnvProcessInput(bshd, 'C'); BShellEnvProcessInput(bshd, 'C');
BShellEnvProcessInput(bshd, 'D'); BShellEnvProcessInput(bshd, 'D');
} }
}; };
HWTEST_F(ParamShellUnitTest, TestInitParamShell, TestSize.Level1) HWTEST_F(ParamShellUnitTest, TestInitParamShell, TestSize.Level1)
{ {
ParamShellUnitTest test; ParamShellUnitTest test;
test.TestInitParamShell(); test.TestInitParamShell();
test.TestParamShellCmd(); test.TestParamShellCmd();
test.TestParamShellCmd1(); test.TestParamShellCmd1();
} }
HWTEST_F(ParamShellUnitTest, TestParamShellInput, TestSize.Level1) HWTEST_F(ParamShellUnitTest, TestParamShellInput, TestSize.Level1)
{ {
BShellHandle bshd = GetShellHandle(); BShellHandle bshd = GetShellHandle();
BShellEnvProcessInput(bshd, '\n'); BShellEnvProcessInput(bshd, '\n');
BShellEnvProcessInput(bshd, 'l'); BShellEnvProcessInput(bshd, 'l');
bshd->length = BSH_COMMAND_MAX_LENGTH; bshd->length = BSH_COMMAND_MAX_LENGTH;
BShellEnvProcessInput(bshd, 'l'); BShellEnvProcessInput(bshd, 'l');
bshd->length = sizeof('l'); bshd->length = sizeof('l');
bshd->cursor = 0; bshd->cursor = 0;
BShellEnvProcessInput(bshd, 's'); BShellEnvProcessInput(bshd, 's');
BShellEnvProcessInput(bshd, '\n'); BShellEnvProcessInput(bshd, '\n');
BShellEnvProcessInput(bshd, '\n'); // test bshd buff length is 0 BShellEnvProcessInput(bshd, '\n'); // test bshd buff length is 0
int ret = BShellEnvRegisterKeyHandle(bshd, 'z', (BShellkeyHandle)(void*)0x409600); // 0x409600 construct address int ret = BShellEnvRegisterKeyHandle(bshd, 'z', (BShellkeyHandle)(void*)0x409600); // 0x409600 construct address
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
} }
HWTEST_F(ParamShellUnitTest, TestParamShellcmd2, TestSize.Level1) HWTEST_F(ParamShellUnitTest, TestParamShellcmd2, TestSize.Level1)
{ {
ParamShellUnitTest test; ParamShellUnitTest test;
test.TestParamShellcmdEndkey(); test.TestParamShellcmdEndkey();
GetSystemCommitId(); GetSystemCommitId();
BShellEnvLoop(nullptr); BShellEnvLoop(nullptr);
BShellEnvErrString(GetShellHandle(), 1); BShellEnvErrString(GetShellHandle(), 1);
BShellEnvOutputResult(GetShellHandle(), 1); BShellEnvOutputResult(GetShellHandle(), 1);
demoExit(); demoExit();
} }
} // namespace init_ut } // namespace init_ut
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "param_stub.h" #include "param_stub.h"
#include <dirent.h> #include <dirent.h>
#include "beget_ext.h" #include "beget_ext.h"
#include "init_param.h" #include "init_param.h"
#include "param_manager.h" #include "param_manager.h"
#include "param_security.h" #include "param_security.h"
#include "param_utils.h" #include "param_utils.h"
#include "init_group_manager.h" #include "init_group_manager.h"
#ifdef PARAM_LOAD_CFG_FROM_CODE #ifdef PARAM_LOAD_CFG_FROM_CODE
#include "param_cfg.h" #include "param_cfg.h"
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
extern "C" { extern "C" {
#endif #endif
#endif #endif
int LoadParamFromCmdLine(void); int LoadParamFromCmdLine(void);
static int g_testPermissionResult = DAC_RESULT_PERMISSION; static int g_testPermissionResult = DAC_RESULT_PERMISSION;
void SetTestPermissionResult(int result) void SetTestPermissionResult(int result)
{ {
g_testPermissionResult = result; g_testPermissionResult = result;
} }
static const char *selinuxLabels[][2] = { static const char *selinuxLabels[][2] = {
{"test.permission.read", "test.persmission.read"}, {"test.permission.read", "test.persmission.read"},
{"test.permission.write", "test.persmission.write"}, {"test.permission.write", "test.persmission.write"},
{"test.permission.watch", "test.persmission.watch"} {"test.permission.watch", "test.persmission.watch"}
}; };
static int TestGenHashCode(const char *buff) static int TestGenHashCode(const char *buff)
{ {
int code = 0; int code = 0;
size_t buffLen = strlen(buff); size_t buffLen = strlen(buff);
for (size_t i = 0; i < buffLen; i++) { for (size_t i = 0; i < buffLen; i++) {
code += buff[i] - 'A'; code += buff[i] - 'A';
} }
return code; return code;
} }
static void TestSetSelinuxLogCallback(void) {} static void TestSetSelinuxLogCallback(void) {}
static const char *forbitWriteParamName[] = { static const char *forbitWriteParamName[] = {
"ohos.servicectrl.", "ohos.servicectrl.",
"test.permission.read", "test.permission.read",
"test.persmission.watch" "test.persmission.watch"
}; };
static int TestSetParamCheck(const char *paraName, struct ucred *uc) static int TestSetParamCheck(const char *paraName, struct ucred *uc)
{ {
// forbid to read ohos.servicectrl. // forbid to read ohos.servicectrl.
for (size_t i = 0; i < ARRAY_LENGTH(forbitWriteParamName); i++) { for (size_t i = 0; i < ARRAY_LENGTH(forbitWriteParamName); i++) {
if (strncmp(paraName, forbitWriteParamName[i], strlen(forbitWriteParamName[i])) == 0) { if (strncmp(paraName, forbitWriteParamName[i], strlen(forbitWriteParamName[i])) == 0) {
return 1; return 1;
} }
} }
return g_testPermissionResult; return g_testPermissionResult;
} }
static const char *TestGetParamLabel(const char *paraName) static const char *TestGetParamLabel(const char *paraName)
{ {
BEGET_LOGI("TestGetParamLabel %s", paraName); BEGET_LOGI("TestGetParamLabel %s", paraName);
for (size_t i = 0; i < ARRAY_LENGTH(selinuxLabels); i++) { for (size_t i = 0; i < ARRAY_LENGTH(selinuxLabels); i++) {
if (strncmp(selinuxLabels[i][0], paraName, strlen(selinuxLabels[i][0])) == 0) { if (strncmp(selinuxLabels[i][0], paraName, strlen(selinuxLabels[i][0])) == 0) {
return selinuxLabels[i][1]; return selinuxLabels[i][1];
} }
} }
int code = TestGenHashCode(paraName); int code = TestGenHashCode(paraName);
code = code % (ARRAY_LENGTH(selinuxLabels)); code = code % (ARRAY_LENGTH(selinuxLabels));
return selinuxLabels[code][1]; return selinuxLabels[code][1];
} }
static const char *forbitReadParamName[] = { static const char *forbitReadParamName[] = {
"ohos.servicectrl.", "ohos.servicectrl.",
// "test.permission.write", // "test.permission.write",
}; };
static int TestReadParamCheck(const char *paraName) static int TestReadParamCheck(const char *paraName)
{ {
// forbid to read ohos.servicectrl. // forbid to read ohos.servicectrl.
for (size_t i = 0; i < ARRAY_LENGTH(forbitReadParamName); i++) { for (size_t i = 0; i < ARRAY_LENGTH(forbitReadParamName); i++) {
if (strncmp(paraName, forbitReadParamName[i], strlen(forbitReadParamName[i])) == 0) { if (strncmp(paraName, forbitReadParamName[i], strlen(forbitReadParamName[i])) == 0) {
return 1; return 1;
} }
} }
return g_testPermissionResult; return g_testPermissionResult;
} }
static void TestDestroyParamList(ParamContextsList **list) static void TestDestroyParamList(ParamContextsList **list)
{ {
#ifdef PARAM_SUPPORT_SELINUX #ifdef PARAM_SUPPORT_SELINUX
ParamContextsList *head = *list; ParamContextsList *head = *list;
while (head != nullptr) { while (head != nullptr) {
ParamContextsList *next = head->next; ParamContextsList *next = head->next;
free(head->info.paraName); free(head->info.paraName);
free(head->info.paraContext); free(head->info.paraContext);
free(head); free(head);
head = next; head = next;
} }
#endif #endif
} }
static ParamContextsList *TestGetParamList(void) static ParamContextsList *TestGetParamList(void)
{ {
#ifdef PARAM_SUPPORT_SELINUX #ifdef PARAM_SUPPORT_SELINUX
ParamContextsList *head = (ParamContextsList *)malloc(sizeof(ParamContextsList)); ParamContextsList *head = (ParamContextsList *)malloc(sizeof(ParamContextsList));
BEGET_ERROR_CHECK(head != nullptr, return nullptr, "Failed to alloc ParamContextsList"); BEGET_ERROR_CHECK(head != nullptr, return nullptr, "Failed to alloc ParamContextsList");
head->info.paraName = strdup(selinuxLabels[0][0]); head->info.paraName = strdup(selinuxLabels[0][0]);
head->info.paraContext = strdup(selinuxLabels[0][1]); head->info.paraContext = strdup(selinuxLabels[0][1]);
head->next = nullptr; head->next = nullptr;
for (size_t i = 1; i < ARRAY_LENGTH(selinuxLabels); i++) { for (size_t i = 1; i < ARRAY_LENGTH(selinuxLabels); i++) {
ParamContextsList *node = (ParamContextsList *)malloc(sizeof(ParamContextsList)); ParamContextsList *node = (ParamContextsList *)malloc(sizeof(ParamContextsList));
BEGET_ERROR_CHECK(node != nullptr, TestDestroyParamList(&head); BEGET_ERROR_CHECK(node != nullptr, TestDestroyParamList(&head);
return nullptr, "Failed to alloc ParamContextsList"); return nullptr, "Failed to alloc ParamContextsList");
node->info.paraName = strdup(selinuxLabels[i][0]); node->info.paraName = strdup(selinuxLabels[i][0]);
node->info.paraContext = strdup(selinuxLabels[i][1]); node->info.paraContext = strdup(selinuxLabels[i][1]);
node->next = head->next; node->next = head->next;
head->next = node; head->next = node;
} }
return head; return head;
#else #else
return nullptr; return nullptr;
#endif #endif
} }
void TestSetSelinuxOps(void) void TestSetSelinuxOps(void)
{ {
SelinuxSpace space = {}; SelinuxSpace space = {};
space.setSelinuxLogCallback = TestSetSelinuxLogCallback; space.setSelinuxLogCallback = TestSetSelinuxLogCallback;
space.setParamCheck = TestSetParamCheck; space.setParamCheck = TestSetParamCheck;
space.getParamLabel = TestGetParamLabel; space.getParamLabel = TestGetParamLabel;
space.readParamCheck = TestReadParamCheck; space.readParamCheck = TestReadParamCheck;
space.getParamList = TestGetParamList; space.getParamList = TestGetParamList;
space.destroyParamList = TestDestroyParamList; space.destroyParamList = TestDestroyParamList;
#ifdef PARAM_SUPPORT_SELINUX #ifdef PARAM_SUPPORT_SELINUX
SetSelinuxOps(&space); SetSelinuxOps(&space);
#endif #endif
} }
static void CreateTestFile(const char *fileName, const char *data) static void CreateTestFile(const char *fileName, const char *data)
{ {
CheckAndCreateDir(fileName); CheckAndCreateDir(fileName);
PARAM_LOGV("PrepareParamTestData for %s", fileName); PARAM_LOGV("PrepareParamTestData for %s", fileName);
FILE *tmpFile = fopen(fileName, "wr"); FILE *tmpFile = fopen(fileName, "wr");
if (tmpFile != nullptr) { if (tmpFile != nullptr) {
fprintf(tmpFile, "%s", data); fprintf(tmpFile, "%s", data);
(void)fflush(tmpFile); (void)fflush(tmpFile);
fclose(tmpFile); fclose(tmpFile);
} }
} }
static void PrepareUeventdcfg(void) static void PrepareUeventdcfg(void)
{ {
const char *ueventdcfg = "[device]\n" const char *ueventdcfg = "[device]\n"
"/dev/test 0666 1000 1000\n" "/dev/test 0666 1000 1000\n"
"[device]\n" "[device]\n"
"/dev/test1 0666 1000\n" "/dev/test1 0666 1000\n"
"[device]\n" "[device]\n"
"/dev/test2 0666 1000 1000 1000 1000\n" "/dev/test2 0666 1000 1000 1000 1000\n"
"[sysfs]\n" "[sysfs]\n"
"/dir/to/nothing attr_nowhere 0666 1000 1000\n" "/dir/to/nothing attr_nowhere 0666 1000 1000\n"
"[sysfs]\n" "[sysfs]\n"
" #/dir/to/nothing attr_nowhere 0666\n" " #/dir/to/nothing attr_nowhere 0666\n"
"[sysfs\n" "[sysfs\n"
"/dir/to/nothing attr_nowhere 0666\n" "/dir/to/nothing attr_nowhere 0666\n"
"[firmware]\n" "[firmware]\n"
"/etc\n" "/etc\n"
"[device]\n" "[device]\n"
"/dev/testbinder 0666 1000 1000 const.dev.binder\n" "/dev/testbinder 0666 1000 1000 const.dev.binder\n"
"[device]\n" "[device]\n"
"/dev/testbinder1 0666 1000 1000 const.dev.binder\n" "/dev/testbinder1 0666 1000 1000 const.dev.binder\n"
"[device]\n" "[device]\n"
"/dev/testbinder2 0666 1000 1000 const.dev.binder\n" "/dev/testbinder2 0666 1000 1000 const.dev.binder\n"
"[device]\n" "[device]\n"
"/dev/testbinder3 0666 1000 1000 const.dev.binder\n"; "/dev/testbinder3 0666 1000 1000 const.dev.binder\n";
mkdir("/data/ueventd_ut", S_IRWXU | S_IRWXG | S_IRWXO); mkdir("/data/ueventd_ut", S_IRWXU | S_IRWXG | S_IRWXO);
CreateTestFile("/data/ueventd_ut/valid.config", ueventdcfg); CreateTestFile("/data/ueventd_ut/valid.config", ueventdcfg);
} }
static void PrepareModCfg(void) static void PrepareModCfg(void)
{ {
const char *modCfg = "testinsmod"; const char *modCfg = "testinsmod";
CreateTestFile("/data/init_ut/test_insmod", modCfg); CreateTestFile("/data/init_ut/test_insmod", modCfg);
} }
static void PrepareInnerKitsCfg() static void PrepareInnerKitsCfg()
{ {
const char *innerKitsCfg = "/dev/block/platform/soc/10100000.himci.eMMC/by-name/system /system " const char *innerKitsCfg = "/dev/block/platform/soc/10100000.himci.eMMC/by-name/system /system "
"ext4 ro,barrier=1 wait\n" "ext4 ro,barrier=1 wait\n"
"/dev/block/platform/soc/10100000.himci.eMMC/by-name/vendor /vendor " "/dev/block/platform/soc/10100000.himci.eMMC/by-name/vendor /vendor "
"ext4 ro,barrier=1 wait\n" "ext4 ro,barrier=1 wait\n"
"/dev/block/platform/soc/10100000.himci.eMMC/by-name/hos " "/dev/block/platform/soc/10100000.himci.eMMC/by-name/hos "
"/hos ntfs nosuid,nodev,noatime,barrier=1,data=ordered wait\n" "/hos ntfs nosuid,nodev,noatime,barrier=1,data=ordered wait\n"
"/dev/block/platform/soc/10100000.himci.eMMC/by-name/userdata /data ext4 " "/dev/block/platform/soc/10100000.himci.eMMC/by-name/userdata /data ext4 "
"nosuid,nodev,noatime,barrier=1,data=ordered,noauto_da_alloc " "nosuid,nodev,noatime,barrier=1,data=ordered,noauto_da_alloc "
"wait,reservedsize=104857600\n" "wait,reservedsize=104857600\n"
" aaaa\n" " aaaa\n"
"aa aa\n" "aa aa\n"
"aa aa aa\n" "aa aa aa\n"
"aa aa aa aa\n"; "aa aa aa aa\n";
mkdir("/data/init_ut/mount_unitest/", S_IRWXU | S_IRWXG | S_IRWXO); 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/mount_unitest/ReadFstabFromFile1.fstable", innerKitsCfg);
CreateTestFile("/etc/fstab.required", "test"); CreateTestFile("/etc/fstab.required", "test");
} }
static void PrepareGroupTestCfg() static void PrepareGroupTestCfg()
{ {
const char *data = "{" const char *data = "{"
"\"jobs\": [\"param:job1\", \"param:job2\", \"param:job4\"]," "\"jobs\": [\"param:job1\", \"param:job2\", \"param:job4\"],"
"\"services\": [\"service:service1\", \"service:service3\", \"service:service2\"]," "\"services\": [\"service:service1\", \"service:service3\", \"service:service2\"],"
"\"groups\": [\"subsystem.xxx1.group\", \"subsystem.xxx2.group\", \"subsystem.xxx4.group\"]" "\"groups\": [\"subsystem.xxx1.group\", \"subsystem.xxx2.group\", \"subsystem.xxx4.group\"]"
"}"; "}";
const char *xxx1 = "{" const char *xxx1 = "{"
"\"groups\": [\"subsystem.xxx11.group\"" "\"groups\": [\"subsystem.xxx11.group\""
"}"; "}";
const char *xxx11 = "{" const char *xxx11 = "{"
"\"groups\": [\"subsystem.xxx12.group\"" "\"groups\": [\"subsystem.xxx12.group\""
"}"; "}";
const char *xxx12 = "{" const char *xxx12 = "{"
"\"groups\": [\"subsystem.xxx13.group\"" "\"groups\": [\"subsystem.xxx13.group\""
"}"; "}";
const char *xxx13 = "{" const char *xxx13 = "{"
"\"groups\": [\"subsystem.xxx14.group\"" "\"groups\": [\"subsystem.xxx14.group\""
"}"; "}";
const char *xxx14 = "{" const char *xxx14 = "{"
"\"groups\": [\"subsystem.xxx11.group\"" "\"groups\": [\"subsystem.xxx11.group\""
"}"; "}";
CreateTestFile(GROUP_DEFAULT_PATH "/device.boot.group.cfg", data); CreateTestFile(GROUP_DEFAULT_PATH "/device.boot.group.cfg", data);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx1.group.cfg", xxx1); CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx1.group.cfg", xxx1);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx11.group.cfg", xxx11); CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx11.group.cfg", xxx11);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx12.group.cfg", xxx12); CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx12.group.cfg", xxx12);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx13.group.cfg", xxx13); CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx13.group.cfg", xxx13);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx14.group.cfg", xxx14); CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx14.group.cfg", xxx14);
} }
static bool IsDir(const std::string &path) static bool IsDir(const std::string &path)
{ {
struct stat st {}; struct stat st {};
if (stat(path.c_str(), &st) < 0) { if (stat(path.c_str(), &st) < 0) {
return false; return false;
} }
return S_ISDIR(st.st_mode); return S_ISDIR(st.st_mode);
} }
static bool DeleteDir(const std::string &path) static bool DeleteDir(const std::string &path)
{ {
auto pDir = std::unique_ptr<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir); auto pDir = std::unique_ptr<DIR, decltype(&closedir)>(opendir(path.c_str()), closedir);
if (pDir == nullptr) { if (pDir == nullptr) {
return false; return false;
} }
struct dirent *dp = nullptr; struct dirent *dp = nullptr;
while ((dp = readdir(pDir.get())) != nullptr) { while ((dp = readdir(pDir.get())) != nullptr) {
std::string currentName(dp->d_name); std::string currentName(dp->d_name);
if (currentName[0] != '.') { if (currentName[0] != '.') {
std::string tmpName(path); std::string tmpName(path);
tmpName.append("/" + currentName); tmpName.append("/" + currentName);
if (IsDir(tmpName)) { if (IsDir(tmpName)) {
DeleteDir(tmpName); DeleteDir(tmpName);
} }
remove(tmpName.c_str()); remove(tmpName.c_str());
} }
} }
if (remove(path.c_str()) != 0) { if (remove(path.c_str()) != 0) {
return false; return false;
} }
return true; return true;
} }
static void LoadParamFromCfg(void) static void LoadParamFromCfg(void)
{ {
#ifdef PARAM_LOAD_CFG_FROM_CODE #ifdef PARAM_LOAD_CFG_FROM_CODE
for (size_t i = 0; i < ARRAY_LENGTH(g_paramDefCfgNodes); i++) { for (size_t i = 0; i < ARRAY_LENGTH(g_paramDefCfgNodes); i++) {
PARAM_LOGI("InitParamClient name %s = %s", g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value); PARAM_LOGI("InitParamClient name %s = %s", g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value);
uint32_t dataIndex = 0; uint32_t dataIndex = 0;
int ret = WriteParam(g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value, &dataIndex, 0); int ret = WriteParam(g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value, &dataIndex, 0);
PARAM_CHECK(ret == 0, continue, "Failed to set param %d name %s %s", PARAM_CHECK(ret == 0, continue, "Failed to set param %d name %s %s",
ret, g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value); ret, g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value);
} }
#endif #endif
} }
#if !(defined __LITEOS_A__ || defined __LITEOS_M__) #if !(defined __LITEOS_A__ || defined __LITEOS_M__)
static const char *g_triggerData = "{" static const char *g_triggerData = "{"
"\"jobs\" : [{" "\"jobs\" : [{"
" \"name\" : \"early-init\"," " \"name\" : \"early-init\","
" \"cmds\" : [" " \"cmds\" : ["
" \" write '/proc/sys/kernel/sysrq 0'\"," " \" write '/proc/sys/kernel/sysrq 0'\","
" \" load_persist_params \"," " \" load_persist_params \","
" \" load_persist_params \"," " \" load_persist_params \","
" \" # load_persist_params \"," " \" # load_persist_params \","
" \" restorecon /postinstall\"," " \" restorecon /postinstall\","
" \"mkdir /acct/uid\"," " \"mkdir /acct/uid\","
" \"chown root system /dev/memcg/memory.pressure_level\"," " \"chown root system /dev/memcg/memory.pressure_level\","
" \"chmod 0040 /dev/memcg/memory.pressure_level\"," " \"chmod 0040 /dev/memcg/memory.pressure_level\","
" \"mkdir /dev/memcg/apps/ 0755 system system\"," " \"mkdir /dev/memcg/apps/ 0755 system system\","
" \"mkdir /dev/memcg/system 0550 system system\"," " \"mkdir /dev/memcg/system 0550 system system\","
" \"start ueventd\"," " \"start ueventd\","
" \"exec_start apexd-bootstrap\"," " \"exec_start apexd-bootstrap\","
" \"setparam sys.usb.config ${persist.sys.usb.config}\"" " \"setparam sys.usb.config ${persist.sys.usb.config}\""
" ]" " ]"
" }," " },"
" {" " {"
" \"name\" : \"param:trigger_test_1\"," " \"name\" : \"param:trigger_test_1\","
" \"condition\" : \"test.sys.boot_from_charger_mode=5\"," " \"condition\" : \"test.sys.boot_from_charger_mode=5\","
" \"cmds\" : [" " \"cmds\" : ["
" \"class_stop charger\"," " \"class_stop charger\","
" \"trigger late-init\"" " \"trigger late-init\""
" ]" " ]"
" }," " },"
" {" " {"
" \"name\" : \"param:trigger_test_2\"," " \"name\" : \"param:trigger_test_2\","
" \"condition\" : \"test.sys.boot_from_charger_mode=1 " " \"condition\" : \"test.sys.boot_from_charger_mode=1 "
" || test.sys.boot_from_charger_mode=2 || test.sys.boot_from_charger_mode=3\"," " || test.sys.boot_from_charger_mode=2 || test.sys.boot_from_charger_mode=3\","
" \"cmds\" : [" " \"cmds\" : ["
" \"class_stop charger\"," " \"class_stop charger\","
" \"trigger late-init\"" " \"trigger late-init\""
" ]" " ]"
" }," " },"
" {" " {"
" \"name\" : \"load_persist_params_action\"," " \"name\" : \"load_persist_params_action\","
" \"cmds\" : [" " \"cmds\" : ["
" \"load_persist_params\"," " \"load_persist_params\","
" \"start logd\"," " \"start logd\","
" \"start logd-reinit\"" " \"start logd-reinit\""
" ]" " ]"
" }," " },"
" {" " {"
" \"name\" : \"firmware_mounts_complete\"," " \"name\" : \"firmware_mounts_complete\","
" \"cmds\" : [" " \"cmds\" : ["
" \"rm /dev/.booting\"" " \"rm /dev/.booting\""
" ]" " ]"
" }" " }"
"]" "]"
"}"; "}";
#endif #endif
void PrepareCmdLineHasSn() void PrepareCmdLineHasSn()
{ {
// for cmdline // for cmdline
const char *cmdLineHasSnroot = "bootgroup=device.charge.group earlycon=uart8250,mmio32,0xfe660000 " const char *cmdLineHasSnroot = "bootgroup=device.charge.group earlycon=uart8250,mmio32,0xfe660000 "
"root=PARTUUID=614e0000-0000 rw rootwait rootfstype=ext4 console=ttyFIQ0 hardware=rk3568" "root=PARTUUID=614e0000-0000 rw rootwait rootfstype=ext4 console=ttyFIQ0 hardware=rk3568"
" BOOT_IMAGE=/kernel ohos.boot.sn=/test init=/init ohos.required_mount.system=" " BOOT_IMAGE=/kernel ohos.boot.sn=/test init=/init ohos.required_mount.system="
"/dev/block/platform/soc/10100000.himci.eMMC/by-name/misc@none@none@none@wait,required"; "/dev/block/platform/soc/10100000.himci.eMMC/by-name/misc@none@none@none@wait,required";
CreateTestFile(BOOT_CMD_LINE, cmdLineHasSnroot); CreateTestFile(BOOT_CMD_LINE, cmdLineHasSnroot);
LoadParamFromCmdLine(); LoadParamFromCmdLine();
const char *cmdLineHasntSn = "bootgroup=device.charge.group earlycon=uart8250,mmio32,0xfe660000 " const char *cmdLineHasntSn = "bootgroup=device.charge.group earlycon=uart8250,mmio32,0xfe660000 "
"root=PARTUUID=614e0000-0000 rw rootwait rootfstype=ext4 console=ttyFIQ0 hardware=rk3568" "root=PARTUUID=614e0000-0000 rw rootwait rootfstype=ext4 console=ttyFIQ0 hardware=rk3568"
" BOOT_IMAGE=/kernel init=/init ohos.required_mount.system=" " BOOT_IMAGE=/kernel init=/init ohos.required_mount.system="
"/dev/block/platform/soc/10100000.himci.eMMC/by-name/misc@none@none@none@wait,required"; "/dev/block/platform/soc/10100000.himci.eMMC/by-name/misc@none@none@none@wait,required";
CreateTestFile(BOOT_CMD_LINE, cmdLineHasntSn); CreateTestFile(BOOT_CMD_LINE, cmdLineHasntSn);
} }
void PrepareInitUnitTestEnv(void) void PrepareInitUnitTestEnv(void)
{ {
static int evnOk = 0; static int evnOk = 0;
if (evnOk) { if (evnOk) {
return; return;
} }
PARAM_LOGI("PrepareInitUnitTestEnv"); PARAM_LOGI("PrepareInitUnitTestEnv");
mkdir(STARTUP_INIT_UT_PATH, S_IRWXU | S_IRWXG | S_IRWXO); mkdir(STARTUP_INIT_UT_PATH, S_IRWXU | S_IRWXG | S_IRWXO);
PrepareUeventdcfg(); PrepareUeventdcfg();
PrepareInnerKitsCfg(); PrepareInnerKitsCfg();
PrepareModCfg(); PrepareModCfg();
PrepareGroupTestCfg(); PrepareGroupTestCfg();
EnableInitLog(INIT_DEBUG); EnableInitLog(INIT_DEBUG);
#if !(defined __LITEOS_A__ || defined __LITEOS_M__) #if !(defined __LITEOS_A__ || defined __LITEOS_M__)
PrepareCmdLineHasSn(); PrepareCmdLineHasSn();
// for dac // for dac
std::string dacData = "ohos.servicectrl. = system:servicectrl:0775 \n"; std::string dacData = "ohos.servicectrl. = system:servicectrl:0775 \n";
dacData += "test.permission. = root:root:0770\n"; dacData += "test.permission. = root:root:0770\n";
dacData += "test.permission.read. = root:root:0774\n"; dacData += "test.permission.read. = root:root:0774\n";
dacData += "test.permission.write.= root:root:0772\n"; dacData += "test.permission.write.= root:root:0772\n";
dacData += "test.permission.watcher. = root:root:0771\n"; dacData += "test.permission.watcher. = root:root:0771\n";
CreateTestFile(STARTUP_INIT_UT_PATH "/system/etc/param/ohos.para.dac", dacData.c_str()); CreateTestFile(STARTUP_INIT_UT_PATH "/system/etc/param/ohos.para.dac", dacData.c_str());
CreateTestFile(STARTUP_INIT_UT_PATH"/trigger_test.cfg", g_triggerData); CreateTestFile(STARTUP_INIT_UT_PATH"/trigger_test.cfg", g_triggerData);
TestSetSelinuxOps(); TestSetSelinuxOps();
#endif #endif
InitParamService(); InitParamService();
// read system parameters // read system parameters
LoadDefaultParams("/system/etc/param/ohos_const", LOAD_PARAM_NORMAL); LoadDefaultParams("/system/etc/param/ohos_const", LOAD_PARAM_NORMAL);
LoadDefaultParams("/vendor/etc/param", LOAD_PARAM_NORMAL); LoadDefaultParams("/vendor/etc/param", LOAD_PARAM_NORMAL);
LoadDefaultParams("/system/etc/param", LOAD_PARAM_ONLY_ADD); LoadDefaultParams("/system/etc/param", LOAD_PARAM_ONLY_ADD);
// read ut parameters // read ut parameters
LoadDefaultParams(STARTUP_INIT_UT_PATH "/system/etc/param/ohos_const", LOAD_PARAM_NORMAL); 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 "/vendor/etc/param", LOAD_PARAM_NORMAL);
LoadDefaultParams(STARTUP_INIT_UT_PATH "/system/etc/param", LOAD_PARAM_ONLY_ADD); LoadDefaultParams(STARTUP_INIT_UT_PATH "/system/etc/param", LOAD_PARAM_ONLY_ADD);
LoadParamFromCfg(); LoadParamFromCfg();
evnOk = 1; evnOk = 1;
} }
int TestCheckParamPermission(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode) int TestCheckParamPermission(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode)
{ {
// DAC_RESULT_FORBIDED // DAC_RESULT_FORBIDED
return g_testPermissionResult; return g_testPermissionResult;
} }
int TestFreeLocalSecurityLabel(ParamSecurityLabel *srcLabel) int TestFreeLocalSecurityLabel(ParamSecurityLabel *srcLabel)
{ {
return 0; return 0;
} }
static __attribute__((constructor(101))) void ParamTestStubInit(void) static __attribute__((constructor(101))) void ParamTestStubInit(void)
{ {
PARAM_LOGI("ParamTestStubInit"); PARAM_LOGI("ParamTestStubInit");
PrepareInitUnitTestEnv(); PrepareInitUnitTestEnv();
} }
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
} }
#endif #endif
#endif #endif
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * 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 * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "init_param.h" #include "init_param.h"
#include "parameter.h" #include "parameter.h"
#include "sysparam_errno.h" #include "sysparam_errno.h"
#include "param_comm.h" #include "param_comm.h"
#include "param_wrapper.h" #include "param_wrapper.h"
#include "sysversion.h" #include "sysversion.h"
using namespace testing::ext; using namespace testing::ext;
extern "C" { extern "C" {
int GetIntParameter(const char *key, int def); int GetIntParameter(const char *key, int def);
} }
namespace OHOS { namespace OHOS {
class SysparaUnitTest : public testing::Test { class SysparaUnitTest : public testing::Test {
public: public:
static void SetUpTestCase() {} static void SetUpTestCase() {}
static void TearDownTestCase() {} static void TearDownTestCase() {}
void SetUp() {} void SetUp() {}
void TearDown() {} void TearDown() {}
}; };
HWTEST_F(SysparaUnitTest, parameterTest001, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest001, TestSize.Level0)
{ {
printf("Device type =%s\n", GetDeviceType()); printf("Device type =%s\n", GetDeviceType());
printf("Manufacture =%s\n", GetManufacture()); printf("Manufacture =%s\n", GetManufacture());
printf("GetBrand =%s\n", GetBrand()); printf("GetBrand =%s\n", GetBrand());
printf("MarketName =%s\n", GetMarketName()); printf("MarketName =%s\n", GetMarketName());
printf("ProductSeries =%s\n", GetProductSeries()); printf("ProductSeries =%s\n", GetProductSeries());
printf("ProductModel =%s\n", GetProductModel()); printf("ProductModel =%s\n", GetProductModel());
printf("SoftwareModel =%s\n", GetSoftwareModel()); printf("SoftwareModel =%s\n", GetSoftwareModel());
printf("HardwareModel =%s\n", GetHardwareModel()); printf("HardwareModel =%s\n", GetHardwareModel());
printf("Software profile =%s\n", GetHardwareProfile()); printf("Software profile =%s\n", GetHardwareProfile());
printf("Serial =%s\n", GetSerial()); printf("Serial =%s\n", GetSerial());
printf("OS full name =%s\n", GetOSFullName()); printf("OS full name =%s\n", GetOSFullName());
printf("OS Release type =%s\n", GetOsReleaseType()); printf("OS Release type =%s\n", GetOsReleaseType());
printf("Display version =%s\n", GetDisplayVersion()); printf("Display version =%s\n", GetDisplayVersion());
printf("bootloader version =%s\n", GetBootloaderVersion()); printf("bootloader version =%s\n", GetBootloaderVersion());
printf("secure patch level =%s\n", GetSecurityPatchTag()); printf("secure patch level =%s\n", GetSecurityPatchTag());
} }
HWTEST_F(SysparaUnitTest, parameterTest001_1, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest001_1, TestSize.Level0)
{ {
printf("secure patch level =%s\n", GetSecurityPatchTag()); printf("secure patch level =%s\n", GetSecurityPatchTag());
printf("abi list =%s\n", GetAbiList()); printf("abi list =%s\n", GetAbiList());
printf("first api version =%d\n", GetFirstApiVersion()); printf("first api version =%d\n", GetFirstApiVersion());
printf("SDK api version =%d\n", GetSdkApiVersion()); printf("SDK api version =%d\n", GetSdkApiVersion());
printf("Incremental version = %s\n", GetIncrementalVersion()); printf("Incremental version = %s\n", GetIncrementalVersion());
printf("formal id =%s\n", GetVersionId()); printf("formal id =%s\n", GetVersionId());
printf("build type =%s\n", GetBuildType()); printf("build type =%s\n", GetBuildType());
printf("build user =%s\n", GetBuildUser()); printf("build user =%s\n", GetBuildUser());
printf("Build host = %s\n", GetBuildHost()); printf("Build host = %s\n", GetBuildHost());
printf("build time =%s\n", GetBuildTime()); printf("build time =%s\n", GetBuildTime());
printf("build root later..., %s\n", GetBuildRootHash()); printf("build root later..., %s\n", GetBuildRootHash());
} }
HWTEST_F(SysparaUnitTest, parameterTest001_2, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest001_2, TestSize.Level0)
{ {
EXPECT_STRNE(GetDeviceType(), nullptr); EXPECT_STRNE(GetDeviceType(), nullptr);
EXPECT_STRNE(GetManufacture(), nullptr); EXPECT_STRNE(GetManufacture(), nullptr);
EXPECT_STRNE(GetBrand(), nullptr); EXPECT_STRNE(GetBrand(), nullptr);
EXPECT_STRNE(GetMarketName(), nullptr); EXPECT_STRNE(GetMarketName(), nullptr);
EXPECT_STRNE(GetProductSeries(), nullptr); EXPECT_STRNE(GetProductSeries(), nullptr);
EXPECT_STRNE(GetProductModel(), nullptr); EXPECT_STRNE(GetProductModel(), nullptr);
EXPECT_STRNE(GetSoftwareModel(), nullptr); EXPECT_STRNE(GetSoftwareModel(), nullptr);
EXPECT_STRNE(GetHardwareModel(), nullptr); EXPECT_STRNE(GetHardwareModel(), nullptr);
EXPECT_STRNE(GetHardwareProfile(), nullptr); EXPECT_STRNE(GetHardwareProfile(), nullptr);
EXPECT_STRNE(GetOSFullName(), nullptr); EXPECT_STRNE(GetOSFullName(), nullptr);
EXPECT_STRNE(GetOsReleaseType(), nullptr); EXPECT_STRNE(GetOsReleaseType(), nullptr);
EXPECT_STRNE(GetDisplayVersion(), nullptr); EXPECT_STRNE(GetDisplayVersion(), nullptr);
EXPECT_STRNE(GetBootloaderVersion(), nullptr); EXPECT_STRNE(GetBootloaderVersion(), nullptr);
EXPECT_STRNE(GetSecurityPatchTag(), nullptr); EXPECT_STRNE(GetSecurityPatchTag(), nullptr);
} }
HWTEST_F(SysparaUnitTest, parameterTest001_3, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest001_3, TestSize.Level0)
{ {
EXPECT_STRNE(GetSecurityPatchTag(), nullptr); EXPECT_STRNE(GetSecurityPatchTag(), nullptr);
EXPECT_STRNE(GetAbiList(), nullptr); EXPECT_STRNE(GetAbiList(), nullptr);
EXPECT_GT(GetFirstApiVersion(), 0); EXPECT_GT(GetFirstApiVersion(), 0);
EXPECT_GT(GetSdkApiVersion(), 0); EXPECT_GT(GetSdkApiVersion(), 0);
EXPECT_STRNE(GetIncrementalVersion(), nullptr); EXPECT_STRNE(GetIncrementalVersion(), nullptr);
EXPECT_STRNE(GetVersionId(), nullptr); EXPECT_STRNE(GetVersionId(), nullptr);
EXPECT_STRNE(GetBuildType(), nullptr); EXPECT_STRNE(GetBuildType(), nullptr);
EXPECT_STRNE(GetBuildUser(), nullptr); EXPECT_STRNE(GetBuildUser(), nullptr);
EXPECT_STRNE(GetBuildHost(), nullptr); EXPECT_STRNE(GetBuildHost(), nullptr);
EXPECT_STRNE(GetBuildTime(), nullptr); EXPECT_STRNE(GetBuildTime(), nullptr);
EXPECT_STRNE(GetBuildRootHash(), nullptr); EXPECT_STRNE(GetBuildRootHash(), nullptr);
} }
HWTEST_F(SysparaUnitTest, parameterTest002, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest002, TestSize.Level0)
{ {
char key1[] = "test.ro.sys.version"; char key1[] = "test.ro.sys.version";
char value1[] = "set read only key"; char value1[] = "set read only key";
int ret = SetParameter(key1, value1); int ret = SetParameter(key1, value1);
EXPECT_EQ(ret, EC_SUCCESS); EXPECT_EQ(ret, EC_SUCCESS);
} }
HWTEST_F(SysparaUnitTest, parameterTest003, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest003, TestSize.Level0)
{ {
char key2[] = "rw.sys.version*%version"; char key2[] = "rw.sys.version*%version";
char value2[] = "set value with illegal key"; char value2[] = "set value with illegal key";
int ret = SetParameter(key2, value2); int ret = SetParameter(key2, value2);
EXPECT_EQ(ret, EC_FAILURE); EXPECT_EQ(ret, EC_FAILURE);
} }
/* key = 32 */ /* key = 32 */
HWTEST_F(SysparaUnitTest, parameterTest004, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest004, TestSize.Level0)
{ {
char key3[] = "rw.sys.version.utilskvparameter0"; char key3[] = "rw.sys.version.utilskvparameter0";
char value3[] = "set with key = 32"; char value3[] = "set with key = 32";
int ret = SetParameter(key3, value3); int ret = SetParameter(key3, value3);
EXPECT_EQ(ret, EC_SUCCESS); EXPECT_EQ(ret, EC_SUCCESS);
} }
/* value > 128 */ /* value > 128 */
HWTEST_F(SysparaUnitTest, parameterTest005, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest005, TestSize.Level0)
{ {
char key4[] = "rw.sys.version.version"; char key4[] = "rw.sys.version.version";
char value4[] = "rw.sys.version.version.version.version flash_offset = *(hi_u32 *)DT_SetGetU32(&g_Element[0], 0)a\ char value4[] = "rw.sys.version.version.version.version flash_offset = *(hi_u32 *)DT_SetGetU32(&g_Element[0], 0)a\
size = *(hi_u32 *)DT_SetGetU32(&g_Element[1], 0)a"; size = *(hi_u32 *)DT_SetGetU32(&g_Element[1], 0)a";
int ret = SetParameter(key4, value4); int ret = SetParameter(key4, value4);
EXPECT_EQ(ret, EC_FAILURE); EXPECT_EQ(ret, EC_FAILURE);
} }
HWTEST_F(SysparaUnitTest, parameterTest006, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest006, TestSize.Level0)
{ {
char key1[] = "rw.product.not.exist"; char key1[] = "rw.product.not.exist";
char value1[64] = {0}; char value1[64] = {0};
char defValue1[] = "value of key not exist..."; char defValue1[] = "value of key not exist...";
int ret = GetParameter(key1, defValue1, value1, 64); int ret = GetParameter(key1, defValue1, value1, 64);
EXPECT_EQ(ret, static_cast<int>(strlen(defValue1))); EXPECT_EQ(ret, static_cast<int>(strlen(defValue1)));
} }
HWTEST_F(SysparaUnitTest, parameterTest007, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest007, TestSize.Level0)
{ {
char key2[] = "rw.sys.version.version.version.version"; char key2[] = "rw.sys.version.version.version.version";
char value2[64] = {0}; char value2[64] = {0};
char defValue2[] = "value of key > 32 ..."; char defValue2[] = "value of key > 32 ...";
int ret = GetParameter(key2, defValue2, value2, 64); int ret = GetParameter(key2, defValue2, value2, 64);
EXPECT_EQ(ret, static_cast<int>(strlen(defValue2))); EXPECT_EQ(ret, static_cast<int>(strlen(defValue2)));
} }
HWTEST_F(SysparaUnitTest, parameterTest008, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest008, TestSize.Level0)
{ {
char key4[] = "test.rw.sys.version"; char key4[] = "test.rw.sys.version";
char* value4 = nullptr; char* value4 = nullptr;
char defValue3[] = "value of key > 32 ..."; char defValue3[] = "value of key > 32 ...";
int ret = GetParameter(key4, defValue3, value4, 0); int ret = GetParameter(key4, defValue3, value4, 0);
EXPECT_EQ(ret, EC_INVALID); EXPECT_EQ(ret, EC_INVALID);
} }
HWTEST_F(SysparaUnitTest, parameterTest009, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest009, TestSize.Level0)
{ {
char key5[] = "test.rw.product.type.2222222"; char key5[] = "test.rw.product.type.2222222";
char value5[] = "rw.sys.version.version.version.version \ char value5[] = "rw.sys.version.version.version.version \
flash_offset = *(hi_u32 *)DT_SetGetU32(&g_Element[0], 0)"; flash_offset = *(hi_u32 *)DT_SetGetU32(&g_Element[0], 0)";
int ret = SetParameter(key5, value5); int ret = SetParameter(key5, value5);
EXPECT_EQ(ret, EC_FAILURE); EXPECT_EQ(ret, EC_FAILURE);
char valueGet[2] = {0}; char valueGet[2] = {0};
char defValue3[] = "value of key > 32 ..."; char defValue3[] = "value of key > 32 ...";
ret = GetParameter(key5, defValue3, valueGet, 2); ret = GetParameter(key5, defValue3, valueGet, 2);
EXPECT_EQ(ret, EC_INVALID); EXPECT_EQ(ret, EC_INVALID);
} }
HWTEST_F(SysparaUnitTest, parameterTest0010, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest0010, TestSize.Level0)
{ {
char key1[] = "test.rw.sys.version"; char key1[] = "test.rw.sys.version";
char value1[] = "10.1.0"; char value1[] = "10.1.0";
int ret = SetParameter(key1, value1); int ret = SetParameter(key1, value1);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = SystemWriteParam(key1, value1); ret = SystemWriteParam(key1, value1);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
char valueGet1[32] = {0}; char valueGet1[32] = {0};
ret = GetParameter(key1, "version=10.1.0", valueGet1, 32); ret = GetParameter(key1, "version=10.1.0", valueGet1, 32);
EXPECT_EQ(ret, static_cast<int>(strlen(valueGet1))); EXPECT_EQ(ret, static_cast<int>(strlen(valueGet1)));
char key2[] = "test.rw.product.type"; char key2[] = "test.rw.product.type";
char value2[] = "wifi_iot"; char value2[] = "wifi_iot";
ret = SetParameter(key2, value2); ret = SetParameter(key2, value2);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = SystemWriteParam(key2, value2); ret = SystemWriteParam(key2, value2);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
char valueGet2[32] = {0}; char valueGet2[32] = {0};
ret = GetParameter(key2, "version=10.1.0", valueGet2, 32); ret = GetParameter(key2, "version=10.1.0", valueGet2, 32);
EXPECT_EQ(ret, static_cast<int>(strlen(valueGet2))); EXPECT_EQ(ret, static_cast<int>(strlen(valueGet2)));
char key3[] = "test.rw.product.manufacturer"; char key3[] = "test.rw.product.manufacturer";
char value3[] = "TEST MANUFACTURER"; char value3[] = "TEST MANUFACTURER";
ret = SetParameter(key3, value3); ret = SetParameter(key3, value3);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = SystemWriteParam(key3, value3); ret = SystemWriteParam(key3, value3);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
char valueGet3[32] = {0}; char valueGet3[32] = {0};
ret = GetParameter(key3, "version=10.1.0", valueGet3, 32); ret = GetParameter(key3, "version=10.1.0", valueGet3, 32);
EXPECT_EQ(ret, static_cast<int>(strlen(valueGet3))); EXPECT_EQ(ret, static_cast<int>(strlen(valueGet3)));
char key4[] = "test.rw.product.marketname"; char key4[] = "test.rw.product.marketname";
char value4[] = "TEST MARKETNAME"; char value4[] = "TEST MARKETNAME";
ret = SetParameter(key4, value4); ret = SetParameter(key4, value4);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = SystemWriteParam(key4, value4); ret = SystemWriteParam(key4, value4);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
char valueGet4[32] = {0}; char valueGet4[32] = {0};
ret = GetParameter(key4, "version=10.1.0", valueGet4, 32); ret = GetParameter(key4, "version=10.1.0", valueGet4, 32);
EXPECT_EQ(ret, static_cast<int>(strlen(valueGet4))); EXPECT_EQ(ret, static_cast<int>(strlen(valueGet4)));
} }
HWTEST_F(SysparaUnitTest, parameterTest0011, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest0011, TestSize.Level0)
{ {
char key1[] = "test.rw.sys.version.wait1"; char key1[] = "test.rw.sys.version.wait1";
char value1[] = "10.1.0"; char value1[] = "10.1.0";
int ret = SetParameter(key1, value1); int ret = SetParameter(key1, value1);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = SystemWriteParam(key1, value1); ret = SystemWriteParam(key1, value1);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = WaitParameter(key1, value1, 10); ret = WaitParameter(key1, value1, 10);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = WaitParameter(key1, "*", 10); ret = WaitParameter(key1, "*", 10);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
char key2[] = "test.rw.sys.version.wait2"; char key2[] = "test.rw.sys.version.wait2";
ret = WaitParameter(key2, "*", 1); ret = WaitParameter(key2, "*", 1);
EXPECT_EQ(ret, 105); EXPECT_EQ(ret, 105);
} }
HWTEST_F(SysparaUnitTest, parameterTest0012, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest0012, TestSize.Level0)
{ {
char key1[] = "test.rw.sys.version.version1"; char key1[] = "test.rw.sys.version.version1";
char value1[] = "10.1.0"; char value1[] = "10.1.0";
int ret = SetParameter(key1, value1); int ret = SetParameter(key1, value1);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = SystemWriteParam(key1, value1); ret = SystemWriteParam(key1, value1);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
// success // success
unsigned int handle = FindParameter(key1); unsigned int handle = FindParameter(key1);
EXPECT_NE(handle, static_cast<unsigned int>(-1)); EXPECT_NE(handle, static_cast<unsigned int>(-1));
char valueGet1[32] = {0}; char valueGet1[32] = {0};
ret = GetParameterValue(handle, valueGet1, 32); ret = GetParameterValue(handle, valueGet1, 32);
EXPECT_EQ(ret, static_cast<int>(strlen(valueGet1))); EXPECT_EQ(ret, static_cast<int>(strlen(valueGet1)));
char nameGet1[32] = {0}; char nameGet1[32] = {0};
ret = GetParameterName(handle, nameGet1, 32); ret = GetParameterName(handle, nameGet1, 32);
EXPECT_EQ(ret, static_cast<int>(strlen(nameGet1))); EXPECT_EQ(ret, static_cast<int>(strlen(nameGet1)));
// fail // fail
char key2[] = "test.rw.sys.version.version2"; char key2[] = "test.rw.sys.version.version2";
handle = FindParameter(key2); handle = FindParameter(key2);
EXPECT_EQ(handle, static_cast<unsigned int>(-1)); EXPECT_EQ(handle, static_cast<unsigned int>(-1));
ret = GetParameterValue(handle, valueGet1, 32); ret = GetParameterValue(handle, valueGet1, 32);
EXPECT_EQ(ret, -1); EXPECT_EQ(ret, -1);
ret = GetParameterName(handle, nameGet1, 32); ret = GetParameterName(handle, nameGet1, 32);
EXPECT_EQ(ret, -1); EXPECT_EQ(ret, -1);
} }
HWTEST_F(SysparaUnitTest, parameterTest0013, TestSize.Level0) HWTEST_F(SysparaUnitTest, parameterTest0013, TestSize.Level0)
{ {
long long int out = 0; long long int out = 0;
unsigned long long int uout = 0; unsigned long long int uout = 0;
char key1[] = "test.int"; char key1[] = "test.int";
char value1[] = "101"; char value1[] = "101";
int ret = SetParameter(key1, value1); int ret = SetParameter(key1, value1);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
GetParameter_(nullptr, nullptr, nullptr, 0); GetParameter_(nullptr, nullptr, nullptr, 0);
EXPECT_EQ(GetIntParameter(key1, 0), 0); EXPECT_EQ(GetIntParameter(key1, 0), 0);
EXPECT_EQ(IsValidParamValue(nullptr, 0), 0); EXPECT_EQ(IsValidParamValue(nullptr, 0), 0);
EXPECT_EQ(IsValidParamValue("testvalue", strlen("testvalue") + 1), 1); EXPECT_EQ(IsValidParamValue("testvalue", strlen("testvalue") + 1), 1);
EXPECT_EQ(StringToLL("0x11", &out), 0); EXPECT_EQ(StringToLL("0x11", &out), 0);
EXPECT_EQ(StringToULL("0x11", &uout), 0); EXPECT_EQ(StringToULL("0x11", &uout), 0);
EXPECT_EQ(StringToLL("not vailed", &out), -1); EXPECT_EQ(StringToLL("not vailed", &out), -1);
EXPECT_EQ(StringToULL("not vailed", &uout), -1); EXPECT_EQ(StringToULL("not vailed", &uout), -1);
SystemSetParameter("ohos.boot.sn", "1"); SystemSetParameter("ohos.boot.sn", "1");
char udid[UDID_LEN] = {0}; char udid[UDID_LEN] = {0};
ret = GetDevUdid(udid, UDID_LEN); ret = GetDevUdid(udid, UDID_LEN);
EXPECT_NE(ret, -1); EXPECT_NE(ret, -1);
EXPECT_NE(GetMajorVersion(), 0); EXPECT_NE(GetMajorVersion(), 0);
GetSeniorVersion(); GetSeniorVersion();
GetFeatureVersion(); GetFeatureVersion();
GetBuildVersion(); GetBuildVersion();
} }
} // namespace OHOS } // namespace OHOS
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册