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