From 71de81b4cb8f3563502bcaf3e18594a7572bd5b8 Mon Sep 17 00:00:00 2001 From: luqing Date: Thu, 3 Jul 2025 15:52:02 +0800 Subject: [PATCH] =?UTF-8?q?=E9=97=AE=E9=A2=98=E5=8D=95=E5=A4=84=E7=90=86?= =?UTF-8?q?=20Signed-off-by:=20luqing=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../route_head_handler_impl.cpp | 7 +- .../service/object/BUILD.gn | 1 + .../service/object/include/object_manager.h | 8 +- .../service/object/src/object_manager.cpp | 88 ++++++- .../service/test/BUILD.gn | 67 ++++++ .../service/test/mock/BUILD.gn | 2 + .../service/test/mock/device_matrix_mock.cpp | 29 +++ .../service/test/mock/device_matrix_mock.h | 37 +++ .../test/mock/meta_data_manager_mock.cpp | 6 + .../test/mock/meta_data_manager_mock.h | 2 + .../service/test/object_manager_mock_test.cpp | 217 ++++++++++++++++++ .../service/test/object_manager_test.cpp | 29 --- .../service/test/object_service_impl_test.cpp | 27 ++- 13 files changed, 477 insertions(+), 43 deletions(-) create mode 100644 services/distributeddataservice/service/test/mock/device_matrix_mock.cpp create mode 100644 services/distributeddataservice/service/test/mock/device_matrix_mock.h create mode 100644 services/distributeddataservice/service/test/object_manager_mock_test.cpp diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp index 56d347e2e..8cedf5c9b 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp @@ -101,7 +101,10 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize { ZLOGD("begin"); headSize = 0; - if (appId_ == Bootstrap::GetInstance().GetProcessLabel() && storeId_ == Bootstrap::GetInstance().GetMetaDBName()) { + bool flag = false; + auto peerCap = UpgradeManager::GetInstance().GetCapability(session_.targetDeviceId, flag); + if (!flag || (appId_ == Bootstrap::GetInstance().GetProcessLabel() && + storeId_ == Bootstrap::GetInstance().GetMetaDBName())) { ZLOGI("meta data permitted"); return DistributedDB::OK; } @@ -117,8 +120,6 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize } return DistributedDB::OK; } - bool flag = false; - auto peerCap = UpgradeManager::GetInstance().GetCapability(session_.targetDeviceId, flag); if (!flag) { ZLOGI("get peer cap failed"); return DistributedDB::DB_ERROR; diff --git a/services/distributeddataservice/service/object/BUILD.gn b/services/distributeddataservice/service/object/BUILD.gn index 35412b733..7ebc67331 100644 --- a/services/distributeddataservice/service/object/BUILD.gn +++ b/services/distributeddataservice/service/object/BUILD.gn @@ -18,6 +18,7 @@ config("object_public_config") { include_dirs = [ "${data_service_path}/service/common", + "${data_service_path}/service/matrix/include", "${data_service_path}/adapter/include/communicator", "${data_service_path}/adapter/include/utils", ] diff --git a/services/distributeddataservice/service/object/include/object_manager.h b/services/distributeddataservice/service/object/include/object_manager.h index a5026a5d0..92264ac3a 100644 --- a/services/distributeddataservice/service/object/include/object_manager.h +++ b/services/distributeddataservice/service/object/include/object_manager.h @@ -21,6 +21,7 @@ #include "device_manager_adapter.h" #include "kv_store_delegate_manager.h" #include "kvstore_sync_callback.h" +#include "metadata/store_meta_data.h" #include "object_asset_loader.h" #include "object_callback.h" #include "object_callback_proxy.h" @@ -64,6 +65,7 @@ class ObjectStoreManager { public: using DmAdaper = OHOS::DistributedData::DeviceManagerAdapter; using UriToSnapshot = std::shared_ptr>>; + using StoreMetaData = OHOS::DistributedData::StoreMetaData; enum RestoreStatus : int32_t { NONE = 0, @@ -157,8 +159,8 @@ private: std::string ToPropertyPrefix(); }; DistributedDB::KvStoreNbDelegate *OpenObjectKvStore(); - void FlushClosedStore(); - void Close(); + void FlushClosedStore(bool forceClose = false); + void Close(bool forceClose = false); int32_t SetSyncStatus(bool status); int32_t SaveToStore(const std::string &appId, const std::string &sessionId, const std::string &toDeviceId, const ObjectRecord &data); @@ -171,6 +173,8 @@ private: void ProcessSyncCallback(const std::map &results, const std::string &appId, const std::string &sessionId, const std::string &deviceId); void SaveUserToMeta(); + bool IsNeedMetaSync(const StoreMetaData &meta, const std::vector &networkIds); + int32_t DoSync(const std::string &prefix, const std::vector &deviceList, uint64_t sequenceId); std::string GetCurrentUser(); void DoNotify(uint32_t tokenId, const CallbackInfo& value, const std::map& data, bool allReady); diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 8e08a4cf6..1aeba9ffb 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -26,6 +26,9 @@ #include "common/string_utils.h" #include "datetime_ex.h" #include "distributed_file_daemon_manager.h" +#include "device_matrix.h" +#include "ipc_skeleton.h" +#include "metadata/capability_meta_data.h" #include "kvstore_utils.h" #include "log_print.h" #include "metadata/meta_data_manager.h" @@ -44,6 +47,8 @@ using Account = OHOS::DistributedData::AccountDelegate; using AccessTokenKit = Security::AccessToken::AccessTokenKit; using ValueProxy = OHOS::DistributedData::ValueProxy; using DistributedFileDaemonManager = Storage::DistributedFile::DistributedFileDaemonManager; +using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; + constexpr const char *SAVE_INFO = "p_###SAVEINFO###"; constexpr int32_t PROGRESS_MAX = 100; constexpr int32_t PROGRESS_INVALID = -1; @@ -319,7 +324,7 @@ int32_t ObjectStoreManager::Clear() result = RevokeSaveToStore(""); callbacks_.Clear(); processCallbacks_.Clear(); - Close(); + Close(true); return result; } @@ -571,6 +576,34 @@ void ObjectStoreManager::ComputeStatus(const std::string& objectKey, const SaveI }); } +bool ObjectStoreManager::IsNeedMetaSync(const StoreMetaData &meta, const std::vector &uuids) +{ + bool isAfterMeta = false; + for (const auto &uuid : uuids) { + auto metaData = meta; + metaData.deviceId = uuid; + CapMetaData capMeta; + auto capKey = CapMetaRow::GetKeyFor(uuid); + bool flag = !MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), capMeta) || + !MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData); + if (flag) { + isAfterMeta = true; + break; + } + auto [exist, mask] = DeviceMatrix::GetInstance().GetRemoteMask(uuid); + if ((mask & DeviceMatrix::META_STORE_MASK) == DeviceMatrix::META_STORE_MASK) { + isAfterMeta = true; + break; + } + auto [existLocal, localMask] = DeviceMatrix::GetInstance().GetMask(uuid); + if ((localMask & DeviceMatrix::META_STORE_MASK) == DeviceMatrix::META_STORE_MASK) { + isAfterMeta = true; + break; + } + } + return isAfterMeta; +} + void ObjectStoreManager::NotifyDataChanged(const std::map& data, const SaveInfo& saveInfo) { for (auto const& [objectKey, results] : data) { @@ -852,21 +885,21 @@ int32_t ObjectStoreManager::Open() return OBJECT_SUCCESS; } -void ObjectStoreManager::Close() +void ObjectStoreManager::Close(bool forceClose) { std::lock_guard lock(kvStoreMutex_); if (delegate_ == nullptr) { return; } int32_t taskCount = delegate_->GetTaskCount(); - if (taskCount > 0 && syncCount_ == 1) { + if (taskCount > 0 && syncCount_ == 1 && !forceClose) { CloseAfterMinute(); ZLOGW("Store is busy, close after a minute, task count: %{public}d", taskCount); return; } syncCount_--; ZLOGI("closed a store, syncCount = %{public}d", syncCount_); - FlushClosedStore(); + FlushClosedStore(forceClose); } void ObjectStoreManager::SyncCompleted( @@ -892,7 +925,7 @@ void ObjectStoreManager::SyncCompleted( } } -void ObjectStoreManager::FlushClosedStore() +void ObjectStoreManager::FlushClosedStore(bool forceClose) { std::lock_guard lock(kvStoreMutex_); if (!isSyncing_ && syncCount_ == 0 && delegate_ != nullptr) { @@ -900,13 +933,21 @@ void ObjectStoreManager::FlushClosedStore() auto status = kvStoreDelegateManager_->CloseKvStore(delegate_); if (status != DistributedDB::DBStatus::OK) { int timeOut = 1000; - executors_->Schedule(std::chrono::milliseconds(timeOut), [this]() { - FlushClosedStore(); + executors_->Schedule(std::chrono::milliseconds(timeOut), [this, forceClose]() { + FlushClosedStore(forceClose); }); ZLOGE("GetEntries fail %{public}d", status); return; } delegate_ = nullptr; + } else if (forceClose && delegate_ != nullptr) { + ZLOGW("Force closing store: isSyncing_ = %{public}s, syncCount_ = %{public}d.", + isSyncing_ ? "true" : "false", syncCount_); + auto status = kvStoreDelegateManager_->CloseKvStore(delegate_); + ZLOGW("Force close result: %{public}d.", status); + delegate_ = nullptr; + isSyncing_ = false; + syncCount_ = 0; } } @@ -1006,10 +1047,41 @@ int32_t ObjectStoreManager::SyncOnStore( return OBJECT_SUCCESS; } uint64_t sequenceId = SequenceSyncManager::GetInstance()->AddNotifier(userId_, callback); + + int32_t id = AccountDelegate::GetInstance()->GetUserByToken(IPCSkeleton::GetCallingFullTokenID()); + StoreMetaData meta = StoreMetaData(std::to_string(id), Bootstrap::GetInstance().GetProcessLabel(), + DistributedObject::ObjectCommon::OBJECTSTORE_DB_STOREID); + auto uuids = DmAdapter::GetInstance().ToUUID(syncDevices); + bool isNeedMetaSync = IsNeedMetaSync(meta, uuids); + if (isNeedMetaSync) { + bool metaRes = MetaDataManager::GetInstance().Sync(uuids, + [this, prefix, syncDevices, sequenceId] (auto &results) { + if (DoSync(prefix, syncDevices, sequenceId) != OBJECT_SUCCESS) { + ZLOGE("Store sync failed"); + } + }); + if (!metaRes) { + ZLOGE("prefix:%{public}s, meta sync failed", prefix.c_str()); + return E_DB_ERROR; + } else { + ZLOGI("meta sync success"); + return OBJECT_SUCCESS; + } + } + return DoSync(prefix, syncDevices, sequenceId); +} + +int32_t ObjectStoreManager::DoSync(const std::string &prefix, const std::vector &deviceList, + uint64_t sequenceId) +{ DistributedDB::Query dbQuery = DistributedDB::Query::Select(); dbQuery.PrefixKey(std::vector(prefix.begin(), prefix.end())); ZLOGI("Start sync data, sequenceId: 0x%{public}" PRIx64 "", sequenceId); - auto status = delegate_->Sync(syncDevices, DistributedDB::SyncMode::SYNC_MODE_PUSH_ONLY, + if (delegate_ == nullptr) { + ZLOGE("delegate_ == nullptr"); + return E_DB_ERROR; + } + auto status = delegate_->Sync(deviceList, DistributedDB::SyncMode::SYNC_MODE_PUSH_ONLY, [this, sequenceId](const std::map &devicesMap) { ZLOGI("Sync data finished, sequenceId: 0x%{public}" PRIx64 "", sequenceId); std::map result; diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index c93164adb..276c412d9 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -862,6 +862,72 @@ ohos_unittest("ObjectManagerTest") { ] } +ohos_unittest("ObjectManagerMockTest") { + module_out_path = module_output_path + sources = [ + "${data_service_path}/app/src/kvstore_meta_manager.cpp", + "${data_service_path}/service/common/common_types_utils.cpp", + "${data_service_path}/service/common/value_proxy.cpp", + "../object/src/object_asset_loader.cpp", + "../object/src/object_asset_machine.cpp", + "../object/src/object_callback_proxy.cpp", + "../object/src/object_data_listener.cpp", + "../object/src/object_dms_handler.cpp", + "../object/src/object_manager.cpp", + "../object/src/object_service_impl.cpp", + "../object/src/object_service_stub.cpp", + "../object/src/object_snapshot.cpp", + "../object/src/object_types_utils.cpp", + "mock/device_manager_adapter_mock.cpp", + "mock/kv_store_nb_delegate_mock.cpp", + "object_manager_mock_test.cpp", + "mock/meta_data_manager_mock.cpp", + "mock/device_matrix_mock.cpp", + ] + + include_dirs = [ + "${data_service_path}/adapter/include/utils", + "${data_service_path}/app/src", + "${data_service_path}/service/common", + "${data_service_path}/service/test/mock", + ] + + configs = [ ":module_private_config" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libtoken_setproc", + "access_token:libtokenid_sdk", + "c_utils:utils", + "data_object:distributeddataobject_impl", + "data_object:data_object_inner", + "dataclassification:data_transit_mgr", + "dfs_service:cloudsync_asset_kit_inner", + "dfs_service:distributed_file_daemon_kit_inner", + "dmsfwk:distributed_sdk", + "googletest:gmock_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + "cJSON:cjson", + "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", + "kv_store:distributeddb", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + ] + + deps = [ + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", + ] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] +} + ohos_unittest("ObjectSnapshotTest") { module_out_path = module_output_path sources = [ @@ -2240,6 +2306,7 @@ group("unittest") { ":ObjectDmsHandlerTest", ":ObjectManagerTest", ":ObjectSnapshotTest", + ":ObjectManagerMockTest", ] } diff --git a/services/distributeddataservice/service/test/mock/BUILD.gn b/services/distributeddataservice/service/test/mock/BUILD.gn index ce0a05278..3f49d2d2e 100644 --- a/services/distributeddataservice/service/test/mock/BUILD.gn +++ b/services/distributeddataservice/service/test/mock/BUILD.gn @@ -19,6 +19,7 @@ config("module_private_config") { include_dirs = [ "${data_service_path}/adapter/include/communicator", "${data_service_path}/service/kvdb", + "${data_service_path}/service/matrix/include/", "../../../framework/include/", "../../../service/rdb/", "./", @@ -48,6 +49,7 @@ ohos_static_library("distributeddata_mock_static") { "network_delegate_mock.cpp", "screen_lock_mock.cpp", "user_delegate_mock.cpp", + "device_matrix_mock.cpp", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] diff --git a/services/distributeddataservice/service/test/mock/device_matrix_mock.cpp b/services/distributeddataservice/service/test/mock/device_matrix_mock.cpp new file mode 100644 index 000000000..02a95da84 --- /dev/null +++ b/services/distributeddataservice/service/test/mock/device_matrix_mock.cpp @@ -0,0 +1,29 @@ +/* + * 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 "device_matrix_mock.h" + +namespace OHOS { +namespace DistributedData { +std::pair DeviceMatrix::GetRemoteMask(const std::string &device, DeviceMatrix::LevelType type) +{ + return BDeviceMatrix::deviceMatrix->GetRemoteMask(device, type); +} + +std::pair DeviceMatrix::GetMask(const std::string &device, DeviceMatrix::LevelType type) +{ + return BDeviceMatrix::deviceMatrix->GetMask(device, type); +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/device_matrix_mock.h b/services/distributeddataservice/service/test/mock/device_matrix_mock.h new file mode 100644 index 000000000..44159fa8e --- /dev/null +++ b/services/distributeddataservice/service/test/mock/device_matrix_mock.h @@ -0,0 +1,37 @@ +/* + * 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_DEVICE_MATRIX_MOCK_H +#define OHOS_DEVICE_MATRIX_MOCK_H + +#include + +#include "device_matrix.h" + +namespace OHOS::DistributedData { +class BDeviceMatrix { +public: + virtual std::pair GetMask(const std::string &, DeviceMatrix::LevelType); + virtual std::pair GetRemoteMask(const std::string &, DeviceMatrix::LevelType); + BDeviceMatrix() = default; + virtual ~BDeviceMatrix() = default; + static inline std::shared_ptr deviceMatrix = nullptr; +}; +class DeviceMatrixMock : public BDeviceMatrix { +public: + MOCK_METHOD((std::pair), GetMask, (const std::string &, DeviceMatrix::LevelType), (override)); + MOCK_METHOD((std::pair), GetRemoteMask, (const std::string &, DeviceMatrix::LevelType), (override)); +}; +} // namespace OHOS::DistributedData +#endif //OHOS_DEVICE_MATRIX_MOCK_H diff --git a/services/distributeddataservice/service/test/mock/meta_data_manager_mock.cpp b/services/distributeddataservice/service/test/mock/meta_data_manager_mock.cpp index 634760740..fff2933da 100644 --- a/services/distributeddataservice/service/test/mock/meta_data_manager_mock.cpp +++ b/services/distributeddataservice/service/test/mock/meta_data_manager_mock.cpp @@ -40,6 +40,12 @@ bool OHOS::DistributedData::MetaDataManager::LoadMeta(const std::string &key, Se return BMetaDataManager::metaDataManager->LoadMeta(key, value, isLocal); } +bool OHOS::DistributedData::MetaDataManager::Sync(const std::vector &devices, + MetaDataManager::OnComplete complete, bool wait) +{ + return BMetaDataManager::metaDataManager->Sync(devices, complete, wait); +} + template<> bool OHOS::DistributedData::MetaDataManager::LoadMeta( const std::string &prefix, std::vector &values, bool isLocal) diff --git a/services/distributeddataservice/service/test/mock/meta_data_manager_mock.h b/services/distributeddataservice/service/test/mock/meta_data_manager_mock.h index 6db1bf937..42926ab92 100644 --- a/services/distributeddataservice/service/test/mock/meta_data_manager_mock.h +++ b/services/distributeddataservice/service/test/mock/meta_data_manager_mock.h @@ -26,6 +26,7 @@ namespace OHOS::DistributedData { class BMetaDataManager { public: virtual bool LoadMeta(const std::string &, Serializable &, bool) = 0; + virtual bool Sync(const std::vector &, MetaDataManager::OnComplete, bool) = 0; BMetaDataManager() = default; virtual ~BMetaDataManager() = default; static inline std::shared_ptr metaDataManager = nullptr; @@ -33,6 +34,7 @@ public: class MetaDataManagerMock : public BMetaDataManager { public: MOCK_METHOD(bool, LoadMeta, (const std::string &, Serializable &, bool), (override)); + MOCK_METHOD(bool, Sync, (const std::vector &, MetaDataManager::OnComplete, bool), (override)); }; template class BMetaData { diff --git a/services/distributeddataservice/service/test/object_manager_mock_test.cpp b/services/distributeddataservice/service/test/object_manager_mock_test.cpp new file mode 100644 index 000000000..6c659b24d --- /dev/null +++ b/services/distributeddataservice/service/test/object_manager_mock_test.cpp @@ -0,0 +1,217 @@ +/* +* 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. +*/ + +#define LOG_TAG "ObjectManagerMockTest" +#include "object_manager.h" + +#include +#include "gtest/gtest.h" + +#include "device_matrix_mock.h" +#include "mock/meta_data_manager_mock.h" +#include "device_manager_adapter_mock.h" + +using namespace OHOS::DistributedObject; +using namespace OHOS::DistributedData; +using namespace testing::ext; +using namespace testing; +using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo; +using OnComplete = OHOS::DistributedData::MetaDataManager::OnComplete; + +namespace OHOS::Test { +namespace DistributedDataTest { +class ObjectManagerMockTest : public testing::Test { +public: + static void SetUpTestCase(void) + { + metaDataManagerMock = std::make_shared(); + BMetaDataManager::metaDataManager = metaDataManagerMock; + metaDataMock = std::make_shared>(); + BMetaData::metaDataManager = metaDataMock; + devMgrAdapterMock = std::make_shared(); + BDeviceManagerAdapter::deviceManagerAdapter = devMgrAdapterMock; + deviceMatrixMock = std::make_shared(); + BDeviceMatrix::deviceMatrix = deviceMatrixMock; + } + static void TearDownTestCase(void) + { + metaDataManagerMock = nullptr; + BMetaDataManager::metaDataManager = nullptr; + metaDataMock = nullptr; + BMetaData::metaDataManager = nullptr; + devMgrAdapterMock = nullptr; + BDeviceManagerAdapter::deviceManagerAdapter = nullptr; + deviceMatrixMock = nullptr; + BDeviceMatrix::deviceMatrix = nullptr; + } + + static inline std::shared_ptr metaDataManagerMock = nullptr; + static inline std::shared_ptr> metaDataMock = nullptr; + static inline std::shared_ptr devMgrAdapterMock = nullptr; + static inline std::shared_ptr deviceMatrixMock = nullptr; + void SetUp() {}; + void TearDown() {}; +}; + +/** + * @tc.name: IsNeedMetaSync001 + * @tc.desc: Test IsNeedMetaSync when LoadMeta fails for CapMetaData. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(ObjectManagerMockTest, IsNeedMetaSync001, TestSize.Level0) +{ + auto manager = ObjectStoreManager::GetInstance(); + StoreMetaData meta; + meta.deviceId = "test_device_id"; + meta.user = "0"; + meta.storeId = "distributedObject_"; + meta.bundleName = "test_bundle"; + std::vector uuids = {"test_uuid"}; + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(false)) + .WillOnce(testing::Return(false)); + bool isNeedSync = manager->IsNeedMetaSync(meta, uuids); + EXPECT_EQ(isNeedSync, true); + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(false)) + .WillOnce(testing::Return(true)); + isNeedSync = manager->IsNeedMetaSync(meta, uuids); + EXPECT_EQ(isNeedSync, true); + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(true)) + .WillOnce(testing::Return(false)); + isNeedSync = manager->IsNeedMetaSync(meta, uuids); + EXPECT_EQ(isNeedSync, true); +} + +/** + * @tc.name: IsNeedMetaSync002 + * @tc.desc: Test IsNeedMetaSync when LoadMeta fails for StoreMetaData. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(ObjectManagerMockTest, IsNeedMetaSync002, TestSize.Level0) +{ + auto manager = ObjectStoreManager::GetInstance(); + StoreMetaData meta; + meta.deviceId = "test_device_id"; + meta.user = "0"; + meta.storeId = "distributedObject_"; + meta.bundleName = "test_bundle"; + + std::vector uuids = {"test_uuid"}; + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) + .WillRepeatedly(Return((true))); + + EXPECT_CALL(*deviceMatrixMock, GetRemoteMask(_, _)) + .WillRepeatedly(Return(std::make_pair(true, DeviceMatrix::META_STORE_MASK))); + + bool result = manager->IsNeedMetaSync(meta, uuids); + EXPECT_EQ(result, true); +} + +/** + * @tc.name: IsNeedMetaSync003 + * @tc.desc: Test IsNeedMetaSync when LoadMeta fails for StoreMetaData. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(ObjectManagerMockTest, IsNeedMetaSync003, TestSize.Level0) +{ + auto manager = ObjectStoreManager::GetInstance(); + StoreMetaData meta; + meta.deviceId = "test_device_id"; + meta.user = "0"; + meta.storeId = "distributedObject_"; + meta.bundleName = "test_bundle"; + + std::vector uuids = {"test_uuid"}; + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) + .WillRepeatedly(Return(true)); + + EXPECT_CALL(*deviceMatrixMock, GetRemoteMask(_, _)) + .WillOnce(Return(std::make_pair(true, 0))); + + EXPECT_CALL(*deviceMatrixMock, GetMask(_, _)) + .WillOnce(Return(std::make_pair(true, DeviceMatrix::META_STORE_MASK))); + + bool result = manager->IsNeedMetaSync(meta, uuids); + EXPECT_EQ(result, true); +} + +HWTEST_F(ObjectManagerMockTest, SyncOnStore001, TestSize.Level0) +{ + auto manager = ObjectStoreManager::GetInstance(); + std::function &results)> func; + func = [](const std::map &results) { + return results; + }; + std::string prefix = "ObjectManagerTest"; + StoreMetaData meta; + meta.deviceId = "test_device_id"; + meta.user = "0"; + meta.storeId = "distributedObject_"; + meta.bundleName = "test_bundle"; + std::vector uuids = {"test_uuid"}; + + + // local device + { + std::vector localDeviceList = {"local"}; + auto result = manager->SyncOnStore(prefix, localDeviceList, func); + EXPECT_EQ(result, OBJECT_SUCCESS); + } + + // remote device. IsNeedMetaSync: true; Sync: true + { + std::vector remoteDeviceList = {"remote_device_1"}; + + EXPECT_CALL(*devMgrAdapterMock, GetUuidByNetworkId(_)).WillRepeatedly(Return("mock_uuid")); + EXPECT_CALL(*devMgrAdapterMock, ToUUID(_)) + .WillOnce(Return(std::vector{"mock_uuid_1"})); + EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) + .WillOnce(testing::Return(false)) + .WillOnce(testing::Return(false)); + EXPECT_CALL(*metaDataManagerMock, Sync(_, _, _)).WillOnce(testing::Return(true)); + auto result = manager->SyncOnStore(prefix, remoteDeviceList, func); + EXPECT_EQ(result, OBJECT_SUCCESS); + } + + // remote device. IsNeedMetaSync: true; Sync: false + { + std::vector remoteDeviceList = {"remote_device_1"}; + + EXPECT_CALL(*devMgrAdapterMock, GetUuidByNetworkId(_)).WillRepeatedly(Return("mock_uuid")); + EXPECT_CALL(*devMgrAdapterMock, ToUUID(_)) + .WillOnce(Return(std::vector{"mock_uuid_1"})); + EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) + .WillOnce(testing::Return(false)) + .WillOnce(testing::Return(false)); + EXPECT_CALL(*metaDataManagerMock, Sync(_, _, _)).WillOnce(testing::Return(false)); + auto result = manager->SyncOnStore(prefix, remoteDeviceList, func); + EXPECT_EQ(result, E_DB_ERROR); + } +} +}; // namespace OHOS::Test +} \ No newline at end of file diff --git a/services/distributeddataservice/service/test/object_manager_test.cpp b/services/distributeddataservice/service/test/object_manager_test.cpp index e68fbf262..838ee4020 100644 --- a/services/distributeddataservice/service/test/object_manager_test.cpp +++ b/services/distributeddataservice/service/test/object_manager_test.cpp @@ -529,35 +529,6 @@ HWTEST_F(ObjectManagerTest, Close001, TestSize.Level0) ASSERT_EQ(manager->syncCount_, 0); // 0 is for testing } -/** -* @tc.name: SyncOnStore001 -* @tc.desc: SyncOnStore test. -* @tc.type: FUNC -* @tc.require: -* @tc.author: wangbin -*/ -HWTEST_F(ObjectManagerTest, SyncOnStore001, TestSize.Level0) -{ - auto manager = ObjectStoreManager::GetInstance(); - manager->delegate_ = manager->OpenObjectKvStore(); - std::function &results)> func; - func = [](const std::map &results) { - return results; - }; - std::string prefix = "ObjectManagerTest"; - std::vector deviceList; - // not local device & syncDevices empty - deviceList.push_back("local1"); - EXPECT_CALL(*devMgrAdapterMock, IsSameAccount(_)).WillOnce(Return(true)); - auto result = manager->SyncOnStore(prefix, deviceList, func); - ASSERT_NE(result, OBJECT_SUCCESS); - // local device - deviceList.push_back("local"); - EXPECT_CALL(*devMgrAdapterMock, IsSameAccount(_)).WillOnce(Return(true)); - result = manager->SyncOnStore(prefix, deviceList, func); - ASSERT_EQ(result, OBJECT_SUCCESS); -} - /** * @tc.name: RetrieveFromStore001 * @tc.desc: RetrieveFromStore test. diff --git a/services/distributeddataservice/service/test/object_service_impl_test.cpp b/services/distributeddataservice/service/test/object_service_impl_test.cpp index 11a66c41f..d433822af 100644 --- a/services/distributeddataservice/service/test/object_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/object_service_impl_test.cpp @@ -20,11 +20,14 @@ #include #include "accesstoken_kit.h" +#include "device_manager_adapter_mock.h" #include "ipc_skeleton.h" #include "token_setproc.h" using namespace testing::ext; using namespace OHOS::DistributedObject; +using namespace std; +using namespace testing; namespace OHOS::Test { class ObjectServiceImplTest : public testing::Test { public: @@ -45,6 +48,7 @@ protected: ObjectStore::AssetBindInfo assetBindInfo_; pid_t pid_ = 10; uint32_t tokenId_ = 100; + static inline std::shared_ptr devMgrAdapterMock = nullptr; }; void ObjectServiceImplTest::SetUp() @@ -73,9 +77,14 @@ void ObjectServiceImplTest::SetUp() .assetName = "asset1.jpg", }; assetBindInfo_ = AssetBindInfo; + devMgrAdapterMock = make_shared(); + BDeviceManagerAdapter::deviceManagerAdapter = devMgrAdapterMock; } -void ObjectServiceImplTest::TearDown() {} +void ObjectServiceImplTest::TearDown() +{ + devMgrAdapterMock = nullptr; +} /** * @tc.name: OnAssetChanged001 @@ -152,6 +161,22 @@ HWTEST_F(ObjectServiceImplTest, ResolveAutoLaunch001, TestSize.Level1) EXPECT_EQ(ret, OBJECT_SUCCESS); } +/** + * @tc.name: OnInitialize001 + * @tc.desc: OnInitialize test. + * @tc.type: FUNC + */ +HWTEST_F(ObjectServiceImplTest, OnInitialize001, TestSize.Level1) +{ + std::shared_ptr objectServiceImpl = std::make_shared(); + objectServiceImpl->executors_ = nullptr; + DeviceInfo devInfo = { .uuid = "123" }; + EXPECT_CALL(*devMgrAdapterMock, GetLocalDevice()) + .WillOnce(Return(devInfo)); + int32_t ret = objectServiceImpl->OnInitialize(); + EXPECT_EQ(ret, OBJECT_INNER_ERROR); +} + /** * @tc.name: RegisterProgressObserver001 * @tc.desc: RegisterProgressObserver test. -- Gitee