diff --git a/services/distributeddataservice/app/distributed_data.cfg b/services/distributeddataservice/app/distributed_data.cfg index 65e8ac880c053d0127039baf03f077fdf5034fd0..0480668eb4b13c724ec8d9ef56e421d626c69549 100644 --- a/services/distributeddataservice/app/distributed_data.cfg +++ b/services/distributeddataservice/app/distributed_data.cfg @@ -17,7 +17,7 @@ "name" : "distributeddata", "path" : ["/system/bin/sa_main","/system/profile/distributeddata.json"], "uid" : "ddms", - "gid" : ["system","shell","readproc","ddms","dfs_share","netsys_socket","data_reserve"], + "gid" : ["system","shell","readproc","ddms","dfs_share","data_reserve"], "writepid":[ "/dev/cpuset/foreground/tasks", "/dev/stune/foreground/tasks", diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index fce1de0bab6c83693fb2b0aeb50aa28ca77e0da4..4309f2f2c6028e6826944031c33f1b35679e1164 100644 --- a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -1256,7 +1256,11 @@ void CloudServiceImpl::GetSchema(const Event &event) storeInfo.bundleName.c_str(), Anonymous::Change(storeInfo.storeName).c_str(), storeInfo.instanceId); if (storeInfo.user == 0) { std::vector users; - AccountDelegate::GetInstance()->QueryUsers(users); + auto ret = AccountDelegate::GetInstance()->QueryUsers(users); + if (!ret || users.empty()) { + ZLOGE("failed to query os accounts, ret:%{public}d", ret); + return; + } GetSchemaMeta(users[0], storeInfo.bundleName, storeInfo.instanceId); } else { GetSchemaMeta(storeInfo.user, storeInfo.bundleName, storeInfo.instanceId); diff --git a/services/distributeddataservice/service/cloud/sync_manager.cpp b/services/distributeddataservice/service/cloud/sync_manager.cpp index 0eb1e8f456e63b2fd4d441196e7b147c0d940728..773fca44bac834540d494dc7bf73daf23538d448 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.cpp +++ b/services/distributeddataservice/service/cloud/sync_manager.cpp @@ -476,6 +476,9 @@ void SyncManager::ReportSyncEvent(const SyncEvent &evt, BizState bizState, int32 std::function SyncManager::GetClientChangeHandler() { return [this](const Event &event) { + if (executor_ == nullptr) { + return; + } auto &evt = static_cast(event); auto store = evt.GetStoreInfo(); SyncInfo syncInfo(store.user, store.bundleName, store.storeName); @@ -501,23 +504,29 @@ void SyncManager::Report( Reporter::GetInstance()->CloudSyncFault()->Report(msg); } +bool SyncManager::HandleRetryFinished(const SyncInfo &info, int32_t user, int32_t code, int32_t dbCode, + const std::string &prepareTraceId) +{ + if (code == E_OK || code == E_SYNC_TASK_MERGED) { + return true; + } + info.SetError(code); + RadarReporter::Report({ info.bundleName_.c_str(), CLOUD_SYNC, FINISH_SYNC, info.syncId_, info.triggerMode_, + dbCode }, + "GetRetryer", BizState::END); + SyncManager::Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, + dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode, "GetRetryer finish" }); + Report(FT_CALLBACK, info.bundleName_, static_cast(Fault::CSF_GS_CLOUD_SYNC), + "code=" + std::to_string(code) + ",dbCode=" + std::to_string(static_cast(dbCode))); + return true; +} + SyncManager::Retryer SyncManager::GetRetryer(int32_t times, const SyncInfo &syncInfo, int32_t user) { if (times >= RETRY_TIMES) { return [this, user, info = SyncInfo(syncInfo)](Duration, int32_t code, int32_t dbCode, const std::string &prepareTraceId) mutable { - if (code == E_OK || code == E_SYNC_TASK_MERGED) { - return true; - } - info.SetError(code); - RadarReporter::Report({ info.bundleName_.c_str(), CLOUD_SYNC, FINISH_SYNC, info.syncId_, info.triggerMode_, - dbCode }, - "GetRetryer", BizState::END); - SyncManager::Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, - dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode, "GetRetryer finish" }); - Report(FT_CALLBACK, info.bundleName_, static_cast(Fault::CSF_GS_CLOUD_SYNC), - "code=" + std::to_string(code) + ",dbCode=" + std::to_string(static_cast(dbCode))); - return true; + return HandleRetryFinished(info, user, code, dbCode, prepareTraceId); }; } return [this, times, user, info = SyncInfo(syncInfo)](Duration interval, int32_t code, int32_t dbCode, @@ -537,6 +546,9 @@ SyncManager::Retryer SyncManager::GetRetryer(int32_t times, const SyncInfo &sync return true; } + if (executor_ == nullptr) { + return false; + } activeInfos_.ComputeIfAbsent(info.syncId_, [this, times, interval, &info](uint64_t key) mutable { auto syncId = GenerateId(info.user_); auto ref = GenSyncRef(syncId); diff --git a/services/distributeddataservice/service/cloud/sync_manager.h b/services/distributeddataservice/service/cloud/sync_manager.h index ad1d9bb30fa809e98893299aee9ee4f0904ba08e..a24f0ae6649a07bb18c8ec6dd8ea8882972cc0be 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.h +++ b/services/distributeddataservice/service/cloud/sync_manager.h @@ -149,6 +149,8 @@ private: const std::string &message = ""); static void ReportSyncEvent(const DistributedData::SyncEvent &evt, DistributedDataDfx::BizState bizState, int32_t code); + static bool HandleRetryFinished(const SyncInfo &info, int32_t user, int32_t code, int32_t dbCode, + const std::string &prepareTraceId); Task GetSyncTask(int32_t times, bool retry, RefCount ref, SyncInfo &&syncInfo); void UpdateSchema(const SyncInfo &syncInfo); std::function GetSyncHandler(Retryer retryer); diff --git a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp index 9fd1fe9d0f0d4785b940859fa673f5ed6341fd50..64964d040b1777b93692ecd2e32d1b1f75278d55 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp @@ -380,7 +380,11 @@ DBStatus KVDBGeneralStore::CloudSync(const Devices &devices, DistributedDB::Sync syncOption.lockAction = DistributedDB::LockAction::NONE; if (storeInfo_.user == 0) { std::vector users; - AccountDelegate::GetInstance()->QueryUsers(users); + auto ret = AccountDelegate::GetInstance()->QueryUsers(users); + if (!ret || users.empty()) { + ZLOGE("failed to query os accounts, ret:%{public}d", ret); + return DBStatus::DB_ERROR; + } syncOption.users.push_back(std::to_string(users[0])); } else { syncOption.users.push_back(std::to_string(storeInfo_.user)); diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index e0665f7407cd9f57eaa2b9cf7203c3eb698b9911..a50aedfd9f3fff65291e3180395c49e641546cb5 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -1275,8 +1275,9 @@ std::vector ObjectStoreManager::SplitEntryKey(const std::string &ke std::string ObjectStoreManager::GetCurrentUser() { std::vector users; - if (!AccountDelegate::GetInstance()->QueryUsers(users)) { - ZLOGE("QueryUsers failed."); + auto ret = AccountDelegate::GetInstance()->QueryUsers(users); + if (!ret || users.empty()) { + ZLOGE("failed to query os accounts, ret:%{public}d", ret); return ""; } return std::to_string(users[0]); diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 3f2faa385118f9ef5e6be3be48ce2657832ff008..e8f9258a80cbb396fc3e89b8f12d396e6374d7be 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -110,6 +110,63 @@ ohos_unittest("CloudDataTest") { cflags_cc = cflags } +ohos_unittest("CloudDataMockTest") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${datamgr_service_path}/cfi_blocklist.txt" + } + module_out_path = module_output_path + sources = [ + "${data_service_path}/service/cloud/cloud_data_translate.cpp", + "${data_service_path}/service/cloud/cloud_notifier_proxy.cpp", + "${data_service_path}/service/cloud/cloud_service_impl.cpp", + "${data_service_path}/service/cloud/cloud_service_stub.cpp", + "${data_service_path}/service/cloud/cloud_types_util.cpp", + "${data_service_path}/service/cloud/cloud_value_util.cpp", + "${data_service_path}/service/cloud/sync_manager.cpp", + "${data_service_path}/service/cloud/sync_strategies/network_sync_strategy.cpp", + "${data_service_path}/service/test/mock/checker_mock.cpp", + "mock/account_delegate_mock.cpp", + "cloud_data_mock_test.cpp", + ] + + configs = [ ":module_private_config" ] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + deps = [ + "${data_service_path}/adapter/account:distributeddata_account", + "${data_service_path}/adapter/communicator:distributeddata_communicator", + "${data_service_path}/adapter/dfx:distributeddata_dfx", + "${data_service_path}/adapter/schema_helper:distributeddata_schema_helper", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service/bootstrap:distributeddata_bootstrap", + "${data_service_path}/service/common:distributeddata_common", + "${data_service_path}/service/rdb:distributeddata_rdb", + "mock:distributeddata_mock_static", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "device_manager:devicemanagersdk", + "googletest:gmock", + "googletest:gtest", + "hicollie:libhicollie", + "hilog:libhilog", + "ipc:ipc_single", + "json:nlohmann_json_static", + "kv_store:distributeddata_inner", + "kv_store:distributeddb", + "relational_store:native_rdb", + ] +} + + ohos_unittest("CloudServiceImplTest") { sanitize = { cfi = true @@ -340,10 +397,12 @@ ohos_unittest("KVDBGeneralStoreTest") { cfi = true cfi_cross_dso = true debug = false + blocklist = "${datamgr_service_path}/cfi_blocklist.txt" } module_out_path = module_output_path sources = [ "kvdb_general_store_test.cpp", + "mock/account_delegate_mock.cpp", "mock/db_change_data_mock.cpp", "mock/db_store_mock.cpp", "mock/general_watcher_mock.cpp", @@ -370,6 +429,7 @@ ohos_unittest("KVDBGeneralStoreTest") { "access_token:libnativetoken", "c_utils:utils", "device_manager:devicemanagersdk", + "googletest:gmock_main", "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", @@ -878,6 +938,7 @@ ohos_unittest("ObjectManagerMockTest") { "../object/src/object_service_stub.cpp", "../object/src/object_snapshot.cpp", "../object/src/object_types_utils.cpp", + "mock/account_delegate_mock.cpp", "mock/device_manager_adapter_mock.cpp", "mock/kv_store_nb_delegate_mock.cpp", "object_manager_mock_test.cpp", @@ -2417,6 +2478,7 @@ group("unittest") { if (datamgr_service_cloud) { deps += [ ":CloudDataTest", + ":CloudDataMockTest", ":CloudServiceImplTest", ":CloudTest", "ohos_test:copy_ohos_test", diff --git a/services/distributeddataservice/service/test/cloud_data_mock_test.cpp b/services/distributeddataservice/service/test/cloud_data_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e3d576b1ab935dec84c5b3b10428b1648e51f75 --- /dev/null +++ b/services/distributeddataservice/service/test/cloud_data_mock_test.cpp @@ -0,0 +1,313 @@ +/* +* 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 +#include + +#include "cloud/cloud_server.h" +#include "cloud_service_impl.h" +#include "communicator/device_manager_adapter.h" +#include "device_matrix.h" +#include "eventcenter/event_center.h" +#include "ipc_skeleton.h" +#include "metadata/meta_data_manager.h" +#include "mock/account_delegate_mock.h" +#include "mock/db_store_mock.h" +#include "network_delegate_mock.h" + +using namespace testing::ext; +using namespace testing; +using namespace DistributedDB; +using namespace OHOS::DistributedData; +using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; + +namespace OHOS::Test { +namespace DistributedDataTest { +static constexpr const char *TEST_CLOUD_BUNDLE = "test_cloud_bundleName"; +static constexpr const char *TEST_CLOUD_APPID = "test_cloud_appid"; +static constexpr const char *TEST_CLOUD_STORE = "test_cloud_store"; +static constexpr const char *TEST_CLOUD_ID = "test_cloud_id"; +static constexpr const char *TEST_CLOUD_DATABASE_ALIAS_1 = "test_cloud_database_alias_1"; +static constexpr const char *TEST_CLOUD_DATABASE_ALIAS_2 = "test_cloud_database_alias_2"; +static constexpr const char *TEST_CLOUD_PATH = + "/data/app/el2/100/database/test_cloud_bundleName/entry/rdb/test_cloud_store"; +class CloudDataMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static SchemaMeta schemaMeta_; + static std::shared_ptr cloudServiceImpl_; +protected: + static void InitMetaData(); + static void InitSchemaMeta(); + static void InitCloudInfo(); + static std::shared_ptr dbStoreMock_; + static StoreMetaData metaData_; + static CloudInfo cloudInfo_; + static NetworkDelegateMock delegate_; +}; + +class CloudServerMock : public CloudServer { +public: + std::pair GetServerInfo(int32_t userId, bool needSpaceInfo) override; + std::pair GetAppSchema(int32_t userId, const std::string &bundleName) override; + virtual ~CloudServerMock() = default; + static constexpr uint64_t REMAINSPACE = 1000; + static constexpr uint64_t TATALSPACE = 2000; + static constexpr int32_t INVALID_USER_ID = -1; +}; + +std::pair CloudServerMock::GetServerInfo(int32_t userId, bool needSpaceInfo) +{ + CloudInfo cloudInfo; + cloudInfo.user = userId; + cloudInfo.id = TEST_CLOUD_ID; + cloudInfo.remainSpace = REMAINSPACE; + cloudInfo.totalSpace = TATALSPACE; + cloudInfo.enableCloud = true; + + CloudInfo::AppInfo appInfo; + appInfo.bundleName = TEST_CLOUD_BUNDLE; + appInfo.appId = TEST_CLOUD_APPID; + appInfo.version = 1; + appInfo.cloudSwitch = true; + + cloudInfo.apps[TEST_CLOUD_BUNDLE] = std::move(appInfo); + return { E_OK, cloudInfo }; +} + +std::pair CloudServerMock::GetAppSchema(int32_t userId, const std::string &bundleName) +{ + if (userId == INVALID_USER_ID) { + return { E_ERROR, CloudDataMockTest::schemaMeta_ }; + } + + if (bundleName.empty()) { + SchemaMeta schemaMeta; + return { E_OK, schemaMeta }; + } + return { E_OK, CloudDataMockTest::schemaMeta_ }; +} + +std::shared_ptr CloudDataMockTest::dbStoreMock_ = std::make_shared(); +SchemaMeta CloudDataMockTest::schemaMeta_; +StoreMetaData CloudDataMockTest::metaData_; +CloudInfo CloudDataMockTest::cloudInfo_; +std::shared_ptr CloudDataMockTest::cloudServiceImpl_ = + std::make_shared(); +NetworkDelegateMock CloudDataMockTest::delegate_; + +void CloudDataMockTest::InitMetaData() +{ + metaData_.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + metaData_.appId = TEST_CLOUD_APPID; + metaData_.bundleName = TEST_CLOUD_BUNDLE; + metaData_.tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + metaData_.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(metaData_.tokenId)); + metaData_.area = OHOS::DistributedKv::EL1; + metaData_.instanceId = 0; + metaData_.isAutoSync = true; + metaData_.storeType = DistributedRdb::RDB_DEVICE_COLLABORATION; + metaData_.storeId = TEST_CLOUD_STORE; + metaData_.dataDir = TEST_CLOUD_PATH; + PolicyValue value; + value.type = OHOS::DistributedKv::PolicyType::IMMEDIATE_SYNC_ON_ONLINE; +} + +void CloudDataMockTest::InitSchemaMeta() +{ + SchemaMeta::Field field1; + field1.colName = "test_cloud_field_name1"; + field1.alias = "test_cloud_field_alias1"; + SchemaMeta::Field field2; + field2.colName = "test_cloud_field_name2"; + field2.alias = "test_cloud_field_alias2"; + + SchemaMeta::Table table; + table.name = "test_cloud_table_name"; + table.alias = "test_cloud_table_alias"; + table.fields.emplace_back(field1); + table.fields.emplace_back(field2); + + SchemaMeta::Database database; + database.name = TEST_CLOUD_STORE; + database.alias = TEST_CLOUD_DATABASE_ALIAS_1; + database.tables.emplace_back(table); + + schemaMeta_.version = 1; + schemaMeta_.bundleName = TEST_CLOUD_BUNDLE; + schemaMeta_.databases.emplace_back(database); + database.alias = TEST_CLOUD_DATABASE_ALIAS_2; + schemaMeta_.databases.emplace_back(database); + schemaMeta_.e2eeEnable = false; +} + +void CloudDataMockTest::InitCloudInfo() +{ + cloudInfo_.user = AccountDelegate::GetInstance()->GetUserByToken(IPCSkeleton::GetCallingTokenID()); + cloudInfo_.id = TEST_CLOUD_ID; + cloudInfo_.enableCloud = true; + + CloudInfo::AppInfo appInfo; + appInfo.bundleName = TEST_CLOUD_BUNDLE; + appInfo.appId = TEST_CLOUD_APPID; + appInfo.version = 1; + appInfo.cloudSwitch = true; + + cloudInfo_.apps[TEST_CLOUD_BUNDLE] = std::move(appInfo); +} + +void CloudDataMockTest::SetUpTestCase(void) +{ + MetaDataManager::GetInstance().Initialize(dbStoreMock_, nullptr, ""); + MetaDataManager::GetInstance().SetSyncer([](const auto &, auto) { + DeviceMatrix::GetInstance().OnChanged(DeviceMatrix::META_STORE_MASK); + }); + + auto cloudServerMock = new CloudServerMock(); + CloudServer::RegisterCloudInstance(cloudServerMock); + size_t max = 12; + size_t min = 5; + + auto executor = std::make_shared(max, min); + cloudServiceImpl_->OnBind( + { "CloudDataMockTest", static_cast(IPCSkeleton::GetSelfTokenID()), std::move(executor) }); + auto dmExecutor = std::make_shared(max, min); + DeviceManagerAdapter::GetInstance().Init(dmExecutor); + NetworkDelegate::RegisterNetworkInstance(&delegate_); + delegate_.isNetworkAvailable_ = true; + InitCloudInfo(); + InitMetaData(); + InitSchemaMeta(); +} + +void CloudDataMockTest::TearDownTestCase() {} + +void CloudDataMockTest::SetUp() +{ + MetaDataManager::GetInstance().SaveMeta(cloudInfo_.GetKey(), cloudInfo_, true); + MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, true); + StoreMetaMapping storeMetaMapping(metaData_); + MetaDataManager::GetInstance().SaveMeta(storeMetaMapping.GetKey(), storeMetaMapping, true); + MetaDataManager::GetInstance().SaveMeta(cloudInfo_.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta_, true); +} + +void CloudDataMockTest::TearDown() +{ + EventCenter::GetInstance().Unsubscribe(CloudEvent::LOCAL_CHANGE); + MetaDataManager::GetInstance().DelMeta(cloudInfo_.GetKey(), true); + MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), true); + StoreMetaMapping storeMetaMapping(metaData_); + MetaDataManager::GetInstance().DelMeta(storeMetaMapping.GetKey(), true); + MetaDataManager::GetInstance().DelMeta(cloudInfo_.GetSchemaKey(TEST_CLOUD_BUNDLE), true); +} + +/** +* @tc.name: GetSchema001 +* @tc.desc: Test the scenario where the QueryUsers users not empty and return true in the GetSchema function. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudDataMockTest, GetSchema001, TestSize.Level1) +{ + auto cloudServerMock = std::make_shared(); + auto user = AccountDelegate::GetInstance()->GetUserByToken(OHOS::IPCSkeleton::GetCallingTokenID()); + auto [status, cloudInfo] = cloudServerMock->GetServerInfo(user, true); + ASSERT_TRUE(MetaDataManager::GetInstance().DelMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), true)); + SchemaMeta schemaMeta; + ASSERT_FALSE(MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true)); + std::vector users = {0, 1}; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .Times(1) + .WillOnce(DoAll( + SetArgReferee<0>(users), + Return(true))); + EXPECT_CALL(AccountDelegateMock::Init(), IsVerified(_)) + .Times(1) + .WillOnce(DoAll(Return(true))); + DistributedData::StoreInfo storeInfo{ OHOS::IPCSkeleton::GetCallingTokenID(), TEST_CLOUD_BUNDLE, + TEST_CLOUD_STORE, 0 }; + auto event = std::make_unique(CloudEvent::GET_SCHEMA, storeInfo); + EventCenter::GetInstance().PostEvent(std::move(event)); + auto ret = MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true); + ASSERT_TRUE(ret); +} + +/** +* @tc.name: GetSchema002 +* @tc.desc: Test the scenario where the QueryUsers users empty in the GetSchema function. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudDataMockTest, GetSchema002, TestSize.Level1) +{ + auto cloudServerMock = std::make_shared(); + auto user = AccountDelegate::GetInstance()->GetUserByToken(OHOS::IPCSkeleton::GetCallingTokenID()); + auto [status, cloudInfo] = cloudServerMock->GetServerInfo(user, true); + ASSERT_TRUE(MetaDataManager::GetInstance().DelMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), true)); + SchemaMeta schemaMeta; + ASSERT_FALSE(MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true)); + + std::vector users; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .Times(1) + .WillOnce(DoAll( + SetArgReferee<0>(users), + Invoke([](std::vector& users) { users.clear(); }), + Return(true))); + DistributedData::StoreInfo storeInfo{ OHOS::IPCSkeleton::GetCallingTokenID(), TEST_CLOUD_BUNDLE, + TEST_CLOUD_STORE, 0 }; + auto event = std::make_unique(CloudEvent::GET_SCHEMA, storeInfo); + EventCenter::GetInstance().PostEvent(std::move(event)); + auto ret = MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true); + ASSERT_FALSE(ret); +} + +/** +* @tc.name: GetSchema003 +* @tc.desc: Test the scenario where the QueryUsers return false in the GetSchema function. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudDataMockTest, GetSchema003, TestSize.Level1) +{ + auto cloudServerMock = std::make_shared(); + auto user = AccountDelegate::GetInstance()->GetUserByToken(OHOS::IPCSkeleton::GetCallingTokenID()); + auto [status, cloudInfo] = cloudServerMock->GetServerInfo(user, true); + ASSERT_TRUE(MetaDataManager::GetInstance().DelMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), true)); + SchemaMeta schemaMeta; + ASSERT_FALSE(MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true)); + + std::vector users; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .Times(1) + .WillOnce(DoAll( + SetArgReferee<0>(users), + Return(false))); + DistributedData::StoreInfo storeInfo{ OHOS::IPCSkeleton::GetCallingTokenID(), TEST_CLOUD_BUNDLE, + TEST_CLOUD_STORE, 0 }; + auto event = std::make_unique(CloudEvent::GET_SCHEMA, storeInfo); + EventCenter::GetInstance().PostEvent(std::move(event)); + auto ret = MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true); + ASSERT_FALSE(ret); +} +} // namespace DistributedDataTest +} // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/cloud_data_test.cpp b/services/distributeddataservice/service/test/cloud_data_test.cpp index 40d39394640128d486d1f61fc2476fa29ca4ab90..369960108d13a459e4d51b74141ea912ef121884 100644 --- a/services/distributeddataservice/service/test/cloud_data_test.cpp +++ b/services/distributeddataservice/service/test/cloud_data_test.cpp @@ -2006,12 +2006,12 @@ HWTEST_F(CloudDataTest, GetPostEventTask, TestSize.Level0) } /** -* @tc.name: GetRetryer +* @tc.name: GetRetryer001 * @tc.desc: Test the input parameters of different interfaces * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, GetRetryer, TestSize.Level0) +HWTEST_F(CloudDataTest, GetRetryer001, TestSize.Level0) { int32_t user = 100; CloudData::SyncManager::SyncInfo info(user); @@ -2029,6 +2029,28 @@ HWTEST_F(CloudDataTest, GetRetryer, TestSize.Level0) EXPECT_TRUE(ret); } +/** +* @tc.name: GetRetryer002 +* @tc.desc: Test the executor_ is nullptr scenarios. +* @tc.type: FUNC +* @tc.require: + */ +HWTEST_F(CloudDataTest, GetRetryer002, TestSize.Level0) +{ + int32_t user = 100; + std::string prepareTraceId; + CloudData::SyncManager sync; + sync.executor_ = nullptr; + int32_t evtId = 100; + auto event = std::make_unique(evtId); + auto handler = sync.GetClientChangeHandler(); + handler(*event); + CloudData::SyncManager::Duration duration; + CloudData::SyncManager::SyncInfo info(user); + auto ret = sync.GetRetryer(0, info, user)(duration, E_CLOUD_DISABLED, E_CLOUD_DISABLED, prepareTraceId); + EXPECT_FALSE(ret); +} + /** * @tc.name: GetCallback * @tc.desc: Test the processing logic of different progress callbacks diff --git a/services/distributeddataservice/service/test/kvdb_general_store_test.cpp b/services/distributeddataservice/service/test/kvdb_general_store_test.cpp index efcb438523629b85817dbf3dfa4bfc4946b6ca2e..11aa042e5bb4bf57b08e55573195b86eed38ee84 100644 --- a/services/distributeddataservice/service/test/kvdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_general_store_test.cpp @@ -33,10 +33,12 @@ #include "metadata/secret_key_meta_data.h" #include "metadata/store_meta_data.h" #include "metadata/store_meta_data_local.h" +#include "mock/account_delegate_mock.h" #include "mock/db_store_mock.h" #include "mock/general_watcher_mock.h" using namespace testing::ext; +using namespace testing; using namespace DistributedDB; using namespace OHOS::DistributedData; using DBStoreMock = OHOS::DistributedData::DBStoreMock; @@ -508,13 +510,43 @@ HWTEST_F(KVDBGeneralStoreTest, GetDBSyncCompleteCB, TestSize.Level0) } /** -* @tc.name: CloudSync +* @tc.name: CloudSync001 +* @tc.desc: Test the scenario where the QueryUsers return false in the CloudSync function. +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KVDBGeneralStoreTest, CloudSync001, TestSize.Level0) +{ + auto store = new (std::nothrow) KVDBGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + store->SetEqualIdentifier(bundleName, storeName); + KvStoreNbDelegateMock mockDelegate; + store->delegate_ = &mockDelegate; + std::vector devices = { "device1", "device2" }; + auto asyncs = [](const GenDetails &result) {}; + store->storeInfo_.user = 0; + auto cloudSyncMode = DistributedDB::SyncMode::SYNC_MODE_PUSH_ONLY; + store->SetEqualIdentifier(bundleName, storeName); + std::string prepareTraceId; + std::vector users; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .Times(1) + .WillOnce(DoAll( + SetArgReferee<0>(users), + Return(false))); + auto ret = store->CloudSync(devices, cloudSyncMode, asyncs, 0, prepareTraceId); + EXPECT_EQ(ret, DBStatus::DB_ERROR); +} + +/** +* @tc.name: CloudSync002 * @tc.desc: CloudSync test the functionality of different branches. * @tc.type: FUNC * @tc.require: * @tc.author: SQL */ -HWTEST_F(KVDBGeneralStoreTest, CloudSync, TestSize.Level0) +HWTEST_F(KVDBGeneralStoreTest, CloudSync002, TestSize.Level0) { auto store = new (std::nothrow) KVDBGeneralStore(metaData_); ASSERT_NE(store, nullptr); @@ -527,8 +559,15 @@ HWTEST_F(KVDBGeneralStoreTest, CloudSync, TestSize.Level0) auto cloudSyncMode = DistributedDB::SyncMode::SYNC_MODE_PUSH_ONLY; store->SetEqualIdentifier(bundleName, storeName); std::string prepareTraceId; + std::vector users; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .Times(1) + .WillOnce(DoAll( + SetArgReferee<0>(users), + Invoke([](std::vector& users) { users.clear(); }), + Return(true))); auto ret = store->CloudSync(devices, cloudSyncMode, asyncs, 0, prepareTraceId); - EXPECT_EQ(ret, DBStatus::OK); + EXPECT_EQ(ret, DBStatus::DB_ERROR); store->storeInfo_.user = 1; cloudSyncMode = DistributedDB::SyncMode::SYNC_MODE_CLOUD_FORCE_PUSH; @@ -557,13 +596,13 @@ HWTEST_F(KVDBGeneralStoreTest, GetIdentifierParams, TestSize.Level0) } /** -* @tc.name: Sync -* @tc.desc: Sync test the functionality of different branches. +* @tc.name: Sync002 +* @tc.desc: Sync test the functionality of 3 < syncMode < 7 branches. * @tc.type: FUNC * @tc.require: * @tc.author: SQL */ -HWTEST_F(KVDBGeneralStoreTest, Sync, TestSize.Level0) +HWTEST_F(KVDBGeneralStoreTest, Sync002, TestSize.Level0) { mkdir(("/data/service/el1/public/database/" + std::string(bundleName)).c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); @@ -578,6 +617,11 @@ HWTEST_F(KVDBGeneralStoreTest, Sync, TestSize.Level0) syncParam.mode = mixMode; KvStoreNbDelegateMock mockDelegate; store->delegate_ = &mockDelegate; + std::vector users1 = {0, 1}; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .WillRepeatedly(DoAll( + SetArgReferee<0>(users1), + Return(true))); auto ret = store->Sync({}, query, [](const GenDetails &result) {}, syncParam); EXPECT_EQ(ret.first, GeneralError::E_NOT_SUPPORT); GeneralStore::StoreConfig storeConfig; @@ -585,13 +629,32 @@ HWTEST_F(KVDBGeneralStoreTest, Sync, TestSize.Level0) store->SetConfig(storeConfig); ret = store->Sync({}, query, [](const GenDetails &result) {}, syncParam); EXPECT_EQ(ret.first, GeneralError::E_OK); +} - syncMode = GeneralStore::SyncMode::NEARBY_END; - mixMode = GeneralStore::MixMode(syncMode, highMode); +/** +* @tc.name: Sync003 +* @tc.desc: Sync test the functionality of different branches. +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KVDBGeneralStoreTest, Sync003, TestSize.Level0) +{ + mkdir(("/data/service/el1/public/database/" + std::string(bundleName)).c_str(), + (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); + auto store = new (std::nothrow) KVDBGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + uint32_t syncMode = GeneralStore::SyncMode::NEARBY_END; + uint32_t highMode = GeneralStore::HighMode::MANUAL_SYNC_MODE; + auto mixMode = GeneralStore::MixMode(syncMode, highMode); + std::string kvQuery = ""; + DistributedKv::KVDBQuery query(kvQuery); + SyncParam syncParam{}; syncParam.mode = mixMode; - ret = store->Sync({}, query, [](const GenDetails &result) {}, syncParam); + KvStoreNbDelegateMock mockDelegate; + store->delegate_ = &mockDelegate; + auto ret = store->Sync({}, query, [](const GenDetails &result) {}, syncParam); EXPECT_EQ(ret.first, GeneralError::E_INVALID_ARGS); - std::vector devices = { "device1", "device2" }; syncMode = GeneralStore::SyncMode::NEARBY_SUBSCRIBE_REMOTE; mixMode = GeneralStore::MixMode(syncMode, highMode); diff --git a/services/distributeddataservice/service/test/object_manager_mock_test.cpp b/services/distributeddataservice/service/test/object_manager_mock_test.cpp index dc03bec6fe7ec1e04fbe729a7bcee1347c65dc2a..befd1510f49757c3c275ab3ab3db8bb4ab149b00 100644 --- a/services/distributeddataservice/service/test/object_manager_mock_test.cpp +++ b/services/distributeddataservice/service/test/object_manager_mock_test.cpp @@ -19,6 +19,7 @@ #include "device_manager_adapter_mock.h" #include "device_matrix_mock.h" #include "gtest/gtest.h" +#include "mock/account_delegate_mock.h" #include "mock/meta_data_manager_mock.h" #include "object_manager.h" @@ -202,5 +203,66 @@ HWTEST_F(ObjectManagerMockTest, SyncOnStore001, TestSize.Level0) EXPECT_EQ(result, E_DB_ERROR); } } + +/** +* @tc.name: GetCurrentUser001 +* @tc.desc: Test the scenario where the QueryUsers return false in the GetCurrentUser function. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(ObjectManagerMockTest, GetCurrentUser001, TestSize.Level1) +{ + auto manager = ObjectStoreManager::GetInstance(); + std::vector users; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .Times(1) + .WillOnce(DoAll( + SetArgReferee<0>(users), + Return(false))); + auto result = manager->GetCurrentUser(); + EXPECT_EQ(result, ""); +} + +/** +* @tc.name: GetCurrentUser002 +* @tc.desc: Test the scenario where the QueryUsers users empty in the GetCurrentUser function. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(ObjectManagerMockTest, GetCurrentUser002, TestSize.Level1) +{ + auto manager = ObjectStoreManager::GetInstance(); + std::vector users; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .Times(1) + .WillOnce(DoAll( + SetArgReferee<0>(users), + Invoke([](std::vector& users) { users.clear(); }), + Return(true))); + auto result = manager->GetCurrentUser(); + EXPECT_EQ(result, ""); +} + +/** +* @tc.name: GetCurrentUser003 +* @tc.desc: Test the scenario where the QueryUsers return true in the GetCurrentUser function. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(ObjectManagerMockTest, GetCurrentUser003, TestSize.Level1) +{ + auto manager = ObjectStoreManager::GetInstance(); + std::vector users = {0, 1}; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .Times(1) + .WillOnce(DoAll( + SetArgReferee<0>(users), + Return(true))); + auto result = manager->GetCurrentUser(); + EXPECT_EQ(result, std::to_string(users[0])); +} }; // namespace DistributedDataTest } // namespace OHOS::Test \ No newline at end of file