From a5d2207915c5fa76d7f3fee1ac62add05da3c38a Mon Sep 17 00:00:00 2001 From: zhuzhihui7 Date: Wed, 26 Feb 2025 10:06:23 +0800 Subject: [PATCH] =?UTF-8?q?dm=E6=A8=A1=E5=9D=97=E6=96=B0=E5=A2=9E=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhuzhihui7 --- .../UTTest_dm_device_state_manager_two.cpp | 355 ++++++++++++++++++ .../UTTest_dm_device_state_manager_two.h | 39 ++ test/unittest/BUILD.gn | 92 +++++ test/unittest/UTTest_advertise_manager.cpp | 122 ++++++ test/unittest/UTTest_advertise_manager.h | 33 ++ test/unittest/UTTest_app_manager.cpp | 337 +++++++++++++++++ test/unittest/UTTest_app_manager.h | 42 +++ test/unittest/UTTest_device_name_manager.cpp | 344 +++++++++++++++++ test/unittest/UTTest_device_name_manager.h | 43 +++ test/unittest/UTTest_dm_pin_holder.cpp | 133 +++++++ test/unittest/mock/accesstoken_kit_mock.cpp | 67 ++++ test/unittest/mock/accesstoken_kit_mock.h | 61 +++ test/unittest/mock/bundle_mgr_mock.h | 38 ++ test/unittest/mock/datashare_helper_mock.cpp | 45 +++ test/unittest/mock/datashare_helper_mock.h | 89 +++++ .../mock/datashare_result_set_mock.cpp | 150 ++++++++ .../unittest/mock/datashare_result_set_mock.h | 41 ++ test/unittest/mock/ipc_skeleton_mock.cpp | 53 +++ test/unittest/mock/ipc_skeleton_mock.h | 50 +++ .../mock/multiple_user_connector_mock.cpp | 10 + .../mock/multiple_user_connector_mock.h | 4 + .../unittest/mock/os_account_manager_mock.cpp | 45 +++ test/unittest/mock/os_account_manager_mock.h | 41 ++ test/unittest/mock/softbus_bus_center.cpp | 26 +- test/unittest/mock/softbus_connector_mock.cpp | 10 + test/unittest/mock/softbus_connector_mock.h | 4 + .../system_ability_manager_client_mock.cpp | 49 +++ .../mock/system_ability_manager_client_mock.h | 41 ++ 28 files changed, 2363 insertions(+), 1 deletion(-) create mode 100644 test/commonunittest/UTTest_dm_device_state_manager_two.cpp create mode 100644 test/commonunittest/UTTest_dm_device_state_manager_two.h create mode 100644 test/unittest/UTTest_advertise_manager.cpp create mode 100644 test/unittest/UTTest_advertise_manager.h create mode 100644 test/unittest/UTTest_app_manager.cpp create mode 100644 test/unittest/UTTest_app_manager.h create mode 100644 test/unittest/UTTest_device_name_manager.cpp create mode 100644 test/unittest/UTTest_device_name_manager.h create mode 100644 test/unittest/mock/accesstoken_kit_mock.cpp create mode 100644 test/unittest/mock/accesstoken_kit_mock.h create mode 100644 test/unittest/mock/bundle_mgr_mock.h create mode 100644 test/unittest/mock/datashare_helper_mock.cpp create mode 100644 test/unittest/mock/datashare_helper_mock.h create mode 100644 test/unittest/mock/datashare_result_set_mock.cpp create mode 100644 test/unittest/mock/datashare_result_set_mock.h create mode 100644 test/unittest/mock/ipc_skeleton_mock.cpp create mode 100644 test/unittest/mock/ipc_skeleton_mock.h create mode 100644 test/unittest/mock/os_account_manager_mock.cpp create mode 100644 test/unittest/mock/os_account_manager_mock.h create mode 100644 test/unittest/mock/system_ability_manager_client_mock.cpp create mode 100644 test/unittest/mock/system_ability_manager_client_mock.h diff --git a/test/commonunittest/UTTest_dm_device_state_manager_two.cpp b/test/commonunittest/UTTest_dm_device_state_manager_two.cpp new file mode 100644 index 000000000..7ae3721e6 --- /dev/null +++ b/test/commonunittest/UTTest_dm_device_state_manager_two.cpp @@ -0,0 +1,355 @@ +/* + * 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_dm_device_state_manager_two.h" + +#include + +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_adapter_manager.h" +#include "ipc_notify_device_state_req.h" +#include "ipc_notify_auth_result_req.h" +#include "dm_device_state_manager.h" +#include "ipc_notify_device_found_req.h" +#include "ipc_notify_discover_result_req.h" +#include "hichain_connector.h" +#include "device_manager_service_listener.h" + +using namespace testing; +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { +void DmDeviceStateManagerTestTwo::SetUp() +{ +} + +void DmDeviceStateManagerTestTwo::TearDown() +{ +} + +void DmDeviceStateManagerTestTwo::SetUpTestCase() +{ + DmSoftbusConnector::dmSoftbusConnector = softbusConnectorMock_; +} + +void DmDeviceStateManagerTestTwo::TearDownTestCase() +{ + DmSoftbusConnector::dmSoftbusConnector = nullptr; + softbusConnectorMock_ = nullptr; +} +namespace { +std::shared_ptr hiChainConnector_ = std::make_shared(); +std::shared_ptr softbusConnector = std::make_shared(); +std::shared_ptr listener_ = std::make_shared(); +std::shared_ptr hiChainAuthConnector = std::make_shared(); +std::shared_ptr dmDeviceStateManager = + std::make_shared(softbusConnector, listener_, hiChainConnector_, hiChainAuthConnector); + +HWTEST_F(DmDeviceStateManagerTestTwo, RegisterSoftbusStateCallback_001, testing::ext::TestSize.Level0) +{ + auto softbusConnector = dmDeviceStateManager->softbusConnector_; + dmDeviceStateManager->softbusConnector_ = nullptr; + int32_t ret = dmDeviceStateManager->RegisterSoftbusStateCallback(); + EXPECT_EQ(ret, DM_OK); + dmDeviceStateManager->softbusConnector_ = softbusConnector; +} + +HWTEST_F(DmDeviceStateManagerTestTwo, DeleteOfflineDeviceInfo_002, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + dmDeviceStateManager->remoteDeviceInfos_["123"] = info; + dmDeviceStateManager->stateDeviceInfos_["123"] = info; + dmDeviceStateManager->DeleteOfflineDeviceInfo(info); + for (auto iter: dmDeviceStateManager->remoteDeviceInfos_) { + if (iter.second.deviceId == info.deviceId) { + EXPECT_EQ(dmDeviceStateManager->remoteDeviceInfos_.count(iter.first), 0); + break; + } + } +} + +HWTEST_F(DmDeviceStateManagerTestTwo, DeleteOfflineDeviceInfo_003, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + dmDeviceStateManager->remoteDeviceInfos_["123"] = info; + dmDeviceStateManager->stateDeviceInfos_["123"] = info; + strcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, "456"); + dmDeviceStateManager->DeleteOfflineDeviceInfo(info); + for (auto iter: dmDeviceStateManager->remoteDeviceInfos_) { + if (iter.second.deviceId == info.deviceId) { + EXPECT_EQ(dmDeviceStateManager->remoteDeviceInfos_.count(iter.first), 0); + break; + } + } +} + +HWTEST_F(DmDeviceStateManagerTestTwo, OnDeviceOffline_002, testing::ext::TestSize.Level0) +{ + std::string deviceId = "123"; + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + dmDeviceStateManager->stateDeviceInfos_["123"] = info; + dmDeviceStateManager->OnDeviceOffline(deviceId); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, HandleDeviceStatusChange_001, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + auto softbusConnector = dmDeviceStateManager->softbusConnector_; + dmDeviceStateManager->softbusConnector_ = nullptr; + dmDeviceStateManager->HandleDeviceStatusChange(DmDeviceState::DEVICE_STATE_OFFLINE, info); + dmDeviceStateManager->softbusConnector_ = softbusConnector; + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); + dmDeviceStateManager->HandleDeviceStatusChange(DmDeviceState::DEVICE_STATE_OFFLINE, info); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, ProcessDeviceStateChange_001, testing::ext::TestSize.Level0) +{ + ProcessInfo info; + DmDeviceInfo devInfo; + std::vector processInfoVec; + processInfoVec.push_back(info); + EXPECT_CALL(*softbusConnectorMock_, GetProcessInfo()).WillOnce(Return(processInfoVec)); + dmDeviceStateManager->ProcessDeviceStateChange(DmDeviceState::DEVICE_STATE_OFFLINE, devInfo); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, OnDeviceOnline_001, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + std::vector processInfoVec; + EXPECT_CALL(*softbusConnectorMock_, GetDeviceInfoByDeviceId("123")).WillOnce(Return(info)); + EXPECT_CALL(*softbusConnectorMock_, GetProcessInfo()).WillOnce(Return(processInfoVec)); + dmDeviceStateManager->OnDeviceOnline("123", 0); + EXPECT_CALL(*softbusConnectorMock_, GetDeviceInfoByDeviceId("123")).WillOnce(Return(info)); + EXPECT_CALL(*softbusConnectorMock_, GetProcessInfo()).WillOnce(Return(processInfoVec)); + dmDeviceStateManager->OnDeviceOnline("123", 0); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, OnDbReady_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "123"; + std::string deviceId = "123"; + DmDeviceInfo info; + strcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, "123"); + dmDeviceStateManager->OnDbReady(pkgName, deviceId); + DmDeviceInfo deviceInfo = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + dmDeviceStateManager->remoteDeviceInfos_["123"] = deviceInfo; + dmDeviceStateManager->OnDbReady(pkgName, deviceId); + EXPECT_NE(dmDeviceStateManager->listener_, nullptr); + auto listener = dmDeviceStateManager->listener_; + dmDeviceStateManager->listener_ = nullptr; + dmDeviceStateManager->OnDbReady(pkgName, deviceId); + dmDeviceStateManager->listener_ = listener; + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, RegisterOffLineTimer_001, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + StateTimerInfo stateTimerInfo; + dmDeviceStateManager->stateTimerInfoMap_["123"] = stateTimerInfo; + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + dmDeviceStateManager->RegisterOffLineTimer(info); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, StartOffLineTimer_001, testing::ext::TestSize.Level0) +{ + DmDeviceInfo deviceInfo; + dmDeviceStateManager->timer_ = std::make_shared(); + dmDeviceStateManager->StartOffLineTimer(deviceInfo); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, DeleteOffLineTimer_001, testing::ext::TestSize.Level0) +{ + dmDeviceStateManager->timer_ = nullptr; + dmDeviceStateManager->DeleteOffLineTimer("123"); + dmDeviceStateManager->timer_ = std::make_shared(); + dmDeviceStateManager->DeleteOffLineTimer(""); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, DeleteOffLineTimer_002, testing::ext::TestSize.Level0) +{ + dmDeviceStateManager->timer_ = std::make_shared(); + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + StateTimerInfo stateTimerInfo; + dmDeviceStateManager->stateTimerInfoMap_["123"] = stateTimerInfo; + dmDeviceStateManager->DeleteOffLineTimer("deviceInfo"); + dmDeviceStateManager->DeleteOffLineTimer("123"); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, DeleteOffLineTimer_003, testing::ext::TestSize.Level0) +{ + dmDeviceStateManager->timer_ = std::make_shared(); + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + StateTimerInfo stateTimerInfo; + dmDeviceStateManager->stateTimerInfoMap_["123"] = stateTimerInfo; + dmDeviceStateManager->DeleteOffLineTimer("123"); + dmDeviceStateManager->udidhash2udidMap_["123"] = "test"; + dmDeviceStateManager->DeleteOffLineTimer("123"); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, DeleteOffLineTimer_004, testing::ext::TestSize.Level0) +{ + dmDeviceStateManager->timer_ = std::make_shared(); + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + StateTimerInfo stateTimerInfo; + dmDeviceStateManager->stateTimerInfoMap_["123"] = stateTimerInfo; + dmDeviceStateManager->udidhash2udidMap_["123"] = "test"; + dmDeviceStateManager->DeleteOffLineTimer("123"); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, DeleteTimeOutGroup_001, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + StateTimerInfo stateTimerInfo; + dmDeviceStateManager->stateTimerInfoMap_["test"] = stateTimerInfo; + dmDeviceStateManager->DeleteTimeOutGroup("123"); + stateTimerInfo.timerName = "123"; + dmDeviceStateManager->stateTimerInfoMap_["123"] = stateTimerInfo; + auto hiChainConnector = dmDeviceStateManager->hiChainConnector_; + dmDeviceStateManager->hiChainConnector_ = nullptr; + dmDeviceStateManager->DeleteTimeOutGroup("123"); + dmDeviceStateManager->hiChainConnector_ = hiChainConnector; + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, DeleteTimeOutGroup_002, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + StateTimerInfo stateTimerInfo; + stateTimerInfo.timerName = "123"; + dmDeviceStateManager->stateTimerInfoMap_["123"] = stateTimerInfo; + dmDeviceStateManager->DeleteTimeOutGroup("123"); + dmDeviceStateManager->udidhash2udidMap_["123"] = "test"; + dmDeviceStateManager->DeleteTimeOutGroup("123"); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, RunTask_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr task = std::make_shared(1, ""); + dmDeviceStateManager->RunTask(task); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, GetAuthForm_001, testing::ext::TestSize.Level0) +{ + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + dmDeviceStateManager->GetAuthForm("task"); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, ChangeDeviceInfo_001, testing::ext::TestSize.Level0) +{ + std::string deviceId = "123"; + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + dmDeviceStateManager->stateDeviceInfos_.clear(); + dmDeviceStateManager->stateDeviceInfos_["123"] = info; + dmDeviceStateManager->ChangeDeviceInfo(info); + strcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, "456"); + dmDeviceStateManager->ChangeDeviceInfo(info); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, CheckIsOnline_001, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + }; + dmDeviceStateManager->stateDeviceInfos_["123"] = info; + bool ret = dmDeviceStateManager->CheckIsOnline("123"); + EXPECT_EQ(ret, true); +} + +HWTEST_F(DmDeviceStateManagerTestTwo, GetUdidByNetWorkId_001, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info = { + .deviceId = "123", + .deviceName = "asda", + .deviceTypeId = 1, + .networkId = "123" + }; + dmDeviceStateManager->stateDeviceInfos_["123"] = info; + std::string ret = dmDeviceStateManager->GetUdidByNetWorkId("123"); + EXPECT_EQ(ret, "123"); + ret = dmDeviceStateManager->GetUdidByNetWorkId("test"); + EXPECT_EQ(ret, ""); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_device_state_manager_two.h b/test/commonunittest/UTTest_dm_device_state_manager_two.h new file mode 100644 index 000000000..b6d26fe45 --- /dev/null +++ b/test/commonunittest/UTTest_dm_device_state_manager_two.h @@ -0,0 +1,39 @@ +/* + * 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_UTTEST_DM_DEVICE_STATE_MANAGER_H +#define OHOS_UTTEST_DM_DEVICE_STATE_MANAGER_H + +#include +#include + +#include "dm_adapter_manager.h" +#include "softbus_connector_mock.h" +#include "device_manager_service_listener.h" +#include "softbus_session_callback.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceStateManagerTestTwo : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; + static inline std::shared_ptr softbusConnectorMock_ = + std::make_shared(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index bae195d72..b6fa86653 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -19,6 +19,7 @@ group("unittest") { testonly = true deps = [ + ":UTTest_app_manager", ":UTTest_auth_message_processor", ":UTTest_auth_request_state", ":UTTest_auth_response_state", @@ -30,6 +31,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", @@ -43,6 +45,7 @@ group("unittest") { ":UTTest_dm_credential_manager", ":UTTest_dm_crypto", ":UTTest_dm_device_state_manager", + ":UTTest_dm_device_state_manager_two", ":UTTest_dm_deviceprofile_connector", ":UTTest_dm_deviceprofile_connector_second", ":UTTest_dm_dfx", @@ -1083,6 +1086,31 @@ ohos_unittest("UTTest_dm_device_state_manager") { ## UnitTest UTTest_dm_device_state_manager }}} +## UnitTest UTTest_dm_device_state_manager_two {{{ +ohos_unittest("UTTest_dm_device_state_manager_two") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/commonunittest" ] + + sources = [ + "${devicemanager_path}/test/commonunittest/UTTest_dm_device_state_manager_two.cpp", + "mock/softbus_connector_mock.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "device_auth:deviceauth_sdk", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "googletest:gmock", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + ] +} + +## UnitTest UTTest_dm_device_state_manager_two }}} + ## UnitTest UTTest_dm_dfx {{{ ohos_unittest("UTTest_dm_dfx") { module_out_path = module_out_path @@ -1703,6 +1731,70 @@ 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", + "googletest:gmock", + "googletest:gmock_main", + "os_account:libaccountkits", + "os_account:os_account_innerkits", + ] +} + +## UnitTest UTTest_app_manager }}} + +## 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 }}} + ## 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 000000000..2ebe3fcc0 --- /dev/null +++ b/test/unittest/UTTest_advertise_manager.cpp @@ -0,0 +1,122 @@ +/* + * 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 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 000000000..2f573015e --- /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 000000000..93de659a8 --- /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 000000000..15a31e706 --- /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_device_name_manager.cpp b/test/unittest/UTTest_device_name_manager.cpp new file mode 100644 index 000000000..e7057f181 --- /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 000000000..4ab1633ac --- /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 ea1a4a52a..75de85d67 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 diff --git a/test/unittest/mock/accesstoken_kit_mock.cpp b/test/unittest/mock/accesstoken_kit_mock.cpp new file mode 100644 index 000000000..08fc14581 --- /dev/null +++ b/test/unittest/mock/accesstoken_kit_mock.cpp @@ -0,0 +1,67 @@ +/* + * 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 "accesstoken_kit_mock.h" + +using namespace OHOS::DistributedHardware; + +namespace OHOS { +namespace Security { +namespace AccessToken { +ATokenTypeEnum AccessTokenKit::GetTokenTypeFlag(AccessTokenID tokenID) +{ + return AccessTokenKitInterface::GetOrCreateAccessTokenKit()->GetTokenTypeFlag(tokenID); +} + +int AccessTokenKit::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo &hapTokenInfoRes) +{ + return AccessTokenKitInterface::GetOrCreateAccessTokenKit()->GetHapTokenInfo(tokenID, hapTokenInfoRes); +} + +int AccessTokenKit::GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo &nativeTokenInfoRes) +{ + return AccessTokenKitInterface::GetOrCreateAccessTokenKit()->GetNativeTokenInfo(tokenID, nativeTokenInfoRes); +} + +AccessTokenID AccessTokenKit::GetNativeTokenId(const std::string &GetNativeTokenId) +{ + return AccessTokenKitInterface::GetOrCreateAccessTokenKit()->GetNativeTokenId(GetNativeTokenId); +} + +AccessTokenID AccessTokenKit::GetHapTokenID(int32_t userID, const std::string &bundleName, int32_t instIndex) +{ + return AccessTokenKitInterface::GetOrCreateAccessTokenKit()->GetHapTokenID(userID, bundleName, instIndex); +} +} // namespace AccessToken +} // namespace Security + +namespace DistributedHardware { +std::shared_ptr AccessTokenKitInterface::token_ = nullptr; + +std::shared_ptr AccessTokenKitInterface::GetOrCreateAccessTokenKit() +{ + if (!token_) { + token_ = std::make_shared(); + } + return token_; +} + +void AccessTokenKitInterface::ReleaseAccessTokenKit() +{ + token_.reset(); + token_ = nullptr; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/accesstoken_kit_mock.h b/test/unittest/mock/accesstoken_kit_mock.h new file mode 100644 index 000000000..c0249469b --- /dev/null +++ b/test/unittest/mock/accesstoken_kit_mock.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * 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_ACCESS_TOKEN_KIT_MOCK_H +#define OHOS_DM_ACCESS_TOKEN_KIT_MOCK_H + +#include + +#include "accesstoken_kit.h" +#include "tokenid_kit.h" + +using OHOS::Security::AccessToken::ATokenTypeEnum; +using OHOS::Security::AccessToken::AccessTokenID; +using OHOS::Security::AccessToken::HapTokenInfo; +using OHOS::Security::AccessToken::NativeTokenInfo; + +namespace OHOS { +namespace DistributedHardware { +class AccessTokenKitInterface { +public: + AccessTokenKitInterface() = default; + virtual ~AccessTokenKitInterface() = default; + + virtual ATokenTypeEnum GetTokenTypeFlag(AccessTokenID) = 0; + virtual int GetHapTokenInfo(AccessTokenID, HapTokenInfo &) = 0; + virtual int GetNativeTokenInfo(AccessTokenID, NativeTokenInfo &) = 0; + virtual AccessTokenID GetNativeTokenId(const std::string &) = 0; + virtual AccessTokenID GetHapTokenID(int32_t, const std::string &, int32_t) = 0; + + static std::shared_ptr GetOrCreateAccessTokenKit(); + static void ReleaseAccessTokenKit(); +private: + static std::shared_ptr token_; +}; + +class AccessTokenKitMock : public AccessTokenKitInterface { +public: + AccessTokenKitMock() = default; + ~AccessTokenKitMock() override = default; + + MOCK_METHOD(ATokenTypeEnum, GetTokenTypeFlag, (AccessTokenID)); + MOCK_METHOD(int, GetHapTokenInfo, (AccessTokenID, HapTokenInfo &)); + MOCK_METHOD(int, GetNativeTokenInfo, (AccessTokenID, NativeTokenInfo &)); + MOCK_METHOD(AccessTokenID, GetNativeTokenId, (const std::string &)); + MOCK_METHOD(AccessTokenID, GetHapTokenID, (int32_t, const std::string &, int32_t)); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_ACCESS_TOKEN_KIT_MOCK_H \ No newline at end of file diff --git a/test/unittest/mock/bundle_mgr_mock.h b/test/unittest/mock/bundle_mgr_mock.h new file mode 100644 index 000000000..91239c02d --- /dev/null +++ b/test/unittest/mock/bundle_mgr_mock.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * 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_BUNDLE_MGR_MOCK_H +#define OHOS_DM_BUNDLE_MGR_MOCK_H + +#include + +#include "bundle_mgr_interface.h" +#include "iremote_stub.h" + +using OHOS::AppExecFwk::BundleInfo; + +namespace OHOS { +namespace DistributedHardware { +class BundleMgrMock : public IRemoteStub { +public: + BundleMgrMock() = default; + ~BundleMgrMock() override = default; + + MOCK_METHOD(ErrCode, GetNameForUid, (const int, std::string &)); + MOCK_METHOD(ErrCode, GetBundleInfoV9, (const std::string &, int32_t, BundleInfo &, int32_t)); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_BUNDLE_MGR_MOCK_H \ No newline at end of file diff --git a/test/unittest/mock/datashare_helper_mock.cpp b/test/unittest/mock/datashare_helper_mock.cpp new file mode 100644 index 000000000..9f3c3a100 --- /dev/null +++ b/test/unittest/mock/datashare_helper_mock.cpp @@ -0,0 +1,45 @@ +/* + * 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 "datashare_helper_mock.h" + +using namespace OHOS::DistributedHardware; + +namespace OHOS { +namespace DistributedHardware { +std::shared_ptr DataShareHelperMock::instance_; + +std::shared_ptr DataShareHelperMock::GetOrCreateInstance() +{ + if (!instance_) { + instance_ = std::make_shared(); + } + return instance_; +} + +void DataShareHelperMock::ReleaseInstance() +{ + instance_.reset(); + instance_ = nullptr; +} +} // namespace DistributedHardware +namespace DataShare { +std::pair> DataShareHelper::Create(const sptr &token, + const std::string &strUri, const std::string &extUri, const int waitTime) +{ + return std::make_pair(E_OK, DataShareHelperMock::GetOrCreateInstance()); +} +} // namespace DataShare +} // namespace OHOS diff --git a/test/unittest/mock/datashare_helper_mock.h b/test/unittest/mock/datashare_helper_mock.h new file mode 100644 index 000000000..5d675ea02 --- /dev/null +++ b/test/unittest/mock/datashare_helper_mock.h @@ -0,0 +1,89 @@ +/* + * 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_DATASHARE_HELPER_MOCK_H +#define OHOS_DM_DATASHARE_HELPER_MOCK_H + +#include +#include "datashare_helper.h" + +namespace OHOS { +namespace DistributedHardware { +using OHOS::AAFwk::IDataAbilityObserver; +using OHOS::DataShare::BatchUpdateResult; +using OHOS::DataShare::Data; +using OHOS::DataShare::DatashareBusinessError; +using OHOS::DataShare::DataShareHelper; +using OHOS::DataShare::DataSharePredicates; +using OHOS::DataShare::DataShareResultSet; +using OHOS::DataShare::DataShareValuesBucket; +using OHOS::DataShare::OperationStatement; +using OHOS::DataShare::ExecResultSet; +using OHOS::DataShare::OperationResult; +using OHOS::DataShare::PublishedDataChangeNode; +using OHOS::DataShare::RdbChangeNode; +using OHOS::DataShare::Template; +using OHOS::DataShare::TemplateId; +using OHOS::DataShare::UpdateOperations; + +class DataShareHelperMock : public DataShareHelper { +public: + static std::shared_ptr GetOrCreateInstance(); + static void ReleaseInstance(); + + MOCK_METHOD(bool, Release, ()); + MOCK_METHOD(std::vector, GetFileTypes, (Uri &, const std::string &)); + MOCK_METHOD(int, OpenFile, (Uri &, const std::string &)); + MOCK_METHOD(int, OpenRawFile, (Uri &, const std::string &)); + MOCK_METHOD(int, Insert, (Uri &, const DataShareValuesBucket &)); + MOCK_METHOD(int, InsertExt, (Uri &, const DataShareValuesBucket &, std::string &)); + MOCK_METHOD(int, Update, (Uri &, const DataSharePredicates &, const DataShareValuesBucket &)); + MOCK_METHOD(int, BatchUpdate, (const UpdateOperations &, std::vector &)); + MOCK_METHOD(int, Delete, (Uri &, const DataSharePredicates &)); + MOCK_METHOD(std::shared_ptr, Query, + (Uri &, const DataSharePredicates &, std::vector &, DatashareBusinessError *)); + MOCK_METHOD(std::string, GetType, (Uri &)); + MOCK_METHOD(int, BatchInsert, (Uri &, const std::vector &)); + MOCK_METHOD(int, ExecuteBatch, (const std::vector &, ExecResultSet &)); + MOCK_METHOD(int, RegisterObserver, (const Uri &, const sptr &)); + MOCK_METHOD(int, UnregisterObserver, (const Uri &, const sptr &)); + MOCK_METHOD(void, NotifyChange, (const Uri &)); + MOCK_METHOD(Uri, NormalizeUri, (Uri &)); + MOCK_METHOD(Uri, DenormalizeUri, (Uri &)); + MOCK_METHOD(int, AddQueryTemplate, (const std::string &, int64_t, Template &)); + MOCK_METHOD(int, DelQueryTemplate, (const std::string &, int64_t)); + MOCK_METHOD(std::vector, Publish, (const Data &, const std::string &)); + MOCK_METHOD(Data, GetPublishedData, (const std::string &, int &)); + MOCK_METHOD(std::vector, SubscribeRdbData, (const std::vector &, + const TemplateId &, const std::function &)); + MOCK_METHOD(std::vector, UnsubscribeRdbData, (const std::vector &, + const TemplateId &)); + MOCK_METHOD(std::vector, EnableRdbSubs, (const std::vector &, + const TemplateId &)); + MOCK_METHOD(std::vector, DisableRdbSubs, (const std::vector &, + const TemplateId &)); + MOCK_METHOD(std::vector, SubscribePublishedData, (const std::vector &, int64_t, + const std::function &)); + MOCK_METHOD(std::vector, UnsubscribePublishedData, (const std::vector &, int64_t)); + MOCK_METHOD(std::vector, EnablePubSubs, (const std::vector &, int64_t)); + MOCK_METHOD(std::vector, DisablePubSubs, (const std::vector &, int64_t)); +private: + DataShareHelperMock() = default; + ~DataShareHelperMock() override = default; + static std::shared_ptr instance_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_DATASHARE_HELPER_MOCK_H diff --git a/test/unittest/mock/datashare_result_set_mock.cpp b/test/unittest/mock/datashare_result_set_mock.cpp new file mode 100644 index 000000000..2508311c3 --- /dev/null +++ b/test/unittest/mock/datashare_result_set_mock.cpp @@ -0,0 +1,150 @@ +/* + * 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 "datashare_result_set_mock.h" + +namespace OHOS { +namespace DataShare { +DataShareAbsResultSet::DataShareAbsResultSet() +{} + +DataShareAbsResultSet::~DataShareAbsResultSet() {} + +int DataShareAbsResultSet::GetRowCount(int &count) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetAllColumnNames(std::vector &columnNames) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetBlob(int columnIndex, std::vector &blob) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetString(int columnIndex, std::string &value) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetInt(int columnIndex, int &value) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetLong(int columnIndex, int64_t &value) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetDouble(int columnIndex, double &value) +{ + return E_OK; +} + +int DataShareAbsResultSet::IsColumnNull(int columnIndex, bool &isNull) +{ + return E_OK; +} + +int DataShareAbsResultSet::GoToRow(int position) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetDataType(int columnIndex, DataType &dataType) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetRowIndex(int &position) const +{ + return E_OK; +} + +int DataShareAbsResultSet::GoTo(int offset) +{ + return E_OK; +} + +int DataShareAbsResultSet::GoToFirstRow() +{ + return E_OK; +} + +int DataShareAbsResultSet::GoToLastRow() +{ + return E_OK; +} + +int DataShareAbsResultSet::GoToNextRow() +{ + return E_OK; +} + +int DataShareAbsResultSet::GoToPreviousRow() +{ + return E_OK; +} + +int DataShareAbsResultSet::IsAtFirstRow(bool &result) const +{ + return E_OK; +} + +int DataShareAbsResultSet::IsAtLastRow(bool &result) +{ + return E_OK; +} + +int DataShareAbsResultSet::IsStarted(bool &result) const +{ + return E_OK; +} + +int DataShareAbsResultSet::IsEnded(bool &result) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetColumnCount(int &count) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetColumnIndex(const std::string &columnName, int &columnIndex) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetColumnName(int columnIndex, std::string &columnName) +{ + return E_OK; +} + +bool DataShareAbsResultSet::IsClosed() const +{ + return true; +} + +int DataShareAbsResultSet::Close() +{ + return E_OK; +} +} // namespace DataShare +} // namespace OHOS diff --git a/test/unittest/mock/datashare_result_set_mock.h b/test/unittest/mock/datashare_result_set_mock.h new file mode 100644 index 000000000..c3c3663af --- /dev/null +++ b/test/unittest/mock/datashare_result_set_mock.h @@ -0,0 +1,41 @@ +/* + * 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_DATASHARE_RESULT_SET_MOCK_H +#define OHOS_DM_DATASHARE_RESULT_SET_MOCK_H + +#include + +#include "datashare_result_set.h" + +namespace OHOS { +namespace DistributedHardware { +using OHOS::DataShare::DataShareResultSet; +using OHOS::DataShare::ResultSetBridge; + +class DataShareResultSetMock : public DataShareResultSet { +public: + explicit DataShareResultSetMock(std::shared_ptr bridge) : DataShareResultSet(bridge) + {} + ~DataShareResultSetMock() override = default; + + MOCK_METHOD(int, GetRowCount, (int &)); + MOCK_METHOD(int, GoToRow, (int)); + MOCK_METHOD(int, GetString, (int, std::string &)); + MOCK_METHOD(int, Close, ()); +}; +} // namespace namespace +} // namespace OHOS +#endif // OHOS_DM_DATASHARE_RESULT_SET_MOCK_H diff --git a/test/unittest/mock/ipc_skeleton_mock.cpp b/test/unittest/mock/ipc_skeleton_mock.cpp new file mode 100644 index 000000000..0b5d71b46 --- /dev/null +++ b/test/unittest/mock/ipc_skeleton_mock.cpp @@ -0,0 +1,53 @@ +/* + * 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 "ipc_skeleton_mock.h" + +using namespace OHOS::DistributedHardware; + +namespace OHOS { +pid_t IPCSkeleton::GetCallingUid() +{ + return IPCSkeletonInterface::GetOrCreateIPCSkeleton()->GetCallingUid(); +} + +uint32_t IPCSkeleton::GetCallingTokenID() +{ + return IPCSkeletonInterface::GetOrCreateIPCSkeleton()->GetCallingTokenID(); +} + +uint64_t IPCSkeleton::GetCallingFullTokenID() +{ + return IPCSkeletonInterface::GetOrCreateIPCSkeleton()->GetCallingFullTokenID(); +} + +namespace DistributedHardware { +std::shared_ptr IPCSkeletonInterface::skeleton_ = nullptr; + +std::shared_ptr IPCSkeletonInterface::GetOrCreateIPCSkeleton() +{ + if (!skeleton_) { + skeleton_ = std::make_shared(); + } + return skeleton_; +} + +void IPCSkeletonInterface::ReleaseIPCSkeleton() +{ + skeleton_.reset(); + skeleton_ = nullptr; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/ipc_skeleton_mock.h b/test/unittest/mock/ipc_skeleton_mock.h new file mode 100644 index 000000000..d78e5dc8d --- /dev/null +++ b/test/unittest/mock/ipc_skeleton_mock.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * 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_IPC_SKELETON_MOCK_H +#define OHOS_DM_IPC_SKELETON_MOCK_H + +#include + +#include "ipc_skeleton.h" + +namespace OHOS { +namespace DistributedHardware { +class IPCSkeletonInterface { +public: + IPCSkeletonInterface() = default; + virtual ~IPCSkeletonInterface() = default; + + virtual pid_t GetCallingUid() = 0; + virtual uint32_t GetCallingTokenID() = 0; + virtual uint64_t GetCallingFullTokenID() = 0; + static std::shared_ptr GetOrCreateIPCSkeleton(); + static void ReleaseIPCSkeleton(); +private: + static std::shared_ptr skeleton_; +}; + +class IPCSkeletonMock : public IPCSkeletonInterface { +public: + IPCSkeletonMock() = default; + ~IPCSkeletonMock() override = default; + + MOCK_METHOD(pid_t, GetCallingUid, ()); + MOCK_METHOD(uint32_t, GetCallingTokenID, ()); + MOCK_METHOD(uint64_t, GetCallingFullTokenID, ()); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_SKELETON_MOCK_H \ No newline at end of file diff --git a/test/unittest/mock/multiple_user_connector_mock.cpp b/test/unittest/mock/multiple_user_connector_mock.cpp index efc9e9163..2bdba1e92 100644 --- a/test/unittest/mock/multiple_user_connector_mock.cpp +++ b/test/unittest/mock/multiple_user_connector_mock.cpp @@ -48,5 +48,15 @@ std::string MultipleUserConnector::GetOhosAccountId(void) { return DmMultipleUserConnector::dmMultipleUserConnector->GetOhosAccountId(); } + +std::string MultipleUserConnector::GetAccountNickName(int32_t userId) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetAccountNickName(userId); +} + +void MultipleUserConnector::GetCallerUserId(int32_t &userId) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetCallerUserId(userId); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/multiple_user_connector_mock.h b/test/unittest/mock/multiple_user_connector_mock.h index dfd60d0ea..2123d08e4 100644 --- a/test/unittest/mock/multiple_user_connector_mock.h +++ b/test/unittest/mock/multiple_user_connector_mock.h @@ -32,6 +32,8 @@ public: virtual int32_t GetBackgroundUserIds(std::vector &userIdVec) = 0; virtual int32_t GetForegroundUserIds(std::vector &userVec) = 0; virtual std::string GetOhosAccountId(void) = 0; + virtual std::string GetAccountNickName(int32_t) = 0; + virtual void GetCallerUserId(int32_t &) = 0; public: static inline std::shared_ptr dmMultipleUserConnector = nullptr; }; @@ -44,6 +46,8 @@ public: MOCK_METHOD(int32_t, GetBackgroundUserIds, (std::vector &)); MOCK_METHOD(int32_t, GetForegroundUserIds, (std::vector &)); MOCK_METHOD(std::string, GetOhosAccountId, ()); + MOCK_METHOD(std::string, GetAccountNickName, (int32_t)); + MOCK_METHOD(void, GetCallerUserId, (int32_t &)); }; } } diff --git a/test/unittest/mock/os_account_manager_mock.cpp b/test/unittest/mock/os_account_manager_mock.cpp new file mode 100644 index 000000000..9bd05b356 --- /dev/null +++ b/test/unittest/mock/os_account_manager_mock.cpp @@ -0,0 +1,45 @@ +/* + * 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 "os_account_manager_mock.h" + +using namespace OHOS::DistributedHardware; + +namespace OHOS { +namespace DistributedHardware { +std::shared_ptr IOsAccountManager::accountManager_ = nullptr; + +std::shared_ptr IOsAccountManager::GetOrCreateOsAccountManager() +{ + if (!accountManager_) { + accountManager_ = std::make_shared(); + } + return accountManager_; +} + +void IOsAccountManager::ReleaseAccountManager() +{ + accountManager_.reset(); + accountManager_ = nullptr; +} +} // namespace DistributedHardware + +namespace AccountSA { +ErrCode OsAccountManager::GetForegroundOsAccountLocalId(int32_t &localId) +{ + return IOsAccountManager::GetOrCreateOsAccountManager()->GetForegroundOsAccountLocalId(localId); +} +} // namespace AccountSA +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/os_account_manager_mock.h b/test/unittest/mock/os_account_manager_mock.h new file mode 100644 index 000000000..29d52a41b --- /dev/null +++ b/test/unittest/mock/os_account_manager_mock.h @@ -0,0 +1,41 @@ +/* + * 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_OS_ACCOUNT_MANAGER_MOCK_H +#define OHOS_DM_OS_ACCOUNT_MANAGER_MOCK_H + +#include +#include "os_account_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class IOsAccountManager { +public: + IOsAccountManager() = default; + virtual ~IOsAccountManager() = default; + + virtual ErrCode GetForegroundOsAccountLocalId(int32_t &localId) = 0; + static std::shared_ptr GetOrCreateOsAccountManager(); + static void ReleaseAccountManager(); +private: + static std::shared_ptr accountManager_; +}; + +class OsAccountManagerMock : public IOsAccountManager { +public: + MOCK_METHOD(ErrCode, GetForegroundOsAccountLocalId, (int32_t &)); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_OS_ACCOUNT_MANAGER_MOCK_H \ No newline at end of file diff --git a/test/unittest/mock/softbus_bus_center.cpp b/test/unittest/mock/softbus_bus_center.cpp index 6c55bca6e..471ad110e 100644 --- a/test/unittest/mock/softbus_bus_center.cpp +++ b/test/unittest/mock/softbus_bus_center.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -40,3 +40,27 @@ int32_t GetAllNodeDeviceInfo(const char *pkgName, NodeBasicInfo **info, int32_t (void)infoNum; return 0; } + +int32_t PublishLNN(const char *pkgName, const PublishInfo *info, const IPublishCb *cb) +{ + (void)pkgName; + (void)info; + (void)cb; + return 0; +} + +int32_t StopPublishLNN(const char *pkgName, int32_t publishId) +{ + (void)pkgName; + (void)publishId; + return 0; +} + +int CreateSessionServer(const char *pkgName, const char *sessionName, const ISessionListener *listener) +{ + (void)pkgName; + (void)sessionName; + (void)listener; + return 0; +} + diff --git a/test/unittest/mock/softbus_connector_mock.cpp b/test/unittest/mock/softbus_connector_mock.cpp index 70351519e..171311d9e 100644 --- a/test/unittest/mock/softbus_connector_mock.cpp +++ b/test/unittest/mock/softbus_connector_mock.cpp @@ -24,10 +24,20 @@ int32_t SoftbusConnector::GetUdidByNetworkId(const char *networkId, std::string { return DmSoftbusConnector::dmSoftbusConnector->GetUdidByNetworkId(networkId, udid); } + bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) { return DmSoftbusConnector::dmSoftbusConnector->CheckIsOnline(targetDeviceId); } +std::vector SoftbusConnector::GetProcessInfo() +{ + return DmSoftbusConnector::dmSoftbusConnector->GetProcessInfo(); +} + +DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &deviceId) +{ + return DmSoftbusConnector::dmSoftbusConnector->GetDeviceInfoByDeviceId(deviceId); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_connector_mock.h b/test/unittest/mock/softbus_connector_mock.h index 10145e8c5..fa25cade0 100644 --- a/test/unittest/mock/softbus_connector_mock.h +++ b/test/unittest/mock/softbus_connector_mock.h @@ -28,6 +28,8 @@ public: public: virtual int32_t GetUdidByNetworkId(const char *networkId, std::string &udid) = 0; virtual bool CheckIsOnline(const std::string &targetDeviceId) = 0; + virtual std::vector GetProcessInfo() = 0; + virtual DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId) = 0; public: static inline std::shared_ptr dmSoftbusConnector = nullptr; }; @@ -36,6 +38,8 @@ class SoftbusConnectorMock : public DmSoftbusConnector { public: MOCK_METHOD(int32_t, GetUdidByNetworkId, (const char *, std::string &)); MOCK_METHOD(bool, CheckIsOnline, (const std::string &)); + MOCK_METHOD(std::vector, GetProcessInfo, ()); + MOCK_METHOD(DmDeviceInfo, GetDeviceInfoByDeviceId, (const std::string &deviceId)); }; } } diff --git a/test/unittest/mock/system_ability_manager_client_mock.cpp b/test/unittest/mock/system_ability_manager_client_mock.cpp new file mode 100644 index 000000000..777a6d0fd --- /dev/null +++ b/test/unittest/mock/system_ability_manager_client_mock.cpp @@ -0,0 +1,49 @@ +/* +* 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 "system_ability_manager_client_mock.h" + +using namespace OHOS::DistributedHardware; + +namespace OHOS { +SystemAbilityManagerClient& SystemAbilityManagerClient::GetInstance() +{ + static auto instance = std::make_shared(); + return *instance; +} + +sptr SystemAbilityManagerClient::GetSystemAbilityManager() +{ + return ISystemAbilityManagerClient::GetOrCreateSAMgrClient()->GetSystemAbilityManager(); +} + +namespace DistributedHardware { +std::shared_ptr ISystemAbilityManagerClient::client_ = nullptr; + +std::shared_ptr ISystemAbilityManagerClient::GetOrCreateSAMgrClient() +{ + if (!client_) { + client_ = std::make_shared(); + } + return client_; +} + +void ISystemAbilityManagerClient::ReleaseSAMgrClient() +{ + client_.reset(); + client_ = nullptr; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/system_ability_manager_client_mock.h b/test/unittest/mock/system_ability_manager_client_mock.h new file mode 100644 index 000000000..dc6e4fcc4 --- /dev/null +++ b/test/unittest/mock/system_ability_manager_client_mock.h @@ -0,0 +1,41 @@ +/* +* 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_SYSTEM_ABILITY_MANAGER_CLIENT_MOCK_H +#define OHOS_DM_SYSTEM_ABILITY_MANAGER_CLIENT_MOCK_H + +#include +#include "iservice_registry.h" + +namespace OHOS { +namespace DistributedHardware { +class ISystemAbilityManagerClient { +public: + ISystemAbilityManagerClient() = default; + virtual ~ISystemAbilityManagerClient() = default; + + virtual sptr GetSystemAbilityManager() = 0; + static std::shared_ptr GetOrCreateSAMgrClient(); + static void ReleaseSAMgrClient(); +private: + static std::shared_ptr client_; +}; + +class SystemAbilityManagerClientMock : public ISystemAbilityManagerClient { +public: + MOCK_METHOD0(GetSystemAbilityManager, sptr()); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SYSTEM_ABILITY_MANAGER_CLIENT_MOCK_H -- Gitee