diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index eadcdfe5603ce2a7b13f7783f58f8e9a69780d84..f000b6dd433d9ea5f2a58de6a7e27d5ea84daaee 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -19,9 +19,12 @@ group("unittest") { testonly = true deps = [ + ":UTTest_advertise_manager", + ":UTTest_app_manager", ":UTTest_auth_message_processor", ":UTTest_auth_request_state", ":UTTest_auth_response_state", + ":UTTest_crypto_mgr", ":UTTest_device_manager_impl", ":UTTest_device_manager_notify", ":UTTest_device_manager_service", @@ -30,6 +33,7 @@ group("unittest") { ":UTTest_device_manager_service_listener", ":UTTest_device_manager_service_notify", ":UTTest_device_manager_service_three", + ":UTTest_device_name_manager", ":UTTest_discovery_filter", ":UTTest_discovery_manager", ":UTTest_dm_account_common_event", @@ -1794,6 +1798,115 @@ ohos_unittest("UTTest_kv_adapter_manager") { ## UnitTest UTTest_kv_adapter_manager }}} +## UnitTest UTTest_app_manager {{{ +ohos_unittest("UTTest_app_manager") { + module_out_path = module_out_path + + include_dirs = [ + "${devicemanager_path}/commondependency/include", + "${devicemanager_path}/test/commonunittest", + ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_app_manager.cpp", + "${devicemanager_path}/test/unittest/mock/accesstoken_kit_mock.cpp", + "${devicemanager_path}/test/unittest/mock/ipc_skeleton_mock.cpp", + "${devicemanager_path}/test/unittest/mock/os_account_manager_mock.cpp", + "${devicemanager_path}/test/unittest/mock/system_ability_manager_client_mock.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "eventhandler:libeventhandler", + "googletest:gmock", + "googletest:gmock_main", + "os_account:libaccountkits", + "os_account:os_account_innerkits", + ] +} + +## UnitTest UTTest_app_manager }}} + +## UnitTest UTTest_crypto_mgr {{{ +ohos_unittest("UTTest_crypto_mgr") { + module_out_path = module_out_path + + include_dirs = [ + "${devicemanager_path}/commondependency/include", + "${devicemanager_path}/test/commonunittest", + ] + + sources = [ "${devicemanager_path}/test/unittest/UTTest_crypto_mgr.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_crypto_mgr }}} + +## UnitTest UTTest_device_name_manager {{{ +ohos_unittest("UTTest_device_name_manager") { + module_out_path = module_out_path + + include_dirs = [ + "${devicemanager_path}/commondependency/include", + "${devicemanager_path}/test/commonunittest", + ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_device_name_manager.cpp", + "${devicemanager_path}/test/unittest/mock/datashare_helper_mock.cpp", + "${devicemanager_path}/test/unittest/mock/datashare_result_set_mock.cpp", + "${devicemanager_path}/test/unittest/mock/multiple_user_connector_mock.cpp", + "${devicemanager_path}/test/unittest/mock/system_ability_manager_client_mock.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "cJSON:cjson", + "data_share:datashare_common", + "data_share:datashare_consumer", + "googletest:gmock", + "googletest:gmock_main", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +## UnitTest UTTest_device_name_manager }}} + +## UnitTest UTTest_advertise_manager {{{ +ohos_unittest("UTTest_advertise_manager") { + module_out_path = module_out_path + + include_dirs = [ + "${ext_path}/pin_auth/include/standard", + "${devicemanager_path}/test/unittest", + ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_advertise_manager.cpp", + "mock/softbus_bus_center.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "cJSON:cjson", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "googletest:gmock", + ] +} + +## UnitTest UTTest_advertise_manager }}} + ## Build device_manager_test_common.a {{{ config("device_manager_test_common_public_config") { include_dirs = [ diff --git a/test/unittest/UTTest_advertise_manager.cpp b/test/unittest/UTTest_advertise_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d11c0e7cd68c9f780dbacc8478b9cecc975b3496 --- /dev/null +++ b/test/unittest/UTTest_advertise_manager.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2025 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 "UTTest_advertise_manager.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +constexpr int32_t VALUABLE_PUBLISH_ID = 10; +constexpr int32_t DEFAULT_META_TYPE = 10; +constexpr int32_t DEFAULT_DISC_MODE = 20; +constexpr int32_t DEFAULT_DISC_FREQ = 30; +const std::string PKG_NAME = "pkgName"; +const std::string DEFAULT_CUSTOM_DATA = "CUSTOM_DATA"; +} // namespace +void AdvertiseManagerTest::SetUp() +{} + +void AdvertiseManagerTest::TearDown() +{} + +void AdvertiseManagerTest::SetUpTestCase() +{} + +void AdvertiseManagerTest::TearDownTestCase() +{} + +HWTEST_F(AdvertiseManagerTest, StartAdvertising_001, testing::ext::TestSize.Level0) +{ + std::string stopTime = std::to_string(100); + auto softbusListener = std::make_shared(); + auto advertiseManager = std::make_shared(softbusListener); + + std::map advertiseParam; + advertiseParam[PARAM_KEY_DISC_CAPABILITY] = DM_CAPABILITY_APPROACH; + advertiseParam[PARAM_KEY_CUSTOM_DATA] = DEFAULT_CUSTOM_DATA; + advertiseParam[PARAM_KEY_AUTO_STOP_ADVERTISE] = stopTime; + advertiseParam[PARAM_KEY_META_TYPE] = std::to_string(DEFAULT_META_TYPE); + advertiseParam[PARAM_KEY_PUBLISH_ID] = std::to_string(VALUABLE_PUBLISH_ID); + advertiseParam[PARAM_KEY_DISC_MODE] = std::to_string(DEFAULT_DISC_MODE); + advertiseParam[PARAM_KEY_DISC_FREQ] = std::to_string(DEFAULT_DISC_FREQ); + auto ret = advertiseManager->StartAdvertising(PKG_NAME, advertiseParam); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(AdvertiseManagerTest, StartAdvertising_002, testing::ext::TestSize.Level0) +{ + std::string stopTime = std::to_string(-5); + auto softbusListener = std::make_shared(); + auto advertiseManager = std::make_shared(softbusListener); + + std::map advertiseParam; + advertiseParam[PARAM_KEY_DISC_CAPABILITY] = DM_CAPABILITY_APPROACH; + advertiseParam[PARAM_KEY_CUSTOM_DATA] = DEFAULT_CUSTOM_DATA; + advertiseParam[PARAM_KEY_AUTO_STOP_ADVERTISE] = stopTime; + advertiseParam[PARAM_KEY_META_TYPE] = std::to_string(DEFAULT_META_TYPE); + advertiseParam[PARAM_KEY_PUBLISH_ID] = std::to_string(VALUABLE_PUBLISH_ID); + advertiseParam[PARAM_KEY_DISC_MODE] = std::to_string(DEFAULT_DISC_MODE); + advertiseParam[PARAM_KEY_DISC_FREQ] = std::to_string(DEFAULT_DISC_FREQ); + auto ret = advertiseManager->StartAdvertising(PKG_NAME, advertiseParam); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(AdvertiseManagerTest, StartAdvertising_003, testing::ext::TestSize.Level2) +{ + std::string emptyPackageName; + std::string stopTime = std::to_string(100); + auto softbusListener = std::make_shared(); + auto advertiseManager = std::make_shared(softbusListener); + + std::map advertiseParam; + advertiseParam[PARAM_KEY_DISC_CAPABILITY] = DM_CAPABILITY_APPROACH; + advertiseParam[PARAM_KEY_CUSTOM_DATA] = DEFAULT_CUSTOM_DATA; + advertiseParam[PARAM_KEY_AUTO_STOP_ADVERTISE] = stopTime; + advertiseParam[PARAM_KEY_META_TYPE] = std::to_string(DEFAULT_META_TYPE); + advertiseParam[PARAM_KEY_PUBLISH_ID] = std::to_string(VALUABLE_PUBLISH_ID); + advertiseParam[PARAM_KEY_DISC_MODE] = std::to_string(DEFAULT_DISC_MODE); + advertiseParam[PARAM_KEY_DISC_FREQ] = std::to_string(DEFAULT_DISC_FREQ); + auto ret = advertiseManager->StartAdvertising(emptyPackageName, advertiseParam); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(AdvertiseManagerTest, HandleAutoStopAdvertise_001, testing::ext::TestSize.Level0) +{ + auto softbusListener = std::make_shared(); + auto advertiseManager = std::make_shared(softbusListener); + std::string timerName = "timer"; + advertiseManager->HandleAutoStopAdvertise(timerName, PKG_NAME, VALUABLE_PUBLISH_ID); + ASSERT_TRUE(advertiseManager->softbusListener_ != nullptr); +} + +HWTEST_F(AdvertiseManagerTest, StopAdvertising_001, testing::ext::TestSize.Level2) +{ + std::string emptyPackageName; + auto softbusListener = std::make_shared(); + auto advertiseManager = std::make_shared(softbusListener); + auto ret = advertiseManager->StopAdvertising(emptyPackageName, VALUABLE_PUBLISH_ID); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(AdvertiseManagerTest, StopAdvertising_002, testing::ext::TestSize.Level0) +{ + auto softbusListener = std::make_shared(); + auto advertiseManager = std::make_shared(softbusListener); + auto innerPublishId = advertiseManager->GenInnerPublishId(PKG_NAME, VALUABLE_PUBLISH_ID); + auto ret = advertiseManager->StopAdvertising(PKG_NAME, VALUABLE_PUBLISH_ID); + EXPECT_EQ(ret, DM_OK); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_advertise_manager.h b/test/unittest/UTTest_advertise_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..2f573015ea429e82e7957ac02ab38c0a346cccd0 --- /dev/null +++ b/test/unittest/UTTest_advertise_manager.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 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. + */ + +#ifndef OHOS_DM_ADVERTISE_MANAGER_TEST_H +#define OHOS_DM_ADVERTISE_MANAGER_TEST_H + +#include +#include "advertise_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class AdvertiseManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_ADVERTISE_MANAGER_TEST_H diff --git a/test/unittest/UTTest_app_manager.cpp b/test/unittest/UTTest_app_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93de659a83e582d1dac4f9e6319bbebdbe42a680 --- /dev/null +++ b/test/unittest/UTTest_app_manager.cpp @@ -0,0 +1,337 @@ +/* + * Copyright (c) 2025 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 "UTTest_app_manager.h" +#include "bundle_mgr_mock.h" +#include "dm_constants.h" +#include "dm_system_ability_manager_mock.h" + +using namespace OHOS::AppExecFwk; +using namespace testing; + +namespace OHOS { +namespace DistributedHardware { +namespace { +constexpr size_t ARG_THIRD = 2; +constexpr size_t INVOKE_COUNT = 1; +constexpr size_t ERR_FAILED_VALUE = 11600101; +constexpr uint32_t VALUABLE_TOKEN_ID = 153; +constexpr uint32_t UNVALUABLE_TOKEN_ID = 0; +} // namespace +void AppManagerTest::SetUp() +{ + auto skeleton = IPCSkeletonInterface::GetOrCreateIPCSkeleton(); + skeleton_ = std::static_pointer_cast(skeleton); + auto token = AccessTokenKitInterface::GetOrCreateAccessTokenKit(); + token_ = std::static_pointer_cast(token); + auto client = ISystemAbilityManagerClient::GetOrCreateSAMgrClient(); + client_ = std::static_pointer_cast(client); + auto accountManager = IOsAccountManager::GetOrCreateOsAccountManager(); + accountManager_ = std::static_pointer_cast(accountManager); +} + +void AppManagerTest::TearDown() +{ + IPCSkeletonInterface::ReleaseIPCSkeleton(); + AccessTokenKitInterface::ReleaseAccessTokenKit(); + ISystemAbilityManagerClient::ReleaseSAMgrClient(); + IOsAccountManager::ReleaseAccountManager(); + skeleton_ = nullptr; + token_ = nullptr; + client_ = nullptr; + accountManager_ = nullptr; +} + +void AppManagerTest::SetUpTestCase() +{} + +void AppManagerTest::TearDownTestCase() +{} + +HWTEST_F(AppManagerTest, RegisterCallerAppId_success_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(skeleton_ != nullptr); + ASSERT_TRUE(token_ != nullptr); + ASSERT_TRUE(client_ != nullptr); + ASSERT_TRUE(accountManager_ != nullptr); + + EXPECT_CALL(*skeleton_, GetCallingTokenID()) + .Times(INVOKE_COUNT) + .WillOnce(Return(VALUABLE_TOKEN_ID)); + EXPECT_CALL(*skeleton_, GetCallingUid()) + .Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*token_, GetTokenTypeFlag(_)) + .Times(INVOKE_COUNT) + .WillOnce(Return(ATokenTypeEnum::TOKEN_HAP)); + auto bundleMgr = sptr(new (std::nothrow) BundleMgrMock()); + auto systemAbilityManager = sptr(new (std::nothrow) SystemAbilityManagerMock()); + EXPECT_CALL(*systemAbilityManager, GetSystemAbility(_)) + .Times(INVOKE_COUNT) + .WillOnce(Return(bundleMgr)); + EXPECT_CALL(*client_, GetSystemAbilityManager()) + .Times(INVOKE_COUNT) + .WillOnce(Return(systemAbilityManager)); + EXPECT_CALL(*accountManager_, GetForegroundOsAccountLocalId(_)) + .Times(INVOKE_COUNT) + .WillOnce(Return(ERR_OK)); + EXPECT_CALL(*bundleMgr, GetNameForUid(_, _)) + .Times(INVOKE_COUNT) + .WillOnce(Return(ERR_OK)); + BundleInfo bundleInfo; + bundleInfo.appId = "mock_appId"; + EXPECT_CALL(*bundleMgr, GetBundleInfoV9(_, _, _, _)) + .Times(INVOKE_COUNT) + .WillOnce(DoAll(SetArgReferee(bundleInfo), Return(ERR_OK))); + std::string packageName = "packageName"; + AppManager::GetInstance().RegisterCallerAppId(packageName); + + std::string appId; + auto result = AppManager::GetInstance().GetAppIdByPkgName(packageName, appId); + EXPECT_EQ(result, DM_OK); + EXPECT_STREQ(bundleInfo.appId.c_str(), appId.c_str()); + AppManager::GetInstance().UnRegisterCallerAppId(packageName); +} + +HWTEST_F(AppManagerTest, RegisterCallerAppId_failed_001, testing::ext::TestSize.Level2) +{ + ASSERT_TRUE(skeleton_ != nullptr); + ASSERT_TRUE(token_ != nullptr); + + std::string emptyPackageName; + std::string appId; + AppManager::GetInstance().RegisterCallerAppId(emptyPackageName); + AppManager::GetInstance().GetAppIdByPkgName(emptyPackageName, appId); + AppManager::GetInstance().UnRegisterCallerAppId(emptyPackageName); + + EXPECT_CALL(*skeleton_, GetCallingTokenID()) + .Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*token_, GetTokenTypeFlag(_)) + .Times(INVOKE_COUNT) + .WillOnce(Return(ATokenTypeEnum::TOKEN_NATIVE)); + std::string packageName = "packageName"; + AppManager::GetInstance().RegisterCallerAppId(packageName); + auto result = AppManager::GetInstance().GetAppIdByPkgName(packageName, appId); + EXPECT_EQ(result, ERR_DM_FAILED); + AppManager::GetInstance().UnRegisterCallerAppId(packageName); +} + +HWTEST_F(AppManagerTest, GetAppId_001, testing::ext::TestSize.Level2) +{ + ASSERT_TRUE(skeleton_ != nullptr); + ASSERT_TRUE(token_ != nullptr); + ASSERT_TRUE(client_ != nullptr); + ASSERT_TRUE(accountManager_ != nullptr); + + EXPECT_CALL(*skeleton_, GetCallingTokenID()).Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*skeleton_, GetCallingUid()).Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*token_, GetTokenTypeFlag(_)).WillRepeatedly(Return(ATokenTypeEnum::TOKEN_HAP)); + + auto bundleMgr = sptr(new (std::nothrow) BundleMgrMock()); + auto systemAbilityManager = sptr(new (std::nothrow) SystemAbilityManagerMock()); + size_t getSAMgrcallCount = 0; + size_t getSACallCount = 0; + size_t getForegroundOsAccountLocalIdCallCount = 0; + size_t getBInfoCallCount = 0; + ON_CALL(*client_, GetSystemAbilityManager()) + .WillByDefault(Invoke([&getSAMgrcallCount, systemAbilityManager]() -> sptr { + return (getSAMgrcallCount++ == 0) ? nullptr : systemAbilityManager; + })); + ON_CALL(*systemAbilityManager, GetSystemAbility(_)) + .WillByDefault(Invoke([&getSACallCount, bundleMgr](int32_t) -> sptr { + return (getSACallCount++ == 0) ? nullptr : bundleMgr; + })); + ON_CALL(*accountManager_, GetForegroundOsAccountLocalId(_)) + .WillByDefault(Invoke([&getForegroundOsAccountLocalIdCallCount](int32_t &) -> ErrCode { + return (getForegroundOsAccountLocalIdCallCount++ == 0) ? ERR_FAILED_VALUE : ERR_OK; + })); + ON_CALL(*bundleMgr, GetBundleInfoV9(_, _, _, _)) + .WillByDefault(Invoke([&getBInfoCallCount](const std::string &, int32_t, BundleInfo &, int32_t) -> ErrCode { + return (getBInfoCallCount++ == 0) ? ERR_FAILED_VALUE : ERR_OK; + })); + EXPECT_CALL(*client_, GetSystemAbilityManager()).Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*systemAbilityManager, GetSystemAbility(_)).Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*accountManager_, GetForegroundOsAccountLocalId(_)).Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*bundleMgr, GetNameForUid(_, _)).Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*bundleMgr, GetBundleInfoV9(_, _, _, _)).Times(AtLeast(INVOKE_COUNT)); + for (size_t i = 0; i < 5; ++i) { + auto appId = AppManager::GetInstance().GetAppId(); + EXPECT_TRUE(appId.empty()); + } +} + +HWTEST_F(AppManagerTest, IsSystemSA_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(skeleton_ != nullptr); + ASSERT_TRUE(token_ != nullptr); + size_t getCallingTokenIDCallCount = 0; + size_t getTokenTypeFlagCallCount = 0; + + ON_CALL(*skeleton_, GetCallingTokenID()) + .WillByDefault(Invoke([&getCallingTokenIDCallCount]() { + return (getCallingTokenIDCallCount++ == 0) ? UNVALUABLE_TOKEN_ID : VALUABLE_TOKEN_ID; + })); + ON_CALL(*token_, GetTokenTypeFlag(_)) + .WillByDefault(Invoke([&getTokenTypeFlagCallCount](AccessTokenID) -> ATokenTypeEnum { + return (getTokenTypeFlagCallCount++ == 0) ? ATokenTypeEnum::TOKEN_HAP : ATokenTypeEnum::TOKEN_NATIVE; + })); + EXPECT_CALL(*skeleton_, GetCallingTokenID()).Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*token_, GetTokenTypeFlag(_)).Times(AtLeast(INVOKE_COUNT)); + for (size_t i = 0; i < 3; ++i) { + auto ret = AppManager::GetInstance().IsSystemSA(); + if (getCallingTokenIDCallCount > 1 && getTokenTypeFlagCallCount > 1) { + EXPECT_TRUE(ret); + } else { + EXPECT_FALSE(ret); + } + } +} + +HWTEST_F(AppManagerTest, GetCallerName_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(skeleton_ != nullptr); + ASSERT_TRUE(token_ != nullptr); + size_t getCallingTokenIDCallCount = 0; + size_t getHapTokenInfoCallCount = 0; + + ON_CALL(*skeleton_, GetCallingTokenID()) + .WillByDefault(Invoke([&getCallingTokenIDCallCount]() { + return (getCallingTokenIDCallCount++ == 0) ? UNVALUABLE_TOKEN_ID : VALUABLE_TOKEN_ID; + })); + ON_CALL(*token_, GetHapTokenInfo(_, _)) + .WillByDefault(Invoke([&getHapTokenInfoCallCount](AccessTokenID, HapTokenInfo &) { + return (getHapTokenInfoCallCount++ == 0) ? ERR_FAILED_VALUE : ERR_OK; + })); + EXPECT_CALL(*skeleton_, GetCallingTokenID()).Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*token_, GetTokenTypeFlag(_)).WillRepeatedly(Return(ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token_, GetHapTokenInfo(_, _)).Times(AtLeast(INVOKE_COUNT)); + for (size_t i = 0; i < 3; ++i) { + bool isSystemSA = false; + std::string output; + auto ret = AppManager::GetInstance().GetCallerName(isSystemSA, output); + if (getCallingTokenIDCallCount > 1 && getHapTokenInfoCallCount > 1) { + EXPECT_EQ(ret, DM_OK); + } else { + EXPECT_EQ(ret, ERR_DM_FAILED); + } + } +} + +HWTEST_F(AppManagerTest, GetCallerName_002, testing::ext::TestSize.Level2) +{ + ASSERT_TRUE(skeleton_ != nullptr); + ASSERT_TRUE(token_ != nullptr); + + EXPECT_CALL(*skeleton_, GetCallingTokenID()).WillRepeatedly(Return(VALUABLE_TOKEN_ID)); + EXPECT_CALL(*token_, GetTokenTypeFlag(_)).WillOnce(Return(ATokenTypeEnum::TOKEN_NATIVE)); + EXPECT_CALL(*token_, GetNativeTokenInfo(_, _)).WillOnce(Return(ERR_FAILED_VALUE)); + bool isSystemSA = true; + std::string output; + auto ret = AppManager::GetInstance().GetCallerName(isSystemSA, output); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*token_, GetTokenTypeFlag(_)).WillOnce(Return(ATokenTypeEnum::TOKEN_INVALID)); + ret = AppManager::GetInstance().GetCallerName(isSystemSA, output); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(AppManagerTest, GetNativeTokenIdByName_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(token_ != nullptr); + + EXPECT_CALL(*token_, GetNativeTokenId(_)).WillOnce(Return(UNVALUABLE_TOKEN_ID)); + std::string processName; + int64_t tokenId = 0; + auto ret = AppManager::GetInstance().GetNativeTokenIdByName(processName, tokenId); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*token_, GetNativeTokenId(_)).WillOnce(Return(VALUABLE_TOKEN_ID)); + ret = AppManager::GetInstance().GetNativeTokenIdByName(processName, tokenId); + EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(tokenId, VALUABLE_TOKEN_ID); +} + +HWTEST_F(AppManagerTest, GetHapTokenIdByName_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(token_ != nullptr); + EXPECT_CALL(*token_, GetHapTokenID(_, _, _)).WillOnce(Return(UNVALUABLE_TOKEN_ID)); + int32_t userId = 0; + std::string bundleName; + int32_t instIndex = 0; + int64_t tokenId = 0; + auto ret = AppManager::GetInstance().GetHapTokenIdByName(userId, bundleName, instIndex, tokenId); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*token_, GetHapTokenID(_, _, _)).WillOnce(Return(VALUABLE_TOKEN_ID)); + ret = AppManager::GetInstance().GetHapTokenIdByName(userId, bundleName, instIndex, tokenId); + EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(tokenId, VALUABLE_TOKEN_ID); +} + +HWTEST_F(AppManagerTest, GetCallerProcessName_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(skeleton_ != nullptr); + ASSERT_TRUE(token_ != nullptr); + size_t getCallingTokenIDCallCount = 0; + size_t getNativeTokenInfoCallCount = 0; + + ON_CALL(*skeleton_, GetCallingTokenID()) + .WillByDefault(Invoke([&getCallingTokenIDCallCount]() { + return (getCallingTokenIDCallCount++ == 0) ? UNVALUABLE_TOKEN_ID : VALUABLE_TOKEN_ID; + })); + ON_CALL(*token_, GetNativeTokenInfo(_, _)) + .WillByDefault(Invoke([&getNativeTokenInfoCallCount](AccessTokenID, NativeTokenInfo &) { + return (getNativeTokenInfoCallCount++ == 0) ? ERR_FAILED_VALUE : ERR_OK; + })); + EXPECT_CALL(*skeleton_, GetCallingTokenID()).Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*token_, GetTokenTypeFlag(_)).WillRepeatedly(Return(ATokenTypeEnum::TOKEN_NATIVE)); + EXPECT_CALL(*token_, GetNativeTokenInfo(_, _)).Times(AtLeast(INVOKE_COUNT)); + for (size_t i = 0; i < 3; ++i) { + std::string output; + auto ret = AppManager::GetInstance().GetCallerProcessName(output); + if (getCallingTokenIDCallCount > 1 && getNativeTokenInfoCallCount > 1) { + EXPECT_EQ(ret, DM_OK); + } else { + EXPECT_EQ(ret, ERR_DM_FAILED); + } + } +} + +HWTEST_F(AppManagerTest, GetCallerProcessName_002, testing::ext::TestSize.Level2) +{ + ASSERT_TRUE(skeleton_ != nullptr); + ASSERT_TRUE(token_ != nullptr); + size_t GetHapTokenInfoCallCount = 0; + + ON_CALL(*token_, GetHapTokenInfo(_, _)) + .WillByDefault(Invoke([&GetHapTokenInfoCallCount](AccessTokenID, HapTokenInfo &) { + return (GetHapTokenInfoCallCount++ == 0) ? ERR_FAILED_VALUE : ERR_OK; + })); + + EXPECT_CALL(*skeleton_, GetCallingTokenID()).WillRepeatedly(Return(VALUABLE_TOKEN_ID)); + EXPECT_CALL(*skeleton_, GetCallingFullTokenID()).Times(AtLeast(INVOKE_COUNT)); + EXPECT_CALL(*token_, GetTokenTypeFlag(_)).WillRepeatedly(Return(ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token_, GetHapTokenInfo(_, _)).Times(AtLeast(INVOKE_COUNT)); + std::string output; + for (size_t i = 0; i < 2; ++i) { + auto ret = AppManager::GetInstance().GetCallerProcessName(output); + EXPECT_EQ(ret, ERR_DM_FAILED); + } + + EXPECT_CALL(*token_, GetTokenTypeFlag(_)).WillOnce(Return(ATokenTypeEnum::TOKEN_INVALID)); + auto ret = AppManager::GetInstance().GetCallerProcessName(output); + EXPECT_EQ(ret, ERR_DM_FAILED); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_app_manager.h b/test/unittest/UTTest_app_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..15a31e706cca6521a8f4cd6752dd710695f877eb --- /dev/null +++ b/test/unittest/UTTest_app_manager.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 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. + */ + +#ifndef OHOS_DM_APP_MANAGER_TEST_H +#define OHOS_DM_APP_MANAGER_TEST_H + +#include +#include "app_manager.h" +#include "ipc_skeleton_mock.h" +#include "accesstoken_kit_mock.h" +#include "system_ability_manager_client_mock.h" +#include "os_account_manager_mock.h" + +namespace OHOS { +namespace DistributedHardware { +class AppManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +private: + std::shared_ptr skeleton_; + std::shared_ptr token_; + std::shared_ptr client_; + std::shared_ptr accountManager_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/test/unittest/UTTest_crypto_mgr.cpp b/test/unittest/UTTest_crypto_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f0900b0cebab46267650f3157fa5ceda6a2e5a9 --- /dev/null +++ b/test/unittest/UTTest_crypto_mgr.cpp @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2025 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 "UTTest_crypto_mgr.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace DistributedHardware { +void CryptoMgrTest::SetUp() +{} + +void CryptoMgrTest::TearDown() +{} + +void CryptoMgrTest::SetUpTestCase() +{} + +void CryptoMgrTest::TearDownTestCase() +{} + +HWTEST_F(CryptoMgrTest, EncryptAndDecryptMessage_001, testing::ext::TestSize.Level0) +{ + auto cryptoMgr = std::make_shared(); + uint8_t sessionKey[SESSION_KEY_LENGTH] = "sessionKey_fm88"; + auto ret = cryptoMgr->SaveSessionKey(sessionKey, SESSION_KEY_LENGTH); + ASSERT_EQ(ret, DM_OK); + + nlohmann::json jsonObj; + jsonObj[TAG_DEVICE_ID] = "51352xxxx"; + jsonObj[TAG_CRYPTO_SUPPORT] = true; + std::string message = SafetyDump(jsonObj); + std::string encryptData; + std::string decryptData; + ret = cryptoMgr->EncryptMessage(message, encryptData); + ASSERT_EQ(ret, DM_OK); + cryptoMgr->DecryptMessage(encryptData, decryptData); + EXPECT_STREQ(decryptData.c_str(), message.c_str()); +} + +HWTEST_F(CryptoMgrTest, EncryptAndDecryptMessage_002, testing::ext::TestSize.Level0) +{ + auto cryptoMgr = std::make_shared(); + uint8_t sessionKey[SESSION_KEY_LENGTH] = "sessionKey_fm88"; + auto ret = cryptoMgr->SaveSessionKey(sessionKey, SESSION_KEY_LENGTH); + ASSERT_EQ(ret, DM_OK); + + nlohmann::json jsonObj; + jsonObj[TAG_DEVICE_ID] = "51352xxxx"; + jsonObj[TAG_CRYPTO_SUPPORT] = true; + std::string message = SafetyDump(jsonObj); + std::string encryptData1; + std::string encryptData2; + std::string decryptData; + ret = cryptoMgr->EncryptMessage(message, encryptData1); + ASSERT_EQ(ret, DM_OK); + ret = cryptoMgr->EncryptMessage(message, encryptData2); + ASSERT_EQ(ret, DM_OK); + cryptoMgr->DecryptMessage(encryptData1, decryptData); + EXPECT_STREQ(decryptData.c_str(), message.c_str()); + cryptoMgr->DecryptMessage(encryptData2, decryptData); + EXPECT_STREQ(decryptData.c_str(), message.c_str()); +} + +HWTEST_F(CryptoMgrTest, EncryptAndDecryptMessage_003, testing::ext::TestSize.Level2) +{ + auto cryptoMgr = std::make_shared(); + uint8_t sessionKey[SESSION_KEY_LENGTH] = "sessionKey_fm88"; + auto ret = cryptoMgr->SaveSessionKey(sessionKey, SESSION_KEY_LENGTH); + ASSERT_EQ(ret, DM_OK); + + std::string emptyMessage; + std::string encryptData; + std::string decryptData; + ret = cryptoMgr->EncryptMessage(emptyMessage, encryptData); + EXPECT_NE(ret, DM_OK); + cryptoMgr->DecryptMessage(encryptData, decryptData); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(CryptoMgrTest, EncryptAndDecryptMessage_004, testing::ext::TestSize.Level2) +{ + auto cryptoMgr = std::make_shared(); + const size_t sessionKeyLen = 15; + uint8_t sessionKey[sessionKeyLen] = {'\0'}; + auto ret = cryptoMgr->SaveSessionKey(sessionKey, sessionKeyLen); + ASSERT_EQ(ret, DM_OK); + + std::string emptyMessage; + std::string encryptData; + std::string decryptData; + ret = cryptoMgr->EncryptMessage(emptyMessage, encryptData); + EXPECT_NE(ret, DM_OK); + cryptoMgr->DecryptMessage(encryptData, decryptData); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(CryptoMgrTest, EncryptAndDecryptMessage_005, testing::ext::TestSize.Level2) +{ + auto cryptoMgr = std::make_shared(); + + nlohmann::json jsonObj; + jsonObj[TAG_DEVICE_ID] = "51352xxxx"; + jsonObj[TAG_CRYPTO_SUPPORT] = true; + std::string message = SafetyDump(jsonObj); + std::string encryptData; + std::string decryptData; + auto ret = cryptoMgr->EncryptMessage(message, encryptData); + EXPECT_NE(ret, DM_OK); + cryptoMgr->DecryptMessage(encryptData, decryptData); + EXPECT_NE(ret, DM_OK); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_crypto_mgr.h b/test/unittest/UTTest_crypto_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..ca9f5449b41e3c251b753e445af258bc50408826 --- /dev/null +++ b/test/unittest/UTTest_crypto_mgr.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 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. + */ + +#ifndef OHOS_DM_CRYPYO_MGR_TEST_H +#define OHOS_DM_CRYPYO_MGR_TEST_H + +#include +#include "crypto_mgr.h" + +namespace OHOS { +namespace DistributedHardware { +class CryptoMgrTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_CRYPYO_MGR_TEST_H diff --git a/test/unittest/UTTest_device_name_manager.cpp b/test/unittest/UTTest_device_name_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e7057f181134c553268dd51d4497e1ebeaaee2d6 --- /dev/null +++ b/test/unittest/UTTest_device_name_manager.cpp @@ -0,0 +1,344 @@ +/* + * Copyright (c) 2025 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 "UTTest_device_name_manager.h" +#include "bundle_mgr_mock.h" +#include "datashare_result_set_mock.h" +#include "dm_constants.h" +#include "dm_system_ability_manager_mock.h" + +using namespace testing; +using namespace OHOS::DataShare; + +namespace OHOS { +namespace DistributedHardware { +namespace { +constexpr int32_t DEFAULT_USER_ID = -1; +constexpr int32_t DEFAULT_VALUABLE_USER_ID = 0; +const std::string SETTINGS_GENERAL_DEVICE_NAME = "settings.general.device_name"; +} // namespace +void DeviceNameManagerTest::SetUp() +{ + multipleUserConnector_ = std::make_shared(); + DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnector_; + auto client = ISystemAbilityManagerClient::GetOrCreateSAMgrClient(); + client_ = std::static_pointer_cast(client); + helper_ = DataShareHelperMock::GetOrCreateInstance(); +} + +void DeviceNameManagerTest::TearDown() +{ + DmMultipleUserConnector::dmMultipleUserConnector = nullptr; + multipleUserConnector_ = nullptr; + ISystemAbilityManagerClient::ReleaseSAMgrClient(); + client_ = nullptr; + DataShareHelperMock::ReleaseInstance(); + helper_ = nullptr; +} + +void DeviceNameManagerTest::SetUpTestCase() +{} + +void DeviceNameManagerTest::TearDownTestCase() +{} + +/** + * @tc.name: Init_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceNameManagerTest, Init_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(client_ != nullptr); + ASSERT_TRUE(multipleUserConnector_ != nullptr); + ASSERT_TRUE(helper_ != nullptr); + + std::string subffixName = "手机"; + auto bundleMgr = sptr(new (std::nothrow) BundleMgrMock()); + auto systemAbilityManager = sptr(new (std::nothrow) SystemAbilityManagerMock()); + EXPECT_CALL(*systemAbilityManager, GetSystemAbility(_)) + .WillRepeatedly(Return(bundleMgr)); + EXPECT_CALL(*client_, GetSystemAbilityManager()) + .WillRepeatedly(Return(systemAbilityManager)); + EXPECT_CALL(*multipleUserConnector_, GetCurrentAccountUserID()).WillRepeatedly(Return(DEFAULT_VALUABLE_USER_ID)); + auto resultSet = std::make_shared(nullptr); + EXPECT_CALL(*helper_, Query(_, _, _, _)).WillRepeatedly(Return(resultSet)); + EXPECT_CALL(*helper_, RegisterObserver(_, _)).Times(AtLeast(1)); + EXPECT_CALL(*helper_, Release()).WillRepeatedly(Return(true)); + + EXPECT_CALL(*resultSet, GetRowCount(_)).WillRepeatedly(DoAll(SetArgReferee<0>(1), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, GoToRow(_)).Times(AtLeast(1)); + EXPECT_CALL(*resultSet, GetString(_, _)).WillRepeatedly( + DoAll(SetArgReferee<1>(subffixName), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, Close()).Times(AtLeast(1)); + + DeviceNameManager::GetInstance().Init(); + DeviceNameManager::GetInstance().UnInit(); +} + +/** + * @tc.name: InitDeviceNameWhenUserSwitch_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceNameManagerTest, InitDeviceNameWhenUserSwitch_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(client_ != nullptr); + ASSERT_TRUE(multipleUserConnector_ != nullptr); + ASSERT_TRUE(helper_ != nullptr); + + std::string subffixName = "手机"; + int32_t curUserId = DEFAULT_VALUABLE_USER_ID + 1; + int32_t preUserId = DEFAULT_VALUABLE_USER_ID; + auto bundleMgr = sptr(new (std::nothrow) BundleMgrMock()); + auto systemAbilityManager = sptr(new (std::nothrow) SystemAbilityManagerMock()); + EXPECT_CALL(*systemAbilityManager, GetSystemAbility(_)) + .WillRepeatedly(Return(bundleMgr)); + EXPECT_CALL(*client_, GetSystemAbilityManager()) + .WillRepeatedly(Return(systemAbilityManager)); + EXPECT_CALL(*multipleUserConnector_, GetCurrentAccountUserID()).WillRepeatedly(Return(DEFAULT_VALUABLE_USER_ID)); + auto resultSet = std::make_shared(nullptr); + EXPECT_CALL(*helper_, Query(_, _, _, _)).WillRepeatedly(Return(resultSet)); + EXPECT_CALL(*helper_, RegisterObserver(_, _)).Times(AtLeast(1)); + EXPECT_CALL(*helper_, UnregisterObserver(_, _)).Times(AtLeast(1)); + EXPECT_CALL(*helper_, Release()).WillRepeatedly(Return(true)); + + EXPECT_CALL(*resultSet, GetRowCount(_)).WillRepeatedly(DoAll(SetArgReferee<0>(1), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, GoToRow(_)).Times(AtLeast(1)); + EXPECT_CALL(*resultSet, GetString(_, _)).WillRepeatedly( + DoAll(SetArgReferee<1>(subffixName), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, Close()).Times(AtLeast(1)); + + DeviceNameManager::GetInstance().Init(); + DeviceNameManager::GetInstance().InitDeviceNameWhenUserSwitch(curUserId, preUserId); + DeviceNameManager::GetInstance().UnInit(); +} + +/** + * @tc.name: InitDeviceNameWhenUserSwitch_002 + * @tc.type: FUNC + */ +HWTEST_F(DeviceNameManagerTest, InitDeviceNameWhenUserSwitch_002, testing::ext::TestSize.Level2) +{ + ASSERT_TRUE(client_ != nullptr); + ASSERT_TRUE(helper_ != nullptr); + + std::string subffixName = "手机"; + int32_t curUserId = DEFAULT_USER_ID; + int32_t preUserId = DEFAULT_USER_ID; + + auto bundleMgr = sptr(new (std::nothrow) BundleMgrMock()); + auto systemAbilityManager = sptr(new (std::nothrow) SystemAbilityManagerMock()); + EXPECT_CALL(*systemAbilityManager, GetSystemAbility(_)) + .WillRepeatedly(Return(bundleMgr)); + EXPECT_CALL(*client_, GetSystemAbilityManager()) + .WillRepeatedly(Return(systemAbilityManager)); + auto resultSet = std::make_shared(nullptr); + EXPECT_CALL(*helper_, Query(_, _, _, _)).WillRepeatedly(Return(resultSet)); + EXPECT_CALL(*helper_, Release()).WillRepeatedly(Return(true)); + + EXPECT_CALL(*resultSet, GetRowCount(_)).WillRepeatedly(DoAll(SetArgReferee<0>(1), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, GoToRow(_)).Times(AtLeast(1)); + EXPECT_CALL(*resultSet, GetString(_, _)).WillRepeatedly( + DoAll(SetArgReferee<1>(subffixName), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, Close()).Times(AtLeast(1)); + + DeviceNameManager::GetInstance().InitDeviceNameWhenUserSwitch(curUserId, preUserId); + DeviceNameManager::GetInstance().UnInit(); +} + +/** + * @tc.name: InitDeviceNameWhenLogout_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceNameManagerTest, InitDeviceNameWhenLogout_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(client_ != nullptr); + ASSERT_TRUE(multipleUserConnector_ != nullptr); + ASSERT_TRUE(helper_ != nullptr); + + std::string subffixName = "手机"; + auto bundleMgr = sptr(new (std::nothrow) BundleMgrMock()); + auto systemAbilityManager = sptr(new (std::nothrow) SystemAbilityManagerMock()); + EXPECT_CALL(*systemAbilityManager, GetSystemAbility(_)) + .WillRepeatedly(Return(bundleMgr)); + EXPECT_CALL(*client_, GetSystemAbilityManager()) + .WillRepeatedly(Return(systemAbilityManager)); + EXPECT_CALL(*multipleUserConnector_, GetCurrentAccountUserID()).WillRepeatedly(Return(DEFAULT_VALUABLE_USER_ID)); + auto resultSet = std::make_shared(nullptr); + EXPECT_CALL(*helper_, Query(_, _, _, _)).WillRepeatedly(Return(resultSet)); + EXPECT_CALL(*helper_, Release()).WillRepeatedly(Return(true)); + + EXPECT_CALL(*resultSet, GetRowCount(_)).WillRepeatedly(DoAll(SetArgReferee<0>(1), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, GoToRow(_)).Times(AtLeast(1)); + EXPECT_CALL(*resultSet, GetString(_, _)).WillRepeatedly( + DoAll(SetArgReferee<1>(subffixName), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, Close()).Times(AtLeast(1)); + + DeviceNameManager::GetInstance().InitDeviceNameWhenLogout(); + DeviceNameManager::GetInstance().UnInit(); +} + +/** + * @tc.name: InitDeviceNameWhenLogin_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceNameManagerTest, InitDeviceNameWhenLogin_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(client_ != nullptr); + ASSERT_TRUE(multipleUserConnector_ != nullptr); + ASSERT_TRUE(helper_ != nullptr); + + std::string subffixName = "手机"; + auto bundleMgr = sptr(new (std::nothrow) BundleMgrMock()); + auto systemAbilityManager = sptr(new (std::nothrow) SystemAbilityManagerMock()); + EXPECT_CALL(*systemAbilityManager, GetSystemAbility(_)) + .WillRepeatedly(Return(bundleMgr)); + EXPECT_CALL(*client_, GetSystemAbilityManager()) + .WillRepeatedly(Return(systemAbilityManager)); + EXPECT_CALL(*multipleUserConnector_, GetCurrentAccountUserID()).WillRepeatedly(Return(DEFAULT_VALUABLE_USER_ID)); + auto resultSet = std::make_shared(nullptr); + EXPECT_CALL(*helper_, Query(_, _, _, _)).WillRepeatedly(Return(resultSet)); + EXPECT_CALL(*helper_, Release()).WillRepeatedly(Return(true)); + + EXPECT_CALL(*resultSet, GetRowCount(_)).WillRepeatedly(DoAll(SetArgReferee<0>(1), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, GoToRow(_)).Times(AtLeast(1)); + EXPECT_CALL(*resultSet, GetString(_, _)).WillRepeatedly( + DoAll(SetArgReferee<1>(subffixName), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, Close()).Times(AtLeast(1)); + + DeviceNameManager::GetInstance().InitDeviceNameWhenLogin(); + DeviceNameManager::GetInstance().UnInit(); +} + +/** + * @tc.name: InitDeviceNameWhenNickChange_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceNameManagerTest, InitDeviceNameWhenNickChange_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(client_ != nullptr); + ASSERT_TRUE(multipleUserConnector_ != nullptr); + ASSERT_TRUE(helper_ != nullptr); + + std::string subffixName = "手机"; + auto bundleMgr = sptr(new (std::nothrow) BundleMgrMock()); + auto systemAbilityManager = sptr(new (std::nothrow) SystemAbilityManagerMock()); + EXPECT_CALL(*systemAbilityManager, GetSystemAbility(_)) + .WillRepeatedly(Return(bundleMgr)); + EXPECT_CALL(*client_, GetSystemAbilityManager()) + .WillRepeatedly(Return(systemAbilityManager)); + EXPECT_CALL(*multipleUserConnector_, GetCurrentAccountUserID()).WillRepeatedly(Return(DEFAULT_VALUABLE_USER_ID)); + auto resultSet = std::make_shared(nullptr); + EXPECT_CALL(*helper_, Query(_, _, _, _)).WillRepeatedly(Return(resultSet)); + EXPECT_CALL(*helper_, Release()).WillRepeatedly(Return(true)); + + EXPECT_CALL(*resultSet, GetRowCount(_)).WillRepeatedly(DoAll(SetArgReferee<0>(1), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, GoToRow(_)).Times(AtLeast(1)); + EXPECT_CALL(*resultSet, GetString(_, _)).WillRepeatedly( + DoAll(SetArgReferee<1>(subffixName), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, Close()).Times(AtLeast(1)); + + DeviceNameManager::GetInstance().InitDeviceNameWhenNickChange(); + DeviceNameManager::GetInstance().UnInit(); +} + +/** + * @tc.name: InitDeviceNameWhenNameChange_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceNameManagerTest, InitDeviceNameWhenNameChange_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(client_ != nullptr); + ASSERT_TRUE(multipleUserConnector_ != nullptr); + ASSERT_TRUE(helper_ != nullptr); + + std::string prefixName = "Mr.诸葛张三"; + auto bundleMgr = sptr(new (std::nothrow) BundleMgrMock()); + auto systemAbilityManager = sptr(new (std::nothrow) SystemAbilityManagerMock()); + EXPECT_CALL(*systemAbilityManager, GetSystemAbility(_)) + .WillRepeatedly(Return(bundleMgr)); + EXPECT_CALL(*client_, GetSystemAbilityManager()) + .WillRepeatedly(Return(systemAbilityManager)); + EXPECT_CALL(*helper_, Query(_, _, _, _)).WillRepeatedly(Return(nullptr)); + EXPECT_CALL(*helper_, Release()).WillRepeatedly(Return(true)); + EXPECT_CALL(*multipleUserConnector_, GetAccountNickName(_)).WillRepeatedly(Return(prefixName)); + + DeviceNameManager::GetInstance().InitDeviceNameWhenNameChange(DEFAULT_VALUABLE_USER_ID); + DeviceNameManager::GetInstance().UnInit(); +} + +/** + * @tc.name: GetLocalDisplayDeviceName_001 + * @tc.type: FUNC + */ +HWTEST_F(DeviceNameManagerTest, GetLocalDisplayDeviceName_001, testing::ext::TestSize.Level0) +{ + ASSERT_TRUE(client_ != nullptr); + ASSERT_TRUE(multipleUserConnector_ != nullptr); + ASSERT_TRUE(helper_ != nullptr); + + size_t getStringInvokeCount = 0; + auto bundleMgr = sptr(new (std::nothrow) BundleMgrMock()); + auto systemAbilityManager = sptr(new (std::nothrow) SystemAbilityManagerMock()); + EXPECT_CALL(*systemAbilityManager, GetSystemAbility(_)) + .WillRepeatedly(Return(bundleMgr)); + EXPECT_CALL(*client_, GetSystemAbilityManager()) + .WillRepeatedly(Return(systemAbilityManager)); + EXPECT_CALL(*multipleUserConnector_, GetCurrentAccountUserID()).WillRepeatedly(Return(DEFAULT_VALUABLE_USER_ID)); + auto resultSet = std::make_shared(nullptr); + EXPECT_CALL(*helper_, Query(_, _, _, _)).WillRepeatedly(Return(resultSet)); + EXPECT_CALL(*helper_, Release()).WillRepeatedly(Return(true)); + + EXPECT_CALL(*resultSet, GetRowCount(_)).WillRepeatedly(DoAll(SetArgReferee<0>(1), Return(DataShare::E_OK))); + EXPECT_CALL(*resultSet, GoToRow(_)).Times(AtLeast(1)); + EXPECT_CALL(*resultSet, GetString(_, _)).WillRepeatedly(Invoke([&getStringInvokeCount](int, std::string &output) { + std::string subffixName = "OH-3.2"; + if (getStringInvokeCount++ > 0) { + output = subffixName; + } + return DM_OK; + })); + EXPECT_CALL(*resultSet, Close()).Times(AtLeast(1)); + std::string prefixName = "Mr.诸葛张三"; + EXPECT_CALL(*multipleUserConnector_, GetCallerUserId(_)).Times(AtLeast(1)); + EXPECT_CALL(*multipleUserConnector_, GetAccountNickName(_)).WillRepeatedly(Return(prefixName)); + for (size_t i = 0; i < 2; ++i) { + int32_t maxNamelength = 24; + std::string output; + auto result = DeviceNameManager::GetInstance().GetLocalDisplayDeviceName(maxNamelength, output); + EXPECT_EQ(result, DM_OK); + } +} + +/** + * @tc.name: GetLocalDisplayDeviceName_002 + * @tc.type: FUNC + */ +HWTEST_F(DeviceNameManagerTest, GetLocalDisplayDeviceName_002, testing::ext::TestSize.Level2) +{ + std::string output; + int32_t maxNamelength = -1; + auto result = DeviceNameManager::GetInstance().GetLocalDisplayDeviceName(maxNamelength, output); + EXPECT_EQ(result, ERR_DM_INPUT_PARA_INVALID); + + maxNamelength = 10; + result = DeviceNameManager::GetInstance().GetLocalDisplayDeviceName(maxNamelength, output); + EXPECT_EQ(result, ERR_DM_INPUT_PARA_INVALID); + + maxNamelength = 101; + result = DeviceNameManager::GetInstance().GetLocalDisplayDeviceName(maxNamelength, output); + EXPECT_EQ(result, ERR_DM_INPUT_PARA_INVALID); +} +} // DistributedHardware +} // OHOS diff --git a/test/unittest/UTTest_device_name_manager.h b/test/unittest/UTTest_device_name_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..4ab1633ac280411f70aff1f9640c70c004dfb541 --- /dev/null +++ b/test/unittest/UTTest_device_name_manager.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2025 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. + */ + +#ifndef OHOS_DM_DEVICE_NAME_MANAGER_TEST_H +#define OHOS_DM_DEVICE_NAME_MANAGER_TEST_H + +#include + +#include "device_name_manager.h" +#include "datashare_helper_mock.h" +#include "multiple_user_connector_mock.h" +#include "system_ability_manager_client_mock.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceNameManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +private: + std::shared_ptr client_; + std::shared_ptr multipleUserConnector_; + std::shared_ptr helper_; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_DEVICE_NAME_MANAGER_TEST_H + \ No newline at end of file diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index ea1a4a52a9ae4658abf09ee75a204b199b5714e2..75de85d67ef8539f1b883a773900c46bf7fc95c8 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -116,10 +116,20 @@ constexpr int32_t MSG_TYPE_CREATE_PIN_HOLDER = 600; constexpr int32_t MSG_TYPE_CREATE_PIN_HOLDER_RESP = 601; constexpr int32_t MSG_TYPE_DESTROY_PIN_HOLDER = 650; constexpr int32_t MSG_TYPE_DESTROY_PIN_HOLDER_RESP = 651; +constexpr int32_t MSG_TYPE_PIN_HOLDER_CHANGE = 700; +constexpr int32_t MSG_TYPE_PIN_HOLDER_CHANGE_RESP = 701; +constexpr int32_t MSG_TYPE_PIN_CLOSE_SESSION = 800; +constexpr int32_t SESSION_ID = 0; +constexpr int32_t RESULT = DM_OK; +constexpr int32_t REPLY_SUCCESS = 0; +constexpr int32_t REPLY_FAILED = -1; constexpr const char* TAG_PIN_TYPE = "PIN_TYPE"; constexpr const char* TAG_PAYLOAD = "PAYLOAD"; constexpr const char* TAG_REPLY = "REPLY"; +constexpr int32_t SESSION_ID_INVALID = -1; +const std::string PACKAGE_NAME = "com.ohos.dmtest"; +const std::string PAY_LOAD = "mock_payLoad"; namespace { /** * @tc.name: InitDeviceManager_001 @@ -923,6 +933,129 @@ HWTEST_F(DmPinHolderTest, NotifyPinHolderEvent_102, testing::ext::TestSize.Level ret = pinHolder->NotifyPinHolderEvent(pkgName, event); ASSERT_EQ(ret, ERR_DM_FAILED); } + +HWTEST_F(DmPinHolderTest, CreateMsgScene_101, testing::ext::TestSize.Level0) +{ + nlohmann::json sourceJson; + sourceJson[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; + sourceJson[TAG_PIN_TYPE] = DmPinType::QR_CODE; + sourceJson[TAG_PAYLOAD] = PAY_LOAD; + std::string sourceMessage = SafetyDump(sourceJson); + + nlohmann::json sinkJson; + sinkJson[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER_RESP; + sinkJson[TAG_PIN_TYPE] = DmPinType::QR_CODE; + sinkJson[TAG_PAYLOAD] = PAY_LOAD; + sinkJson[TAG_REPLY] = REPLY_SUCCESS; + std::string sinkMessage = SafetyDump(sourceJson); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + pinHolder->OnSessionOpened(SESSION_ID, SESSION_ID_INVALID, RESULT); + pinHolder->OnDataReceived(SESSION_ID, sourceMessage); + + pinHolder->OnDataReceived(SESSION_ID, sinkMessage); + pinHolder->OnDataReceived(SESSION_ID, sourceMessage); + pinHolder->OnSessionClosed(SESSION_ID); + EXPECT_TRUE(pinHolder->isDestroy_.load()); +} + +HWTEST_F(DmPinHolderTest, CreateRespMsgScene_101, testing::ext::TestSize.Level2) +{ + nlohmann::json jsonObject; + jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER_RESP; + jsonObject[TAG_PIN_TYPE] = DmPinType::QR_CODE; + jsonObject[TAG_PAYLOAD] = PAY_LOAD; + jsonObject[TAG_REPLY] = REPLY_FAILED; + std::string message = SafetyDump(jsonObject); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + pinHolder->OnSessionOpened(SESSION_ID, SESSION_ID_INVALID, RESULT); + pinHolder->OnDataReceived(SESSION_ID, message); + pinHolder->OnSessionClosed(SESSION_ID); + EXPECT_EQ(pinHolder->sessionId_, SESSION_ID_INVALID); +} + +HWTEST_F(DmPinHolderTest, DestroyMsgScene_101, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER; + jsonObject[TAG_PIN_TYPE] = DmPinType::QR_CODE; + jsonObject[TAG_PAYLOAD] = PAY_LOAD; + std::string message = SafetyDump(jsonObject); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + pinHolder->OnSessionOpened(SESSION_ID, SESSION_ID_INVALID, RESULT); + pinHolder->OnDataReceived(SESSION_ID, message); + pinHolder->OnSessionClosed(SESSION_ID); + EXPECT_TRUE(pinHolder->isDestroy_.load()); +} + +HWTEST_F(DmPinHolderTest, DestroyResMsgScene_101, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER_RESP; + jsonObject[TAG_PIN_TYPE] = DmPinType::QR_CODE; + jsonObject[TAG_PAYLOAD] = PAY_LOAD; + std::string message = SafetyDump(jsonObject); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + pinHolder->OnSessionOpened(SESSION_ID, SESSION_ID_INVALID, RESULT); + pinHolder->OnDataReceived(SESSION_ID, message); + pinHolder->OnSessionClosed(SESSION_ID); + EXPECT_TRUE(pinHolder->isDestroy_.load()); +} + +HWTEST_F(DmPinHolderTest, ChangeMsgScene_101, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject[TAG_MSG_TYPE] = MSG_TYPE_PIN_HOLDER_CHANGE; + jsonObject[TAG_PIN_TYPE] = DmPinType::QR_CODE; + jsonObject[TAG_PAYLOAD] = PAY_LOAD; + std::string message = SafetyDump(jsonObject); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + pinHolder->OnSessionOpened(SESSION_ID, SESSION_ID_INVALID, RESULT); + pinHolder->OnDataReceived(SESSION_ID, message); + pinHolder->OnSessionClosed(SESSION_ID); + EXPECT_TRUE(pinHolder->isDestroy_.load()); +} + +HWTEST_F(DmPinHolderTest, ChangeRespMsgScene_101, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject[TAG_MSG_TYPE] = MSG_TYPE_PIN_HOLDER_CHANGE_RESP; + jsonObject[TAG_PIN_TYPE] = DmPinType::QR_CODE; + jsonObject[TAG_PAYLOAD] = PAY_LOAD; + std::string message = SafetyDump(jsonObject); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + pinHolder->OnSessionOpened(SESSION_ID, SESSION_ID_INVALID, RESULT); + pinHolder->OnDataReceived(SESSION_ID, message); + pinHolder->OnSessionClosed(SESSION_ID); + EXPECT_TRUE(pinHolder->isDestroy_.load()); +} + +HWTEST_F(DmPinHolderTest, CloseSessionMsgScene_101, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject[TAG_MSG_TYPE] = MSG_TYPE_PIN_CLOSE_SESSION; + jsonObject[TAG_PIN_TYPE] = DmPinType::QR_CODE; + jsonObject[TAG_PAYLOAD] = PAY_LOAD; + std::string message = SafetyDump(jsonObject); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + pinHolder->OnSessionOpened(SESSION_ID, SESSION_ID_INVALID, RESULT); + pinHolder->OnDataReceived(SESSION_ID, message); + pinHolder->OnSessionClosed(SESSION_ID); + EXPECT_EQ(pinHolder->sessionId_, SESSION_ID_INVALID); +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file