From 70ca68ede4055e594117c77d2aa873d297c55cd1 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Wed, 12 Mar 2025 07:50:29 +0000 Subject: [PATCH 001/225] add rate of coverage ut case-0312 Signed-off-by: suoqilong --- .../service/test/BUILD.gn | 7 +- .../service/test/device_matrix_test.cpp | 220 ++++++++++++++++-- 2 files changed, 202 insertions(+), 25 deletions(-) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 4579d0711..8fbeef79d 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -101,7 +101,6 @@ ohos_unittest("CloudDataTest") { "${data_service_path}/service/rdb/rdb_cloud.cpp", "${data_service_path}/service/rdb/rdb_cursor.cpp", "${data_service_path}/service/rdb/rdb_general_store.cpp", - "${data_service_path}/service/rdb/rdb_hiview_adapter.cpp", "${data_service_path}/service/rdb/rdb_notifier_proxy.cpp", "${data_service_path}/service/rdb/rdb_query.cpp", "${data_service_path}/service/rdb/rdb_result_set_impl.cpp", @@ -196,7 +195,6 @@ ohos_unittest("CloudServiceImplTest") { "${data_service_path}/service/rdb/rdb_cloud.cpp", "${data_service_path}/service/rdb/rdb_cursor.cpp", "${data_service_path}/service/rdb/rdb_general_store.cpp", - "${data_service_path}/service/rdb/rdb_hiview_adapter.cpp", "${data_service_path}/service/rdb/rdb_notifier_proxy.cpp", "${data_service_path}/service/rdb/rdb_query.cpp", "${data_service_path}/service/rdb/rdb_result_set_impl.cpp", @@ -394,6 +392,11 @@ ohos_unittest("DeviceMatrixTest") { configs = [ ":module_private_config" ] + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + external_deps = [ "ability_base:base", "ability_base:want", diff --git a/services/distributeddataservice/service/test/device_matrix_test.cpp b/services/distributeddataservice/service/test/device_matrix_test.cpp index 34434a8a1..0c169f9ce 100644 --- a/services/distributeddataservice/service/test/device_matrix_test.cpp +++ b/services/distributeddataservice/service/test/device_matrix_test.cpp @@ -377,6 +377,146 @@ HWTEST_F(DeviceMatrixTest, Offline, TestSize.Level0) EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().Offline(device)); } +/** + * @tc.name: OnBroadcast + * @tc.desc: OnBroadcast testing exceptions. + * @tc.type: FUNC + * @tc.require: + * @tc.author: suoqilong + */ +HWTEST_F(DeviceMatrixTest, OnBroadcast, TestSize.Level0) +{ + std::string device; + DeviceMatrix::DataLevel dataLevel; + EXPECT_TRUE(!dataLevel.IsValid()); + auto mask = DeviceMatrix::GetInstance().OnBroadcast(device, dataLevel); + EXPECT_EQ(mask.first, DeviceMatrix::INVALID_LEVEL); // true true + + dataLevel = { + .dynamic = DeviceMatrix::META_STORE_MASK, + }; + EXPECT_FALSE(!dataLevel.IsValid()); + mask = DeviceMatrix::GetInstance().OnBroadcast(device, dataLevel); + EXPECT_EQ(mask.first, DeviceMatrix::INVALID_LEVEL); // true false + + EXPECT_FALSE(!dataLevel.IsValid()); + mask = DeviceMatrix::GetInstance().OnBroadcast(TEST_DEVICE, dataLevel); + EXPECT_EQ(mask.first, DeviceMatrix::META_STORE_MASK); // false false + + DeviceMatrix::DataLevel dataLevels; + EXPECT_TRUE(!dataLevels.IsValid()); + mask = DeviceMatrix::GetInstance().OnBroadcast(device, dataLevels); + EXPECT_EQ(mask.first, DeviceMatrix::INVALID_LEVEL); // false true +} + +/** + * @tc.name: ConvertStatics + * @tc.desc: ConvertStatics testing exceptions. + * @tc.type: FUNC + * @tc.require: + * @tc.author: suoqilong + */ +HWTEST_F(DeviceMatrixTest, ConvertStatics, TestSize.Level0) +{ + DeviceMatrix deviceMatrix; + DistributedData::MatrixMetaData meta; + uint16_t mask = 0; + uint16_t result = deviceMatrix.ConvertStatics(meta, mask); + EXPECT_EQ(result, 0); + + mask = 0xFFFF; + result = deviceMatrix.ConvertStatics(meta, mask); + EXPECT_EQ(result, 0); + + meta.version = 4; + meta.dynamic = 0x1F; + meta.deviceId = TEST_DEVICE; + meta.origin = MatrixMetaData::Origin::REMOTE_RECEIVED; + meta.dynamicInfo = { TEST_BUNDLE, dynamicStores_[0].first }; + result = deviceMatrix.ConvertStatics(meta, DeviceMatrix::INVALID_LEVEL); + EXPECT_EQ(result, 0); +} + +/** + * @tc.name: SaveSwitches + * @tc.desc: SaveSwitches testing exceptions. + * @tc.type: FUNC + * @tc.require: + * @tc.author: suoqilong + */ +HWTEST_F(DeviceMatrixTest, SaveSwitches, TestSize.Level0) +{ + DeviceMatrix deviceMatrix; + std::string device; + DeviceMatrix::DataLevel dataLevel; + dataLevel.switches = DeviceMatrix::INVALID_VALUE; + dataLevel.switchesLen = DeviceMatrix::INVALID_LENGTH; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.SaveSwitches(device, dataLevel)); + + device = "SaveSwitches"; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.SaveSwitches(device, dataLevel)); + + dataLevel.switches = 0; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.SaveSwitches(device, dataLevel)); + + dataLevel.switchesLen = 0; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.SaveSwitches(device, dataLevel)); +} + +/** + * @tc.name: Broadcast + * @tc.desc: Broadcast testing exceptions. + * @tc.type: FUNC + * @tc.require: + * @tc.author: suoqilong + */ +HWTEST_F(DeviceMatrixTest, Broadcast, TestSize.Level0) +{ + DeviceMatrix deviceMatrix; + DeviceMatrix::DataLevel dataLevel; + EXPECT_FALSE(deviceMatrix.lasts_.IsValid()); + EXPECT_NO_FATAL_FAILURE(deviceMatrix.Broadcast(dataLevel)); + + dataLevel.statics = 0; + dataLevel.dynamic = 0; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.Broadcast(dataLevel)); + + deviceMatrix.lasts_.statics = 0; + deviceMatrix.lasts_.dynamic = 0; + EXPECT_TRUE(deviceMatrix.lasts_.IsValid()); + EXPECT_NO_FATAL_FAILURE(deviceMatrix.Broadcast(dataLevel)); + + DeviceMatrix::DataLevel dataLevels; + dataLevel = dataLevels; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.Broadcast(dataLevel)); +} + +/** + * @tc.name: UpdateConsistentMeta + * @tc.desc: UpdateConsistentMeta testing exceptions. + * @tc.type: FUNC + * @tc.require: + * @tc.author: suoqilong + */ +HWTEST_F(DeviceMatrixTest, UpdateConsistentMeta, TestSize.Level0) +{ + DeviceMatrix deviceMatrix; + std::string device = "device"; + DeviceMatrix::Mask remote; + remote.statics = 0; + remote.dynamic = 0; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.UpdateConsistentMeta(device, remote)); + + remote.statics = 0x1; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.UpdateConsistentMeta(device, remote)); + + remote.dynamic = 0x1; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.UpdateConsistentMeta(device, remote)); + + remote.statics = 0; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.UpdateConsistentMeta(device, remote)); +} + /** * @tc.name: OnChanged001 * @tc.desc: Test the DeviceMatrix::OnChanged method exception scenario. @@ -392,6 +532,16 @@ HWTEST_F(DeviceMatrixTest, OnChanged001, TestSize.Level0) metaData.dataType = DeviceMatrix::LevelType::BUTT; EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().OnChanged(metaData)); + + metaData.bundleName = "distributeddata"; + metaData.tokenId = selfToken_; + metaData.storeId = "service_meta"; + metaData.dataType = 1; + metaData.dataType = DeviceMatrix::LevelType::STATICS; + EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().OnChanged(metaData)); + + StoreMetaData meta = metaData_; + EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().OnChanged(meta)); } /** @@ -414,6 +564,11 @@ HWTEST_F(DeviceMatrixTest, OnChanged002, TestSize.Level0) type = DeviceMatrix::LevelType::BUTT; EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().OnChanged(code, type)); + + StoreMetaData meta = metaData_; + code = DeviceMatrix::GetInstance().GetCode(meta); + EXPECT_EQ(code, 0); + EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().OnChanged(code, type)); } /** @@ -426,14 +581,23 @@ HWTEST_F(DeviceMatrixTest, OnChanged002, TestSize.Level0) HWTEST_F(DeviceMatrixTest, OnExchanged001, TestSize.Level0) { StoreMetaData metaData; - metaData.dataType = static_cast(DeviceMatrix::LevelType::STATICS - 1); - std::string device = "OnExchanged"; + metaData.bundleName = "distributeddata"; + metaData.tokenId = selfToken_; + metaData.storeId = "service_meta"; + metaData.dataType = 1; + auto code = DeviceMatrix::GetInstance().GetCode(metaData); + DeviceMatrix::LevelType type = static_cast(DeviceMatrix::LevelType::STATICS - 1); + std::string device; EXPECT_NO_FATAL_FAILURE( - DeviceMatrix::GetInstance().OnExchanged(device, metaData, DeviceMatrix::ChangeType::CHANGE_REMOTE)); + DeviceMatrix::GetInstance().OnExchanged(device, code, type, DeviceMatrix::ChangeType::CHANGE_REMOTE)); - metaData.dataType = DeviceMatrix::LevelType::BUTT; + device = "OnExchanged"; EXPECT_NO_FATAL_FAILURE( - DeviceMatrix::GetInstance().OnExchanged(device, metaData, DeviceMatrix::ChangeType::CHANGE_REMOTE)); + DeviceMatrix::GetInstance().OnExchanged(device, code, type, DeviceMatrix::ChangeType::CHANGE_REMOTE)); + + type = DeviceMatrix::LevelType::BUTT; + EXPECT_NO_FATAL_FAILURE( + DeviceMatrix::GetInstance().OnExchanged(device, code, type, DeviceMatrix::ChangeType::CHANGE_REMOTE)); } /** @@ -446,39 +610,37 @@ HWTEST_F(DeviceMatrixTest, OnExchanged001, TestSize.Level0) HWTEST_F(DeviceMatrixTest, OnExchanged002, TestSize.Level0) { StoreMetaData metaData; - metaData.bundleName = "distributeddata"; - metaData.tokenId = selfToken_; - metaData.storeId = "service_meta"; - metaData.dataType = 1; - auto code = DeviceMatrix::GetInstance().GetCode(metaData); - DeviceMatrix::LevelType type = static_cast(DeviceMatrix::LevelType::STATICS - 1); - std::string device; - EXPECT_NO_FATAL_FAILURE( - DeviceMatrix::GetInstance().OnExchanged(device, code, type, DeviceMatrix::ChangeType::CHANGE_REMOTE)); - - device = "OnExchanged"; + metaData.dataType = static_cast(DeviceMatrix::LevelType::STATICS - 1); + std::string device = "OnExchanged"; EXPECT_NO_FATAL_FAILURE( - DeviceMatrix::GetInstance().OnExchanged(device, code, type, DeviceMatrix::ChangeType::CHANGE_REMOTE)); + DeviceMatrix::GetInstance().OnExchanged(device, metaData, DeviceMatrix::ChangeType::CHANGE_REMOTE)); - type = DeviceMatrix::LevelType::BUTT; + metaData.dataType = DeviceMatrix::LevelType::BUTT; EXPECT_NO_FATAL_FAILURE( - DeviceMatrix::GetInstance().OnExchanged(device, code, type, DeviceMatrix::ChangeType::CHANGE_REMOTE)); + DeviceMatrix::GetInstance().OnExchanged(device, metaData, DeviceMatrix::ChangeType::CHANGE_REMOTE)); } /** - * @tc.name: OnExchangedd003 + * @tc.name: OnExchanged003 * @tc.desc: Test the DeviceMatrix::OnExchanged method. * @tc.type: FUNC * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, OnExchangedd003, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, OnExchanged003, TestSize.Level0) { StoreMetaData metaData; - metaData.dataType = DeviceMatrix::LevelType::STATICS; + metaData.bundleName = "distributeddata"; + metaData.tokenId = selfToken_; + metaData.storeId = "service_meta"; + metaData.dataType = 1; std::string device = "OnExchanged"; EXPECT_NO_FATAL_FAILURE( DeviceMatrix::GetInstance().OnExchanged(device, metaData, DeviceMatrix::ChangeType::CHANGE_REMOTE)); + + StoreMetaData meta = metaData_; + EXPECT_NO_FATAL_FAILURE( + DeviceMatrix::GetInstance().OnExchanged(device, meta, DeviceMatrix::ChangeType::CHANGE_REMOTE)); } /** @@ -675,14 +837,26 @@ HWTEST_F(DeviceMatrixTest, IsDynamic, TestSize.Level0) StoreMetaData meta; meta.bundleName = "distributeddata"; meta.tokenId = selfToken_; - meta.storeId = "service_meta"; + meta.storeId = ""; meta.dataType = DeviceMatrix::LevelType::STATICS; bool isDynamic = DeviceMatrix::GetInstance().IsDynamic(meta); EXPECT_EQ(isDynamic, false); meta.dataType = DeviceMatrix::LevelType::DYNAMIC; isDynamic = DeviceMatrix::GetInstance().IsDynamic(meta); + EXPECT_EQ(isDynamic, false); + + meta.storeId = "service_meta"; + isDynamic = DeviceMatrix::GetInstance().IsDynamic(meta); EXPECT_EQ(isDynamic, true); + + meta.tokenId = 1; + isDynamic = DeviceMatrix::GetInstance().IsDynamic(meta); + EXPECT_EQ(isDynamic, false); + + meta.storeId = ""; + isDynamic = DeviceMatrix::GetInstance().IsDynamic(meta); + EXPECT_EQ(isDynamic, false); } /** -- Gitee From 83955f7c1321a1318da1543eb362ee99ac86abfa Mon Sep 17 00:00:00 2001 From: suoqilong Date: Wed, 12 Mar 2025 08:08:39 +0000 Subject: [PATCH 002/225] add rate of coverage ut case-0312 Signed-off-by: suoqilong --- services/distributeddataservice/service/test/BUILD.gn | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 8fbeef79d..1e5148731 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -101,6 +101,7 @@ ohos_unittest("CloudDataTest") { "${data_service_path}/service/rdb/rdb_cloud.cpp", "${data_service_path}/service/rdb/rdb_cursor.cpp", "${data_service_path}/service/rdb/rdb_general_store.cpp", + "${data_service_path}/service/rdb/rdb_hiview_adapter.cpp", "${data_service_path}/service/rdb/rdb_notifier_proxy.cpp", "${data_service_path}/service/rdb/rdb_query.cpp", "${data_service_path}/service/rdb/rdb_result_set_impl.cpp", @@ -195,6 +196,7 @@ ohos_unittest("CloudServiceImplTest") { "${data_service_path}/service/rdb/rdb_cloud.cpp", "${data_service_path}/service/rdb/rdb_cursor.cpp", "${data_service_path}/service/rdb/rdb_general_store.cpp", + "${data_service_path}/service/rdb/rdb_hiview_adapter.cpp", "${data_service_path}/service/rdb/rdb_notifier_proxy.cpp", "${data_service_path}/service/rdb/rdb_query.cpp", "${data_service_path}/service/rdb/rdb_result_set_impl.cpp", -- Gitee From 0708d9f7cf31ba00eb1c84be5353b4043be55f91 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Fri, 14 Mar 2025 06:59:50 +0000 Subject: [PATCH 003/225] add rate of coverage ut case-0312 Signed-off-by: suoqilong --- .../adapter/network/test/BUILD.gn | 43 +++- .../network_delegate_normal_impl_test.cpp | 219 ++++++++++++++++++ .../service/test/device_matrix_test.cpp | 46 ++-- 3 files changed, 284 insertions(+), 24 deletions(-) create mode 100644 services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp diff --git a/services/distributeddataservice/adapter/network/test/BUILD.gn b/services/distributeddataservice/adapter/network/test/BUILD.gn index 6c030e768..1b6065721 100755 --- a/services/distributeddataservice/adapter/network/test/BUILD.gn +++ b/services/distributeddataservice/adapter/network/test/BUILD.gn @@ -47,12 +47,53 @@ ohos_unittest("NetworkDelegateTest") { defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } +ohos_unittest("NetworkDelegateNormalImplTest") { + module_out_path = module_output_path + + sources = [ + "${data_service_path}/framework/network/network_delegate.cpp", + "network_delegate_normal_impl_test.cpp", + ] + include_dirs = [ + "${data_service_path}/adapter/include/communicator", + "${data_service_path}/framework/include/network", + "${data_service_path}/adapter/include/utils", + "${data_service_path}/framework/include", + "${data_service_path}/adapter/network/src", + "${data_service_path}/adapter/include", + ] + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + # deps = [ "../:distributeddata_network" ] + + deps = [ + "${data_service_path}/adapter/communicator:distributeddata_communicator", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:datamgr_common", + "netmanager_base:net_conn_manager_if", + ] + defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] +} + ############################################################################### group("unittest") { testonly = true deps = [] - deps += [ ":NetworkDelegateTest" ] + deps += [ + ":NetworkDelegateNormalImplTest", + ":NetworkDelegateTest", + ] } ############################################################################### diff --git a/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp new file mode 100644 index 000000000..1629745b9 --- /dev/null +++ b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp @@ -0,0 +1,219 @@ +/* +* 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 "NetworkDelegateNormalImplTest" + +#include "network_delegate.h" +#include "network_delegate_normal_impl.h" +#include "network_delegate_normal_impl.cpp" +#include +#include +// #include "log_print.h" + +using namespace testing::ext; +using namespace std; +using namespace OHOS::DistributedData; +using namespace OHOS::NetManagerStandard; +using DmDeviceInfo = OHOS::DistributedHardware::DmDeviceInfo; +namespace OHOS::Test { +namespace DistributedDataTest { +class NetworkDelegateNormalImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void NetworkDelegateNormalImplTest::SetUpTestCase(void) +{ +} + +void NetworkDelegateNormalImplTest::TearDownTestCase() +{ +} + +void NetworkDelegateNormalImplTest::SetUp() +{ +} + +void NetworkDelegateNormalImplTest::TearDown() +{ +} + +/** +* @tc.name: GetNetworkType001 +* @tc.desc: GetNetworkType test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(NetworkDelegateNormalImplTest, GetNetworkType001, TestSize.Level1) +{ + NetworkDelegateNormalImpl delegate; + bool retrieve = false; + EXPECT_NO_FATAL_FAILURE(delegate.RegOnNetworkChange()); + NetworkDelegate::NetworkType status = delegate.GetNetworkType(retrieve); + EXPECT_EQ(status, NetworkDelegate::NetworkType::NONE); +} + +/** +* @tc.name: GetNetworkType002 +* @tc.desc: GetNetworkType test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(NetworkDelegateNormalImplTest, GetNetworkType002, TestSize.Level1) +{ + NetworkDelegateNormalImpl delegate; + bool retrieve = true; + EXPECT_NO_FATAL_FAILURE(delegate.RegOnNetworkChange()); + NetworkDelegate::NetworkType status = delegate.GetNetworkType(retrieve); + EXPECT_EQ(status, NetworkDelegate::NetworkType::NONE); +} + +/** +* @tc.name: IsNetworkAvailable +* @tc.desc: IsNetworkAvailable test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(NetworkDelegateNormalImplTest, IsNetworkAvailable, TestSize.Level1) +{ + NetworkDelegateNormalImpl delegate; + bool ret = delegate.IsNetworkAvailable(); // false false + EXPECT_FALSE(ret); + + DmDeviceInfo& info = const_cast(delegate.cloudDmInfo_); + std::memset(info.networkId, 0, sizeof(info.networkId)); + NetworkDelegateNormalImpl::NetworkType netWorkType = NetworkDelegate::NetworkType::NONE; + NetworkDelegateNormalImpl::NetworkType status = delegate.SetNet(netWorkType); + EXPECT_EQ(status, NetworkDelegate::NONE); + ret = delegate.IsNetworkAvailable(); // false true + EXPECT_FALSE(ret); + + netWorkType = NetworkDelegate::NetworkType::WIFI; + status = delegate.SetNet(netWorkType); + EXPECT_EQ(status, NetworkDelegate::WIFI); + ret = delegate.IsNetworkAvailable(); // true true + EXPECT_TRUE(ret); + + netWorkType = NetworkDelegate::NetworkType::NONE; + status = delegate.SetNet(netWorkType); + EXPECT_EQ(status, NetworkDelegate::NONE); + ret = delegate.IsNetworkAvailable(); // false true + EXPECT_FALSE(ret); + + netWorkType = NetworkDelegate::NetworkType::WIFI; + status = delegate.SetNet(netWorkType); + EXPECT_EQ(status, NetworkDelegate::WIFI); + ret = delegate.IsNetworkAvailable(); // false true + EXPECT_TRUE(ret); +} + +/** +* @tc.name: NetCapabilitiesChange001 +* @tc.desc: NetCapabilitiesChange test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange001, TestSize.Level1) +{ + NetworkDelegateNormalImpl delegate; + sptr observer = new (std::nothrow) NetConnCallbackObserver(delegate); + sptr netHandle = nullptr; + sptr netAllCap = nullptr; + int32_t status = observer->NetCapabilitiesChange(netHandle, netAllCap); + EXPECT_EQ(status, 0); + + netHandle = new (std::nothrow) NetHandle(); + status = observer->NetCapabilitiesChange(netHandle, netAllCap); + EXPECT_EQ(status, 0); + + netHandle = nullptr; + netAllCap = new (std::nothrow) NetAllCapabilities(); + status = observer->NetCapabilitiesChange(netHandle, netAllCap); + EXPECT_EQ(status, 0); +} + +/** +* @tc.name: NetCapabilitiesChange002 +* @tc.desc: NetCapabilitiesChange test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange002, TestSize.Level1) +{ + NetworkDelegateNormalImpl delegate; + DmDeviceInfo& info = const_cast(delegate.cloudDmInfo_); + std::memset(info.networkId, 0, sizeof(info.networkId)); + sptr observer = new (std::nothrow) NetConnCallbackObserver(delegate); + sptr netHandle = new (std::nothrow) NetHandle(); + sptr netAllCap = new (std::nothrow) NetAllCapabilities(); + EXPECT_FALSE(netAllCap->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED)); + EXPECT_FALSE(!netAllCap->bearerTypes_.empty()); + int32_t status = observer->NetCapabilitiesChange(netHandle, netAllCap); + EXPECT_EQ(status, 0); + + netAllCap->netCaps_.insert(NetManagerStandard::NET_CAPABILITY_VALIDATED); + EXPECT_TRUE(netAllCap->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED)); + EXPECT_FALSE(!netAllCap->bearerTypes_.empty()); + status = observer->NetCapabilitiesChange(netHandle, netAllCap); + EXPECT_EQ(status, 0); + + sptr netAllCaps = new (std::nothrow) NetAllCapabilities(); + netAllCaps->bearerTypes_.insert(NetManagerStandard::BEARER_WIFI); + EXPECT_FALSE(netAllCaps->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED)); + EXPECT_TRUE(!netAllCaps->bearerTypes_.empty()); + status = observer->NetCapabilitiesChange(netHandle, netAllCaps); + EXPECT_EQ(status, 0); + + netAllCaps->netCaps_.insert(NetManagerStandard::NET_CAPABILITY_VALIDATED); + EXPECT_TRUE(netAllCaps->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED)); + EXPECT_TRUE(!netAllCaps->bearerTypes_.empty()); + status = observer->NetCapabilitiesChange(netHandle, netAllCaps); + EXPECT_EQ(status, 0); +} + +/** +* @tc.name: Convert +* @tc.desc: Convert test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(NetworkDelegateNormalImplTest, Convert, TestSize.Level1) +{ + NetManagerStandard::NetBearType bearType = NetManagerStandard::BEARER_WIFI; + NetworkDelegateNormalImpl::NetworkType status = Convert(bearType); + EXPECT_EQ(status, NetworkDelegate::WIFI); + + bearType = NetManagerStandard::BEARER_CELLULAR; + status = Convert(bearType); + EXPECT_EQ(status, NetworkDelegate::CELLULAR); + + bearType = NetManagerStandard::BEARER_ETHERNET; + status = Convert(bearType); + EXPECT_EQ(status, NetworkDelegate::ETHERNET); + + bearType = NetManagerStandard::BEARER_VPN; + status = Convert(bearType); + EXPECT_EQ(status, NetworkDelegate::OTHER); +} +} // namespace DistributedDataTest +} // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/device_matrix_test.cpp b/services/distributeddataservice/service/test/device_matrix_test.cpp index 0c169f9ce..66e25b243 100644 --- a/services/distributeddataservice/service/test/device_matrix_test.cpp +++ b/services/distributeddataservice/service/test/device_matrix_test.cpp @@ -350,7 +350,7 @@ HWTEST_F(DeviceMatrixTest, UpdateMatrixMeta, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, Online, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, Online, TestSize.Level1) { RefCount refCount; std::string device = "Online"; @@ -367,7 +367,7 @@ HWTEST_F(DeviceMatrixTest, Online, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, Offline, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, Offline, TestSize.Level1) { RefCount refCount; std::string device = "Offline"; @@ -384,7 +384,7 @@ HWTEST_F(DeviceMatrixTest, Offline, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, OnBroadcast, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, OnBroadcast, TestSize.Level1) { std::string device; DeviceMatrix::DataLevel dataLevel; @@ -416,7 +416,7 @@ HWTEST_F(DeviceMatrixTest, OnBroadcast, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, ConvertStatics, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, ConvertStatics, TestSize.Level1) { DeviceMatrix deviceMatrix; DistributedData::MatrixMetaData meta; @@ -444,7 +444,7 @@ HWTEST_F(DeviceMatrixTest, ConvertStatics, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, SaveSwitches, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, SaveSwitches, TestSize.Level1) { DeviceMatrix deviceMatrix; std::string device; @@ -470,7 +470,7 @@ HWTEST_F(DeviceMatrixTest, SaveSwitches, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, Broadcast, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, Broadcast, TestSize.Level1) { DeviceMatrix deviceMatrix; DeviceMatrix::DataLevel dataLevel; @@ -498,7 +498,7 @@ HWTEST_F(DeviceMatrixTest, Broadcast, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, UpdateConsistentMeta, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, UpdateConsistentMeta, TestSize.Level1) { DeviceMatrix deviceMatrix; std::string device = "device"; @@ -524,7 +524,7 @@ HWTEST_F(DeviceMatrixTest, UpdateConsistentMeta, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, OnChanged001, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, OnChanged001, TestSize.Level1) { StoreMetaData metaData; metaData.dataType = static_cast(DeviceMatrix::LevelType::STATICS - 1); @@ -551,7 +551,7 @@ HWTEST_F(DeviceMatrixTest, OnChanged001, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, OnChanged002, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, OnChanged002, TestSize.Level1) { StoreMetaData metaData; metaData.bundleName = "distributeddata"; @@ -578,7 +578,7 @@ HWTEST_F(DeviceMatrixTest, OnChanged002, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, OnExchanged001, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, OnExchanged001, TestSize.Level1) { StoreMetaData metaData; metaData.bundleName = "distributeddata"; @@ -607,7 +607,7 @@ HWTEST_F(DeviceMatrixTest, OnExchanged001, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, OnExchanged002, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, OnExchanged002, TestSize.Level1) { StoreMetaData metaData; metaData.dataType = static_cast(DeviceMatrix::LevelType::STATICS - 1); @@ -627,7 +627,7 @@ HWTEST_F(DeviceMatrixTest, OnExchanged002, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, OnExchanged003, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, OnExchanged003, TestSize.Level1) { StoreMetaData metaData; metaData.bundleName = "distributeddata"; @@ -650,7 +650,7 @@ HWTEST_F(DeviceMatrixTest, OnExchanged003, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetCode, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetCode, TestSize.Level1) { StoreMetaData metaData; metaData.bundleName = "distributeddata"; @@ -668,7 +668,7 @@ HWTEST_F(DeviceMatrixTest, GetCode, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetMask001, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetMask001, TestSize.Level1) { std::string device = "GetMask"; DeviceMatrix::LevelType type = DeviceMatrix::LevelType::STATICS; @@ -683,7 +683,7 @@ HWTEST_F(DeviceMatrixTest, GetMask001, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetMask002, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetMask002, TestSize.Level1) { std::string device = "GetMask"; DeviceMatrix::LevelType type = DeviceMatrix::LevelType::STATICS; @@ -708,7 +708,7 @@ HWTEST_F(DeviceMatrixTest, GetMask002, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetRemoteMask001, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetRemoteMask001, TestSize.Level1) { std::string device = "GetRemoteMask"; DeviceMatrix::LevelType type = DeviceMatrix::LevelType::STATICS; @@ -723,7 +723,7 @@ HWTEST_F(DeviceMatrixTest, GetRemoteMask001, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetRemoteMask002, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetRemoteMask002, TestSize.Level1) { std::string device = "GetRemoteMask"; StoreMetaData meta = metaData_; @@ -753,7 +753,7 @@ HWTEST_F(DeviceMatrixTest, GetRemoteMask002, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetRecvLevel, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetRecvLevel, TestSize.Level1) { std::string device = "GetRemoteMask"; DeviceMatrix::LevelType type = DeviceMatrix::LevelType::STATICS; @@ -780,7 +780,7 @@ HWTEST_F(DeviceMatrixTest, GetRecvLevel, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetConsLevel, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetConsLevel, TestSize.Level1) { std::string device = "GetRemoteMask"; DeviceMatrix::LevelType type = DeviceMatrix::LevelType::STATICS; @@ -807,7 +807,7 @@ HWTEST_F(DeviceMatrixTest, GetConsLevel, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, UpdateLevel, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, UpdateLevel, TestSize.Level1) { uint16_t level = 0; DeviceMatrix::LevelType type = static_cast(DeviceMatrix::LevelType::STATICS - 1); @@ -832,7 +832,7 @@ HWTEST_F(DeviceMatrixTest, UpdateLevel, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, IsDynamic, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, IsDynamic, TestSize.Level1) { StoreMetaData meta; meta.bundleName = "distributeddata"; @@ -866,7 +866,7 @@ HWTEST_F(DeviceMatrixTest, IsDynamic, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, IsValid, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, IsValid, TestSize.Level1) { DistributedData::DeviceMatrix::DataLevel dataLevel; EXPECT_EQ(dataLevel.IsValid(), false); @@ -893,7 +893,7 @@ public: * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(MatrixEventTest, IsValid, TestSize.Level0) +HWTEST_F(MatrixEventTest, IsValid, TestSize.Level1) { DistributedData::MatrixEvent::MatrixData matrixData; EXPECT_EQ(matrixData.IsValid(), false); -- Gitee From 737c48eb3072b800fc6aaa0d37410eb86acfb1b9 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Fri, 14 Mar 2025 07:03:53 +0000 Subject: [PATCH 004/225] add rate of coverage ut case-0312 Signed-off-by: suoqilong --- .../test/local_kv_store_sham_unit_test.cpp | 1959 +++++++++++++++++ 1 file changed, 1959 insertions(+) create mode 100644 services/distributeddataservice/adapter/network/test/local_kv_store_sham_unit_test.cpp diff --git a/services/distributeddataservice/adapter/network/test/local_kv_store_sham_unit_test.cpp b/services/distributeddataservice/adapter/network/test/local_kv_store_sham_unit_test.cpp new file mode 100644 index 000000000..59dd7c034 --- /dev/null +++ b/services/distributeddataservice/adapter/network/test/local_kv_store_sham_unit_test.cpp @@ -0,0 +1,1959 @@ +/* + * Copyright (c) 2024 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 "LocalKvStoreShamUnitTest" + +#include "block_data.h" +#include "distributed_kv_data_manager.h" +#include "log_print.h" +#include "types.h" +#include +#include +#include +#include + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::DistributedKv; +class LocalKvStoreShamUnitTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static DistributedKvDataManager shamTestManger_; + static std::shared_ptr shamTestStore_; + static Status shamTestStatus_; + static AppId shamTestAppId_; + static StoreId shamTestStoreId_; +}; +std::shared_ptr LocalKvStoreShamUnitTest::shamTestStore_ = nullptr; +Status LocalKvStoreShamUnitTest::shamTestStatus_ = Status::ERROR; +DistributedKvDataManager LocalKvStoreShamUnitTest::shamTestManger_; +AppId LocalKvStoreShamUnitTest::shamTestAppId_; +StoreId LocalKvStoreShamUnitTest::shamTestStoreId_; + +void LocalKvStoreShamUnitTest::SetUpTestCase(void) +{ + mkdir("/data/service/el1/public/database/local", (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); +} + +void LocalKvStoreShamUnitTest::TearDownTestCase(void) +{ + shamTestManger_.CloseKvStore(shamTestAppId_, shamTestStore_); + shamTestStore_ = nullptr; + shamTestManger_.DeleteKvStore(shamTestAppId_, shamTestStoreId_, "/data/service/el1/public/database/local"); + (void)remove("/data/service/el1/public/database/local/kvdb"); + (void)remove("/data/service/el1/public/database/local"); +} + +void LocalKvStoreShamUnitTest::SetUp(void) +{ + Options shamOptions; + shamOptions.securityLevel = S1; + shamOptions.baseDir = std::string("/data/service/el1/public/database/local"); + shamTestAppId_.appId = "local"; // define app name. + shamTestStoreId_.storeId = "MAN"; // define kvstore(database) name + shamTestManger_.DeleteKvStore(shamTestAppId_, shamTestStoreId_, shamOptions.baseDir); + // [create and] open and initialize kvstore instance. + shamTestStatus_ = shamTestManger_.GetSingleKvStore(shamOptions, shamTestAppId_, shamTestStoreId_, shamTestStore_); + ASSERT_EQ(Status::SUCCESS, shamTestStatus_) << "wrong status"; + ASSERT_NE(nullptr, shamTestStore_) << "kvStore is nullptr"; +} + +void LocalKvStoreShamUnitTest::TearDown(void) +{ + shamTestManger_.CloseKvStore(shamTestAppId_, shamTestStore_); + shamTestStore_ = nullptr; + shamTestManger_.DeleteKvStore(shamTestAppId_, shamTestStoreId_); +} + +class DeviceObserverShamUnitTest : public KvStoreObserver { +public: + std::vector insertShamEntries_; + std::vector updateShamEntries_; + std::vector deleteShamEntries_; + std::string shamDeviceId_; + bool isShamClear_ = false; + DeviceObserverShamUnitTest(); + ~DeviceObserverShamUnitTest() = default; + + void OnChange(const ChangeNotification &changeNotification); + + // reset the shamCallCount_ to zero. + void ResetToZero(); + + uint32_t GetCallCount(uint32_t shamTestValue = 1); + +private: + std::mutex shamMutex_; + uint32_t shamCallCount_ = 0; + BlockData shamValue_ { 1, 0 }; +}; + +DeviceObserverShamUnitTest::DeviceObserverShamUnitTest() { } + +void DeviceObserverShamUnitTest::OnChange(const ChangeNotification &changeNotification) +{ + ZLOGD("begin."); + insertShamEntries_ = changeNotification.GetInsertEntries(); + updateShamEntries_ = changeNotification.GetUpdateEntries(); + deleteShamEntries_ = changeNotification.GetDeleteEntries(); + shamDeviceId_ = changeNotification.GetDeviceId(); + isShamClear_ = changeNotification.IsClear(); + std::lock_guard guard(shamMutex_); + ++shamCallCount_; + shamValue_.SetValue(shamCallCount_); +} + +void DeviceObserverShamUnitTest::ResetToZero() +{ + std::lock_guard guard(shamMutex_); + shamCallCount_ = 0; + shamValue_.Clear(0); +} + +uint32_t DeviceObserverShamUnitTest::GetCallCount(uint32_t shamTestValue) +{ + int retryTimes = 0; + uint32_t callCount = 0; + while (retryTimes < shamTestValue) { + callCount = shamValue_.GetValue(); + if (callCount >= shamTestValue) { + break; + } + std::lock_guard guard(shamMutex_); + callCount = shamValue_.GetValue(); + if (callCount >= shamTestValue) { + break; + } + shamValue_.Clear(callCount); + retryTimes++; + } + return callCount; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore001 + * @tc.desc: Subscribe success + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore001, TestSize.Level1) +{ + ZLOGI("KvStoreDdmSubscribeKvStore001 begin."); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + auto shamObserver = std::make_shared(); + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; + shamObserver = nullptr; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore002 + * @tc.desc: Subscribe fail, shamObserver is null + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore002, TestSize.Level1) +{ + ZLOGI("KvStoreDdmSubscribeKvStore002 begin."); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + std::shared_ptr shamObserver = nullptr; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::INVALID_ARGUMENT, shamStatus) << "SubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore003 + * @tc.desc: Subscribe success and OnChange callback after put + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore003, TestSize.Level1) +{ + ZLOGI("KvStoreDdmSubscribeKvStore003 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey = "Id1"; + Value shamTestValue = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; + shamObserver = nullptr; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore004 + * @tc.desc: The same shamObserver subscribe three times and OnChange callback after put + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore004, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore004 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::STORE_ALREADY_SUBSCRIBE, shamStatus) << "SubscribeKvStore return wrong"; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::STORE_ALREADY_SUBSCRIBE, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey = "Id1"; + Value shamTestValue = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore005 + * @tc.desc: The different shamObserver subscribe three times and OnChange callback after put + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore005, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore005 begin."); + auto observer1 = std::make_shared(); + auto observer2 = std::make_shared(); + auto observer3 = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore failed, wrong"; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer2); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore failed, wrong"; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer3); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore failed, wrong"; + + Key shamTestKey = "Id1"; + Value shamTestValue = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "Putting data to KvStore failed, wrong"; + ASSERT_EQ(static_cast(observer1->GetCallCount()), 1); + ASSERT_EQ(static_cast(observer2->GetCallCount()), 1); + ASSERT_EQ(static_cast(observer3->GetCallCount()), 1); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer2); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer3); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore006 + * @tc.desc: Unsubscribe an shamObserver and subscribe again - the map should be cleared after unsubscription. + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore006, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore006 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey1 = "Id1"; + Value shamTestValue1 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; + + Key shamTestKey2 = "Id2"; + Value shamTestValue2 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + + shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + Key shamTestKey3 = "Id3"; + Value shamTestValue3 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore007 + * @tc.desc: Subscribe to an shamObserver - OnChange callback is called multiple times after the put operation. + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore007, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore007 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey1 = "Id1"; + Value shamTestValue1 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + + Key shamTestKey2 = "Id2"; + Value shamTestValue2 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + + Key shamTestKey3 = "Id3"; + Value shamTestValue3 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(3)), 3); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** +* @tc.name: KvStoreDdmSubscribeKvStore008 +* @tc.desc: Subscribe to an shamObserver - OnChange callback is + called multiple times after the put&update operations. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore008, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore008 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey1 = "Id1"; + Value shamTestValue1 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + + Key shamTestKey2 = "Id2"; + Value shamTestValue2 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + + Key shamTestKey3 = "Id1"; + Value shamTestValue3 = "subscribe03"; + shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(3)), 3); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore009 + * @tc.desc: Subscribe to an shamObserver - OnChange callback is called multiple times after the putBatch operation. + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore009, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore009 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + // before update. + std::vector shamTestEntries1; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries1.push_back(shamTestEnty1); + shamTestEntries1.push_back(shamTestEnty2); + shamTestEntries1.push_back(shamTestEnty3); + + std::vector shamTestEntries2; + Entry shamTestEnty4, shamTestEnty5; + shamTestEnty4.shamTestKey = "Id4"; + shamTestEnty4.shamTestValue = "subscribe"; + shamTestEnty5.shamTestKey = "Id5"; + shamTestEnty5.shamTestValue = "subscribe"; + shamTestEntries2.push_back(shamTestEnty4); + shamTestEntries2.push_back(shamTestEnty5); + + shamStatus = shamTestStore_->PutBatch(shamTestEntries1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + shamStatus = shamTestStore_->PutBatch(shamTestEntries2); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** +* @tc.name: KvStoreDdmSubscribeKvStore010 +* @tc.desc: Subscribe to an shamObserver - OnChange callback is + called multiple times after the putBatch update operation. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore010, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore010 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + // before update. + std::vector shamTestEntries1; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries1.push_back(shamTestEnty1); + shamTestEntries1.push_back(shamTestEnty2); + shamTestEntries1.push_back(shamTestEnty3); + + std::vector shamTestEntries2; + Entry shamTestEnty4, shamTestEnty5; + shamTestEnty4.shamTestKey = "Id1"; + shamTestEnty4.shamTestValue = "modify"; + shamTestEnty5.shamTestKey = "Id2"; + shamTestEnty5.shamTestValue = "modify"; + shamTestEntries2.push_back(shamTestEnty4); + shamTestEntries2.push_back(shamTestEnty5); + + shamStatus = shamTestStore_->PutBatch(shamTestEntries1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + shamStatus = shamTestStore_->PutBatch(shamTestEntries2); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore011 + * @tc.desc: Subscribe to an shamObserver - OnChange callback is called after successful deletion. + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore011, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore011 begin."); + auto shamObserver = std::make_shared(); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + shamStatus = shamTestStore_->Delete("Id1"); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore012 + * @tc.desc: Subscribe to an shamObserver - OnChange callback is not called after deletion of non-existing keys. + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore012, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore012 begin."); + auto shamObserver = std::make_shared(); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + shamStatus = shamTestStore_->Delete("Id4"); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore013 + * @tc.desc: Subscribe to an shamObserver - OnChange callback is called after KvStore is cleared. + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore013, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore013 begin."); + auto shamObserver = std::make_shared(); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** +* @tc.name: KvStoreDdmSubscribeKvStore014 +* @tc.desc: Subscribe to an shamObserver - OnChange callback is + not called after non-existing data in KvStore is cleared. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore014, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore014 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore015 + * @tc.desc: Subscribe to an shamObserver - OnChange callback is called after the deleteBatch operation. + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore015, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore015 begin."); + auto shamObserver = std::make_shared(); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + std::vector keys; + keys.push_back("Id1"); + keys.push_back("Id2"); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + shamStatus = shamTestStore_->DeleteBatch(keys); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore016 + * @tc.desc: Subscribe to an shamObserver - OnChange callback is called after deleteBatch of non-existing keys. + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore016, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore016 begin."); + auto shamObserver = std::make_shared(); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + std::vector keys; + keys.push_back("Id4"); + keys.push_back("Id5"); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + shamStatus = shamTestStore_->DeleteBatch(keys); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStore020 + * @tc.desc: Unsubscribe an shamObserver two times. + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore020, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStore020 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::STORE_NOT_SUBSCRIBE, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** +* @tc.name: KvStoreDdmSubscribeKvStoreNotification001 +* @tc.desc: Subscribe to an shamObserver successfully - callback is + called with a notification after the put operation. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification001, TestSize.Level1) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification001 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey = "Id1"; + Value shamTestValue = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ZLOGD("kvstore_ddm_subscribekvstore_003"); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + ZLOGD("kvstore_ddm_subscribekvstore_003 size:%zu.", shamObserver->insertShamEntries_.size()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** +* @tc.name: KvStoreDdmSubscribeKvStoreNotification002 +* @tc.desc: Subscribe to the same shamObserver three times - callback is + called with a notification after the put operation. +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification002, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification002 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::STORE_ALREADY_SUBSCRIBE, shamStatus) << "SubscribeKvStore return wrong"; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::STORE_ALREADY_SUBSCRIBE, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey = "Id1"; + Value shamTestValue = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification003 + * @tc.desc: The different shamObserver subscribe three times and callback with notification after put + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification003, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification003 begin."); + auto observer1 = std::make_shared(); + auto observer2 = std::make_shared(); + auto observer3 = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer2); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer3); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey = "Id1"; + Value shamTestValue = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(observer1->GetCallCount()), 1); + ASSERT_EQ(static_cast(observer1->insertShamEntries_.size()), 1); + ASSERT_EQ("Id1", observer1->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", observer1->insertShamEntries_[0].shamTestValue.ToString()); + + ASSERT_EQ(static_cast(observer2->GetCallCount()), 1); + ASSERT_EQ(static_cast(observer2->insertShamEntries_.size()), 1); + ASSERT_EQ("Id1", observer2->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", observer2->insertShamEntries_[0].shamTestValue.ToString()); + + ASSERT_EQ(static_cast(observer3->GetCallCount()), 1); + ASSERT_EQ(static_cast(observer3->insertShamEntries_.size()), 1); + ASSERT_EQ("Id1", observer3->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", observer3->insertShamEntries_[0].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer2); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer3); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification004 + * @tc.desc: Verify notification after an shamObserver is unsubscribed and then subscribed again. + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification004, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification004 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey1 = "Id1"; + Value shamTestValue1 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; + + Key shamTestKey2 = "Id2"; + Value shamTestValue2 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + + shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + Key shamTestKey3 = "Id3"; + Value shamTestValue3 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id3", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification005 + * @tc.desc: Subscribe to an shamObserver, callback with notification many times after put the different data + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification005, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification005 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey1 = "Id1"; + Value shamTestValue1 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + + Key shamTestKey2 = "Id2"; + Value shamTestValue2 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id2", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + + Key shamTestKey3 = "Id3"; + Value shamTestValue3 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(3)), 3); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id3", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification006 + * @tc.desc: Subscribe to an shamObserver, callback with notification many times after put the same data + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification006, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification006 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey1 = "Id1"; + Value shamTestValue1 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + + Key shamTestKey2 = "Id1"; + Value shamTestValue2 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); + ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); + + Key shamTestKey3 = "Id1"; + Value shamTestValue3 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(3)), 3); + ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification007 + * @tc.desc: Subscribe to an shamObserver, callback with notification many times after put&update + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification007, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification007 begin."); + auto shamObserver = std::make_shared(); + Key shamTestKey1 = "Id1"; + Value shamTestValue1 = "subscribe"; + Status shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); + // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + + Key shamTestKey2 = "Id2"; + Value shamTestValue2 = "subscribe"; + shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey3 = "Id1"; + Value shamTestValue3 = "subscribe03"; + shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe03", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification008 + * @tc.desc: Subscribe to an shamObserver, callback with notification one times after putbatch&update + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification008, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification008 begin."); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + shamTestEntries.clear(); + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe_modify"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe_modify"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 2); + ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe_modify", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id2", shamObserver->updateShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe_modify", shamObserver->updateShamEntries_[1].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification009 + * @tc.desc: Subscribe to an shamObserver, callback with notification one times after putbatch all different data + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification009, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification009 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 3); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id2", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); + ASSERT_EQ("Id3", shamObserver->insertShamEntries_[2].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[2].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** +* @tc.name: KvStoreDdmSubscribeKvStoreNotification010 +* @tc.desc: Subscribe to an shamObserver, + callback with notification one times after putbatch both different and same data +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification010, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification010 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id1"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id2"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 2); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id2", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); + ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 0); + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 0); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification011 + * @tc.desc: Subscribe to an shamObserver, callback with notification one times after putbatch all same data + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification011, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification011 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id1"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id1"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 0); + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 0); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification012 + * @tc.desc: Subscribe to an shamObserver, callback with notification many times after putbatch all different data + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification012, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification012 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + std::vector shamTestEntries1; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries1.push_back(shamTestEnty1); + shamTestEntries1.push_back(shamTestEnty2); + shamTestEntries1.push_back(shamTestEnty3); + + std::vector shamTestEntries2; + Entry shamTestEnty4, shamTestEnty5; + shamTestEnty4.shamTestKey = "Id4"; + shamTestEnty4.shamTestValue = "subscribe"; + shamTestEnty5.shamTestKey = "Id5"; + shamTestEnty5.shamTestValue = "subscribe"; + shamTestEntries2.push_back(shamTestEnty4); + shamTestEntries2.push_back(shamTestEnty5); + + shamStatus = shamTestStore_->PutBatch(shamTestEntries1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 3); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id2", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); + ASSERT_EQ("Id3", shamObserver->insertShamEntries_[2].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[2].shamTestValue.ToString()); +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification012b + * @tc.desc: Subscribe to an shamObserver, callback with notification many times after putbatch all different data + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification012b, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification012b begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + std::vector shamTestEntries1; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries1.push_back(shamTestEnty1); + shamTestEntries1.push_back(shamTestEnty2); + shamTestEntries1.push_back(shamTestEnty3); + + std::vector shamTestEntries2; + Entry shamTestEnty4, shamTestEnty5; + shamTestEnty4.shamTestKey = "Id4"; + shamTestEnty4.shamTestValue = "subscribe"; + shamTestEnty5.shamTestKey = "Id5"; + shamTestEnty5.shamTestValue = "subscribe"; + shamTestEntries2.push_back(shamTestEnty4); + shamTestEntries2.push_back(shamTestEnty5); + + shamStatus = shamTestStore_->PutBatch(shamTestEntries2); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 2); + ASSERT_EQ("Id4", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id5", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} +/** +* @tc.name: KvStoreDdmSubscribeKvStoreNotification013 +* @tc.desc: Subscribe to an shamObserver, + callback with notification many times after putbatch both different and same data +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification013, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification013 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + std::vector shamTestEntries1; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries1.push_back(shamTestEnty1); + shamTestEntries1.push_back(shamTestEnty2); + shamTestEntries1.push_back(shamTestEnty3); + + std::vector shamTestEntries2; + Entry shamTestEnty4, shamTestEnty5; + shamTestEnty4.shamTestKey = "Id1"; + shamTestEnty4.shamTestValue = "subscribe"; + shamTestEnty5.shamTestKey = "Id4"; + shamTestEnty5.shamTestValue = "subscribe"; + shamTestEntries2.push_back(shamTestEnty4); + shamTestEntries2.push_back(shamTestEnty5); + + shamStatus = shamTestStore_->PutBatch(shamTestEntries1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 3); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id2", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); + ASSERT_EQ("Id3", shamObserver->insertShamEntries_[2].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[2].shamTestValue.ToString()); +} + +/** +* @tc.name: KvStoreDdmSubscribeKvStoreNotification013b +* @tc.desc: Subscribe to an shamObserver, + callback with notification many times after putbatch both different and same data +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification013b, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification013b begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + std::vector shamTestEntries1; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries1.push_back(shamTestEnty1); + shamTestEntries1.push_back(shamTestEnty2); + shamTestEntries1.push_back(shamTestEnty3); + + std::vector shamTestEntries2; + Entry shamTestEnty4, shamTestEnty5; + shamTestEnty4.shamTestKey = "Id1"; + shamTestEnty4.shamTestValue = "subscribe"; + shamTestEnty5.shamTestKey = "Id4"; + shamTestEnty5.shamTestValue = "subscribe"; + shamTestEntries2.push_back(shamTestEnty4); + shamTestEntries2.push_back(shamTestEnty5); + shamStatus = shamTestStore_->PutBatch(shamTestEntries2); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); + ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id4", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification014 + * @tc.desc: Subscribe to an shamObserver, callback with notification many times after putbatch all same data + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification014, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification014 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + std::vector shamTestEntries1; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries1.push_back(shamTestEnty1); + shamTestEntries1.push_back(shamTestEnty2); + shamTestEntries1.push_back(shamTestEnty3); + + std::vector shamTestEntries2; + Entry shamTestEnty4, shamTestEnty5; + shamTestEnty4.shamTestKey = "Id1"; + shamTestEnty4.shamTestValue = "subscribe"; + shamTestEnty5.shamTestKey = "Id2"; + shamTestEnty5.shamTestValue = "subscribe"; + shamTestEntries2.push_back(shamTestEnty4); + shamTestEntries2.push_back(shamTestEnty5); + + shamStatus = shamTestStore_->PutBatch(shamTestEntries1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 3); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id2", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); + ASSERT_EQ("Id3", shamObserver->insertShamEntries_[2].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[2].shamTestValue.ToString()); + + shamStatus = shamTestStore_->PutBatch(shamTestEntries2); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); + ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 2); + ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id2", shamObserver->updateShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[1].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification015 + * @tc.desc: Subscribe to an shamObserver, callback with notification many times after putbatch complex data + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification015, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification015 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + std::vector shamTestEntries1; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id1"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries1.push_back(shamTestEnty1); + shamTestEntries1.push_back(shamTestEnty2); + shamTestEntries1.push_back(shamTestEnty3); + + std::vector shamTestEntries2; + Entry shamTestEnty4, shamTestEnty5; + shamTestEnty4.shamTestKey = "Id1"; + shamTestEnty4.shamTestValue = "subscribe"; + shamTestEnty5.shamTestKey = "Id2"; + shamTestEnty5.shamTestValue = "subscribe"; + shamTestEntries2.push_back(shamTestEnty4); + shamTestEntries2.push_back(shamTestEnty5); + + shamStatus = shamTestStore_->PutBatch(shamTestEntries1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 0); + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 0); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 2); + ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id3", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification015b + * @tc.desc: Subscribe to an shamObserver, callback with notification many times after putbatch complex data + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification015b, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification015b begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + std::vector shamTestEntries1; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id1"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries1.push_back(shamTestEnty1); + shamTestEntries1.push_back(shamTestEnty2); + shamTestEntries1.push_back(shamTestEnty3); + + std::vector shamTestEntries2; + Entry shamTestEnty4, shamTestEnty5; + shamTestEnty4.shamTestKey = "Id1"; + shamTestEnty4.shamTestValue = "subscribe"; + shamTestEnty5.shamTestKey = "Id2"; + shamTestEnty5.shamTestValue = "subscribe"; + shamTestEntries2.push_back(shamTestEnty4); + shamTestEntries2.push_back(shamTestEnty5); + shamStatus = shamTestStore_->PutBatch(shamTestEntries2); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); + ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); + ASSERT_EQ("Id2", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification016 + * @tc.desc: Pressure test subscribe, callback with notification many times after putbatch + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification016, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification016 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + int times = 100; // 100 times + std::vector shamTestEntries; + for (int i = 0; i < times; i++) { + Entry shamTestEnty; + shamTestEnty.shamTestKey = std::to_string(i); + shamTestEnty.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty); + } + + shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 100); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification017 + * @tc.desc: Subscribe to an shamObserver, callback with notification after delete success + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification017, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification017 begin."); + auto shamObserver = std::make_shared(); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + shamStatus = shamTestStore_->Delete("Id1"); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->deleteShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[0].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification018 + * @tc.desc: Subscribe to an shamObserver, not callback after delete which shamTestKey not exist + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification018, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification018 begin."); + auto shamObserver = std::make_shared(); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + shamStatus = shamTestStore_->Delete("Id4"); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 0); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** +* @tc.name: KvStoreDdmSubscribeKvStoreNotification019 +* @tc.desc: Subscribe to an shamObserver, + delete the same data many times and only first delete callback with notification +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification019, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification019 begin."); + auto shamObserver = std::make_shared(); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + shamStatus = shamTestStore_->Delete("Id1"); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 1); + ASSERT_EQ("Id1", shamObserver->deleteShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[0].shamTestValue.ToString()); + + shamStatus = shamTestStore_->Delete("Id1"); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 1); + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 1); // not callback so not clear + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification020 + * @tc.desc: Subscribe to an shamObserver, callback with notification after deleteBatch + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification020, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification020 begin."); + auto shamObserver = std::make_shared(); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + std::vector keys; + keys.push_back("Id1"); + keys.push_back("Id2"); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + shamStatus = shamTestStore_->DeleteBatch(keys); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 2); + ASSERT_EQ("Id1", shamObserver->deleteShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id2", shamObserver->deleteShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[1].shamTestValue.ToString()); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification021 + * @tc.desc: Subscribe to an shamObserver, not callback after deleteBatch which all keys not exist + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification021, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification021 begin."); + auto shamObserver = std::make_shared(); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + std::vector keys; + keys.push_back("Id4"); + keys.push_back("Id5"); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + shamStatus = shamTestStore_->DeleteBatch(keys); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 0); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** +* @tc.name: KvStoreDdmSubscribeKvStoreNotification022 +* @tc.desc: Subscribe to an shamObserver, + deletebatch the same data many times and only first deletebatch callback with +* notification +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification022, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification022 begin."); + auto shamObserver = std::make_shared(); + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id1"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id2"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id3"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + std::vector keys; + keys.push_back("Id1"); + keys.push_back("Id2"); + + Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + shamStatus = shamTestStore_->DeleteBatch(keys); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 2); + ASSERT_EQ("Id1", shamObserver->deleteShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id2", shamObserver->deleteShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[1].shamTestValue.ToString()); + + shamStatus = shamTestStore_->DeleteBatch(keys); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 1); + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 2); // not callback so not clear + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification023 + * @tc.desc: Subscribe to an shamObserver, include Clear Put PutBatch Delete DeleteBatch + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification023, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification023 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey1 = "Id1"; + Value shamTestValue1 = "subscribe"; + + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id2"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id3"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id4"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + std::vector keys; + keys.push_back("Id2"); + keys.push_back("Id3"); + + shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + shamStatus = shamTestStore_->Delete(shamTestKey1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore delete data return wrong"; + shamStatus = shamTestStore_->DeleteBatch(keys); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount(4)), 4); + // every callback will clear vector + ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 2); + ASSERT_EQ("Id2", shamObserver->deleteShamEntries_[0].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[0].shamTestValue.ToString()); + ASSERT_EQ("Id3", shamObserver->deleteShamEntries_[1].shamTestKey.ToString()); + ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[1].shamTestValue.ToString()); + ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 0); + ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 0); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} + +/** + * @tc.name: KvStoreDdmSubscribeKvStoreNotification024 + * @tc.desc: Subscribe to an shamObserver[use transaction], include Clear Put PutBatch Delete DeleteBatch + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification024, TestSize.Level2) +{ + ZLOGI("KvStoreDdmSubscribeKvStoreNotification024 begin."); + auto shamObserver = std::make_shared(); + SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; + Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; + + Key shamTestKey1 = "Id1"; + Value shamTestValue1 = "subscribe"; + + std::vector shamTestEntries; + Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; + shamTestEnty1.shamTestKey = "Id2"; + shamTestEnty1.shamTestValue = "subscribe"; + shamTestEnty2.shamTestKey = "Id3"; + shamTestEnty2.shamTestValue = "subscribe"; + shamTestEnty3.shamTestKey = "Id4"; + shamTestEnty3.shamTestValue = "subscribe"; + shamTestEntries.push_back(shamTestEnty1); + shamTestEntries.push_back(shamTestEnty2); + shamTestEntries.push_back(shamTestEnty3); + + std::vector keys; + keys.push_back("Id2"); + keys.push_back("Id3"); + + shamStatus = shamTestStore_->StartTransaction(); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore startTransaction return wrong"; + shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; + shamStatus = shamTestStore_->PutBatch(shamTestEntries); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; + shamStatus = shamTestStore_->Delete(shamTestKey1); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore delete data return wrong"; + shamStatus = shamTestStore_->DeleteBatch(keys); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; + shamStatus = shamTestStore_->Commit(); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Commit return wrong"; + ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); + + shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); + ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; +} \ No newline at end of file -- Gitee From 475b33aeede51e56ad8e05ca38b338f27c5e5227 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Fri, 14 Mar 2025 07:04:17 +0000 Subject: [PATCH 005/225] add rate of coverage ut case-0312 Signed-off-by: suoqilong --- .../test/local_kv_store_sham_unit_test.cpp | 1959 ----------------- 1 file changed, 1959 deletions(-) delete mode 100644 services/distributeddataservice/adapter/network/test/local_kv_store_sham_unit_test.cpp diff --git a/services/distributeddataservice/adapter/network/test/local_kv_store_sham_unit_test.cpp b/services/distributeddataservice/adapter/network/test/local_kv_store_sham_unit_test.cpp deleted file mode 100644 index 59dd7c034..000000000 --- a/services/distributeddataservice/adapter/network/test/local_kv_store_sham_unit_test.cpp +++ /dev/null @@ -1,1959 +0,0 @@ -/* - * Copyright (c) 2024 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 "LocalKvStoreShamUnitTest" - -#include "block_data.h" -#include "distributed_kv_data_manager.h" -#include "log_print.h" -#include "types.h" -#include -#include -#include -#include - -using namespace testing::ext; -using namespace OHOS; -using namespace OHOS::DistributedKv; -class LocalKvStoreShamUnitTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); - - static DistributedKvDataManager shamTestManger_; - static std::shared_ptr shamTestStore_; - static Status shamTestStatus_; - static AppId shamTestAppId_; - static StoreId shamTestStoreId_; -}; -std::shared_ptr LocalKvStoreShamUnitTest::shamTestStore_ = nullptr; -Status LocalKvStoreShamUnitTest::shamTestStatus_ = Status::ERROR; -DistributedKvDataManager LocalKvStoreShamUnitTest::shamTestManger_; -AppId LocalKvStoreShamUnitTest::shamTestAppId_; -StoreId LocalKvStoreShamUnitTest::shamTestStoreId_; - -void LocalKvStoreShamUnitTest::SetUpTestCase(void) -{ - mkdir("/data/service/el1/public/database/local", (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); -} - -void LocalKvStoreShamUnitTest::TearDownTestCase(void) -{ - shamTestManger_.CloseKvStore(shamTestAppId_, shamTestStore_); - shamTestStore_ = nullptr; - shamTestManger_.DeleteKvStore(shamTestAppId_, shamTestStoreId_, "/data/service/el1/public/database/local"); - (void)remove("/data/service/el1/public/database/local/kvdb"); - (void)remove("/data/service/el1/public/database/local"); -} - -void LocalKvStoreShamUnitTest::SetUp(void) -{ - Options shamOptions; - shamOptions.securityLevel = S1; - shamOptions.baseDir = std::string("/data/service/el1/public/database/local"); - shamTestAppId_.appId = "local"; // define app name. - shamTestStoreId_.storeId = "MAN"; // define kvstore(database) name - shamTestManger_.DeleteKvStore(shamTestAppId_, shamTestStoreId_, shamOptions.baseDir); - // [create and] open and initialize kvstore instance. - shamTestStatus_ = shamTestManger_.GetSingleKvStore(shamOptions, shamTestAppId_, shamTestStoreId_, shamTestStore_); - ASSERT_EQ(Status::SUCCESS, shamTestStatus_) << "wrong status"; - ASSERT_NE(nullptr, shamTestStore_) << "kvStore is nullptr"; -} - -void LocalKvStoreShamUnitTest::TearDown(void) -{ - shamTestManger_.CloseKvStore(shamTestAppId_, shamTestStore_); - shamTestStore_ = nullptr; - shamTestManger_.DeleteKvStore(shamTestAppId_, shamTestStoreId_); -} - -class DeviceObserverShamUnitTest : public KvStoreObserver { -public: - std::vector insertShamEntries_; - std::vector updateShamEntries_; - std::vector deleteShamEntries_; - std::string shamDeviceId_; - bool isShamClear_ = false; - DeviceObserverShamUnitTest(); - ~DeviceObserverShamUnitTest() = default; - - void OnChange(const ChangeNotification &changeNotification); - - // reset the shamCallCount_ to zero. - void ResetToZero(); - - uint32_t GetCallCount(uint32_t shamTestValue = 1); - -private: - std::mutex shamMutex_; - uint32_t shamCallCount_ = 0; - BlockData shamValue_ { 1, 0 }; -}; - -DeviceObserverShamUnitTest::DeviceObserverShamUnitTest() { } - -void DeviceObserverShamUnitTest::OnChange(const ChangeNotification &changeNotification) -{ - ZLOGD("begin."); - insertShamEntries_ = changeNotification.GetInsertEntries(); - updateShamEntries_ = changeNotification.GetUpdateEntries(); - deleteShamEntries_ = changeNotification.GetDeleteEntries(); - shamDeviceId_ = changeNotification.GetDeviceId(); - isShamClear_ = changeNotification.IsClear(); - std::lock_guard guard(shamMutex_); - ++shamCallCount_; - shamValue_.SetValue(shamCallCount_); -} - -void DeviceObserverShamUnitTest::ResetToZero() -{ - std::lock_guard guard(shamMutex_); - shamCallCount_ = 0; - shamValue_.Clear(0); -} - -uint32_t DeviceObserverShamUnitTest::GetCallCount(uint32_t shamTestValue) -{ - int retryTimes = 0; - uint32_t callCount = 0; - while (retryTimes < shamTestValue) { - callCount = shamValue_.GetValue(); - if (callCount >= shamTestValue) { - break; - } - std::lock_guard guard(shamMutex_); - callCount = shamValue_.GetValue(); - if (callCount >= shamTestValue) { - break; - } - shamValue_.Clear(callCount); - retryTimes++; - } - return callCount; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore001 - * @tc.desc: Subscribe success - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore001, TestSize.Level1) -{ - ZLOGI("KvStoreDdmSubscribeKvStore001 begin."); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - auto shamObserver = std::make_shared(); - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; - shamObserver = nullptr; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore002 - * @tc.desc: Subscribe fail, shamObserver is null - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore002, TestSize.Level1) -{ - ZLOGI("KvStoreDdmSubscribeKvStore002 begin."); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - std::shared_ptr shamObserver = nullptr; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::INVALID_ARGUMENT, shamStatus) << "SubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore003 - * @tc.desc: Subscribe success and OnChange callback after put - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore003, TestSize.Level1) -{ - ZLOGI("KvStoreDdmSubscribeKvStore003 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey = "Id1"; - Value shamTestValue = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; - shamObserver = nullptr; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore004 - * @tc.desc: The same shamObserver subscribe three times and OnChange callback after put - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore004, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore004 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::STORE_ALREADY_SUBSCRIBE, shamStatus) << "SubscribeKvStore return wrong"; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::STORE_ALREADY_SUBSCRIBE, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey = "Id1"; - Value shamTestValue = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore005 - * @tc.desc: The different shamObserver subscribe three times and OnChange callback after put - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore005, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore005 begin."); - auto observer1 = std::make_shared(); - auto observer2 = std::make_shared(); - auto observer3 = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore failed, wrong"; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer2); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore failed, wrong"; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer3); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore failed, wrong"; - - Key shamTestKey = "Id1"; - Value shamTestValue = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "Putting data to KvStore failed, wrong"; - ASSERT_EQ(static_cast(observer1->GetCallCount()), 1); - ASSERT_EQ(static_cast(observer2->GetCallCount()), 1); - ASSERT_EQ(static_cast(observer3->GetCallCount()), 1); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer2); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer3); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore006 - * @tc.desc: Unsubscribe an shamObserver and subscribe again - the map should be cleared after unsubscription. - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore006, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore006 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey1 = "Id1"; - Value shamTestValue1 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; - - Key shamTestKey2 = "Id2"; - Value shamTestValue2 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - - shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - Key shamTestKey3 = "Id3"; - Value shamTestValue3 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore007 - * @tc.desc: Subscribe to an shamObserver - OnChange callback is called multiple times after the put operation. - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore007, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore007 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey1 = "Id1"; - Value shamTestValue1 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - - Key shamTestKey2 = "Id2"; - Value shamTestValue2 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - - Key shamTestKey3 = "Id3"; - Value shamTestValue3 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(3)), 3); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** -* @tc.name: KvStoreDdmSubscribeKvStore008 -* @tc.desc: Subscribe to an shamObserver - OnChange callback is - called multiple times after the put&update operations. -* @tc.type: FUNC -* @tc.require: -* @tc.author: -*/ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore008, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore008 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey1 = "Id1"; - Value shamTestValue1 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - - Key shamTestKey2 = "Id2"; - Value shamTestValue2 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - - Key shamTestKey3 = "Id1"; - Value shamTestValue3 = "subscribe03"; - shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(3)), 3); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore009 - * @tc.desc: Subscribe to an shamObserver - OnChange callback is called multiple times after the putBatch operation. - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore009, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore009 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - // before update. - std::vector shamTestEntries1; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries1.push_back(shamTestEnty1); - shamTestEntries1.push_back(shamTestEnty2); - shamTestEntries1.push_back(shamTestEnty3); - - std::vector shamTestEntries2; - Entry shamTestEnty4, shamTestEnty5; - shamTestEnty4.shamTestKey = "Id4"; - shamTestEnty4.shamTestValue = "subscribe"; - shamTestEnty5.shamTestKey = "Id5"; - shamTestEnty5.shamTestValue = "subscribe"; - shamTestEntries2.push_back(shamTestEnty4); - shamTestEntries2.push_back(shamTestEnty5); - - shamStatus = shamTestStore_->PutBatch(shamTestEntries1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - shamStatus = shamTestStore_->PutBatch(shamTestEntries2); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** -* @tc.name: KvStoreDdmSubscribeKvStore010 -* @tc.desc: Subscribe to an shamObserver - OnChange callback is - called multiple times after the putBatch update operation. -* @tc.type: FUNC -* @tc.require: -* @tc.author: -*/ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore010, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore010 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - // before update. - std::vector shamTestEntries1; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries1.push_back(shamTestEnty1); - shamTestEntries1.push_back(shamTestEnty2); - shamTestEntries1.push_back(shamTestEnty3); - - std::vector shamTestEntries2; - Entry shamTestEnty4, shamTestEnty5; - shamTestEnty4.shamTestKey = "Id1"; - shamTestEnty4.shamTestValue = "modify"; - shamTestEnty5.shamTestKey = "Id2"; - shamTestEnty5.shamTestValue = "modify"; - shamTestEntries2.push_back(shamTestEnty4); - shamTestEntries2.push_back(shamTestEnty5); - - shamStatus = shamTestStore_->PutBatch(shamTestEntries1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - shamStatus = shamTestStore_->PutBatch(shamTestEntries2); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore011 - * @tc.desc: Subscribe to an shamObserver - OnChange callback is called after successful deletion. - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore011, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore011 begin."); - auto shamObserver = std::make_shared(); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - shamStatus = shamTestStore_->Delete("Id1"); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore012 - * @tc.desc: Subscribe to an shamObserver - OnChange callback is not called after deletion of non-existing keys. - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore012, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore012 begin."); - auto shamObserver = std::make_shared(); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - shamStatus = shamTestStore_->Delete("Id4"); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore013 - * @tc.desc: Subscribe to an shamObserver - OnChange callback is called after KvStore is cleared. - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore013, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore013 begin."); - auto shamObserver = std::make_shared(); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** -* @tc.name: KvStoreDdmSubscribeKvStore014 -* @tc.desc: Subscribe to an shamObserver - OnChange callback is - not called after non-existing data in KvStore is cleared. -* @tc.type: FUNC -* @tc.require: -* @tc.author: -*/ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore014, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore014 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore015 - * @tc.desc: Subscribe to an shamObserver - OnChange callback is called after the deleteBatch operation. - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore015, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore015 begin."); - auto shamObserver = std::make_shared(); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - std::vector keys; - keys.push_back("Id1"); - keys.push_back("Id2"); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - shamStatus = shamTestStore_->DeleteBatch(keys); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore016 - * @tc.desc: Subscribe to an shamObserver - OnChange callback is called after deleteBatch of non-existing keys. - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore016, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore016 begin."); - auto shamObserver = std::make_shared(); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - std::vector keys; - keys.push_back("Id4"); - keys.push_back("Id5"); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - shamStatus = shamTestStore_->DeleteBatch(keys); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStore020 - * @tc.desc: Unsubscribe an shamObserver two times. - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStore020, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStore020 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::STORE_NOT_SUBSCRIBE, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** -* @tc.name: KvStoreDdmSubscribeKvStoreNotification001 -* @tc.desc: Subscribe to an shamObserver successfully - callback is - called with a notification after the put operation. -* @tc.type: FUNC -* @tc.require: -* @tc.author: -*/ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification001, TestSize.Level1) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification001 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey = "Id1"; - Value shamTestValue = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ZLOGD("kvstore_ddm_subscribekvstore_003"); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - ZLOGD("kvstore_ddm_subscribekvstore_003 size:%zu.", shamObserver->insertShamEntries_.size()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** -* @tc.name: KvStoreDdmSubscribeKvStoreNotification002 -* @tc.desc: Subscribe to the same shamObserver three times - callback is - called with a notification after the put operation. -* @tc.type: FUNC -* @tc.require: -* @tc.author: -*/ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification002, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification002 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::STORE_ALREADY_SUBSCRIBE, shamStatus) << "SubscribeKvStore return wrong"; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::STORE_ALREADY_SUBSCRIBE, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey = "Id1"; - Value shamTestValue = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification003 - * @tc.desc: The different shamObserver subscribe three times and callback with notification after put - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification003, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification003 begin."); - auto observer1 = std::make_shared(); - auto observer2 = std::make_shared(); - auto observer3 = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer2); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, observer3); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey = "Id1"; - Value shamTestValue = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey, shamTestValue); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(observer1->GetCallCount()), 1); - ASSERT_EQ(static_cast(observer1->insertShamEntries_.size()), 1); - ASSERT_EQ("Id1", observer1->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", observer1->insertShamEntries_[0].shamTestValue.ToString()); - - ASSERT_EQ(static_cast(observer2->GetCallCount()), 1); - ASSERT_EQ(static_cast(observer2->insertShamEntries_.size()), 1); - ASSERT_EQ("Id1", observer2->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", observer2->insertShamEntries_[0].shamTestValue.ToString()); - - ASSERT_EQ(static_cast(observer3->GetCallCount()), 1); - ASSERT_EQ(static_cast(observer3->insertShamEntries_.size()), 1); - ASSERT_EQ("Id1", observer3->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", observer3->insertShamEntries_[0].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer2); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, observer3); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification004 - * @tc.desc: Verify notification after an shamObserver is unsubscribed and then subscribed again. - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification004, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification004 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey1 = "Id1"; - Value shamTestValue1 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; - - Key shamTestKey2 = "Id2"; - Value shamTestValue2 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - - shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - Key shamTestKey3 = "Id3"; - Value shamTestValue3 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id3", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification005 - * @tc.desc: Subscribe to an shamObserver, callback with notification many times after put the different data - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification005, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification005 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey1 = "Id1"; - Value shamTestValue1 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - - Key shamTestKey2 = "Id2"; - Value shamTestValue2 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id2", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - - Key shamTestKey3 = "Id3"; - Value shamTestValue3 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(3)), 3); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id3", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification006 - * @tc.desc: Subscribe to an shamObserver, callback with notification many times after put the same data - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification006, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification006 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey1 = "Id1"; - Value shamTestValue1 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - - Key shamTestKey2 = "Id1"; - Value shamTestValue2 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); - ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); - - Key shamTestKey3 = "Id1"; - Value shamTestValue3 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(3)), 3); - ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification007 - * @tc.desc: Subscribe to an shamObserver, callback with notification many times after put&update - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification007, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification007 begin."); - auto shamObserver = std::make_shared(); - Key shamTestKey1 = "Id1"; - Value shamTestValue1 = "subscribe"; - Status shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); - // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - - Key shamTestKey2 = "Id2"; - Value shamTestValue2 = "subscribe"; - shamStatus = shamTestStore_->Put(shamTestKey2, shamTestValue2); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey3 = "Id1"; - Value shamTestValue3 = "subscribe03"; - shamStatus = shamTestStore_->Put(shamTestKey3, shamTestValue3); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe03", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification008 - * @tc.desc: Subscribe to an shamObserver, callback with notification one times after putbatch&update - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification008, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification008 begin."); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - shamTestEntries.clear(); - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe_modify"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe_modify"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 2); - ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe_modify", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id2", shamObserver->updateShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe_modify", shamObserver->updateShamEntries_[1].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification009 - * @tc.desc: Subscribe to an shamObserver, callback with notification one times after putbatch all different data - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification009, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification009 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 3); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id2", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); - ASSERT_EQ("Id3", shamObserver->insertShamEntries_[2].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[2].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** -* @tc.name: KvStoreDdmSubscribeKvStoreNotification010 -* @tc.desc: Subscribe to an shamObserver, - callback with notification one times after putbatch both different and same data -* @tc.type: FUNC -* @tc.require: -* @tc.author: -*/ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification010, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification010 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id1"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id2"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 2); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id2", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); - ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 0); - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 0); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification011 - * @tc.desc: Subscribe to an shamObserver, callback with notification one times after putbatch all same data - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification011, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification011 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id1"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id1"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 0); - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 0); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification012 - * @tc.desc: Subscribe to an shamObserver, callback with notification many times after putbatch all different data - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification012, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification012 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - std::vector shamTestEntries1; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries1.push_back(shamTestEnty1); - shamTestEntries1.push_back(shamTestEnty2); - shamTestEntries1.push_back(shamTestEnty3); - - std::vector shamTestEntries2; - Entry shamTestEnty4, shamTestEnty5; - shamTestEnty4.shamTestKey = "Id4"; - shamTestEnty4.shamTestValue = "subscribe"; - shamTestEnty5.shamTestKey = "Id5"; - shamTestEnty5.shamTestValue = "subscribe"; - shamTestEntries2.push_back(shamTestEnty4); - shamTestEntries2.push_back(shamTestEnty5); - - shamStatus = shamTestStore_->PutBatch(shamTestEntries1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 3); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id2", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); - ASSERT_EQ("Id3", shamObserver->insertShamEntries_[2].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[2].shamTestValue.ToString()); -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification012b - * @tc.desc: Subscribe to an shamObserver, callback with notification many times after putbatch all different data - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification012b, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification012b begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - std::vector shamTestEntries1; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries1.push_back(shamTestEnty1); - shamTestEntries1.push_back(shamTestEnty2); - shamTestEntries1.push_back(shamTestEnty3); - - std::vector shamTestEntries2; - Entry shamTestEnty4, shamTestEnty5; - shamTestEnty4.shamTestKey = "Id4"; - shamTestEnty4.shamTestValue = "subscribe"; - shamTestEnty5.shamTestKey = "Id5"; - shamTestEnty5.shamTestValue = "subscribe"; - shamTestEntries2.push_back(shamTestEnty4); - shamTestEntries2.push_back(shamTestEnty5); - - shamStatus = shamTestStore_->PutBatch(shamTestEntries2); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 2); - ASSERT_EQ("Id4", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id5", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} -/** -* @tc.name: KvStoreDdmSubscribeKvStoreNotification013 -* @tc.desc: Subscribe to an shamObserver, - callback with notification many times after putbatch both different and same data -* @tc.type: FUNC -* @tc.require: -* @tc.author: -*/ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification013, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification013 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - std::vector shamTestEntries1; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries1.push_back(shamTestEnty1); - shamTestEntries1.push_back(shamTestEnty2); - shamTestEntries1.push_back(shamTestEnty3); - - std::vector shamTestEntries2; - Entry shamTestEnty4, shamTestEnty5; - shamTestEnty4.shamTestKey = "Id1"; - shamTestEnty4.shamTestValue = "subscribe"; - shamTestEnty5.shamTestKey = "Id4"; - shamTestEnty5.shamTestValue = "subscribe"; - shamTestEntries2.push_back(shamTestEnty4); - shamTestEntries2.push_back(shamTestEnty5); - - shamStatus = shamTestStore_->PutBatch(shamTestEntries1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 3); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id2", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); - ASSERT_EQ("Id3", shamObserver->insertShamEntries_[2].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[2].shamTestValue.ToString()); -} - -/** -* @tc.name: KvStoreDdmSubscribeKvStoreNotification013b -* @tc.desc: Subscribe to an shamObserver, - callback with notification many times after putbatch both different and same data -* @tc.type: FUNC -* @tc.require: -* @tc.author: -*/ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification013b, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification013b begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - std::vector shamTestEntries1; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries1.push_back(shamTestEnty1); - shamTestEntries1.push_back(shamTestEnty2); - shamTestEntries1.push_back(shamTestEnty3); - - std::vector shamTestEntries2; - Entry shamTestEnty4, shamTestEnty5; - shamTestEnty4.shamTestKey = "Id1"; - shamTestEnty4.shamTestValue = "subscribe"; - shamTestEnty5.shamTestKey = "Id4"; - shamTestEnty5.shamTestValue = "subscribe"; - shamTestEntries2.push_back(shamTestEnty4); - shamTestEntries2.push_back(shamTestEnty5); - shamStatus = shamTestStore_->PutBatch(shamTestEntries2); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); - ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id4", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification014 - * @tc.desc: Subscribe to an shamObserver, callback with notification many times after putbatch all same data - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification014, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification014 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - std::vector shamTestEntries1; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries1.push_back(shamTestEnty1); - shamTestEntries1.push_back(shamTestEnty2); - shamTestEntries1.push_back(shamTestEnty3); - - std::vector shamTestEntries2; - Entry shamTestEnty4, shamTestEnty5; - shamTestEnty4.shamTestKey = "Id1"; - shamTestEnty4.shamTestValue = "subscribe"; - shamTestEnty5.shamTestKey = "Id2"; - shamTestEnty5.shamTestValue = "subscribe"; - shamTestEntries2.push_back(shamTestEnty4); - shamTestEntries2.push_back(shamTestEnty5); - - shamStatus = shamTestStore_->PutBatch(shamTestEntries1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 3); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id2", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); - ASSERT_EQ("Id3", shamObserver->insertShamEntries_[2].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[2].shamTestValue.ToString()); - - shamStatus = shamTestStore_->PutBatch(shamTestEntries2); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); - ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 2); - ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id2", shamObserver->updateShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[1].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification015 - * @tc.desc: Subscribe to an shamObserver, callback with notification many times after putbatch complex data - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification015, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification015 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - std::vector shamTestEntries1; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id1"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries1.push_back(shamTestEnty1); - shamTestEntries1.push_back(shamTestEnty2); - shamTestEntries1.push_back(shamTestEnty3); - - std::vector shamTestEntries2; - Entry shamTestEnty4, shamTestEnty5; - shamTestEnty4.shamTestKey = "Id1"; - shamTestEnty4.shamTestValue = "subscribe"; - shamTestEnty5.shamTestKey = "Id2"; - shamTestEnty5.shamTestValue = "subscribe"; - shamTestEntries2.push_back(shamTestEnty4); - shamTestEntries2.push_back(shamTestEnty5); - - shamStatus = shamTestStore_->PutBatch(shamTestEntries1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 0); - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 0); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 2); - ASSERT_EQ("Id1", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id3", shamObserver->insertShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[1].shamTestValue.ToString()); -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification015b - * @tc.desc: Subscribe to an shamObserver, callback with notification many times after putbatch complex data - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification015b, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification015b begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - std::vector shamTestEntries1; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id1"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries1.push_back(shamTestEnty1); - shamTestEntries1.push_back(shamTestEnty2); - shamTestEntries1.push_back(shamTestEnty3); - - std::vector shamTestEntries2; - Entry shamTestEnty4, shamTestEnty5; - shamTestEnty4.shamTestKey = "Id1"; - shamTestEnty4.shamTestValue = "subscribe"; - shamTestEnty5.shamTestKey = "Id2"; - shamTestEnty5.shamTestValue = "subscribe"; - shamTestEntries2.push_back(shamTestEnty4); - shamTestEntries2.push_back(shamTestEnty5); - shamStatus = shamTestStore_->PutBatch(shamTestEntries2); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 2); - ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->updateShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->updateShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 1); - ASSERT_EQ("Id2", shamObserver->insertShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->insertShamEntries_[0].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification016 - * @tc.desc: Pressure test subscribe, callback with notification many times after putbatch - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification016, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification016 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - int times = 100; // 100 times - std::vector shamTestEntries; - for (int i = 0; i < times; i++) { - Entry shamTestEnty; - shamTestEnty.shamTestKey = std::to_string(i); - shamTestEnty.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty); - } - - shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 100); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification017 - * @tc.desc: Subscribe to an shamObserver, callback with notification after delete success - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification017, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification017 begin."); - auto shamObserver = std::make_shared(); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - shamStatus = shamTestStore_->Delete("Id1"); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->deleteShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[0].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification018 - * @tc.desc: Subscribe to an shamObserver, not callback after delete which shamTestKey not exist - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification018, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification018 begin."); - auto shamObserver = std::make_shared(); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - shamStatus = shamTestStore_->Delete("Id4"); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 0); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** -* @tc.name: KvStoreDdmSubscribeKvStoreNotification019 -* @tc.desc: Subscribe to an shamObserver, - delete the same data many times and only first delete callback with notification -* @tc.type: FUNC -* @tc.require: -* @tc.author: -*/ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification019, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification019 begin."); - auto shamObserver = std::make_shared(); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - shamStatus = shamTestStore_->Delete("Id1"); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 1); - ASSERT_EQ("Id1", shamObserver->deleteShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[0].shamTestValue.ToString()); - - shamStatus = shamTestStore_->Delete("Id1"); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Delete data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 1); - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 1); // not callback so not clear - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification020 - * @tc.desc: Subscribe to an shamObserver, callback with notification after deleteBatch - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification020, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification020 begin."); - auto shamObserver = std::make_shared(); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - std::vector keys; - keys.push_back("Id1"); - keys.push_back("Id2"); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - shamStatus = shamTestStore_->DeleteBatch(keys); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 2); - ASSERT_EQ("Id1", shamObserver->deleteShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id2", shamObserver->deleteShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[1].shamTestValue.ToString()); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification021 - * @tc.desc: Subscribe to an shamObserver, not callback after deleteBatch which all keys not exist - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification021, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification021 begin."); - auto shamObserver = std::make_shared(); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - std::vector keys; - keys.push_back("Id4"); - keys.push_back("Id5"); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - shamStatus = shamTestStore_->DeleteBatch(keys); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 0); - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 0); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** -* @tc.name: KvStoreDdmSubscribeKvStoreNotification022 -* @tc.desc: Subscribe to an shamObserver, - deletebatch the same data many times and only first deletebatch callback with -* notification -* @tc.type: FUNC -* @tc.require: -* @tc.author: -*/ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification022, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification022 begin."); - auto shamObserver = std::make_shared(); - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id1"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id2"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id3"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - std::vector keys; - keys.push_back("Id1"); - keys.push_back("Id2"); - - Status shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - shamStatus = shamTestStore_->DeleteBatch(keys); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 2); - ASSERT_EQ("Id1", shamObserver->deleteShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id2", shamObserver->deleteShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[1].shamTestValue.ToString()); - - shamStatus = shamTestStore_->DeleteBatch(keys); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(2)), 1); - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 2); // not callback so not clear - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification023 - * @tc.desc: Subscribe to an shamObserver, include Clear Put PutBatch Delete DeleteBatch - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification023, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification023 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey1 = "Id1"; - Value shamTestValue1 = "subscribe"; - - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id2"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id3"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id4"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - std::vector keys; - keys.push_back("Id2"); - keys.push_back("Id3"); - - shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - shamStatus = shamTestStore_->Delete(shamTestKey1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore delete data return wrong"; - shamStatus = shamTestStore_->DeleteBatch(keys); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount(4)), 4); - // every callback will clear vector - ASSERT_EQ(static_cast(shamObserver->deleteShamEntries_.size()), 2); - ASSERT_EQ("Id2", shamObserver->deleteShamEntries_[0].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[0].shamTestValue.ToString()); - ASSERT_EQ("Id3", shamObserver->deleteShamEntries_[1].shamTestKey.ToString()); - ASSERT_EQ("subscribe", shamObserver->deleteShamEntries_[1].shamTestValue.ToString()); - ASSERT_EQ(static_cast(shamObserver->updateShamEntries_.size()), 0); - ASSERT_EQ(static_cast(shamObserver->insertShamEntries_.size()), 0); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} - -/** - * @tc.name: KvStoreDdmSubscribeKvStoreNotification024 - * @tc.desc: Subscribe to an shamObserver[use transaction], include Clear Put PutBatch Delete DeleteBatch - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(LocalKvStoreShamUnitTest, KvStoreDdmSubscribeKvStoreNotification024, TestSize.Level2) -{ - ZLOGI("KvStoreDdmSubscribeKvStoreNotification024 begin."); - auto shamObserver = std::make_shared(); - SubscribeType shamSubscribeType = SubscribeType::SUBSCRIBE_TYPE_ALL; - Status shamStatus = shamTestStore_->SubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "SubscribeKvStore return wrong"; - - Key shamTestKey1 = "Id1"; - Value shamTestValue1 = "subscribe"; - - std::vector shamTestEntries; - Entry shamTestEnty1, shamTestEnty2, shamTestEnty3; - shamTestEnty1.shamTestKey = "Id2"; - shamTestEnty1.shamTestValue = "subscribe"; - shamTestEnty2.shamTestKey = "Id3"; - shamTestEnty2.shamTestValue = "subscribe"; - shamTestEnty3.shamTestKey = "Id4"; - shamTestEnty3.shamTestValue = "subscribe"; - shamTestEntries.push_back(shamTestEnty1); - shamTestEntries.push_back(shamTestEnty2); - shamTestEntries.push_back(shamTestEnty3); - - std::vector keys; - keys.push_back("Id2"); - keys.push_back("Id3"); - - shamStatus = shamTestStore_->StartTransaction(); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore startTransaction return wrong"; - shamStatus = shamTestStore_->Put(shamTestKey1, shamTestValue1); // insert or update shamTestKey-shamTestValue - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore put data return wrong"; - shamStatus = shamTestStore_->PutBatch(shamTestEntries); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore putbatch data return wrong"; - shamStatus = shamTestStore_->Delete(shamTestKey1); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore delete data return wrong"; - shamStatus = shamTestStore_->DeleteBatch(keys); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore DeleteBatch data return wrong"; - shamStatus = shamTestStore_->Commit(); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "KvStore Commit return wrong"; - ASSERT_EQ(static_cast(shamObserver->GetCallCount()), 1); - - shamStatus = shamTestStore_->UnSubscribeKvStore(shamSubscribeType, shamObserver); - ASSERT_EQ(Status::SUCCESS, shamStatus) << "UnSubscribeKvStore return wrong"; -} \ No newline at end of file -- Gitee From 75e65193d9cbf7a7b17126ddee326efd5abbf241 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Fri, 14 Mar 2025 07:14:59 +0000 Subject: [PATCH 006/225] add rate of coverage ut case-0312 Signed-off-by: suoqilong --- .../adapter/network/test/BUILD.gn | 3 +-- .../network_delegate_normal_impl_test.cpp | 26 +++++++++---------- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/services/distributeddataservice/adapter/network/test/BUILD.gn b/services/distributeddataservice/adapter/network/test/BUILD.gn index 1b6065721..ef81e2b61 100755 --- a/services/distributeddataservice/adapter/network/test/BUILD.gn +++ b/services/distributeddataservice/adapter/network/test/BUILD.gn @@ -62,13 +62,12 @@ ohos_unittest("NetworkDelegateNormalImplTest") { "${data_service_path}/adapter/network/src", "${data_service_path}/adapter/include", ] + cflags = [ "-Dprivate=public", "-Dprotected=public", ] - # deps = [ "../:distributeddata_network" ] - deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", ] diff --git a/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp index 1629745b9..1f656fde6 100644 --- a/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp +++ b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp @@ -12,14 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// #define LOG_TAG "NetworkDelegateNormalImplTest" #include "network_delegate.h" #include "network_delegate_normal_impl.h" #include "network_delegate_normal_impl.cpp" #include #include -// #include "log_print.h" using namespace testing::ext; using namespace std; @@ -54,10 +52,10 @@ void NetworkDelegateNormalImplTest::TearDown() /** * @tc.name: GetNetworkType001 -* @tc.desc: GetNetworkType test. +* @tc.desc: GetNetworkType testing exception branching scenarios. * @tc.type: FUNC * @tc.require: -* @tc.author: +* @tc.author: suoqilong */ HWTEST_F(NetworkDelegateNormalImplTest, GetNetworkType001, TestSize.Level1) { @@ -70,10 +68,10 @@ HWTEST_F(NetworkDelegateNormalImplTest, GetNetworkType001, TestSize.Level1) /** * @tc.name: GetNetworkType002 -* @tc.desc: GetNetworkType test. +* @tc.desc: GetNetworkType testing normal branching scenarios. * @tc.type: FUNC * @tc.require: -* @tc.author: +* @tc.author: suoqilong */ HWTEST_F(NetworkDelegateNormalImplTest, GetNetworkType002, TestSize.Level1) { @@ -86,10 +84,10 @@ HWTEST_F(NetworkDelegateNormalImplTest, GetNetworkType002, TestSize.Level1) /** * @tc.name: IsNetworkAvailable -* @tc.desc: IsNetworkAvailable test. +* @tc.desc: IsNetworkAvailable testing different branching scenarios. * @tc.type: FUNC * @tc.require: -* @tc.author: +* @tc.author: suoqilong */ HWTEST_F(NetworkDelegateNormalImplTest, IsNetworkAvailable, TestSize.Level1) { @@ -126,10 +124,10 @@ HWTEST_F(NetworkDelegateNormalImplTest, IsNetworkAvailable, TestSize.Level1) /** * @tc.name: NetCapabilitiesChange001 -* @tc.desc: NetCapabilitiesChange test. +* @tc.desc: NetCapabilitiesChange testing different branching scenarios. * @tc.type: FUNC * @tc.require: -* @tc.author: +* @tc.author: suoqilong */ HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange001, TestSize.Level1) { @@ -152,10 +150,10 @@ HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange001, TestSize.Level /** * @tc.name: NetCapabilitiesChange002 -* @tc.desc: NetCapabilitiesChange test. +* @tc.desc: NetCapabilitiesChange testing different branching scenarios. * @tc.type: FUNC * @tc.require: -* @tc.author: +* @tc.author: suoqilong */ HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange002, TestSize.Level1) { @@ -192,10 +190,10 @@ HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange002, TestSize.Level /** * @tc.name: Convert -* @tc.desc: Convert test. +* @tc.desc: Convert testing different branching scenarios. * @tc.type: FUNC * @tc.require: -* @tc.author: +* @tc.author: suoqilong */ HWTEST_F(NetworkDelegateNormalImplTest, Convert, TestSize.Level1) { -- Gitee From ee000ef0a7a45963de03a286ceccf39467fc940f Mon Sep 17 00:00:00 2001 From: suoqilong Date: Fri, 14 Mar 2025 07:24:43 +0000 Subject: [PATCH 007/225] add rate of coverage ut case-0312 Signed-off-by: suoqilong --- .../network/test/network_delegate_normal_impl_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp index 1f656fde6..8ad4c6111 100644 --- a/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp +++ b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp @@ -96,7 +96,7 @@ HWTEST_F(NetworkDelegateNormalImplTest, IsNetworkAvailable, TestSize.Level1) EXPECT_FALSE(ret); DmDeviceInfo& info = const_cast(delegate.cloudDmInfo_); - std::memset(info.networkId, 0, sizeof(info.networkId)); + std::memset_s(info.networkId, 0, sizeof(info.networkId)); NetworkDelegateNormalImpl::NetworkType netWorkType = NetworkDelegate::NetworkType::NONE; NetworkDelegateNormalImpl::NetworkType status = delegate.SetNet(netWorkType); EXPECT_EQ(status, NetworkDelegate::NONE); @@ -159,7 +159,7 @@ HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange002, TestSize.Level { NetworkDelegateNormalImpl delegate; DmDeviceInfo& info = const_cast(delegate.cloudDmInfo_); - std::memset(info.networkId, 0, sizeof(info.networkId)); + std::memset_s(info.networkId, 0, sizeof(info.networkId)); sptr observer = new (std::nothrow) NetConnCallbackObserver(delegate); sptr netHandle = new (std::nothrow) NetHandle(); sptr netAllCap = new (std::nothrow) NetAllCapabilities(); -- Gitee From a160a92e802f61dc66c419f7435c36a779759346 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Fri, 14 Mar 2025 07:53:28 +0000 Subject: [PATCH 008/225] add rate of coverage ut case-0312 Signed-off-by: suoqilong --- .../test/network_delegate_normal_impl_test.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp index 8ad4c6111..78647b39c 100644 --- a/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp +++ b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp @@ -96,7 +96,7 @@ HWTEST_F(NetworkDelegateNormalImplTest, IsNetworkAvailable, TestSize.Level1) EXPECT_FALSE(ret); DmDeviceInfo& info = const_cast(delegate.cloudDmInfo_); - std::memset_s(info.networkId, 0, sizeof(info.networkId)); + std::fill(info.networkId, info.networkId + sizeof(info.networkId), '\0'); NetworkDelegateNormalImpl::NetworkType netWorkType = NetworkDelegate::NetworkType::NONE; NetworkDelegateNormalImpl::NetworkType status = delegate.SetNet(netWorkType); EXPECT_EQ(status, NetworkDelegate::NONE); @@ -146,6 +146,10 @@ HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange001, TestSize.Level netAllCap = new (std::nothrow) NetAllCapabilities(); status = observer->NetCapabilitiesChange(netHandle, netAllCap); EXPECT_EQ(status, 0); + + delete observer; + delete netHandle; + delete netAllCap; } /** @@ -159,7 +163,7 @@ HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange002, TestSize.Level { NetworkDelegateNormalImpl delegate; DmDeviceInfo& info = const_cast(delegate.cloudDmInfo_); - std::memset_s(info.networkId, 0, sizeof(info.networkId)); + std::fill(info.networkId, info.networkId + sizeof(info.networkId), '\0'); sptr observer = new (std::nothrow) NetConnCallbackObserver(delegate); sptr netHandle = new (std::nothrow) NetHandle(); sptr netAllCap = new (std::nothrow) NetAllCapabilities(); @@ -186,6 +190,11 @@ HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange002, TestSize.Level EXPECT_TRUE(!netAllCaps->bearerTypes_.empty()); status = observer->NetCapabilitiesChange(netHandle, netAllCaps); EXPECT_EQ(status, 0); + + delete observer; + delete netHandle; + delete netAllCap; + delete netAllCaps; } /** -- Gitee From 835fa36297a79e0517f5ca04820df47f1cc0dab5 Mon Sep 17 00:00:00 2001 From: ZhaoJinghui Date: Fri, 14 Mar 2025 16:05:46 +0800 Subject: [PATCH 009/225] =?UTF-8?q?=E7=94=A8=E4=BE=8B=E8=BE=93=E5=87=BA?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E7=BB=9F=E4=B8=80=E9=83=A8=E4=BB=B6=E3=80=81?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: ZhaoJinghui Change-Id: Id1dc7ba558cc54d3ecea1651d7dcf2ff827a9a00 --- services/distributeddataservice/adapter/account/test/BUILD.gn | 2 +- .../distributeddataservice/adapter/communicator/test/BUILD.gn | 2 +- services/distributeddataservice/adapter/dfx/test/BUILD.gn | 2 +- services/distributeddataservice/adapter/network/test/BUILD.gn | 2 +- .../distributeddataservice/adapter/screenlock/test/BUILD.gn | 2 +- services/distributeddataservice/app/test/BUILD.gn | 2 +- services/distributeddataservice/framework/test/BUILD.gn | 2 +- services/distributeddataservice/service/test/BUILD.gn | 2 +- .../distributeddataservice/service/test/ohos_test/BUILD.gn | 3 +-- .../distributeddataservice/service/test/testCloud/BUILD.gn | 3 +-- 10 files changed, 10 insertions(+), 12 deletions(-) diff --git a/services/distributeddataservice/adapter/account/test/BUILD.gn b/services/distributeddataservice/adapter/account/test/BUILD.gn index 998613742..39c09ee55 100755 --- a/services/distributeddataservice/adapter/account/test/BUILD.gn +++ b/services/distributeddataservice/adapter/account/test/BUILD.gn @@ -12,7 +12,7 @@ # limitations under the License. import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### ohos_unittest("AccountDelegateTest") { diff --git a/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/BUILD.gn index c92ff75ae..cf89c4464 100755 --- a/services/distributeddataservice/adapter/communicator/test/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/ohos.gni") import("//build/ohos_var.gni") import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### ohos_unittest("CommunicationProviderTest") { diff --git a/services/distributeddataservice/adapter/dfx/test/BUILD.gn b/services/distributeddataservice/adapter/dfx/test/BUILD.gn index 8916b3dc1..78a3fa45b 100755 --- a/services/distributeddataservice/adapter/dfx/test/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/test/BUILD.gn @@ -13,7 +13,7 @@ import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### config("module_dfx_mst_config") { diff --git a/services/distributeddataservice/adapter/network/test/BUILD.gn b/services/distributeddataservice/adapter/network/test/BUILD.gn index 6c030e768..d9aed4b59 100755 --- a/services/distributeddataservice/adapter/network/test/BUILD.gn +++ b/services/distributeddataservice/adapter/network/test/BUILD.gn @@ -12,7 +12,7 @@ # limitations under the License. import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### ohos_unittest("NetworkDelegateTest") { diff --git a/services/distributeddataservice/adapter/screenlock/test/BUILD.gn b/services/distributeddataservice/adapter/screenlock/test/BUILD.gn index 8a1c3084c..f1f16b53b 100755 --- a/services/distributeddataservice/adapter/screenlock/test/BUILD.gn +++ b/services/distributeddataservice/adapter/screenlock/test/BUILD.gn @@ -12,7 +12,7 @@ # limitations under the License. import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### ohos_unittest("ScreenLockTest") { diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index 04caea8c4..548129eec 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -13,7 +13,7 @@ import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddataservice" +module_output_path = "datamgr_service/datamgr_service/distributeddataservice" ############################################################################### config("module_private_config") { diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn index eb7c9c8c3..44818b93b 100644 --- a/services/distributeddataservice/framework/test/BUILD.gn +++ b/services/distributeddataservice/framework/test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/ohos_var.gni") import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### config("module_private_config") { diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index fea5a473a..2f4181753 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/ohos_var.gni") import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### config("module_private_config") { diff --git a/services/distributeddataservice/service/test/ohos_test/BUILD.gn b/services/distributeddataservice/service/test/ohos_test/BUILD.gn index d0140c7d0..ed9f42f06 100644 --- a/services/distributeddataservice/service/test/ohos_test/BUILD.gn +++ b/services/distributeddataservice/service/test/ohos_test/BUILD.gn @@ -17,6 +17,5 @@ ohos_copy("copy_ohos_test") { subsystem_name = "distributeddatamgr" part_name = "datamgr_service" sources = [ "./ohos_test.xml" ] - outputs = - [ "$root_out_dir/tests/unittest/datamgr_service/resource/ohos_test.xml" ] + outputs = [ "$root_out_dir/tests/unittest/datamgr_service/datamgr_service/resource/ohos_test.xml" ] } diff --git a/services/distributeddataservice/service/test/testCloud/BUILD.gn b/services/distributeddataservice/service/test/testCloud/BUILD.gn index e4d86447f..db1355d58 100644 --- a/services/distributeddataservice/service/test/testCloud/BUILD.gn +++ b/services/distributeddataservice/service/test/testCloud/BUILD.gn @@ -18,8 +18,7 @@ ohos_hap("testCloud") { hap_name = "testCloud" subsystem_name = "distributeddatamgr" part_name = "datamgr_service" - final_hap_path = - "$root_out_dir/tests/unittest/datamgr_service/resource/${hap_name}.hap" + final_hap_path = "$root_out_dir/tests/unittest/datamgr_service/datamgr_service/resource/${hap_name}.hap" testonly = true deps = [ ":testCloud_ets_assets", -- Gitee From 7701e03c3814dc201da403de7d9cf7d7936825bf Mon Sep 17 00:00:00 2001 From: zph Date: Fri, 14 Mar 2025 17:00:59 +0800 Subject: [PATCH 010/225] update: Signed-off-by: zph --- .../service/udmf/preprocess/data_handler.cpp | 41 ++++++++ .../service/udmf/preprocess/data_handler.h | 4 + .../udmf/preprocess/preprocess_utils.cpp | 59 ++++++++++++ .../udmf/preprocess/preprocess_utils.h | 3 + .../service/udmf/store/runtime_store.cpp | 94 ++++++++++--------- .../service/udmf/store/runtime_store.h | 5 +- .../service/udmf/store/store.h | 3 + .../service/udmf/udmf_service_impl.cpp | 56 +++++++---- .../service/udmf/udmf_service_impl.h | 1 + 9 files changed, 203 insertions(+), 63 deletions(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp index 94d6ad7f1..bafe79cb8 100644 --- a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp @@ -136,4 +136,45 @@ Status DataHandler::BuildEntries(const std::vector &>(value)); + if (!TLVUtil::ReadTlv(summary, data, TAG::TAG_SUMMARY)) { + ZLOGE("Unmarshall summary failed."); + return E_READ_PARCEL_ERROR; + } + return E_OK; +} + +Status DataHandler::MarshalToEntries(const Runtime &runtime, Value &value) +{ + auto runtimeTlv = TLVObject(value); + if (!TLVUtil::Writing(runtime, runtimeTlv, TAG::TAG_RUNTIME)) { + ZLOGE("Marshall runtime failed."); + return E_WRITE_PARCEL_ERROR; + } + return E_OK; +} + +Status DataHandler::UnmarshalEntries(const Value &value, Runtime &runtime) +{ + auto data = TLVObject(const_cast &>(value)); + if (!TLVUtil::ReadTlv(runtime, data, TAG::TAG_RUNTIME)) { + ZLOGE("Unmarshall runtime failed."); + return E_READ_PARCEL_ERROR; + } + return E_OK; +} + } // namespace UDMF::OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/preprocess/data_handler.h b/services/distributeddataservice/service/udmf/preprocess/data_handler.h index 3be27dfa3..b32a355d3 100644 --- a/services/distributeddataservice/service/udmf/preprocess/data_handler.h +++ b/services/distributeddataservice/service/udmf/preprocess/data_handler.h @@ -26,6 +26,10 @@ public: static Status MarshalToEntries(const UnifiedData &unifiedData, std::vector &entries); static Status UnmarshalEntries(const std::string &key, const std::vector &entries, UnifiedData &unifiedData); + static Status MarshalToEntries(const Summary &summary, Value &value); + static Status UnmarshalEntries(const Value &value, Summary &summary); + static Status MarshalToEntries(const Runtime &runtime, Value &value); + static Status UnmarshalEntries(const Value &value, Runtime &runtime); private: static Status BuildEntries(const std::vector> &records, diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index fcb2eb437..75eef0ff4 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -40,6 +40,10 @@ constexpr const char *FILE_SCHEME_PREFIX = "file://"; constexpr const char *DOCS_LOCAL_TAG = "/docs/"; static constexpr uint32_t DOCS_LOCAL_PATH_SUBSTR_START_INDEX = 1; static constexpr uint32_t VERIFY_URI_PERMISSION_MAX_SIZE = 500; +constexpr const char *TEMP_UNIFIED_DATA_FLAG = "temp_udmf_file_flag"; +static constexpr size_t TEMP_UDATA_RECORD_SIZE = 1; +static constexpr uint32_t PREFIX_LEN = 24; +static constexpr uint32_t INDEX_LEN = 8; using namespace OHOS::DistributedDataDfx; using namespace Security::AccessToken; using namespace OHOS::AppFileService::ModuleRemoteFileShare; @@ -401,5 +405,60 @@ void PreProcessUtils::ProcessHtmlFileUris(uint32_t tokenId, UnifiedData &data, b PreProcessUtils::ClearHtmlDfsUris(data); } } + +void PreProcessUtils::SetRecordUid(UnifiedData &data) +{ + uint32_t index = 0; + auto prefix = PreProcessUtils::GenerateId().substr(0, PREFIX_LEN); + for (const auto &record : data.GetRecords()) { + std::ostringstream oss; + oss << std::setw(INDEX_LEN) << std::setfill('0') << index; + record->SetUid(prefix + oss.str()); + index++; + } +} + +bool PreProcessUtils::GetDetailsFromUData(const UnifiedData &data, UDDetails &details) +{ + auto records = data.GetRecords(); + if (records.size() != TEMP_UDATA_RECORD_SIZE) { + return false; + } + if (records[0] == nullptr || records[0]->GetType() != UDType::FILE) { + return false; + } + auto obj = std::get>(records[0]->GetOriginValue()); + if (obj == nullptr) { + ZLOGE("ValueType is not Object!"); + return false; + } + std::shared_ptr detailObj; + obj->GetValue(DETAILS, detailObj); + if (detailObj == nullptr) { + ZLOGE("Not contain details for object!"); + return false; + } + auto result = ObjectUtils::ConvertToUDDetails(detailObj); + if (result.find(TEMP_UNIFIED_DATA_FLAG) == result.end()) { + return false; + } + details = result; + return true; +} + +Status PreProcessUtils::GetSummaryFromDetails(const UDDetails &details, Summary &summary) +{ + for (auto &item : details) { + if (item.first != TEMP_UNIFIED_DATA_FLAG) { + auto int64Value = std::get_if(&item.second); + if (int64Value != nullptr) { + auto size = std::get(item.second); + summary.summary[item.first] = size; + summary.totalSize += size; + } + } + } + return E_OK; +} } // namespace UDMF } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h index e57061af7..6d6130078 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h @@ -39,6 +39,9 @@ public: static void ProcessHtmlFileUris(uint32_t tokenId, UnifiedData &data, bool isLocal, std::vector &uris); static void ProcessRecord(std::shared_ptr record, uint32_t tokenId, bool isLocal, std::vector &uris); + static void SetRecordUid(UnifiedData &data); + static bool GetDetailsFromUData(const UnifiedData &data, UDDetails &details); + static Status GetSummaryFromDetails(const UDDetails &details, Summary &summary); private: static bool CheckUriAuthorization(const std::vector& uris, uint32_t tokenId); static int32_t GetDfsUrisFromLocal(const std::vector &uris, int32_t userId, UnifiedData &data); diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index a8dd78f5d..843f4412d 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -35,9 +35,7 @@ using namespace RadarReporter; using namespace DistributedDB; using Anonymous = OHOS::DistributedData::Anonymous; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; - -constexpr const char *TEMP_UNIFIED_DATA_FLAG = "temp_udmf_file_flag"; -static constexpr size_t TEMP_UDATA_RECORD_SIZE = 1; +constexpr const char *SUMMARY_SUFIX = "#summary"; RuntimeStore::RuntimeStore(const std::string &storeId) : storeId_(storeId) { @@ -121,63 +119,73 @@ Status RuntimeStore::Get(const std::string &key, UnifiedData &unifiedData) return DataHandler::UnmarshalEntries(key, entries, unifiedData); } -bool RuntimeStore::GetDetailsFromUData(UnifiedData &data, UDDetails &details) +Status RuntimeStore::PutSummary(const std::string &key, const Summary &summary) { - auto records = data.GetRecords(); - if (records.size() != TEMP_UDATA_RECORD_SIZE) { - return false; + UpdateTime(); + Value value; + auto status = DataHandler::MarshalToEntries(summary, value); + if (status != E_OK) { + ZLOGE("Marshal summary failed, key: %{public}s, status:%{public}d", key.c_str(), status); + return status; } - if (records[0] == nullptr || records[0]->GetType() != UDType::FILE) { - return false; + auto summaryKey = key + SUMMARY_SUFIX; + auto res = kvStore_->Put({summaryKey.begin(), summaryKey.end()}, value); + if (res != OK) { + ZLOGE("Put failed, key:%{public}s, status:%{public}d", key.c_str(), res); + return E_DB_ERROR; } - auto obj = std::get>(records[0]->GetOriginValue()); - if (obj == nullptr) { - ZLOGE("ValueType is not Object!"); - return false; + return E_OK; +} + +Status RuntimeStore::GetSummary(const std::string &key, Summary &summary) +{ + UpdateTime(); + Value value; + auto summaryKey = key + SUMMARY_SUFIX; + auto res = kvStore_->Get({summaryKey.begin(), summaryKey.end()}, value); + if (res != OK || value.empty()) { + ZLOGE("Get failed, key: %{public}s, status:%{public}d", key.c_str(), res); + return E_DB_ERROR; } - std::shared_ptr detailObj; - obj->GetValue(DETAILS, detailObj); - if (detailObj == nullptr) { - ZLOGE("Not contain details for object!"); - return false; - } - auto result = ObjectUtils::ConvertToUDDetails(detailObj); - if (result.find(TEMP_UNIFIED_DATA_FLAG) == result.end()) { - return false; + auto status = DataHandler::UnmarshalEntries(value, summary); + if (status != E_OK) { + ZLOGE("Unmarshal summary failed, key: %{public}s, status:%{public}d", key.c_str(), status); + return status; } - details = result; - return true; + return E_OK; } -Status RuntimeStore::GetSummaryFromDetails(const UDDetails &details, Summary &summary) +Status RuntimeStore::PutRuntime(const std::string &key, const Runtime &runtime) { - for (auto &item : details) { - if (item.first != TEMP_UNIFIED_DATA_FLAG) { - auto int64Value = std::get_if(&item.second); - if (int64Value != nullptr) { - auto size = std::get(item.second); - summary.summary[item.first] = size; - summary.totalSize += size; - } - } + UpdateTime(); + Value value; + auto status = DataHandler::MarshalToEntries(runtime, value); + if (status != E_OK) { + ZLOGE("Marshal runtime failed, key: %{public}s, status:%{public}d", key.c_str(), status); + return status; + } + auto res = kvStore_->Put({key.begin(), key.end()}, value); + if (res != OK) { + ZLOGE("Put failed, key:%{public}s, status:%{public}d", key.c_str(), res); + return E_DB_ERROR; } return E_OK; } -Status RuntimeStore::GetSummary(const std::string &key, Summary &summary) +Status RuntimeStore::GetRuntime(const std::string &key, Runtime &runtime) { UpdateTime(); - UnifiedData unifiedData; - if (Get(key, unifiedData) != E_OK) { - ZLOGE("Get unified data failed, dataPrefix: %{public}s", key.c_str()); + Value value; + auto res = kvStore_->Get({key.begin(), key.end()}, value); + if (res != OK || value.empty()) { + ZLOGE("Get failed, key: %{public}s, status:%{public}d", key.c_str(), res); return E_DB_ERROR; } - - UDDetails details {}; - if (GetDetailsFromUData(unifiedData, details)) { - return GetSummaryFromDetails(details, summary); + auto status = DataHandler::UnmarshalEntries(value, runtime); + if (status != E_OK) { + ZLOGE("Unmarshal runtime failed, key: %{public}s, status:%{public}d", key.c_str(), status); + return status; } - UnifiedDataHelper::GetSummary(unifiedData, summary); return E_OK; } diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.h b/services/distributeddataservice/service/udmf/store/runtime_store.h index 623b9204c..ad561281c 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.h +++ b/services/distributeddataservice/service/udmf/store/runtime_store.h @@ -30,6 +30,7 @@ public: ~RuntimeStore(); Status Put(const UnifiedData &unifiedData) override; Status Get(const std::string &key, UnifiedData &unifiedData) override; + Status PutSummary(const std::string &key, const Summary &summary) override; Status GetSummary(const std::string &key, Summary &summary) override; Status Update(const UnifiedData &unifiedData) override; Status Delete(const std::string &key) override; @@ -41,6 +42,8 @@ public: Status PutLocal(const std::string &key, const std::string &value) override; Status GetLocal(const std::string &key, std::string &value) override; Status DeleteLocal(const std::string &key) override; + Status PutRuntime(const std::string &key, const Runtime &runtime) override; + Status GetRuntime(const std::string &key, Runtime &runtime) override; void Close() override; bool Init() override; @@ -59,8 +62,6 @@ private: Status DeleteEntries(const std::vector &keys); Status UnmarshalEntries( const std::string &key, std::vector &entries, UnifiedData &unifiedData); - bool GetDetailsFromUData(UnifiedData &data, UDDetails &details); - Status GetSummaryFromDetails(const UDDetails &details, Summary &summary); bool BuildMetaDataParam(DistributedData::StoreMetaData &metaData); void NotifySyncProcss(const DevSyncProcessMap &processMap, ProcessCallback callback, const DevNameMap &deviceNameMap); diff --git a/services/distributeddataservice/service/udmf/store/store.h b/services/distributeddataservice/service/udmf/store/store.h index 1a728c374..bcaa0e6fd 100644 --- a/services/distributeddataservice/service/udmf/store/store.h +++ b/services/distributeddataservice/service/udmf/store/store.h @@ -26,6 +26,7 @@ public: using Time = std::chrono::steady_clock::time_point; virtual Status Put(const UnifiedData &unifiedData) = 0; virtual Status Get(const std::string &key, UnifiedData &unifiedData) = 0; + virtual Status PutSummary(const std::string &key, const Summary &summary) = 0; virtual Status GetSummary(const std::string &key, Summary &summary) = 0; virtual Status Update(const UnifiedData &unifiedData) = 0; virtual Status Delete(const std::string &key) = 0; @@ -37,6 +38,8 @@ public: virtual Status PutLocal(const std::string &key, const std::string &value) = 0; virtual Status GetLocal(const std::string &key, std::string &value) = 0; virtual Status DeleteLocal(const std::string &key) = 0; + virtual Status PutRuntime(const std::string &key, const Runtime &runtime) = 0; + virtual Status GetRuntime(const std::string &key, Runtime &runtime) = 0; virtual bool Init() = 0; virtual void Close() = 0; diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index fc75e80b0..f995f67fc 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -34,6 +34,7 @@ #include "bootstrap.h" #include "metadata/store_meta_data.h" #include "metadata/meta_data_manager.h" +#include "unified_data_helper.h" namespace OHOS { namespace UDMF { @@ -132,11 +133,13 @@ int32_t UdmfServiceImpl::SaveData(CustomOption &option, UnifiedData &unifiedData unifiedData.GetRuntime()->createPackage.c_str()); return ret; } + ret = SetSummary(unifiedData); + if (ret != E_OK) { + ZLOGE("Set summary failed, key: %{public}s.", key.c_str()); + return ret; + } } - - for (const auto &record : unifiedData.GetRecords()) { - record->SetUid(PreProcessUtils::GenerateId()); - } + PreProcessUtils::SetRecordUid(unifiedData); auto store = StoreCache::GetInstance().GetStore(intention); if (store == nullptr) { @@ -399,9 +402,7 @@ int32_t UdmfServiceImpl::UpdateData(const QueryOption &query, UnifiedData &unifi } runtime->lastModifiedTime = PreProcessUtils::GetTimestamp(); unifiedData.SetRuntime(*runtime); - for (auto &record : unifiedData.GetRecords()) { - record->SetUid(PreProcessUtils::GenerateId()); - } + PreProcessUtils::SetRecordUid(unifiedData); if (store->Update(unifiedData) != E_OK) { ZLOGE("Unified data update failed:%{public}s", key.intention.c_str()); return E_DB_ERROR; @@ -500,26 +501,23 @@ int32_t UdmfServiceImpl::AddPrivilege(const QueryOption &query, Privilege &privi return E_DB_ERROR; } - UnifiedData data; - int32_t res = store->Get(query.key, data); + Runtime runtime; + auto res = store->GetRuntime(query.key, runtime); if (res == E_NOT_FOUND) { privilegeCache_[query.key] = privilege; ZLOGW("Add privilege in cache, key: %{public}s.", query.key.c_str()); return E_OK; } if (res != E_OK) { - ZLOGE("Get data from store failed, res:%{public}d,intention: %{public}s.", res, key.intention.c_str()); + ZLOGE("Get runtime failed, res:%{public}d, key:%{public}s.", res, query.key.c_str()); return res; } - if (data.GetRuntime() == nullptr) { - return E_DB_ERROR; - } - data.GetRuntime()->privileges.emplace_back(privilege); - if (store->Update(data) != E_OK) { - ZLOGE("Update unified data failed:%{public}s", key.intention.c_str()); - return E_DB_ERROR; + runtime.privileges.emplace_back(privilege); + res = store->PutRuntime(query.key, runtime); + if (res != E_OK) { + ZLOGE("Update runtime failed, res:%{public}d, key:%{public}s", res, query.key.c_str()); } - return E_OK; + return res; } int32_t UdmfServiceImpl::Sync(const QueryOption &query, const std::vector &devices) @@ -838,5 +836,27 @@ int32_t UdmfServiceImpl::OnUserChange(uint32_t code, const std::string &user, co } return Feature::OnUserChange(code, user, account); } + +int32_t UdmfServiceImpl::SetSummary(const UnifiedData &data) const +{ + UnifiedKey key = data.GetRuntime()->key; + auto store = StoreCache::GetInstance().GetStore(key.intention); + if (store == nullptr) { + ZLOGE("Get store failed, key:%{public}s", key.GetUnifiedKey().c_str()); + return E_DB_ERROR; + } + + UDDetails details {}; + Summary summary; + if (PreProcessUtils::GetDetailsFromUData(data, details)) { + return PreProcessUtils::GetSummaryFromDetails(details, summary); + } + UnifiedDataHelper::GetSummary(data, summary); + auto status = store->PutSummary(key.GetUnifiedKey(), summary); + if (status != E_OK) { + ZLOGE("Put summary failed, status:%{public}d, key:%{public}s.", status, key.GetUnifiedKey().c_str()); + } + return status; +} } // namespace UDMF } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.h b/services/distributeddataservice/service/udmf/udmf_service_impl.h index 93082d45a..0f8d79b7b 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.h +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.h @@ -58,6 +58,7 @@ private: bool VerifyPermission(const std::string &permission, uint32_t callerTokenId); bool HasDatahubPriviledge(const std::string &bundleName); void RegisterAsyncProcessInfo(const std::string &businessUdKey); + int32_t SetSummary(const UnifiedData &data) const; class Factory { public: -- Gitee From bc1308e0c980e64237c30aff1c386f2c0b95f533 Mon Sep 17 00:00:00 2001 From: xuyong Date: Fri, 14 Mar 2025 17:03:27 +0800 Subject: [PATCH 011/225] build: add direct dependency of hisysevent:libhisysevent Signed-off-by: xuyong --- services/distributeddataservice/service/test/BUILD.gn | 3 +++ .../service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn | 1 + .../service/test/fuzztest/dumphelper_fuzzer/BUILD.gn | 1 + .../service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn | 1 + .../service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn | 1 + .../service/test/fuzztest/udmfservice_fuzzer/BUILD.gn | 1 + services/distributeddataservice/service/udmf/BUILD.gn | 1 + 7 files changed, 9 insertions(+) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 9b359e5aa..f83510a69 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -128,6 +128,7 @@ ohos_unittest("CloudDataTest") { "device_manager:devicemanagersdk", "hicollie:libhicollie", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -223,6 +224,7 @@ ohos_unittest("CloudServiceImplTest") { "device_manager:devicemanagersdk", "hicollie:libhicollie", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -1304,6 +1306,7 @@ ohos_unittest("UdmfServiceStubMockTest") { "device_manager:devicemanagersdk", "googletest:gtest_main", "hilog:libhilog", + "hisysevent:libhisysevent", "hitrace:hitrace_meter", "hitrace:libhitracechain", "ipc:ipc_core", diff --git a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn index 30cc77cc7..3cb8f10bd 100644 --- a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn @@ -133,6 +133,7 @@ ohos_fuzztest("CloudServiceStubFuzzTest") { "device_manager:devicemanagersdk", "hicollie:libhicollie", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", diff --git a/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn index 3e39786a1..2fd165553 100644 --- a/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn @@ -70,6 +70,7 @@ ohos_fuzztest("DumpHelperFuzzTest") { "device_auth:deviceauth_sdk", "device_manager:devicemanagersdk", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", diff --git a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn index b7dffe3f1..984eddf37 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn @@ -75,6 +75,7 @@ ohos_fuzztest("RdbResultSetStubFuzzTest") { "device_auth:deviceauth_sdk", "device_manager:devicemanagersdk", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", diff --git a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn index 43309645c..e51d78511 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn @@ -120,6 +120,7 @@ ohos_fuzztest("RdbServiceStubFuzzTest") { "device_manager:devicemanagersdk", "hicollie:libhicollie", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", diff --git a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn index e3e58f256..723fdfcc9 100644 --- a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn @@ -60,6 +60,7 @@ ohos_fuzztest("UdmfServiceFuzzTest") { "bundle_framework:appexecfwk_core", "c_utils:utils", "hilog:libhilog", + "hisysevent:libhisysevent", "ipc:ipc_core", "kv_store:distributeddata_inner", "kv_store:distributeddata_mgr", diff --git a/services/distributeddataservice/service/udmf/BUILD.gn b/services/distributeddataservice/service/udmf/BUILD.gn index 5fd231303..5d0f44c13 100644 --- a/services/distributeddataservice/service/udmf/BUILD.gn +++ b/services/distributeddataservice/service/udmf/BUILD.gn @@ -81,6 +81,7 @@ ohos_source_set("udmf_server") { "app_file_service:remote_file_share_native", "device_manager:devicemanagersdk", "hilog:libhilog", + "hisysevent:libhisysevent", "hitrace:hitrace_meter", "hitrace:libhitracechain", "ipc:ipc_core", -- Gitee From 3ee2334b5f224f28883a5110759e39142eb4af9c Mon Sep 17 00:00:00 2001 From: zph Date: Sat, 15 Mar 2025 11:21:20 +0800 Subject: [PATCH 012/225] update Signed-off-by: zph --- .../service/udmf/preprocess/data_handler.cpp | 41 ------------------- .../service/udmf/preprocess/data_handler.h | 29 +++++++++++-- .../service/udmf/store/runtime_store.cpp | 10 ++--- 3 files changed, 30 insertions(+), 50 deletions(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp index bafe79cb8..94d6ad7f1 100644 --- a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp @@ -136,45 +136,4 @@ Status DataHandler::BuildEntries(const std::vector &>(value)); - if (!TLVUtil::ReadTlv(summary, data, TAG::TAG_SUMMARY)) { - ZLOGE("Unmarshall summary failed."); - return E_READ_PARCEL_ERROR; - } - return E_OK; -} - -Status DataHandler::MarshalToEntries(const Runtime &runtime, Value &value) -{ - auto runtimeTlv = TLVObject(value); - if (!TLVUtil::Writing(runtime, runtimeTlv, TAG::TAG_RUNTIME)) { - ZLOGE("Marshall runtime failed."); - return E_WRITE_PARCEL_ERROR; - } - return E_OK; -} - -Status DataHandler::UnmarshalEntries(const Value &value, Runtime &runtime) -{ - auto data = TLVObject(const_cast &>(value)); - if (!TLVUtil::ReadTlv(runtime, data, TAG::TAG_RUNTIME)) { - ZLOGE("Unmarshall runtime failed."); - return E_READ_PARCEL_ERROR; - } - return E_OK; -} - } // namespace UDMF::OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/preprocess/data_handler.h b/services/distributeddataservice/service/udmf/preprocess/data_handler.h index b32a355d3..b3e89721f 100644 --- a/services/distributeddataservice/service/udmf/preprocess/data_handler.h +++ b/services/distributeddataservice/service/udmf/preprocess/data_handler.h @@ -16,6 +16,7 @@ #define DATA_HANDLER_H #include "unified_data.h" +#include "tlv_util.h" #include "types_export.h" namespace OHOS::UDMF { @@ -26,10 +27,10 @@ public: static Status MarshalToEntries(const UnifiedData &unifiedData, std::vector &entries); static Status UnmarshalEntries(const std::string &key, const std::vector &entries, UnifiedData &unifiedData); - static Status MarshalToEntries(const Summary &summary, Value &value); - static Status UnmarshalEntries(const Value &value, Summary &summary); - static Status MarshalToEntries(const Runtime &runtime, Value &value); - static Status UnmarshalEntries(const Value &value, Runtime &runtime); + template + static Status MarshalToEntries(const T &data, Value &value, TAG tag); + template + static Status UnmarshalEntries(const Value &value, T &data, TAG tag); private: static Status BuildEntries(const std::vector> &records, @@ -38,5 +39,25 @@ private: const std::string &key, std::map> &records, std::map> &innerEntries); }; + +template +Status DataHandler::MarshalToEntries(const T &data, Value &value, TAG tag) +{ + auto tlvObject = TLVObject(value); + if (!TLVUtil::Writing(data, tlvObject, tag)) { + return E_WRITE_PARCEL_ERROR; + } + return E_OK; +} + +template +Status DataHandler::UnmarshalEntries(const Value &value, T &data, TAG tag) +{ + auto tlvObject = TLVObject(const_cast &>(value)); + if (!TLVUtil::ReadTlv(data, tlvObject, tag)) { + return E_READ_PARCEL_ERROR; + } + return E_OK; +} } // namespace UDMF::OHOS #endif // DATA_HANDLER_H \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index 843f4412d..f28ea8be1 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -123,7 +123,7 @@ Status RuntimeStore::PutSummary(const std::string &key, const Summary &summary) { UpdateTime(); Value value; - auto status = DataHandler::MarshalToEntries(summary, value); + auto status = DataHandler::MarshalToEntries(summary, value, TAG::TAG_SUMMARY); if (status != E_OK) { ZLOGE("Marshal summary failed, key: %{public}s, status:%{public}d", key.c_str(), status); return status; @@ -147,7 +147,7 @@ Status RuntimeStore::GetSummary(const std::string &key, Summary &summary) ZLOGE("Get failed, key: %{public}s, status:%{public}d", key.c_str(), res); return E_DB_ERROR; } - auto status = DataHandler::UnmarshalEntries(value, summary); + auto status = DataHandler::UnmarshalEntries(value, summary, TAG::TAG_SUMMARY); if (status != E_OK) { ZLOGE("Unmarshal summary failed, key: %{public}s, status:%{public}d", key.c_str(), status); return status; @@ -159,7 +159,7 @@ Status RuntimeStore::PutRuntime(const std::string &key, const Runtime &runtime) { UpdateTime(); Value value; - auto status = DataHandler::MarshalToEntries(runtime, value); + auto status = DataHandler::MarshalToEntries(runtime, value, TAG::TAG_RUNTIME); if (status != E_OK) { ZLOGE("Marshal runtime failed, key: %{public}s, status:%{public}d", key.c_str(), status); return status; @@ -181,11 +181,11 @@ Status RuntimeStore::GetRuntime(const std::string &key, Runtime &runtime) ZLOGE("Get failed, key: %{public}s, status:%{public}d", key.c_str(), res); return E_DB_ERROR; } - auto status = DataHandler::UnmarshalEntries(value, runtime); + auto status = DataHandler::UnmarshalEntries(value, runtime, TAG::TAG_RUNTIME); if (status != E_OK) { ZLOGE("Unmarshal runtime failed, key: %{public}s, status:%{public}d", key.c_str(), status); return status; - } + } return E_OK; } -- Gitee From edde89d834b1db25301e6760022d495080766fb4 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Sat, 15 Mar 2025 03:49:27 +0000 Subject: [PATCH 013/225] add rate of coverage ut case-0312 Signed-off-by: suoqilong --- .../network/test/network_delegate_normal_impl_test.cpp | 9 --------- 1 file changed, 9 deletions(-) diff --git a/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp index 78647b39c..64c639475 100644 --- a/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp +++ b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp @@ -146,10 +146,6 @@ HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange001, TestSize.Level netAllCap = new (std::nothrow) NetAllCapabilities(); status = observer->NetCapabilitiesChange(netHandle, netAllCap); EXPECT_EQ(status, 0); - - delete observer; - delete netHandle; - delete netAllCap; } /** @@ -190,11 +186,6 @@ HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange002, TestSize.Level EXPECT_TRUE(!netAllCaps->bearerTypes_.empty()); status = observer->NetCapabilitiesChange(netHandle, netAllCaps); EXPECT_EQ(status, 0); - - delete observer; - delete netHandle; - delete netAllCap; - delete netAllCaps; } /** -- Gitee From 64b9bcc3269163384d47f6f2206ad8b45e7788b9 Mon Sep 17 00:00:00 2001 From: zph Date: Sat, 15 Mar 2025 14:24:14 +0800 Subject: [PATCH 014/225] update Signed-off-by: zph --- services/distributeddataservice/service/test/BUILD.gn | 7 +++++++ .../service/test/udmf_run_time_store_test.cpp | 9 ++++----- .../service/udmf/store/runtime_store.cpp | 2 +- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 9b359e5aa..2d53f9850 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -909,6 +909,8 @@ ohos_unittest("UdmfRunTimeStoreTest") { "${data_service_path}/app/src", "${data_service_path}/service/kvdb", "${data_service_path}/service/udmf", + "${data_service_path}/service/udmf/store", + "${data_service_path}/service/udmf/preprocess", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", @@ -942,6 +944,11 @@ ohos_unittest("UdmfRunTimeStoreTest") { "//third_party/googletest:gtest_main", "//third_party/openssl:libcrypto_shared", ] + + defines = [ + "private=public", + "protected=public", + ] } ohos_unittest("DataShareServiceImplTest") { diff --git a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp index ec7fb210a..463a522b1 100644 --- a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp +++ b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp @@ -25,11 +25,10 @@ #include "kvstore_meta_manager.h" #include "metadata/meta_data_manager.h" #include "nativetoken_kit.h" +#include "preprocess_utils.h" +#include "runtime_store.h" #include "text.h" #include "token_setproc.h" -#define private public -#include "store/runtime_store.h" -#undef private using namespace testing::ext; using namespace OHOS::DistributedData; @@ -501,7 +500,7 @@ HWTEST_F(UdmfRunTimeStoreTest, GetDetailsFromUData, TestSize.Level1) details1.insert({ "udmf_key", "udmf_value" }); auto records = data1.GetRecords(); EXPECT_EQ(records.size(), 0); - status = store->GetDetailsFromUData(data1, details1); + status = PreProcessUtils::GetDetailsFromUData(data1, details1); EXPECT_FALSE(status); status = store->Delete(KEY_PREFIX); @@ -548,7 +547,7 @@ HWTEST_F(UdmfRunTimeStoreTest, GetDetailsFromUData01, TestSize.Level1) auto outputRecords = outputData.GetRecords(); ASSERT_EQ(inputRecords.size(), 512); ASSERT_EQ(0, outputRecords.size()); - status = store->GetDetailsFromUData(inputData, details1); + status = PreProcessUtils::GetDetailsFromUData(inputData, details1); EXPECT_FALSE(status); } diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index f28ea8be1..1f76169e6 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -185,7 +185,7 @@ Status RuntimeStore::GetRuntime(const std::string &key, Runtime &runtime) if (status != E_OK) { ZLOGE("Unmarshal runtime failed, key: %{public}s, status:%{public}d", key.c_str(), status); return status; - } + } return E_OK; } -- Gitee From de7f9d4fccdd3a8816df6bb9a911cfe7a1a5fd38 Mon Sep 17 00:00:00 2001 From: wTong6 Date: Mon, 10 Mar 2025 20:06:18 +0800 Subject: [PATCH 015/225] fix:delete enablecloud xcollie Signed-off-by: wTong6 --- .../distributeddataservice/service/cloud/cloud_service_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index 249240166..a286b810c 100644 --- a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -61,7 +61,7 @@ using namespace DistributedDataDfx; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; using Account = AccountDelegate; using AccessTokenKit = Security::AccessToken::AccessTokenKit; -static constexpr uint32_t RESTART_SERVICE_TIME_THRESHOLD = 60; +static constexpr uint32_t RESTART_SERVICE_TIME_THRESHOLD = 120; static constexpr const char *FT_ENABLE_CLOUD = "ENABLE_CLOUD"; static constexpr const char *FT_DISABLE_CLOUD = "DISABLE_CLOUD"; static constexpr const char *FT_SWITCH_ON = "SWITCH_ON"; -- Gitee From 620b18d7fb07f35f5c51f3d59d6234bb2338db99 Mon Sep 17 00:00:00 2001 From: yangliu Date: Sat, 15 Mar 2025 19:29:53 +0800 Subject: [PATCH 016/225] update Signed-off-by: yangliu --- .../app/src/kvstore_meta_manager.cpp | 172 ++++++++++++++++++ .../app/src/kvstore_meta_manager.h | 9 + .../distributeddataservice/framework/BUILD.gn | 1 + .../metadata/deviceid_pair_meta_data.h | 37 ++++ .../include/metadata/meta_data_manager.h | 8 +- .../include/metadata/store_meta_data.h | 1 + .../framework/include/store/general_store.h | 5 + .../framework/include/utils/constant.h | 1 + .../metadata/deviceid_pair_meta_data.cpp | 46 +++++ .../framework/metadata/meta_data_manager.cpp | 55 ++++++ .../framework/metadata/store_meta_data.cpp | 5 +- .../framework/utils/constant.cpp | 19 ++ .../service/kvdb/kvdb_service_impl.cpp | 8 + .../service/kvdb/upgrade.cpp | 23 +++ .../service/kvdb/upgrade.h | 1 + .../service/rdb/rdb_general_store.cpp | 5 + .../service/rdb/rdb_general_store.h | 1 + .../service/rdb/rdb_service_impl.cpp | 24 +++ .../service/rdb/rdb_service_impl.h | 2 + 19 files changed, 421 insertions(+), 2 deletions(-) create mode 100644 services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h create mode 100644 services/distributeddataservice/framework/metadata/deviceid_pair_meta_data.cpp diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index f7e315cab..cd33b5ff5 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -46,6 +46,12 @@ #include "utils/crypto.h" #include "utils/ref_count.h" #include "utils/converter.h" +#include "metadata/matrix_meta_data.h" +#include "metadata/switches_meta_data.h" +#include "utils/constant.h" +#include "metadata/user_meta_data.h" +#include "metadata/deviceid_pair_meta_data.h" +#include "metadata/strategy_meta_data.h" namespace OHOS { namespace DistributedKv { @@ -134,6 +140,11 @@ void KvStoreMetaManager::InitMetaData() ZLOGI("get meta failed."); return; } + if (IsMetaDeviceIdChanged()) { + UpdateLocalMetaDeviceId(); + UpdateSyncMetaDeviceId(); + } + auto uid = getuid(); auto tokenId = IPCSkeleton::GetCallingTokenID(); const std::string accountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); @@ -554,5 +565,166 @@ AppDistributedKv::ChangeLevelType KvStoreMetaManager::DBInfoDeviceChangeListener { return AppDistributedKv::ChangeLevelType::MIN; } + +bool KvStoreMetaManager::IsMetaDeviceIdChanged() +{ + DeviceIDMetaData meta; + auto localUUID = DmAdapter::GetInstance().GetLocalDevice().uuid; + if (!MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true)) { + meta.currentUUID = localUUID; + MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); + } else { + std::string currentUUID = localUUID; + if (!currentUUID.empty() && meta.currentUUID != currentUUID) { + meta.oldUUID = meta.currentUUID; + oldUUID_ = meta.currentUUID; + meta.currentUUID = currentUUID; + MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); + ZLOGI("meta changed! curruuid:%{public}s, olduuid:%{public}s, cache:%{public}s", + meta.currentUUID.c_str(), meta.oldUUID.c_str(), oldUUID_.c_str()); + return true; + } + } + return false; +} + +void KvStoreMetaManager::UpdateLocalMetaDeviceId() +{ + std::vector localStoreMetas; + auto currentUuid = DmAdapter::GetInstance().GetLocalDevice().uuid; + MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({}), localStoreMetas, true); + for (auto &localStoreMeta : localStoreMetas) { + StoreMetaData oldMeta = localStoreMeta; + localStoreMeta.deviceId = currentUuid; + localStoreMeta.isNeedUpdateDeviceId = true; + MetaDataManager::GetInstance().SaveMeta(localStoreMeta.GetKey(), localStoreMeta, true); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey(), true); + } + + std::vector localMatrixMetas; + MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({}), localMatrixMetas, true); + for (auto &localMatrixMeta : localMatrixMetas) { + if (localMatrixMeta.origin != MatrixMetaData::Origin::LOCAL) { + continue; + } + MatrixMetaData oldMeta = localMatrixMeta; + localMatrixMeta.deviceId = currentUuid; + MetaDataManager::GetInstance().SaveMeta(localMatrixMeta.GetKey(), localMatrixMeta, true); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey(), true); + } + + std::vector localSwitchesMetaDatas; + MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({}), localSwitchesMetaDatas, true); + for (auto &localSwitchesMetaData : localSwitchesMetaDatas) { + if (localSwitchesMetaData.deviceId != oldUUID_) { + continue; + } + SwitchesMetaData oldMeta = localSwitchesMetaData; + localSwitchesMetaData.deviceId = currentUuid; + MetaDataManager::GetInstance().SaveMeta(localSwitchesMetaData.GetKey(), localSwitchesMetaData, true); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey(), true); + } + + std::string prefix = "AutoLaunchMetaData"; + std::vector localAutoLaunchMetaDatas; + MetaDataManager::GetInstance().GetEntries(prefix, localAutoLaunchMetaDatas, true); + for (const auto &localautoLaunchMetaData : localAutoLaunchMetaDatas) { + std::string metaKey(localautoLaunchMetaData.key.begin(), localautoLaunchMetaData.key.end()); + std::string value(localautoLaunchMetaData.value.begin(), localautoLaunchMetaData.value.end()); + auto tokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); + if (tokens.size() > 1) { + tokens[1] = currentUuid; + } + auto newKey = vectorToString(tokens); + MetaDataManager::GetInstance().SaveMeta(newKey, value, true); + MetaDataManager::GetInstance().DelMeta(metaKey, true); + } + + prefix = "KvStoreMetaDataLocal"; + std::vector kvStoreMetaDataLocals; + MetaDataManager::GetInstance().GetEntries(prefix, kvStoreMetaDataLocals, true); + for (const auto &kvStoreMetaDataLocal : kvStoreMetaDataLocals) { + std::string metaKey(kvStoreMetaDataLocal.key.begin(), kvStoreMetaDataLocal.key.end()); + std::string value(kvStoreMetaDataLocal.value.begin(), kvStoreMetaDataLocal.value.end()); + auto tokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); + if (tokens.size() > 1) { + tokens[1] = currentUuid; + } + auto newKey = vectorToString(tokens); + MetaDataManager::GetInstance().SaveMeta(newKey, value, true); + MetaDataManager::GetInstance().DelMeta(metaKey, true); + } +} + +void KvStoreMetaManager::UpdateSyncMetaDeviceId() +{ + std::vector syncStoreMetas; + auto currentUuid = DmAdapter::GetInstance().GetLocalDevice().uuid; + MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({}), syncStoreMetas); + for (auto &syncStoreMeta : syncStoreMetas) { + if (syncStoreMeta.deviceId != oldUUID_) { + continue; + } + StoreMetaData oldMeta = syncStoreMeta; + syncStoreMeta.deviceId = currentUuid; + MetaDataManager::GetInstance().SaveMeta(syncStoreMeta.GetKey(), syncStoreMeta); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); + } + + std::string prefix = "CapabilityMeta"; + std::vector syncCapabilityMetas; + MetaDataManager::GetInstance().GetEntries(prefix, syncCapabilityMetas); + for (const auto &syncCapabilityMeta : syncCapabilityMetas) { + std::string metaKey(syncCapabilityMeta.key.begin(), syncCapabilityMeta.key.end()); + std::string value(syncCapabilityMeta.value.begin(), syncCapabilityMeta.value.end()); + auto tokens = Constant::Split(metaKey, Constant::KEY_SEPARATOR); + if (tokens.size() <= 1 || tokens[1] != oldUUID_) { + continue; + } + tokens[1] = currentUuid; + auto newKey = vectorToString(tokens); + MetaDataManager::GetInstance().SaveMeta(newKey, value); + MetaDataManager::GetInstance().DelMeta(metaKey); + } + + std::vector syncMatrixMetas; + MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({}), syncMatrixMetas); + for (auto &syncMatrixMeta : syncMatrixMetas) { + if (syncMatrixMeta.deviceId != oldUUID_) { + continue; + } + MatrixMetaData oldMeta = syncMatrixMeta; + syncMatrixMeta.deviceId = currentUuid; + MetaDataManager::GetInstance().SaveMeta(syncMatrixMeta.GetKey(), syncMatrixMeta); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); + } + + prefix = "StrategyMetaData"; + std::vector synctrategyMetas; + MetaDataManager::GetInstance().GetEntries(prefix, synctrategyMetas); + for (const auto &synctrategyMeta : synctrategyMetas) { + std::string metaKey(synctrategyMeta.key.begin(), synctrategyMeta.key.end()); + std::string value(synctrategyMeta.value.begin(), synctrategyMeta.value.end()); + auto tokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); + if (tokens.size() <= 1 || tokens[1] != oldUUID_) { + continue; + } + tokens[1] = currentUuid; + auto newKey = vectorToString(tokens); + MetaDataManager::GetInstance().SaveMeta(newKey, value); + MetaDataManager::GetInstance().DelMeta(metaKey); + } + + std::vector syncUserMetas; + MetaDataManager::GetInstance().LoadMeta(UserMetaRow::GetKeyFor(""), syncUserMetas); + for (auto &syncUserMeta : syncUserMetas) { + if (syncUserMeta.deviceId != oldUUID_) { + continue; + } + syncUserMeta.deviceId = currentUuid; + MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor(currentUuid), syncUserMeta); + MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor(oldUUID_)); + } +} } // namespace DistributedKv } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index 87bcc7162..e0377ed4f 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -96,6 +96,14 @@ private: DistributedDB::KvStoreNbDelegate::Option InitDBOption(); + std::string vectorToString(const std::vector &vec, const std::string separator = "###"); + + void UpdateSyncMetaDeviceId(); + + void UpdateLocalMetaDeviceId(); + + bool IsMetaDeviceIdChanged(); + static ExecutorPool::Task GetBackupTask( TaskQueue queue, std::shared_ptr executors, const NbDelegate store); @@ -133,6 +141,7 @@ private: TaskId delaySyncTaskId_ = ExecutorPool::INVALID_TASK_ID; static constexpr int32_t META_VERSION = 4; static constexpr int32_t MAX_TASK_COUNT = 1; + std::string oldUUID_; }; } // namespace DistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index f85d7b550..c528785aa 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -89,6 +89,7 @@ ohos_shared_library("distributeddatasvcfwk") { "metadata/capability_range.cpp", "metadata/corrupted_meta_data.cpp", "metadata/matrix_meta_data.cpp", + "metadata/deviceid_pair_meta_data.cpp", "metadata/meta_data.cpp", "metadata/meta_data_manager.cpp", "metadata/secret_key_meta_data.cpp", diff --git a/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h b/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h new file mode 100644 index 000000000..3f7a3f71c --- /dev/null +++ b/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.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_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_PAIR_META_DATA_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_PAIR_META_DATA_H +#include + +#include "serializable/serializable.h" +namespace OHOS::DistributedData { +class API_EXPORT DeviceIDMetaData final : public Serializable { +public: + std::string currentUUID = ""; + std::string oldUUID = ""; + + API_EXPORT DeviceIDMetaData(); + API_EXPORT ~DeviceIDMetaData(); + API_EXPORT bool Marshal(json &node) const override; + API_EXPORT bool Unmarshal(const json &node) override; + API_EXPORT std::string GetKey() const; + +private: + static constexpr const char *KEY_PREFIX = "DeviceIDKey"; +}; +} // namespace OHOS::DistributedData +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_APPID_META_DATA_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h index 08a2465c4..c33939d3c 100644 --- a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h +++ b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h @@ -51,6 +51,10 @@ public: using Backup = std::function &)>; using Bytes = std::vector; using OnComplete = std::function &)>; + struct Entry { + Bytes key; + Bytes value; + }; API_EXPORT static MetaDataManager &GetInstance(); API_EXPORT void Initialize(std::shared_ptr metaStore, const Backup &backup, const std::string &storeId); API_EXPORT void SetSyncer(const Syncer &syncer); @@ -79,7 +83,9 @@ public: API_EXPORT bool Subscribe(std::string prefix, Observer observer, bool isLocal = false); API_EXPORT bool Unsubscribe(std::string filter); API_EXPORT bool Sync(const std::vector &devices, OnComplete complete, bool wait = false); - + API_EXPORT bool GetEntries(const std::string &prefix, std::vector &entries, + bool isLocal = false); + API_EXPORT bool SaveMeta(const std::string &key, const std::string &value, bool isLocal = false); private: MetaDataManager(); ~MetaDataManager(); diff --git a/services/distributeddataservice/framework/include/metadata/store_meta_data.h b/services/distributeddataservice/framework/include/metadata/store_meta_data.h index e0a614e2d..2d1776341 100644 --- a/services/distributeddataservice/framework/include/metadata/store_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/store_meta_data.h @@ -60,6 +60,7 @@ struct API_EXPORT StoreMetaData final : public Serializable { std::string account = ""; int32_t authType = 0; bool asyncDownloadAsset = false; + bool isNeedUpdateDeviceId = false; enum StoreType { STORE_KV_BEGIN = 0, diff --git a/services/distributeddataservice/framework/include/store/general_store.h b/services/distributeddataservice/framework/include/store/general_store.h index 3789ae685..47cb37975 100644 --- a/services/distributeddataservice/framework/include/store/general_store.h +++ b/services/distributeddataservice/framework/include/store/general_store.h @@ -197,6 +197,11 @@ public: virtual std::pair LockCloudDB() = 0; virtual int32_t UnLockCloudDB() = 0; + + virtual int32_t OperateDataStatus() + { + return 0; + } }; } // namespace OHOS::DistributedData #endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_STORE_GENERAL_STORE_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/utils/constant.h b/services/distributeddataservice/framework/include/utils/constant.h index bfeaee6b3..b2c319b53 100644 --- a/services/distributeddataservice/framework/include/utils/constant.h +++ b/services/distributeddataservice/framework/include/utils/constant.h @@ -44,6 +44,7 @@ public: API_EXPORT static std::vector Split(const std::string &str, const std::string &delim); + API_EXPORT static std::vector SplitKeepSpace(const std::string &str, const std::string &delim); template inline static constexpr bool is_pod = (std::is_standard_layout_v && std::is_trivial_v); diff --git a/services/distributeddataservice/framework/metadata/deviceid_pair_meta_data.cpp b/services/distributeddataservice/framework/metadata/deviceid_pair_meta_data.cpp new file mode 100644 index 000000000..7c1d323e3 --- /dev/null +++ b/services/distributeddataservice/framework/metadata/deviceid_pair_meta_data.cpp @@ -0,0 +1,46 @@ +/* ++ * 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 "metadata/deviceid_pair_meta_data.h" + +namespace OHOS { +namespace DistributedData { +bool DeviceIDMetaData::Marshal(json &node) const +{ + SetValue(node[GET_NAME(currentUUID)], currentUUID); + SetValue(node[GET_NAME(oldUUID)], oldUUID); + return true; +} + +bool DeviceIDMetaData::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(currentUUID), currentUUID); + GetValue(node, GET_NAME(oldUUID), oldUUID); + return true; +} + +DeviceIDMetaData::DeviceIDMetaData() +{ +} + +DeviceIDMetaData::~DeviceIDMetaData() +{ +} + +std::string DeviceIDMetaData::GetKey() const +{ + return KEY_PREFIX; +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/framework/metadata/meta_data_manager.cpp b/services/distributeddataservice/framework/metadata/meta_data_manager.cpp index e7ade4b82..2594cbd62 100644 --- a/services/distributeddataservice/framework/metadata/meta_data_manager.cpp +++ b/services/distributeddataservice/framework/metadata/meta_data_manager.cpp @@ -353,4 +353,59 @@ void MetaDataManager::StopSA() ZLOGE("stop distributeddata failed, errCode: %{public}d", err); } } + +bool MetaDataManager::GetEntries(const std::string &prefix, std::vector &entries, bool isLocal) +{ + std::vector dbEntries; + auto status = isLocal ? metaStore_->GetLocalEntries({ prefix.begin(), prefix.end() }, dbEntries) + : metaStore_->GetEntries({ prefix.begin(), prefix.end() }, dbEntries); + if (status == DistributedDB::DBStatus::INVALID_PASSWD_OR_CORRUPTED_DB) { + ZLOGE("db corrupted! status:%{public}d isLocal:%{public}d", status, isLocal); + CorruptReporter::CreateCorruptedFlag(DirectoryManager::GetInstance().GetMetaStorePath(), storeId_); + StopSA(); + return false; + } + if (status != DistributedDB::DBStatus::OK && status != DistributedDB::DBStatus::NOT_FOUND) { + ZLOGE("failed! prefix:%{public}s status:%{public}d isLocal:%{public}d", Anonymous::Change(prefix).c_str(), + status, isLocal); + return false; + } + entries.resize(dbEntries.size()); + auto it = entries.begin(); + for (auto &dbEntry : dbEntries) { + auto &entry = *it; + entry.key = std::move(dbEntry.key); + entry.value = std::move(dbEntry.value); + ++it; + } + return true; +} + +bool MetaDataManager::SaveMeta(const std::string &key, const std::string &value, bool isLocal) +{ + if (!inited_) { + return false; + } + + auto status = isLocal ? metaStore_->PutLocal({ key.begin(), key.end() }, { value.begin(), value.end() }) + : metaStore_->Put({ key.begin(), key.end() }, { value.begin(), value.end() }); + if (status == DistributedDB::DBStatus::INVALID_PASSWD_OR_CORRUPTED_DB) { + ZLOGE("db corrupted! status:%{public}d isLocal:%{public}d, key:%{public}s", + status, isLocal, Anonymous::Change(key).c_str()); + CorruptReporter::CreateCorruptedFlag(DirectoryManager::GetInstance().GetMetaStorePath(), storeId_); + StopSA(); + return false; + } + if (status == DistributedDB::DBStatus::OK && backup_) { + backup_(metaStore_); + } + if (!isLocal && cloudSyncer_) { + cloudSyncer_(); + } + if (status != DistributedDB::DBStatus::OK) { + ZLOGE("failed! status:%{public}d isLocal:%{public}d, key:%{public}s", status, isLocal, + Anonymous::Change(key).c_str()); + } + return status == DistributedDB::DBStatus::OK; +} } // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/framework/metadata/store_meta_data.cpp b/services/distributeddataservice/framework/metadata/store_meta_data.cpp index f3d163326..61d678580 100644 --- a/services/distributeddataservice/framework/metadata/store_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/store_meta_data.cpp @@ -57,6 +57,7 @@ bool StoreMetaData::Marshal(json &node) const SetValue(node[GET_NAME(enableCloud)], enableCloud); SetValue(node[GET_NAME(cloudAutoSync)], cloudAutoSync); SetValue(node[GET_NAME(asyncDownloadAsset)], asyncDownloadAsset); + SetValue(node[GET_NAME(isNeedUpdateDeviceId)], isNeedUpdateDeviceId); // compatible with the versions which lower than VERSION_TAG_0000 SetValue(node[GET_NAME(kvStoreType)], storeType); SetValue(node[GET_NAME(deviceAccountID)], user); @@ -98,6 +99,7 @@ bool StoreMetaData::Unmarshal(const json &node) GetValue(node, GET_NAME(enableCloud), enableCloud); GetValue(node, GET_NAME(cloudAutoSync), cloudAutoSync); GetValue(node, GET_NAME(asyncDownloadAsset), asyncDownloadAsset); + GetValue(node, GET_NAME(isNeedUpdateDeviceId), isNeedUpdateDeviceId); // compatible with the older versions if (version < FIELD_CHANGED_TAG) { GetValue(node, GET_NAME(kvStoreType), storeType); @@ -138,7 +140,8 @@ bool StoreMetaData::operator==(const StoreMetaData &metaData) const Constant::NotEqual(isNeedCompress, metaData.isNeedCompress) || Constant::NotEqual(enableCloud, metaData.enableCloud) || Constant::NotEqual(cloudAutoSync, metaData.cloudAutoSync) || - Constant::NotEqual(isManualClean, metaData.isManualClean)) { + Constant::NotEqual(isManualClean, metaData.isManualClean) || + Constant::NotEqual(isNeedUpdateDeviceId, metaData.isNeedUpdateDeviceId)) { return false; } return (version == metaData.version && storeType == metaData.storeType && dataType == metaData.dataType && diff --git a/services/distributeddataservice/framework/utils/constant.cpp b/services/distributeddataservice/framework/utils/constant.cpp index 6fedf3f61..084545743 100644 --- a/services/distributeddataservice/framework/utils/constant.cpp +++ b/services/distributeddataservice/framework/utils/constant.cpp @@ -70,6 +70,25 @@ std::vector Constant::Split(const std::string &str, const std::stri return res; } +std::vector Constant::SplitKeepSpace(const std::string &str, const std::string &delim) +{ + if (str.empty()) { + return { str }; + } + std::vector res; + size_t pos = 0; + while (pos <= str.size()) { + size_t found = str.find(delim, pos); + if (found == std::string::npos) { + res.push_back(str.substr(pos)); + break; + } + res.push_back(str.substr(pos, found - pos)); + pos = found + delim.size(); + } + return res; +} + bool Constant::Equal(bool first, bool second) { return (first && second) || (!first && !second); diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index f04980ccc..878c46597 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -620,6 +620,13 @@ Status KVDBServiceImpl::GetBackupPassword(const AppId &appId, const StoreId &sto return res ? SUCCESS : ERROR; } if (passwordType == KVDBService::PasswordType::SECRET_KEY) { + StoreMetaData meta; + MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), meta, true); + if (meta.isNeedUpdateDeviceId) { + ZLOGW("device already update uuid, appId:%{public}s, storeId:%{public}s", + appId.appId.c_str(), Anonymous::Change(storeId.storeId).c_str()); + return ERROR; + } passwords.reserve(SECRET_KEY_COUNT); SecretKeyMetaData secretKey; std::vector password; @@ -733,6 +740,7 @@ Status KVDBServiceImpl::AfterCreate( auto isCreated = MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), oldMeta, true); Status status = SUCCESS; if (isCreated && oldMeta != metaData) { + Upgrade::GetInstance().UpdateDeviceId(oldMeta, metaData, password); auto dbStatus = Upgrade::GetInstance().UpdateStore(oldMeta, metaData, password); ZLOGI("update status:%{public}d appId:%{public}s storeId:%{public}s inst:%{public}d " "type:%{public}d->%{public}d dir:%{public}s dataType:%{public}d->%{public}d", diff --git a/services/distributeddataservice/service/kvdb/upgrade.cpp b/services/distributeddataservice/service/kvdb/upgrade.cpp index c9888a622..bad12350d 100644 --- a/services/distributeddataservice/service/kvdb/upgrade.cpp +++ b/services/distributeddataservice/service/kvdb/upgrade.cpp @@ -69,6 +69,29 @@ Upgrade::DBStatus Upgrade::UpdateStore(const StoreMeta &old, const StoreMeta &me return DBStatus::OK; } +void Upgrade::UpdateDeviceId(const StoreMeta &oldMeta, const StoreMeta &meta, const std::vector &pwd) +{ + if (oldMeta.storeType < StoreMetaData::StoreType::STORE_KV_BEGIN || + oldMeta.storeType > StoreMetaData::StoreType::STORE_KV_END) { + return; + } + + if (oldMeta.isNeedUpdateDeviceId && !oldMeta.isEncrypt) { + auto store = GetDBStore(meta, pwd); + if (store == nullptr) { + ZLOGI("store is null appId:%{public}s storeId:%{public}s", oldMeta.appId.c_str(), + Anonymous::Change(oldMeta.storeId).c_str()); + return; + } + store->OperateDataStatus(static_cast(DistributedDB::DataOperator::UPDATE_TIME) | + static_cast(DistributedDB::DataOperator::RESET_UPLOAD_CLOUD )); + } + + if (oldMeta.isNeedUpdateDeviceId && oldMeta.storeType == DEVICE_COLLABORATION && !oldMeta.isEncrypt) { + Upgrade::GetInstance().UpdateUuid(oldMeta, meta, pwd); + } +} + Upgrade::DBStatus Upgrade::ExportStore(const StoreMeta &old, const StoreMeta &meta) { if (old.dataDir == meta.dataDir) { diff --git a/services/distributeddataservice/service/kvdb/upgrade.h b/services/distributeddataservice/service/kvdb/upgrade.h index 62458e235..d42788a7f 100644 --- a/services/distributeddataservice/service/kvdb/upgrade.h +++ b/services/distributeddataservice/service/kvdb/upgrade.h @@ -42,6 +42,7 @@ public: DBStatus UpdateStore(const StoreMeta &old, const StoreMeta &meta, const std::vector &pwd); DBStatus ExportStore(const StoreMeta &old, const StoreMeta &meta); DBStatus UpdateUuid(const StoreMeta &old, const StoreMeta &meta, const std::vector &pwd); + void UpdateDeviceId(const StoreMeta &old, const StoreMeta &meta, const std::vector &pwd); API_EXPORT std::string GetEncryptedUuidByMeta(const StoreMeta &meta); private: diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.cpp b/services/distributeddataservice/service/rdb/rdb_general_store.cpp index 754f258fb..556de1dda 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.cpp +++ b/services/distributeddataservice/service/rdb/rdb_general_store.cpp @@ -1338,4 +1338,9 @@ RdbGeneralStore::DBProcessCB RdbGeneralStore::GetCB(SyncId syncId) return; }; } + +int32_t RdbGeneralStore::OperateDataStatus() +{ + return delegate_->OperateDataStatus(static_cast(DataOperator::UPDATE_TIME)); +} } // namespace OHOS::DistributedRdb \ No newline at end of file diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.h b/services/distributeddataservice/service/rdb/rdb_general_store.h index d51e14ad3..a81279179 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.h +++ b/services/distributeddataservice/service/rdb/rdb_general_store.h @@ -88,6 +88,7 @@ public: int32_t CleanTrackerData(const std::string &tableName, int64_t cursor) override; std::pair LockCloudDB() override; int32_t UnLockCloudDB() override; + int32_t RdbGeneralStore::OperateDataStatus(); private: RdbGeneralStore(const RdbGeneralStore& rdbGeneralStore); diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 4f9cbd8eb..e7396e8c6 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -828,6 +828,7 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) ZLOGI("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " "area:%{public}d->%{public}d", meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), old.storeType, meta.storeType, old.isEncrypt, meta.isEncrypt, old.area, meta.area); + TryUpdateDeviceId(param, old, meta); MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); AutoLaunchMetaData launchData; if (!MetaDataManager::GetInstance().LoadMeta(meta.GetAutoLaunchKey(), launchData, true)) { @@ -1649,4 +1650,27 @@ std::string RdbServiceImpl::GetSubUser(const int32_t subUser) } return userId; } + +int32_t RdbServiceImpl::TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, StoreMetaData &meta) +{ + StoreMetaData syncMeta; + if (oldMeta.isNeedUpdateDeviceId && oldMeta.storeType >= StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN && + oldMeta.storeType <= StoreMetaData::StoreType::STORE_RELATIONAL_END && + MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), syncMeta)) { + auto store = GetStore(param); + if (store == nullptr) { + ZLOGE("store is null, bundleName:%{public}s storeName:%{public}s", param.bundleName_.c_str(), + Anonymous::Change(param.storeName_).c_str()); + return RDB_ERROR; + } + auto errCode = store->OperateDataStatus(); + if (errCode == RDB_OK) { + meta.isNeedUpdateDeviceId = false; + } else { + meta.isNeedUpdateDeviceId = true; + ZLOGE("OperateDataStatus failed errCode %{public}d", errCode); + } + } + return RDB_OK; +} } // namespace OHOS::DistributedRdb \ No newline at end of file diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.h b/services/distributeddataservice/service/rdb/rdb_service_impl.h index a387261f3..96b11236e 100755 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -241,6 +241,8 @@ private: bool UpgradeCloneSecretKey(const StoreMetaData &meta); + int32_t TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, StoreMetaData &meta); + static Factory factory_; ConcurrentMap syncAgents_; std::shared_ptr executors_; -- Gitee From f2af30f19ffbc9d068dbe53c4af227b1308bec84 Mon Sep 17 00:00:00 2001 From: zph Date: Sat, 15 Mar 2025 20:13:05 +0800 Subject: [PATCH 017/225] update Signed-off-by: zph --- .../service/udmf/preprocess/data_handler.cpp | 18 +++++++++++ .../udmf/preprocess/preprocess_utils.cpp | 10 +++--- .../service/udmf/store/runtime_store.cpp | 32 ++++++++++++++----- .../service/udmf/store/runtime_store.h | 2 +- .../service/udmf/store/store.h | 1 - .../service/udmf/udmf_service_impl.cpp | 26 --------------- 6 files changed, 49 insertions(+), 40 deletions(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp index 94d6ad7f1..3910d467d 100644 --- a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp @@ -21,6 +21,7 @@ namespace OHOS::UDMF { constexpr const char *UD_KEY_SEPARATOR = "/"; constexpr const char *UD_KEY_ENTRY_SEPARATOR = "#"; +constexpr const char *VERSION_SUFIX = "/version"; Status DataHandler::MarshalToEntries(const UnifiedData &unifiedData, std::vector &entries) { @@ -34,6 +35,14 @@ Status DataHandler::MarshalToEntries(const UnifiedData &unifiedData, std::vector std::vector udKeyBytes = { unifiedKey.begin(), unifiedKey.end() }; Entry entry = { udKeyBytes, runtimeBytes }; entries.emplace_back(entry); + + Value VersionBytes; + if (MarshalToEntries(unifiedData.GetSdkVersion(), VersionBytes, TAG::TAG_VERSION) != E_OK) { + ZLOGE("Version marshalling failed:%{public}s", unifiedKey.c_str()); + return E_WRITE_PARCEL_ERROR; + } + auto versionKey = unifiedKey + VERSION_SUFIX; + entries.push_back({ { versionKey.begin(), versionKey.end() }, VersionBytes }); return BuildEntries(unifiedData.GetRecords(), unifiedKey, entries); } @@ -74,6 +83,15 @@ Status DataHandler::UnmarshalEntryItem(UnifiedData &unifiedData, const std::vect unifiedData.SetRuntime(runtime); continue; } + if (keyStr == key + VERSION_SUFIX) { + std::string version; + if (UnmarshalEntries(entry.value, version, TAG::TAG_VERSION) != E_OK) { + ZLOGE("Unmarshall version failed."); + return E_READ_PARCEL_ERROR; + } + unifiedData.SetSdkVersion(version); + continue; + } auto isStartWithKey = keyStr.find(key) == 0; if (!isStartWithKey) { continue; diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index 75eef0ff4..4afac4750 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -422,9 +422,11 @@ bool PreProcessUtils::GetDetailsFromUData(const UnifiedData &data, UDDetails &de { auto records = data.GetRecords(); if (records.size() != TEMP_UDATA_RECORD_SIZE) { + ZLOGE("Data has multiple records.size:%{public}d", records.size()); return false; } if (records[0] == nullptr || records[0]->GetType() != UDType::FILE) { + ZLOGE("Record is not file."); return false; } auto obj = std::get>(records[0]->GetOriginValue()); @@ -434,10 +436,10 @@ bool PreProcessUtils::GetDetailsFromUData(const UnifiedData &data, UDDetails &de } std::shared_ptr detailObj; obj->GetValue(DETAILS, detailObj); - if (detailObj == nullptr) { - ZLOGE("Not contain details for object!"); - return false; - } + if (detailObj == nullptr) { + ZLOGE("Not contain details for object!"); + return false; + } auto result = ObjectUtils::ConvertToUDDetails(detailObj); if (result.find(TEMP_UNIFIED_DATA_FLAG) == result.end()) { return false; diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index 1f76169e6..cf24b28d9 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -28,6 +28,7 @@ #include "bootstrap.h" #include "directory/directory_manager.h" #include "utils/anonymous.h" +#include "preprocess_utils.h" namespace OHOS { namespace UDMF { @@ -101,6 +102,7 @@ Status RuntimeStore::Put(const UnifiedData &unifiedData) if (status != E_OK) { return status; } + PutSummary(unifiedData, entries); return PutEntries(entries); } @@ -119,9 +121,17 @@ Status RuntimeStore::Get(const std::string &key, UnifiedData &unifiedData) return DataHandler::UnmarshalEntries(key, entries, unifiedData); } -Status RuntimeStore::PutSummary(const std::string &key, const Summary &summary) +Status RuntimeStore::PutSummary(const UnifiedData &data, std::vector &entries) { UpdateTime(); + UDDetails details {}; + Summary summary; + if (PreProcessUtils::GetDetailsFromUData(data, details)) { + return PreProcessUtils::GetSummaryFromDetails(details, summary); + } + UnifiedDataHelper::GetSummary(data, summary); + + auto key = data.GetRuntime()->key.GetUnifiedKey(); Value value; auto status = DataHandler::MarshalToEntries(summary, value, TAG::TAG_SUMMARY); if (status != E_OK) { @@ -129,11 +139,7 @@ Status RuntimeStore::PutSummary(const std::string &key, const Summary &summary) return status; } auto summaryKey = key + SUMMARY_SUFIX; - auto res = kvStore_->Put({summaryKey.begin(), summaryKey.end()}, value); - if (res != OK) { - ZLOGE("Put failed, key:%{public}s, status:%{public}d", key.c_str(), res); - return E_DB_ERROR; - } + entries.push_back({{summaryKey.begin(), summaryKey.end()}, value}); return E_OK; } @@ -144,8 +150,18 @@ Status RuntimeStore::GetSummary(const std::string &key, Summary &summary) auto summaryKey = key + SUMMARY_SUFIX; auto res = kvStore_->Get({summaryKey.begin(), summaryKey.end()}, value); if (res != OK || value.empty()) { - ZLOGE("Get failed, key: %{public}s, status:%{public}d", key.c_str(), res); - return E_DB_ERROR; + ZLOGW("Get stored summary failed, key: %{public}s, status:%{public}d", key.c_str(), res); + UnifiedData unifiedData; + if (Get(key, unifiedData) != E_OK) { + ZLOGE("Get unified data failed, key: %{public}s", key.c_str()); + return E_DB_ERROR; + } + UDDetails details {}; + if (PreProcessUtils::GetDetailsFromUData(unifiedData, details)) { + return PreProcessUtils::GetSummaryFromDetails(details, summary); + } + UnifiedDataHelper::GetSummary(unifiedData, summary); + return E_OK; } auto status = DataHandler::UnmarshalEntries(value, summary, TAG::TAG_SUMMARY); if (status != E_OK) { diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.h b/services/distributeddataservice/service/udmf/store/runtime_store.h index ad561281c..eb1a44394 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.h +++ b/services/distributeddataservice/service/udmf/store/runtime_store.h @@ -30,7 +30,6 @@ public: ~RuntimeStore(); Status Put(const UnifiedData &unifiedData) override; Status Get(const std::string &key, UnifiedData &unifiedData) override; - Status PutSummary(const std::string &key, const Summary &summary) override; Status GetSummary(const std::string &key, Summary &summary) override; Status Update(const UnifiedData &unifiedData) override; Status Delete(const std::string &key) override; @@ -65,6 +64,7 @@ private: bool BuildMetaDataParam(DistributedData::StoreMetaData &metaData); void NotifySyncProcss(const DevSyncProcessMap &processMap, ProcessCallback callback, const DevNameMap &deviceNameMap); + Status PutSummary(const UnifiedData &data, std::vector &entries); }; } // namespace UDMF } // namespace OHOS diff --git a/services/distributeddataservice/service/udmf/store/store.h b/services/distributeddataservice/service/udmf/store/store.h index bcaa0e6fd..9d3820a86 100644 --- a/services/distributeddataservice/service/udmf/store/store.h +++ b/services/distributeddataservice/service/udmf/store/store.h @@ -26,7 +26,6 @@ public: using Time = std::chrono::steady_clock::time_point; virtual Status Put(const UnifiedData &unifiedData) = 0; virtual Status Get(const std::string &key, UnifiedData &unifiedData) = 0; - virtual Status PutSummary(const std::string &key, const Summary &summary) = 0; virtual Status GetSummary(const std::string &key, Summary &summary) = 0; virtual Status Update(const UnifiedData &unifiedData) = 0; virtual Status Delete(const std::string &key) = 0; diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index f995f67fc..ba3248966 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -133,11 +133,6 @@ int32_t UdmfServiceImpl::SaveData(CustomOption &option, UnifiedData &unifiedData unifiedData.GetRuntime()->createPackage.c_str()); return ret; } - ret = SetSummary(unifiedData); - if (ret != E_OK) { - ZLOGE("Set summary failed, key: %{public}s.", key.c_str()); - return ret; - } } PreProcessUtils::SetRecordUid(unifiedData); @@ -837,26 +832,5 @@ int32_t UdmfServiceImpl::OnUserChange(uint32_t code, const std::string &user, co return Feature::OnUserChange(code, user, account); } -int32_t UdmfServiceImpl::SetSummary(const UnifiedData &data) const -{ - UnifiedKey key = data.GetRuntime()->key; - auto store = StoreCache::GetInstance().GetStore(key.intention); - if (store == nullptr) { - ZLOGE("Get store failed, key:%{public}s", key.GetUnifiedKey().c_str()); - return E_DB_ERROR; - } - - UDDetails details {}; - Summary summary; - if (PreProcessUtils::GetDetailsFromUData(data, details)) { - return PreProcessUtils::GetSummaryFromDetails(details, summary); - } - UnifiedDataHelper::GetSummary(data, summary); - auto status = store->PutSummary(key.GetUnifiedKey(), summary); - if (status != E_OK) { - ZLOGE("Put summary failed, status:%{public}d, key:%{public}s.", status, key.GetUnifiedKey().c_str()); - } - return status; -} } // namespace UDMF } // namespace OHOS \ No newline at end of file -- Gitee From c7cde2eaf8de5ae3c1614fab35621340f9772dd8 Mon Sep 17 00:00:00 2001 From: zph Date: Sat, 15 Mar 2025 21:10:44 +0800 Subject: [PATCH 018/225] update Signed-off-by: zph --- .../service/udmf/preprocess/data_handler.cpp | 18 ------------------ .../udmf/preprocess/preprocess_utils.cpp | 1 + .../service/udmf/udmf_service_impl.cpp | 1 - 3 files changed, 1 insertion(+), 19 deletions(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp index 3910d467d..94d6ad7f1 100644 --- a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp @@ -21,7 +21,6 @@ namespace OHOS::UDMF { constexpr const char *UD_KEY_SEPARATOR = "/"; constexpr const char *UD_KEY_ENTRY_SEPARATOR = "#"; -constexpr const char *VERSION_SUFIX = "/version"; Status DataHandler::MarshalToEntries(const UnifiedData &unifiedData, std::vector &entries) { @@ -35,14 +34,6 @@ Status DataHandler::MarshalToEntries(const UnifiedData &unifiedData, std::vector std::vector udKeyBytes = { unifiedKey.begin(), unifiedKey.end() }; Entry entry = { udKeyBytes, runtimeBytes }; entries.emplace_back(entry); - - Value VersionBytes; - if (MarshalToEntries(unifiedData.GetSdkVersion(), VersionBytes, TAG::TAG_VERSION) != E_OK) { - ZLOGE("Version marshalling failed:%{public}s", unifiedKey.c_str()); - return E_WRITE_PARCEL_ERROR; - } - auto versionKey = unifiedKey + VERSION_SUFIX; - entries.push_back({ { versionKey.begin(), versionKey.end() }, VersionBytes }); return BuildEntries(unifiedData.GetRecords(), unifiedKey, entries); } @@ -83,15 +74,6 @@ Status DataHandler::UnmarshalEntryItem(UnifiedData &unifiedData, const std::vect unifiedData.SetRuntime(runtime); continue; } - if (keyStr == key + VERSION_SUFIX) { - std::string version; - if (UnmarshalEntries(entry.value, version, TAG::TAG_VERSION) != E_OK) { - ZLOGE("Unmarshall version failed."); - return E_READ_PARCEL_ERROR; - } - unifiedData.SetSdkVersion(version); - continue; - } auto isStartWithKey = keyStr.find(key) == 0; if (!isStartWithKey) { continue; diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index 4afac4750..0b9d3a967 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -70,6 +70,7 @@ int32_t PreProcessUtils::RuntimeDataImputation(UnifiedData &data, CustomOption & runtime.deviceId = GetLocalDeviceId(); runtime.recordTotalNum = static_cast(data.GetRecords().size()); runtime.tokenId = option.tokenId; + runtime.sdkVersion = data.GetSdkVersion(); data.SetRuntime(runtime); return E_OK; } diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index ba3248966..9606e1c03 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -831,6 +831,5 @@ int32_t UdmfServiceImpl::OnUserChange(uint32_t code, const std::string &user, co } return Feature::OnUserChange(code, user, account); } - } // namespace UDMF } // namespace OHOS \ No newline at end of file -- Gitee From 89e248f90b8c6811603ade7b100186e7b4080dcc Mon Sep 17 00:00:00 2001 From: zph Date: Sat, 15 Mar 2025 21:43:07 +0800 Subject: [PATCH 019/225] update Signed-off-by: zph --- .../service/udmf/preprocess/preprocess_utils.cpp | 2 +- .../distributeddataservice/service/udmf/udmf_service_impl.h | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index 0b9d3a967..11d063598 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -423,7 +423,7 @@ bool PreProcessUtils::GetDetailsFromUData(const UnifiedData &data, UDDetails &de { auto records = data.GetRecords(); if (records.size() != TEMP_UDATA_RECORD_SIZE) { - ZLOGE("Data has multiple records.size:%{public}d", records.size()); + ZLOGE("Data has multiple records.size:%{public}zu", records.size()); return false; } if (records[0] == nullptr || records[0]->GetType() != UDType::FILE) { diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.h b/services/distributeddataservice/service/udmf/udmf_service_impl.h index 0f8d79b7b..93082d45a 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.h +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.h @@ -58,7 +58,6 @@ private: bool VerifyPermission(const std::string &permission, uint32_t callerTokenId); bool HasDatahubPriviledge(const std::string &bundleName); void RegisterAsyncProcessInfo(const std::string &businessUdKey); - int32_t SetSummary(const UnifiedData &data) const; class Factory { public: -- Gitee From 314cb062c3ee44cb6b7057e7859b808a2736cf04 Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 16 Mar 2025 16:18:38 +0800 Subject: [PATCH 020/225] update Signed-off-by: yangliu --- .../app/src/kvstore_meta_manager.cpp | 44 +++++++------ .../app/src/kvstore_meta_manager.h | 2 + .../metadata/deviceid_pair_meta_data.h | 28 ++++---- .../include/metadata/meta_data_manager.h | 2 +- .../metadata/deviceid_pair_meta_data.cpp | 26 ++++---- .../framework/metadata/meta_data_manager.cpp | 2 +- .../framework/test/meta_data_test.cpp | 64 +++++++++++++++++++ .../service/kvdb/upgrade.cpp | 5 +- .../service/rdb/rdb_service_impl.cpp | 3 +- 9 files changed, 125 insertions(+), 51 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index cd33b5ff5..310ff4888 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -61,7 +61,8 @@ using namespace std::chrono; using namespace OHOS::DistributedData; using namespace DistributedDB; using namespace OHOS::AppDistributedKv; - +constexpr const int UUID_LOC = 1; +constexpr const int MIN_SIZE = 1; KvStoreMetaManager::MetaDeviceChangeListenerImpl KvStoreMetaManager::listener_; KvStoreMetaManager::DBInfoDeviceChangeListenerImpl KvStoreMetaManager::dbInfoListener_; @@ -140,11 +141,8 @@ void KvStoreMetaManager::InitMetaData() ZLOGI("get meta failed."); return; } - if (IsMetaDeviceIdChanged()) { - UpdateLocalMetaDeviceId(); - UpdateSyncMetaDeviceId(); - } + CheckDeviceIDChanged(); auto uid = getuid(); auto tokenId = IPCSkeleton::GetCallingTokenID(); const std::string accountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); @@ -187,6 +185,14 @@ void KvStoreMetaManager::InitMetaData() ZLOGI("end."); } +void KvStoreMetaManager::CheckDeviceIDChanged() +{ + if (IsMetaDeviceIdChanged()) { + UpdateLocalMetaDeviceId(); + UpdateSyncMetaDeviceId(); + } +} + void KvStoreMetaManager::UpdateMetaData() { VersionMetaData versionMeta; @@ -580,7 +586,7 @@ bool KvStoreMetaManager::IsMetaDeviceIdChanged() oldUUID_ = meta.currentUUID; meta.currentUUID = currentUUID; MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); - ZLOGI("meta changed! curruuid:%{public}s, olduuid:%{public}s, cache:%{public}s", + ZLOGI("uuid changed! curruuid:%{public}s, olduuid:%{public}s, cache:%{public}s", meta.currentUUID.c_str(), meta.oldUUID.c_str(), oldUUID_.c_str()); return true; } @@ -604,7 +610,7 @@ void KvStoreMetaManager::UpdateLocalMetaDeviceId() std::vector localMatrixMetas; MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({}), localMatrixMetas, true); for (auto &localMatrixMeta : localMatrixMetas) { - if (localMatrixMeta.origin != MatrixMetaData::Origin::LOCAL) { + if (localMatrixMeta.deviceId != oldUUID_) { continue; } MatrixMetaData oldMeta = localMatrixMeta; @@ -627,13 +633,13 @@ void KvStoreMetaManager::UpdateLocalMetaDeviceId() std::string prefix = "AutoLaunchMetaData"; std::vector localAutoLaunchMetaDatas; - MetaDataManager::GetInstance().GetEntries(prefix, localAutoLaunchMetaDatas, true); + MetaDataManager::GetInstance().LoadMetaPair(prefix, localAutoLaunchMetaDatas, true); for (const auto &localautoLaunchMetaData : localAutoLaunchMetaDatas) { std::string metaKey(localautoLaunchMetaData.key.begin(), localautoLaunchMetaData.key.end()); std::string value(localautoLaunchMetaData.value.begin(), localautoLaunchMetaData.value.end()); auto tokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); - if (tokens.size() > 1) { - tokens[1] = currentUuid; + if (tokens.size() > MIN_SIZE) { + tokens[UUID_LOC] = currentUuid; } auto newKey = vectorToString(tokens); MetaDataManager::GetInstance().SaveMeta(newKey, value, true); @@ -642,13 +648,13 @@ void KvStoreMetaManager::UpdateLocalMetaDeviceId() prefix = "KvStoreMetaDataLocal"; std::vector kvStoreMetaDataLocals; - MetaDataManager::GetInstance().GetEntries(prefix, kvStoreMetaDataLocals, true); + MetaDataManager::GetInstance().LoadMetaPair(prefix, kvStoreMetaDataLocals, true); for (const auto &kvStoreMetaDataLocal : kvStoreMetaDataLocals) { std::string metaKey(kvStoreMetaDataLocal.key.begin(), kvStoreMetaDataLocal.key.end()); std::string value(kvStoreMetaDataLocal.value.begin(), kvStoreMetaDataLocal.value.end()); auto tokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); - if (tokens.size() > 1) { - tokens[1] = currentUuid; + if (tokens.size() > MIN_SIZE) { + tokens[UUID_LOC] = currentUuid; } auto newKey = vectorToString(tokens); MetaDataManager::GetInstance().SaveMeta(newKey, value, true); @@ -673,15 +679,15 @@ void KvStoreMetaManager::UpdateSyncMetaDeviceId() std::string prefix = "CapabilityMeta"; std::vector syncCapabilityMetas; - MetaDataManager::GetInstance().GetEntries(prefix, syncCapabilityMetas); + MetaDataManager::GetInstance().LoadMetaPair(prefix, syncCapabilityMetas); for (const auto &syncCapabilityMeta : syncCapabilityMetas) { std::string metaKey(syncCapabilityMeta.key.begin(), syncCapabilityMeta.key.end()); std::string value(syncCapabilityMeta.value.begin(), syncCapabilityMeta.value.end()); auto tokens = Constant::Split(metaKey, Constant::KEY_SEPARATOR); - if (tokens.size() <= 1 || tokens[1] != oldUUID_) { + if (tokens.size() <= MIN_SIZE || tokens[1] != oldUUID_) { continue; } - tokens[1] = currentUuid; + tokens[UUID_LOC] = currentUuid; auto newKey = vectorToString(tokens); MetaDataManager::GetInstance().SaveMeta(newKey, value); MetaDataManager::GetInstance().DelMeta(metaKey); @@ -701,15 +707,15 @@ void KvStoreMetaManager::UpdateSyncMetaDeviceId() prefix = "StrategyMetaData"; std::vector synctrategyMetas; - MetaDataManager::GetInstance().GetEntries(prefix, synctrategyMetas); + MetaDataManager::GetInstance().LoadMetaPair(prefix, synctrategyMetas); for (const auto &synctrategyMeta : synctrategyMetas) { std::string metaKey(synctrategyMeta.key.begin(), synctrategyMeta.key.end()); std::string value(synctrategyMeta.value.begin(), synctrategyMeta.value.end()); auto tokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); - if (tokens.size() <= 1 || tokens[1] != oldUUID_) { + if (tokens.size() <= MIN_SIZE || tokens[UUID_LOC] != oldUUID_) { continue; } - tokens[1] = currentUuid; + tokens[UUID_LOC] = currentUuid; auto newKey = vectorToString(tokens); MetaDataManager::GetInstance().SaveMeta(newKey, value); MetaDataManager::GetInstance().DelMeta(metaKey); diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index e0377ed4f..4b0e3d360 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -103,6 +103,8 @@ private: void UpdateLocalMetaDeviceId(); bool IsMetaDeviceIdChanged(); + + void CheckDeviceIDChanged(); static ExecutorPool::Task GetBackupTask( TaskQueue queue, std::shared_ptr executors, const NbDelegate store); diff --git a/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h b/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h index 3f7a3f71c..32a4e873a 100644 --- a/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h @@ -1,17 +1,17 @@ -+/* -+ * 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. -+ */ +/* + * 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_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_PAIR_META_DATA_H #define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_PAIR_META_DATA_H diff --git a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h index c33939d3c..7f631fff4 100644 --- a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h +++ b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h @@ -83,7 +83,7 @@ public: API_EXPORT bool Subscribe(std::string prefix, Observer observer, bool isLocal = false); API_EXPORT bool Unsubscribe(std::string filter); API_EXPORT bool Sync(const std::vector &devices, OnComplete complete, bool wait = false); - API_EXPORT bool GetEntries(const std::string &prefix, std::vector &entries, + API_EXPORT bool LoadMetaPair(const std::string &prefix, std::vector &entries, bool isLocal = false); API_EXPORT bool SaveMeta(const std::string &key, const std::string &value, bool isLocal = false); private: diff --git a/services/distributeddataservice/framework/metadata/deviceid_pair_meta_data.cpp b/services/distributeddataservice/framework/metadata/deviceid_pair_meta_data.cpp index 7c1d323e3..c8483699d 100644 --- a/services/distributeddataservice/framework/metadata/deviceid_pair_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/deviceid_pair_meta_data.cpp @@ -1,17 +1,17 @@ /* -+ * 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. -+ */ + * 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 "metadata/deviceid_pair_meta_data.h" namespace OHOS { diff --git a/services/distributeddataservice/framework/metadata/meta_data_manager.cpp b/services/distributeddataservice/framework/metadata/meta_data_manager.cpp index 2594cbd62..b67b96f65 100644 --- a/services/distributeddataservice/framework/metadata/meta_data_manager.cpp +++ b/services/distributeddataservice/framework/metadata/meta_data_manager.cpp @@ -354,7 +354,7 @@ void MetaDataManager::StopSA() } } -bool MetaDataManager::GetEntries(const std::string &prefix, std::vector &entries, bool isLocal) +bool MetaDataManager::LoadMetaPair(const std::string &prefix, std::vector &entries, bool isLocal) { std::vector dbEntries; auto status = isLocal ? metaStore_->GetLocalEntries({ prefix.begin(), prefix.end() }, dbEntries) diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 6bc7f9186..aae9b5aa0 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -794,4 +794,68 @@ HWTEST_F(ServiceMetaDataTest, MatrixMetaData, TestSize.Level1) std::string key = matrixMetaData3.GetConsistentKey(); EXPECT_EQ(key, "MatrixMeta###DEVICE_ID###Consistent"); } + +/** + * @tc.name: DeviceIDMetaData + * @tc.desc: test DeviceIDMetaData function + * @tc.type: FUNC + * @tc.require: + * @tc.author: yl + */ +HWTEST_F(ServiceMetaDataTest, DeviceIDMetaData, TestSize.Level1) +{ + DeviceIDMetaData metaData; + std::string expectedPrefix = "DeviceIDKey"; + std::string prefix = metaData.GetKey(); + + ASSERT_EQ(prefix, expectedPrefix); + std::string currentUUID = "newuuid"; + std::string oldUUID = "olduuid"; + metaData.currentUUID = currentUUID; + metaData.oldUUID = oldUUID; + Serializable::json node1; + metaData.Marshal(node1); + EXPECT_EQ(node1["currentUUID"], currentUUID); + EXPECT_EQ(node1["oldUUID"], oldUUID); + + DeviceIDMetaData newMetaData; + newMetaData.Unmarshal(node1); + EXPECT_EQ(newMetaData.currentUUID, currentUUID); + EXPECT_EQ(newMetaData.oldUUID, oldUUID); +} + +/** + * @tc.name: LoadMatePair + * @tc.desc: test LoadMatePair function + * @tc.type: FUNC + * @tc.require: + * @tc.author: yl + */ +HWTEST_F(ServiceMetaDataTest, LoadMatePair, TestSize.Level1) +{ + StoreMetaData storeMetaData("100", "appid", "test_store"); + storeMetaData.version = TEST_CURRENT_VERSION; + storeMetaData.instanceId = 1; + std::vector entries; + + std::string key = storeMetaData.GetKey(); + EXPECT_EQ(key, "KvStoreMetaData######100###default######test_store_001###1"); + auto result = MetaDataManager::GetInstance().SaveMeta(key, storeMetaData, true); + EXPECT_TRUE(result); + result = MetaDataManager::GetInstance().LoadMatePair(key, entries, true); + EXPECT_TRUE(result); + std::string key(entries.key.begin(), entries.key.end()); + std::string value(entries.value.begin(), entries.value.end()); + EXPECT_EQ(storeMetaData.GetKey(), key); + + auto tokens = Constant::SplitKeepSpace(key, Constant::KEY_SEPARATOR); + if (tokens.size() > 1) { + tokens[1] = "updateuuid"; + } + auto newKey = vectorToString(tokens); + result = MetaDataManager::GetInstance().SaveMeta(newKey, value, true); + EXPECT_TRUE(result); + result = MetaDataManager::GetInstance().DelMeta(key, true); + EXPECT_TRUE(result); +} } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/kvdb/upgrade.cpp b/services/distributeddataservice/service/kvdb/upgrade.cpp index bad12350d..094e34e21 100644 --- a/services/distributeddataservice/service/kvdb/upgrade.cpp +++ b/services/distributeddataservice/service/kvdb/upgrade.cpp @@ -25,6 +25,7 @@ #include "log_print.h" #include "metadata/meta_data_manager.h" #include "metadata/secret_key_meta_data.h" +#include "utils/anonymous.h" namespace OHOS::DistributedKv { using namespace OHOS::DistributedData; using system_clock = std::chrono::system_clock; @@ -80,11 +81,11 @@ void Upgrade::UpdateDeviceId(const StoreMeta &oldMeta, const StoreMeta &meta, co auto store = GetDBStore(meta, pwd); if (store == nullptr) { ZLOGI("store is null appId:%{public}s storeId:%{public}s", oldMeta.appId.c_str(), - Anonymous::Change(oldMeta.storeId).c_str()); + Anonymous::Change(oldMeta.storeId).c_str()); return; } store->OperateDataStatus(static_cast(DistributedDB::DataOperator::UPDATE_TIME) | - static_cast(DistributedDB::DataOperator::RESET_UPLOAD_CLOUD )); + static_cast(DistributedDB::DataOperator::RESET_UPLOAD_CLOUD)); } if (oldMeta.isNeedUpdateDeviceId && oldMeta.storeType == DEVICE_COLLABORATION && !oldMeta.isEncrypt) { diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index e7396e8c6..bfcd88c35 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -1651,7 +1651,8 @@ std::string RdbServiceImpl::GetSubUser(const int32_t subUser) return userId; } -int32_t RdbServiceImpl::TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, StoreMetaData &meta) +int32_t RdbServiceImpl::TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, + StoreMetaData &meta) { StoreMetaData syncMeta; if (oldMeta.isNeedUpdateDeviceId && oldMeta.storeType >= StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN && -- Gitee From f87369e208a2649079147e79ccab9da99231441c Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 16 Mar 2025 16:38:32 +0800 Subject: [PATCH 021/225] update Signed-off-by: yangliu --- .../app/src/kvstore_meta_manager.cpp | 12 ++++++++++++ .../framework/test/meta_data_test.cpp | 12 ++++++++++-- .../service/rdb/rdb_general_store.h | 2 +- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 310ff4888..647ae59ce 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -572,6 +572,18 @@ AppDistributedKv::ChangeLevelType KvStoreMetaManager::DBInfoDeviceChangeListener return AppDistributedKv::ChangeLevelType::MIN; } +std::string KvStoreMetaManager::vectorToString(const std::vector &vec, const std::string separator) +{ + std::string result; + std::for_each(vec.begin(), vec.end(), [&](const std::string &info) { + if (!result.empty()) { + result += separator; + } + result += info; + }); + return result; +} + bool KvStoreMetaManager::IsMetaDeviceIdChanged() { DeviceIDMetaData meta; diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index aae9b5aa0..2378897b3 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -832,7 +832,7 @@ HWTEST_F(ServiceMetaDataTest, DeviceIDMetaData, TestSize.Level1) * @tc.author: yl */ HWTEST_F(ServiceMetaDataTest, LoadMatePair, TestSize.Level1) -{ +{ StoreMetaData storeMetaData("100", "appid", "test_store"); storeMetaData.version = TEST_CURRENT_VERSION; storeMetaData.instanceId = 1; @@ -852,7 +852,15 @@ HWTEST_F(ServiceMetaDataTest, LoadMatePair, TestSize.Level1) if (tokens.size() > 1) { tokens[1] = "updateuuid"; } - auto newKey = vectorToString(tokens); + std::string newKey = ""; + std::string separator = "###"; + std::for_each(tokens.begin(), tokens.end(), [&](const std::string &info) { + if (!newKey.empty()) { + newKey += separator; + } + newKey += info; + }); + EXPECT_TRUE(!newKey.empty()); result = MetaDataManager::GetInstance().SaveMeta(newKey, value, true); EXPECT_TRUE(result); result = MetaDataManager::GetInstance().DelMeta(key, true); diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.h b/services/distributeddataservice/service/rdb/rdb_general_store.h index a81279179..3b34b4d06 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.h +++ b/services/distributeddataservice/service/rdb/rdb_general_store.h @@ -88,7 +88,7 @@ public: int32_t CleanTrackerData(const std::string &tableName, int64_t cursor) override; std::pair LockCloudDB() override; int32_t UnLockCloudDB() override; - int32_t RdbGeneralStore::OperateDataStatus(); + int32_t OperateDataStatus() override;; private: RdbGeneralStore(const RdbGeneralStore& rdbGeneralStore); -- Gitee From cbcfb09a60560fe22441ba0fe1597d4346c42865 Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 16 Mar 2025 17:37:05 +0800 Subject: [PATCH 022/225] update Signed-off-by: yangliu --- .../framework/test/meta_data_test.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 2378897b3..934f1d8a8 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -27,6 +27,7 @@ #include "metadata/store_meta_data_local.h" #include "metadata/strategy_meta_data.h" #include "metadata/user_meta_data.h" +#include "metadata/deviceid_pair_meta_data.h" #include "utils/constant.h" #include "gtest/gtest.h" #include @@ -836,7 +837,7 @@ HWTEST_F(ServiceMetaDataTest, LoadMatePair, TestSize.Level1) StoreMetaData storeMetaData("100", "appid", "test_store"); storeMetaData.version = TEST_CURRENT_VERSION; storeMetaData.instanceId = 1; - std::vector entries; + std::vector entries; std::string key = storeMetaData.GetKey(); EXPECT_EQ(key, "KvStoreMetaData######100###default######test_store_001###1"); @@ -844,8 +845,9 @@ HWTEST_F(ServiceMetaDataTest, LoadMatePair, TestSize.Level1) EXPECT_TRUE(result); result = MetaDataManager::GetInstance().LoadMatePair(key, entries, true); EXPECT_TRUE(result); - std::string key(entries.key.begin(), entries.key.end()); - std::string value(entries.value.begin(), entries.value.end()); + EXPECT_EQ(entries.size(), 1); + std::string key(entries[0].key.begin(), entries[0].key.end()); + std::string value(entries[0].value.begin(), entries[0].value.end()); EXPECT_EQ(storeMetaData.GetKey(), key); auto tokens = Constant::SplitKeepSpace(key, Constant::KEY_SEPARATOR); -- Gitee From e3fdbae5a03db7df5dd8fd86ea730b37d8bc12ae Mon Sep 17 00:00:00 2001 From: zph Date: Sun, 16 Mar 2025 19:03:01 +0800 Subject: [PATCH 023/225] update Signed-off-by: zph --- .../service/test/udmf_run_time_store_test.cpp | 3 ++- .../service/udmf/store/runtime_store.cpp | 19 ++++++++++--------- .../service/udmf/store/runtime_store.h | 2 +- .../service/udmf/store/store.h | 2 +- .../service/udmf/udmf_service_impl.cpp | 2 +- 5 files changed, 15 insertions(+), 13 deletions(-) diff --git a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp index 463a522b1..d8d440cf3 100644 --- a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp +++ b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp @@ -571,7 +571,8 @@ HWTEST_F(UdmfRunTimeStoreTest, GetSummary, TestSize.Level1) data.AddRecord(text); Summary summary; - auto status = store->GetSummary(KEY_PREFIX, summary); + UnifiedKey key(KEY_PREFIX); + auto status = store->GetSummary(key, summary); ASSERT_EQ(status, E_DB_ERROR); } }; // namespace DistributedDataTest diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index cf24b28d9..7a7aa836f 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -131,29 +131,30 @@ Status RuntimeStore::PutSummary(const UnifiedData &data, std::vector &ent } UnifiedDataHelper::GetSummary(data, summary); - auto key = data.GetRuntime()->key.GetUnifiedKey(); + auto propertyKey = data.GetRuntime()->key.GetPropertyKey(); Value value; auto status = DataHandler::MarshalToEntries(summary, value, TAG::TAG_SUMMARY); if (status != E_OK) { - ZLOGE("Marshal summary failed, key: %{public}s, status:%{public}d", key.c_str(), status); + ZLOGE("Marshal summary failed, key: %{public}s, status:%{public}d", propertyKey.c_str(), status); return status; } - auto summaryKey = key + SUMMARY_SUFIX; + auto summaryKey = propertyKey + SUMMARY_SUFIX; entries.push_back({{summaryKey.begin(), summaryKey.end()}, value}); return E_OK; } -Status RuntimeStore::GetSummary(const std::string &key, Summary &summary) +Status RuntimeStore::GetSummary(UnifiedKey &key, Summary &summary) { UpdateTime(); Value value; - auto summaryKey = key + SUMMARY_SUFIX; + auto summaryKey = key.GetPropertyKey() + SUMMARY_SUFIX; auto res = kvStore_->Get({summaryKey.begin(), summaryKey.end()}, value); if (res != OK || value.empty()) { - ZLOGW("Get stored summary failed, key: %{public}s, status:%{public}d", key.c_str(), res); + ZLOGW("Get stored summary failed, key: %{public}s, status:%{public}d", summaryKey.c_str(), res); UnifiedData unifiedData; - if (Get(key, unifiedData) != E_OK) { - ZLOGE("Get unified data failed, key: %{public}s", key.c_str()); + auto udKey = key.GetUnifiedKey(); + if (Get(udKey, unifiedData) != E_OK) { + ZLOGE("Get unified data failed, key: %{public}s", udKey.c_str()); return E_DB_ERROR; } UDDetails details {}; @@ -165,7 +166,7 @@ Status RuntimeStore::GetSummary(const std::string &key, Summary &summary) } auto status = DataHandler::UnmarshalEntries(value, summary, TAG::TAG_SUMMARY); if (status != E_OK) { - ZLOGE("Unmarshal summary failed, key: %{public}s, status:%{public}d", key.c_str(), status); + ZLOGE("Unmarshal summary failed, key: %{public}s, status:%{public}d", summaryKey.c_str(), status); return status; } return E_OK; diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.h b/services/distributeddataservice/service/udmf/store/runtime_store.h index eb1a44394..eb83a3503 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.h +++ b/services/distributeddataservice/service/udmf/store/runtime_store.h @@ -30,7 +30,7 @@ public: ~RuntimeStore(); Status Put(const UnifiedData &unifiedData) override; Status Get(const std::string &key, UnifiedData &unifiedData) override; - Status GetSummary(const std::string &key, Summary &summary) override; + Status GetSummary(UnifiedKey &key, Summary &summary) override; Status Update(const UnifiedData &unifiedData) override; Status Delete(const std::string &key) override; Status DeleteBatch(const std::vector &unifiedKeys) override; diff --git a/services/distributeddataservice/service/udmf/store/store.h b/services/distributeddataservice/service/udmf/store/store.h index 9d3820a86..aaf6fade1 100644 --- a/services/distributeddataservice/service/udmf/store/store.h +++ b/services/distributeddataservice/service/udmf/store/store.h @@ -26,7 +26,7 @@ public: using Time = std::chrono::steady_clock::time_point; virtual Status Put(const UnifiedData &unifiedData) = 0; virtual Status Get(const std::string &key, UnifiedData &unifiedData) = 0; - virtual Status GetSummary(const std::string &key, Summary &summary) = 0; + virtual Status GetSummary(UnifiedKey &key, Summary &summary) = 0; virtual Status Update(const UnifiedData &unifiedData) = 0; virtual Status Delete(const std::string &key) = 0; virtual Status DeleteBatch(const std::vector &unifiedKeys) = 0; diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 9606e1c03..2d0cdacbc 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -458,7 +458,7 @@ int32_t UdmfServiceImpl::GetSummary(const QueryOption &query, Summary &summary) return E_DB_ERROR; } - if (store->GetSummary(query.key, summary) != E_OK) { + if (store->GetSummary(key, summary) != E_OK) { ZLOGE("Store get summary failed:%{public}s", key.intention.c_str()); return E_DB_ERROR; } -- Gitee From cd6301fb14e1a92fd2c331ca98e5d456b337b6ad Mon Sep 17 00:00:00 2001 From: zph Date: Sun, 16 Mar 2025 23:00:24 +0800 Subject: [PATCH 024/225] update Signed-off-by: zph --- .../service/udmf/store/runtime_store.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index 7a7aa836f..ae7fac872 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -98,11 +98,14 @@ Status RuntimeStore::Put(const UnifiedData &unifiedData) { UpdateTime(); std::vector entries; + std::string intention = unifiedData.GetRuntime()->key.intention; + if (intention == UD_INTENTION_MAP.at(UD_INTENTION_DRAG)) { + PutSummary(unifiedData, entries); + } auto status = DataHandler::MarshalToEntries(unifiedData, entries); if (status != E_OK) { return status; } - PutSummary(unifiedData, entries); return PutEntries(entries); } @@ -127,9 +130,10 @@ Status RuntimeStore::PutSummary(const UnifiedData &data, std::vector &ent UDDetails details {}; Summary summary; if (PreProcessUtils::GetDetailsFromUData(data, details)) { - return PreProcessUtils::GetSummaryFromDetails(details, summary); + PreProcessUtils::GetSummaryFromDetails(details, summary); + } else { + UnifiedDataHelper::GetSummary(data, summary); } - UnifiedDataHelper::GetSummary(data, summary); auto propertyKey = data.GetRuntime()->key.GetPropertyKey(); Value value; -- Gitee From 5527715b944d1ae93621ac609201cab26cbda4f7 Mon Sep 17 00:00:00 2001 From: Axi_Beft Date: Sat, 15 Mar 2025 17:56:13 +0800 Subject: [PATCH 025/225] add service UT Signed-off-by: Axi_Beft --- .../service/test/object_asset_loader_test.cpp | 50 +++++++++++ .../service/test/object_manager_test.cpp | 86 ++++++++++++++++++- 2 files changed, 134 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/test/object_asset_loader_test.cpp b/services/distributeddataservice/service/test/object_asset_loader_test.cpp index 57aa68b6f..c25e185cb 100644 --- a/services/distributeddataservice/service/test/object_asset_loader_test.cpp +++ b/services/distributeddataservice/service/test/object_asset_loader_test.cpp @@ -20,6 +20,7 @@ #include #include "executor_pool.h" +#include "object_common.h" #include "snapshot/machine_status.h" using namespace testing::ext; @@ -206,4 +207,53 @@ HWTEST_F(ObjectAssetLoaderTest, UpdateDownloaded002, TestSize.Level0) EXPECT_EQ(success, false); EXPECT_EQ(hash, ""); } + +/** +* @tc.name: PushAsset001 +* @tc.desc: PushAsset test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectAssetLoaderTest, PushAsset001, TestSize.Level0) +{ + auto assetLoader = ObjectAssetLoader::GetInstance(); + ASSERT_NE(assetLoader, nullptr); + sptr assetObj = new AssetObj(); + assetObj->dstBundleName_ = bundleName_; + assetObj->srcBundleName_ = bundleName_; + assetObj->dstNetworkId_ = "1"; + assetObj->sessionId_ = "123"; + + sptr sendCallback = new ObjectAssetsSendListener(); + ASSERT_NE(sendCallback, nullptr); + int32_t ret = assetLoader->PushAsset(userId_, assetObj, sendCallback); + EXPECT_NE(ret, DistributedObject::OBJECT_SUCCESS); +} + +/** +* @tc.name: OnSendResult001 +* @tc.desc: OnSendResult test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectAssetLoaderTest, OnSendResult001, TestSize.Level1) +{ + sptr assetObj = nullptr; + + int32_t result = -1; + sptr sendCallback = new ObjectAssetsSendListener(); + int32_t ret = sendCallback->OnSendResult(assetObj, result); + EXPECT_EQ(ret, result); + + assetObj = new AssetObj(); + assetObj->dstBundleName_ = bundleName_; + assetObj->srcBundleName_ = bundleName_; + assetObj->dstNetworkId_ = "1"; + assetObj->sessionId_ = "123"; + + ret = sendCallback->OnSendResult(assetObj, result); + EXPECT_EQ(ret, result); + + result = 0; + ret = sendCallback->OnSendResult(assetObj, result); + EXPECT_EQ(ret, result); +} } // namespace OHOS::Test diff --git a/services/distributeddataservice/service/test/object_manager_test.cpp b/services/distributeddataservice/service/test/object_manager_test.cpp index 6f4a2c0a1..db1ed7c89 100644 --- a/services/distributeddataservice/service/test/object_manager_test.cpp +++ b/services/distributeddataservice/service/test/object_manager_test.cpp @@ -524,15 +524,20 @@ HWTEST_F(ObjectManagerTest, Close001, TestSize.Level0) 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; - deviceList.push_back("local"); + // not local device & syncDevices empty deviceList.push_back("local1"); auto result = manager->SyncOnStore(prefix, deviceList, func); + ASSERT_NE(result, OBJECT_SUCCESS); + // local device + deviceList.push_back("local"); + result = manager->SyncOnStore(prefix, deviceList, func); ASSERT_EQ(result, OBJECT_SUCCESS); } @@ -683,6 +688,33 @@ HWTEST_F(ObjectManagerTest, ProcessSyncCallback001, TestSize.Level0) manager->ProcessSyncCallback(results, appId_, sessionId_, deviceId_); } +/** +* @tc.name: ProcessSyncCallback002 +* @tc.desc: ProcessSyncCallback test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, ProcessSyncCallback002, TestSize.Level0) +{ + std::string dataDir = "/data/app/el2/100/database"; + auto manager = ObjectStoreManager::GetInstance(); + std::map results; + + results.insert({"remote", 1}); // for testing + ASSERT_EQ(results.empty(), false); + ASSERT_EQ(results.find("local"), results.end()); + + manager->kvStoreDelegateManager_ = nullptr; + // open store failed -> success + manager->ProcessSyncCallback(results, appId_, sessionId_, deviceId_); + + // open store success -> success + manager->SetData(dataDir, userId_); + ASSERT_NE(manager->kvStoreDelegateManager_, nullptr); + manager->delegate_ = manager->OpenObjectKvStore(); + ASSERT_NE(manager->delegate_, nullptr); + manager->ProcessSyncCallback(results, appId_, sessionId_, deviceId_); +} + /** * @tc.name: IsAssetComplete001 * @tc.desc: IsAssetComplete test. @@ -830,7 +862,7 @@ HWTEST_F(ObjectManagerTest, RegisterAssetsLister001, TestSize.Level0) } /** -* @tc.name: RegisterAssetsLister001 +* @tc.name: PushAssets001 * @tc.desc: PushAssets test. * @tc.type: FUNC * @tc.require: @@ -849,6 +881,41 @@ HWTEST_F(ObjectManagerTest, PushAssets001, TestSize.Level0) ASSERT_EQ(result, DistributedObject::OBJECT_SUCCESS); } +/** +* @tc.name: PushAssets002 +* @tc.desc: PushAssets test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, PushAssets002, TestSize.Level0) +{ + auto manager = ObjectStoreManager::GetInstance(); + std::map> data; + std::vector value{0}; + std::string data0 = "[STRING]test"; + value.insert(value.end(), data0.begin(), data0.end()); + + std::string prefix = "bundleName_sessionId_source_target_timestamp"; + std::string dataKey = prefix + "_p_data"; + std::string assetPrefix = prefix + "_p_asset0"; + std::string fieldsPrefix = "p_"; + std::string deviceIdKey = "__deviceId"; + + data.insert({assetPrefix + ObjectStore::NAME_SUFFIX, value}); + data.insert({assetPrefix + ObjectStore::URI_SUFFIX, value}); + data.insert({assetPrefix + ObjectStore::MODIFY_TIME_SUFFIX, value}); + data.insert({assetPrefix + ObjectStore::SIZE_SUFFIX, value}); + data.insert({fieldsPrefix + deviceIdKey, value}); + + manager->objectAssetsSendListener_ = nullptr; + int32_t ret = manager->PushAssets(appId_, appId_, sessionId_, data, deviceId_); + EXPECT_NE(ret, DistributedObject::OBJECT_SUCCESS); + + manager->objectAssetsSendListener_ = new ObjectAssetsSendListener(); + ASSERT_NE(manager->objectAssetsSendListener_, nullptr); + ret = manager->PushAssets(appId_, appId_, sessionId_, data, deviceId_); + EXPECT_NE(ret, DistributedObject::OBJECT_SUCCESS); +} + /** * @tc.name: AddNotifier001 * @tc.desc: AddNotifie and DeleteNotifier test. @@ -897,4 +964,19 @@ HWTEST_F(ObjectManagerTest, BindAsset001, TestSize.Level0) auto result = manager->BindAsset(tokenId, bundleName, sessionId_, assetValue_, assetBindInfo_); ASSERT_EQ(result, DistributedObject::OBJECT_DBSTATUS_ERROR); } + +/** +* @tc.name: OnFinished001 +* @tc.desc: OnFinished test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, OnFinished001, TestSize.Level1) +{ + std::string srcNetworkId = "srcNetworkId"; + sptr assetObj = nullptr; + int32_t result = 100; + ObjectAssetsRecvListener listener; + int32_t ret = listener.OnFinished(srcNetworkId, assetObj, result); + EXPECT_NE(ret, DistributedObject::OBJECT_SUCCESS); +} } // namespace OHOS::Test -- Gitee From f7bd657dacd242acff0a6c48a8fd8ee733ae91fc Mon Sep 17 00:00:00 2001 From: zph Date: Mon, 17 Mar 2025 11:15:24 +0800 Subject: [PATCH 026/225] update Signed-off-by: zph --- .../service/udmf/preprocess/preprocess_utils.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index 11d063598..44d6a004e 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -44,6 +44,7 @@ constexpr const char *TEMP_UNIFIED_DATA_FLAG = "temp_udmf_file_flag"; static constexpr size_t TEMP_UDATA_RECORD_SIZE = 1; static constexpr uint32_t PREFIX_LEN = 24; static constexpr uint32_t INDEX_LEN = 8; +static constexpr const char PLACE_HOLDER = '0'; using namespace OHOS::DistributedDataDfx; using namespace Security::AccessToken; using namespace OHOS::AppFileService::ModuleRemoteFileShare; @@ -413,7 +414,7 @@ void PreProcessUtils::SetRecordUid(UnifiedData &data) auto prefix = PreProcessUtils::GenerateId().substr(0, PREFIX_LEN); for (const auto &record : data.GetRecords()) { std::ostringstream oss; - oss << std::setw(INDEX_LEN) << std::setfill('0') << index; + oss << std::setw(INDEX_LEN) << std::setfill(PLACE_HOLDER) << index; record->SetUid(prefix + oss.str()); index++; } -- Gitee From af84e15db1d1d46f9371d21a2663813353b92ed0 Mon Sep 17 00:00:00 2001 From: zph Date: Mon, 17 Mar 2025 17:14:30 +0800 Subject: [PATCH 027/225] update Signed-off-by: zph --- .../udmf/preprocess/preprocess_utils.cpp | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index 44d6a004e..c1ba6478e 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -424,42 +424,48 @@ bool PreProcessUtils::GetDetailsFromUData(const UnifiedData &data, UDDetails &de { auto records = data.GetRecords(); if (records.size() != TEMP_UDATA_RECORD_SIZE) { - ZLOGE("Data has multiple records.size:%{public}zu", records.size()); + ZLOGE("Records size error.size:%{public}zu", records.size()); return false; } - if (records[0] == nullptr || records[0]->GetType() != UDType::FILE) { - ZLOGE("Record is not file."); + if (records[0] == nullptr) { + ZLOGE("First record is null."); return false; } - auto obj = std::get>(records[0]->GetOriginValue()); + if (records[0]->GetType() != UDType::FILE) { + ZLOGE("First record is not file."); + return false; + } + auto value = records[0]->GetOriginValue(); + auto obj = std::get_if>(&value); if (obj == nullptr) { ZLOGE("ValueType is not Object!"); return false; } std::shared_ptr detailObj; - obj->GetValue(DETAILS, detailObj); + (*obj)->GetValue(DETAILS, detailObj); if (detailObj == nullptr) { ZLOGE("Not contain details for object!"); return false; } auto result = ObjectUtils::ConvertToUDDetails(detailObj); if (result.find(TEMP_UNIFIED_DATA_FLAG) == result.end()) { + ZLOGE("Not find temp file."); return false; } - details = result; + details = std::move(result); return true; } Status PreProcessUtils::GetSummaryFromDetails(const UDDetails &details, Summary &summary) { for (auto &item : details) { - if (item.first != TEMP_UNIFIED_DATA_FLAG) { - auto int64Value = std::get_if(&item.second); - if (int64Value != nullptr) { - auto size = std::get(item.second); - summary.summary[item.first] = size; - summary.totalSize += size; - } + if (item.first == TEMP_UNIFIED_DATA_FLAG) { + continue; + } + auto int64Value = std::get_if(&item.second); + if (int64Value != nullptr) { + summary.summary[item.first] = *int64Value; + summary.totalSize += *int64Value; } } return E_OK; -- Gitee From 320c5953827d33b6afa6d83804c310f7be47fb0b Mon Sep 17 00:00:00 2001 From: zph Date: Mon, 17 Mar 2025 21:05:23 +0800 Subject: [PATCH 028/225] update Signed-off-by: zph --- .../service/udmf/preprocess/preprocess_utils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index c1ba6478e..069609aba 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -437,7 +437,7 @@ bool PreProcessUtils::GetDetailsFromUData(const UnifiedData &data, UDDetails &de } auto value = records[0]->GetOriginValue(); auto obj = std::get_if>(&value); - if (obj == nullptr) { + if (obj == nullptr || *obj == nullptr) { ZLOGE("ValueType is not Object!"); return false; } -- Gitee From dd4fb71511ef3886c715147d6098c69b1e9a0281 Mon Sep 17 00:00:00 2001 From: wangbin Date: Tue, 18 Mar 2025 12:36:11 +0800 Subject: [PATCH 029/225] update SoftbusAdapterStandardTest Signed-off-by: wangbin --- .../adapter/communicator/test/BUILD.gn | 24 +- .../process_communicator_impl_test.cpp | 9 +- .../softbus_adapter_standard_test.cpp | 263 +++++++++++++++++- .../test/mock/device_manager_adapter_mock.cpp | 24 +- .../test/mock/device_manager_adapter_mock.h | 9 +- 5 files changed, 309 insertions(+), 20 deletions(-) diff --git a/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/BUILD.gn index cf89c4464..64b50feef 100755 --- a/services/distributeddataservice/adapter/communicator/test/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/BUILD.gn @@ -188,11 +188,25 @@ ohos_unittest("ProcessCommunicatorImplTest") { ohos_unittest("SoftbusAdapterStandardTest") { module_out_path = module_output_path - sources = [ "unittest/softbus_adapter_standard_test.cpp" ] + sources = [ + "${data_service_path}/service/test/mock/device_manager_adapter_mock.cpp", + "../src/communicator_context.cpp", + "../src/data_buffer.cpp", + "../src/process_communicator_impl.cpp", + "../src/softbus_adapter.h", + "../src/softbus_client.cpp", + "../src/softbus_client.h", + "unittest/softbus_adapter_standard_test.cpp", + ] + include_dirs = [ "${data_service_path}/adapter/include/communicator", "${data_service_path}/framework/include/dfx", + "${data_service_path}/service/test/mock", "../src", + "../../include/communicator", + "../../include/utils", + "${data_service_path}/framework/include/utils", ] external_deps = [ "access_token:libaccesstoken_sdk", @@ -201,16 +215,22 @@ ohos_unittest("SoftbusAdapterStandardTest") { "c_utils:utils", "device_manager:devicemanagersdk", "dsoftbus:softbus_client", + "googletest:gmock_main", "hilog:libhilog", "ipc:ipc_core", + "json:nlohmann_json_static", + "kv_store:datamgr_common", "kv_store:distributeddata_inner", + "kv_store:distributeddb", ] cflags = [ "-Dprivate=public", "-Dprotected=public", ] deps = [ - "${data_service_path}/adapter/communicator:distributeddata_communicator", + "${data_service_path}/adapter/utils:distributeddata_utils", + "${data_service_path}/framework:distributeddatasvcfwk", + "../../dfx:distributeddata_dfx", ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp index 8999b2ea1..935ec97e2 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp @@ -37,6 +37,7 @@ using UserInfo = DistributedDB::UserInfo; namespace OHOS::AppDistributedKv { class MockCommunicationProvider : public CommunicationProvider { public: + ~MockCommunicationProvider() = default; static MockCommunicationProvider& Init() { static MockCommunicationProvider instance; @@ -79,7 +80,7 @@ public: static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); - void TearDown() {} + void TearDown(); ProcessCommunicatorImpl* communicator_; MockCommunicationProvider* mockProvider; @@ -114,6 +115,11 @@ void ProcessCommunicatorImplTest::SetUp(void) mockProvider = &MockCommunicationProvider::Init(); } +void ProcessCommunicatorImplTest::TearDown(void) +{ + mockProvider = nullptr; +} + void ProcessCommunicatorImplTest::SetUpTestCase(void) { deviceManagerAdapterMock = std::make_shared(); @@ -123,6 +129,7 @@ void ProcessCommunicatorImplTest::SetUpTestCase(void) void ProcessCommunicatorImplTest::TearDownTestCase() { deviceManagerAdapterMock = nullptr; + BDeviceManagerAdapter::deviceManagerAdapter = nullptr; } /** diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp index b4b4e92b3..e23a479ed 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp @@ -12,14 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#define LOG_TAG "SoftbusAdapterStandardTest" - #include "app_device_change_listener.h" #include #include "gtest/gtest.h" +#include #include -#include "log_print.h" +#include "device_manager_adapter_mock.h" #include "softbus_adapter.h" +#include "softbus_adapter_standard.cpp" +#include "softbus_error_code.h" #include "types.h" #include #include @@ -27,6 +28,7 @@ namespace OHOS::Test { using namespace testing::ext; using namespace OHOS::AppDistributedKv; +using namespace OHOS::DistributedData; using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo; class AppDataChangeListenerImpl : public AppDataChangeListener { struct ServerSocketInfo { @@ -41,14 +43,13 @@ class AppDataChangeListenerImpl : public AppDataChangeListener { void AppDataChangeListenerImpl::OnMessage(const OHOS::AppDistributedKv::DeviceInfo &info, const uint8_t *ptr, const int size, const struct PipeInfo &id) const -{ - ZLOGI("data %{public}s %s", info.deviceName.c_str(), ptr); -} +{} class SoftbusAdapterStandardTest : public testing::Test { public: - static void SetUpTestCase(void) {} - static void TearDownTestCase(void) {} + static inline std::shared_ptr deviceManagerAdapterMock = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); void SetUp() {} void TearDown() {} protected: @@ -56,6 +57,17 @@ protected: static constexpr uint32_t DEFAULT_TIMEOUT = 30 * 1000; }; +void SoftbusAdapterStandardTest::SetUpTestCase(void) +{ + deviceManagerAdapterMock = std::make_shared(); + BDeviceManagerAdapter::deviceManagerAdapter = deviceManagerAdapterMock; +} + +void SoftbusAdapterStandardTest::TearDownTestCase() +{ + deviceManagerAdapterMock = nullptr; +} + /** * @tc.name: StartWatchDeviceChange * @tc.desc: start watch data change @@ -84,6 +96,9 @@ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange01, TestSize.Level0) const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId); EXPECT_EQ(status, Status::SUCCESS); + status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId); + delete dataListener; + EXPECT_EQ(status, Status::ERROR); } /** @@ -100,6 +115,7 @@ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange02, TestSize.Level0) appId.userId = "groupId"; const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId); + delete dataListener; EXPECT_EQ(status, Status::SUCCESS); } @@ -111,7 +127,6 @@ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange02, TestSize.Level0) */ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange03, TestSize.Level1) { - ZLOGI("begin."); PipeInfo appId; appId.pipeId = "appId06"; appId.userId = "groupId06"; @@ -139,6 +154,9 @@ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange, TestSize.Level0) const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); auto status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId); EXPECT_EQ(status, Status::SUCCESS); + status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId); + delete dataListener; + EXPECT_EQ(status, Status::ERROR); } /** @@ -155,9 +173,27 @@ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange01, TestSize.Level0) appId.userId = "groupId"; const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); auto status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId); + delete dataListener; EXPECT_EQ(status, Status::SUCCESS); } +/** +* @tc.name: GetExpireTime +* @tc.desc: GetExpireTime Test +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin + */ +HWTEST_F(SoftbusAdapterStandardTest, GetExpireTime, TestSize.Level0) +{ + PipeInfo appId; + appId.pipeId = "appId"; + appId.userId = "groupId"; + DeviceId di = {"DeviceId"}; + std::shared_ptr conn = std::make_shared(appId, di, SoftBusClient::QoSType::QOS_HML); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->GetExpireTime(conn)); +} + /** * @tc.name: SendData * @tc.desc: parse sent data @@ -209,6 +245,182 @@ HWTEST_F(SoftbusAdapterStandardTest, SendData01, TestSize.Level1) delete dataListener; } +/** +* @tc.name: StartCloseSessionTask +* @tc.desc: StartCloseSessionTask tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, StartCloseSessionTask, TestSize.Level1) +{ + std::shared_ptr conn = nullptr; + std::vector> clients; + clients.emplace_back(conn); + auto status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId01", clients); + EXPECT_EQ(status, true); + SoftBusAdapter::GetInstance()->connects_.Clear(); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->StartCloseSessionTask("deviceId02")); +} + +/** +* @tc.name: OnClientShutdown +* @tc.desc: DelConnect tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, OnClientShutdown, TestSize.Level1) +{ + PipeInfo appId; + appId.pipeId = "appId"; + appId.userId = "groupId"; + DeviceId di = {"DeviceId"}; + std::shared_ptr conn1 = std::make_shared(appId, di, SoftBusClient::QoSType::QOS_HML); + std::shared_ptr conn2 = nullptr; + std::vector> clients; + clients.emplace_back(conn1); + clients.emplace_back(conn2); + auto status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId01", clients); + EXPECT_EQ(status, true); + status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId02", {}); + EXPECT_EQ(status, true); + auto name = SoftBusAdapter::GetInstance()->OnClientShutdown(-1, true); + EXPECT_EQ(name, "deviceId01 "); + name = SoftBusAdapter::GetInstance()->OnClientShutdown(-1, false); + EXPECT_EQ(name, ""); + name = SoftBusAdapter::GetInstance()->OnClientShutdown(1, true); + SoftBusAdapter::GetInstance()->connects_.Clear(); + EXPECT_EQ(name, ""); +} + +/** +* @tc.name: NotifyDataListeners +* @tc.desc: NotifyDataListeners tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, NotifyDataListeners, TestSize.Level1) +{ + PipeInfo appId; + appId.pipeId = "appId"; + appId.userId = "groupId"; + std::string content = "Helloworlds"; + const uint8_t *t = reinterpret_cast(content.c_str()); + SoftBusAdapter::GetInstance()->dataChangeListeners_.Clear(); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->NotifyDataListeners(t, 1, "deviceId", appId)); + const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); + SoftBusAdapter::GetInstance()->dataChangeListeners_.Insert(appId.pipeId, dataListener); + delete dataListener; + SoftBusAdapter::GetInstance()->dataChangeListeners_.Clear(); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->NotifyDataListeners(t, 1, "deviceId", appId)); +} + +/** +* @tc.name: ListenBroadcastMsg +* @tc.desc: ListenBroadcastMsg tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, ListenBroadcastMsg, TestSize.Level1) +{ + SoftBusAdapter::GetInstance()->onBroadcast_= nullptr; + PipeInfo appId; + appId.pipeId = "appId"; + appId.userId = "groupId"; + auto result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, nullptr); + EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_INVALID_PARAM); + + auto listener = [](const std::string &message, const LevelInfo &info) {}; + result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, listener); + EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_INVALID_PARAM); + result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, listener); + EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_ALREADY_EXISTED); +} + +/** +* @tc.name: OnBroadcast +* @tc.desc: OnBroadcast tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, OnBroadcast, TestSize.Level1) +{ + DeviceId di = {"DeviceId"}; + LevelInfo level; + level.dynamic = 1; + level.statics = 1; + level.switches = 1; + level.switchesLen = 1; + EXPECT_NE(SoftBusAdapter::GetInstance()->onBroadcast_, nullptr); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(di, level)); + SoftBusAdapter::GetInstance()->onBroadcast_ = nullptr; + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(di, level)); +} + +/** +* @tc.name: OnClientSocketChanged +* @tc.desc: OnClientSocketChanged tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, OnClientSocketChanged, TestSize.Level1) +{ + QosTV qosTv; + qosTv.qos = QosType::QOS_TYPE_MIN_BW; + qosTv.value = 1; + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 1)); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 0)); + qosTv.qos = QosType::QOS_TYPE_MAX_WAIT_TIMEOUT; + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 0)); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, nullptr, 0)); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_NOT_SATISFIED, nullptr, 0)); +} + +/** +* @tc.name: OnServerBytesReceived +* @tc.desc: OnServerBytesReceived tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, OnServerBytesReceived, TestSize.Level1) +{ + PeerSocketInfo info; + info.name = strdup(""); + info.networkId = strdup("peertest01"); + info.pkgName = strdup("ohos.kv.test"); + info.dataType = TransDataType::DATA_TYPE_MESSAGE; + AppDistributedKv::SoftBusAdapter::ServerSocketInfo serinfo; + auto result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, serinfo); + EXPECT_EQ(result, false); + char str[] = "Hello"; + const void* data = static_cast(str); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(1, data, 10)); + SoftBusAdapter::GetInstance()->OnBind(1, info); + result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, serinfo); + EXPECT_EQ(result, true); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(1, data, 10)); + info.name = strdup("name"); + SoftBusAdapter::GetInstance()->OnBind(2, info); + result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(2, serinfo); + EXPECT_EQ(result, true); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(2, data, 10)); +} + +/** +* @tc.name: GetPipeId +* @tc.desc: GetPipeId tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, GetPipeId, TestSize.Level1) +{ + std::string names = "GetPipeId"; + auto name = AppDataListenerWrap::GetPipeId(names); + EXPECT_EQ(name, names); + names = "test01_GetPipeId"; + name = AppDataListenerWrap::GetPipeId(names); + EXPECT_EQ(name, "test01"); +} + /** * @tc.name: GetMtuSize * @tc.desc: get size @@ -289,6 +501,26 @@ HWTEST_F(SoftbusAdapterStandardTest, ReuseConnect, TestSize.Level1) delete dataListener; } +/** +* @tc.name: ReuseConnect01 +* @tc.desc: reuse connect +* @tc.type: FUNC +* @tc.author: wangbin +*/ +HWTEST_F(SoftbusAdapterStandardTest, ReuseConnect01, TestSize.Level1) +{ + PipeInfo pipe; + pipe.pipeId = "appId"; + pipe.userId = "groupId"; + DeviceId device = {"DeviceId"}; + auto status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device); + EXPECT_EQ(status, Status::NOT_SUPPORT); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(testing::_)).WillOnce(testing::Return(true)) + .WillRepeatedly(testing::Return(true)); + status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device); + EXPECT_EQ(status, Status::NETWORK_ERROR); +} + /** * @tc.name: GetConnect * @tc.desc: get connect @@ -366,6 +598,17 @@ HWTEST_F(SoftbusAdapterStandardTest, CloseSession, TestSize.Level1) ASSERT_NE(flag, nullptr); auto status = SoftBusAdapter::GetInstance()->CloseSession(networkId); EXPECT_EQ(status, false); + std::string uuid = "CloseSessionTest"; + EXPECT_CALL(*deviceManagerAdapterMock, GetUuidByNetworkId(testing::_)).WillOnce(testing::Return(uuid)) + .WillRepeatedly(testing::Return(uuid)); + std::shared_ptr conn = nullptr; + std::vector> clients; + clients.emplace_back(conn); + auto result = SoftBusAdapter::GetInstance()->connects_.Insert(uuid, clients); + EXPECT_EQ(result, true); + status = SoftBusAdapter::GetInstance()->CloseSession(networkId); + SoftBusAdapter::GetInstance()->connects_.Clear(); + EXPECT_EQ(status, true); } /** @@ -416,6 +659,6 @@ HWTEST_F(SoftbusAdapterStandardTest, GetPeerSocketInfo01, TestSize.Level1) auto flag = SoftBusAdapter::GetInstance(); ASSERT_NE(flag, nullptr); auto status = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, info); - EXPECT_EQ(status, false); + EXPECT_EQ(status, true); } } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp index 4723bb5e6..7e7086114 100644 --- a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp +++ b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp @@ -25,6 +25,9 @@ OHOS::DistributedData::DeviceManagerAdapter::DeviceManagerAdapter() : cloudDmInfo({ "cloudDeviceId", "cloudDeviceName", 0, "cloudNetworkId", 0 }) {} +OHOS::DistributedData::DeviceManagerAdapter::~DeviceManagerAdapter() +{} + std::vector OHOS::DistributedData::DeviceManagerAdapter::ToUUID(std::vector devices) { if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { @@ -85,16 +88,27 @@ std::vector OHOS::DistributedData::DeviceManagerAdapter::GetRemoteDe return BDeviceManagerAdapter::deviceManagerAdapter->GetRemoteDevices(); } -DeviceInfo DeviceManagerAdapter::GetLocalDevice() +std::string OHOS::DistributedData::DeviceManagerAdapter::GetUuidByNetworkId(const std::string &networkId) { if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { - DeviceInfo info; - return info; + return " "; + } + return BDeviceManagerAdapter::deviceManagerAdapter->GetUuidByNetworkId(networkId); +} + +DeviceInfo OHOS::DistributedData::DeviceManagerAdapter::GetDeviceInfo(const std::string &id) +{ + if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { + return {}; } - return BDeviceManagerAdapter::deviceManagerAdapter->GetLocalDevice(); + return BDeviceManagerAdapter::deviceManagerAdapter->GetDeviceInfo(id); } -DeviceManagerAdapter::~DeviceManagerAdapter() +std::string OHOS::DistributedData::DeviceManagerAdapter::ToNetworkID(const std::string &id) { + if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { + return " "; + } + return BDeviceManagerAdapter::deviceManagerAdapter->ToNetworkID(id); } } \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h index 38ab1cac0..46478fbd2 100644 --- a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h +++ b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h @@ -24,6 +24,7 @@ namespace DistributedData { using namespace OHOS::AppDistributedKv; using AccessCaller = OHOS::AppDistributedKv::AccessCaller; using AccessCallee = OHOS::AppDistributedKv::AccessCallee; +using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo; class BDeviceManagerAdapter { public: virtual std::vector GetRemoteDevices() = 0; @@ -32,8 +33,10 @@ public: virtual Status StartWatchDeviceChange(const AppDeviceChangeListener *, const PipeInfo &) = 0; virtual Status StopWatchDeviceChange(const AppDeviceChangeListener *, const PipeInfo &) = 0; virtual bool IsSameAccount(const AccessCaller &, const AccessCallee &) = 0; + virtual std::string GetUuidByNetworkId(const std::string &); + virtual DeviceInfo GetDeviceInfo(const std::string &); + virtual std::string ToNetworkID(const std::string &); virtual bool CheckAccessControl(const AccessCaller &, const AccessCallee &) = 0; - virtual DeviceInfo GetLocalDevice() = 0; static inline std::shared_ptr deviceManagerAdapter = nullptr; BDeviceManagerAdapter() = default; virtual ~BDeviceManagerAdapter() = default; @@ -47,8 +50,10 @@ public: MOCK_METHOD(Status, StartWatchDeviceChange, (const AppDeviceChangeListener *, const PipeInfo &)); MOCK_METHOD(Status, StopWatchDeviceChange, (const AppDeviceChangeListener *, const PipeInfo &)); MOCK_METHOD(bool, IsSameAccount, (const AccessCaller &, const AccessCallee &)); + MOCK_METHOD(std::string, GetUuidByNetworkId, (const std::string &)); + MOCK_METHOD(DeviceInfo, GetDeviceInfo, (const std::string &)); + MOCK_METHOD(std::string, ToNetworkID, (const std::string &)); MOCK_METHOD(bool, CheckAccessControl, (const AccessCaller &, const AccessCallee &)); - MOCK_METHOD(DeviceInfo, GetLocalDevice, ()); }; } // namespace DistributedData -- Gitee From c1b194db6c1111155737b3e562dd85de15979ddb Mon Sep 17 00:00:00 2001 From: wangbin Date: Tue, 18 Mar 2025 13:03:55 +0800 Subject: [PATCH 030/225] fix Signed-off-by: wangbin --- .../test/mock/device_manager_adapter_mock.cpp | 16 +++++++++++++--- .../test/mock/device_manager_adapter_mock.h | 2 ++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp index 7e7086114..fae2fb0f5 100644 --- a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp +++ b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp @@ -25,9 +25,6 @@ OHOS::DistributedData::DeviceManagerAdapter::DeviceManagerAdapter() : cloudDmInfo({ "cloudDeviceId", "cloudDeviceName", 0, "cloudNetworkId", 0 }) {} -OHOS::DistributedData::DeviceManagerAdapter::~DeviceManagerAdapter() -{} - std::vector OHOS::DistributedData::DeviceManagerAdapter::ToUUID(std::vector devices) { if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { @@ -88,6 +85,15 @@ std::vector OHOS::DistributedData::DeviceManagerAdapter::GetRemoteDe return BDeviceManagerAdapter::deviceManagerAdapter->GetRemoteDevices(); } +DeviceInfo DeviceManagerAdapter::GetLocalDevice() +{ + if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { + DeviceInfo info; + return info; + } + return BDeviceManagerAdapter::deviceManagerAdapter->GetLocalDevice(); +} + std::string OHOS::DistributedData::DeviceManagerAdapter::GetUuidByNetworkId(const std::string &networkId) { if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { @@ -111,4 +117,8 @@ std::string OHOS::DistributedData::DeviceManagerAdapter::ToNetworkID(const std:: } return BDeviceManagerAdapter::deviceManagerAdapter->ToNetworkID(id); } + +DeviceManagerAdapter::~DeviceManagerAdapter() +{ +} } \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h index 46478fbd2..9c1114633 100644 --- a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h +++ b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h @@ -37,6 +37,7 @@ public: virtual DeviceInfo GetDeviceInfo(const std::string &); virtual std::string ToNetworkID(const std::string &); virtual bool CheckAccessControl(const AccessCaller &, const AccessCallee &) = 0; + virtual DeviceInfo GetLocalDevice() = 0; static inline std::shared_ptr deviceManagerAdapter = nullptr; BDeviceManagerAdapter() = default; virtual ~BDeviceManagerAdapter() = default; @@ -54,6 +55,7 @@ public: MOCK_METHOD(DeviceInfo, GetDeviceInfo, (const std::string &)); MOCK_METHOD(std::string, ToNetworkID, (const std::string &)); MOCK_METHOD(bool, CheckAccessControl, (const AccessCaller &, const AccessCallee &)); + MOCK_METHOD(DeviceInfo, GetLocalDevice, ()); }; } // namespace DistributedData -- Gitee From 6001f9cc07012022acae7d9278856173bbdc83ae Mon Sep 17 00:00:00 2001 From: wangbin Date: Tue, 18 Mar 2025 14:40:35 +0800 Subject: [PATCH 031/225] fix Signed-off-by: wangbin --- .../communicator/test/unittest/softbus_adapter_standard_test.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp index e23a479ed..6a434da15 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp @@ -66,6 +66,7 @@ void SoftbusAdapterStandardTest::SetUpTestCase(void) void SoftbusAdapterStandardTest::TearDownTestCase() { deviceManagerAdapterMock = nullptr; + BDeviceManagerAdapter::deviceManagerAdapter = nullptr; } /** -- Gitee From b26f1faa5579344d34d52c1b5313998618c519e6 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Tue, 18 Mar 2025 07:29:10 +0000 Subject: [PATCH 032/225] add BackupManagerServiceTest case-0318 Signed-off-by: suoqilong --- .../service/test/BUILD.gn | 55 +++ .../test/backup_manager_service_test.cpp | 326 ++++++++++++++++++ 2 files changed, 381 insertions(+) create mode 100644 services/distributeddataservice/service/test/backup_manager_service_test.cpp diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 269e7e7ec..6f0a74f9e 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -1732,6 +1732,60 @@ ohos_unittest("UserDelegateMockTest") { cflags_cc = cflags } +ohos_unittest("BackupManagerServiceTest") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + module_out_path = module_output_path + sources = [ + "${data_service_path}/app/src/kvstore_meta_manager.cpp", + "backup_manager_service_test.cpp", + ] + + include_dirs = [ + "${data_service_path}/adapter/include/communicator", + "${data_service_path}/app/src", + "${data_service_path}/service/bootstrap/include/", + "${data_service_path}/service/common", + "${data_service_path}/service/crypto/include", + "${data_service_path}/service/matrix/include/", + "${data_service_path}/service/rdb", + "${data_service_path}/service/kvdb", + "${data_service_path}/service/backup/include/", + ] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "c_utils:utils", + "dataclassification:data_transit_mgr", + "device_manager:devicemanagersdk", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", + "kv_store:distributeddb", + ] + + deps = [ + "${data_service_path}/adapter/account:distributeddata_account", + "${data_service_path}/adapter/communicator:distributeddata_communicator", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service/backup:distributeddata_backup", + "${data_service_path}/service/kvdb:distributeddata_kvdb", + ] +} + ############################################################################### group("unittest") { testonly = true @@ -1782,6 +1836,7 @@ group("unittest") { if (datamgr_service_kvdb) { deps += [ ":AuthDelegateMockTest", + ":BackupManagerServiceTest", ":KVDBGeneralStoreAbnormalTest", ":KVDBGeneralStoreTest", ":KvdbServiceImplTest", diff --git a/services/distributeddataservice/service/test/backup_manager_service_test.cpp b/services/distributeddataservice/service/test/backup_manager_service_test.cpp new file mode 100644 index 000000000..4a5a77664 --- /dev/null +++ b/services/distributeddataservice/service/test/backup_manager_service_test.cpp @@ -0,0 +1,326 @@ +/* +* 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 "BackupManagerServiceTest" + +#include +#include +#include +#include "backup_manager.h" +#include "backuprule/backup_rule_manager.h" +#include "bootstrap.h" +#include "crypto_manager.h" +#include "device_manager_adapter.h" +#include "directory/directory_manager.h" +#include "log_print.h" +#include "metadata/meta_data_manager.h" +#include "kvstore_meta_manager.h" +#include "types.h" + +using namespace testing::ext; +using namespace std; +using namespace OHOS::DistributedData; +namespace OHOS::Test { +namespace DistributedDataTest { +static constexpr uint32_t SKEY_SIZE = 32; +static constexpr int MICROSEC_TO_SEC_TEST = 1000; +static constexpr const char *TEST_BACKUP_BUNDLE = "test_backup_bundleName"; +static constexpr const char *TEST_BACKUP_STOREID = "test_backup_storeId"; +class BackupManagerServiceTest : public testing::Test { +public: + class TestRule : public BackupRuleManager::BackupRule { + public: + TestRule() + { + BackupRuleManager::GetInstance().RegisterPlugin("TestRule", [this]() -> auto { + return this; + }); + } + bool CanBackup() override + { + return false; + } + }; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static std::vector Random(uint32_t len); + void InitMetaData(); + StoreMetaData metaData_; +}; + +void BackupManagerServiceTest::SetUpTestCase(void) +{ + auto executors = std::make_shared(1, 0); + Bootstrap::GetInstance().LoadComponents(); + Bootstrap::GetInstance().LoadDirectory(); + Bootstrap::GetInstance().LoadCheckers(); + DeviceManagerAdapter::GetInstance().Init(executors); + DistributedKv::KvStoreMetaManager::GetInstance().BindExecutor(executors); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaParameter(); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaListener(); +} + +void BackupManagerServiceTest::TearDownTestCase() +{ +} + +void BackupManagerServiceTest::SetUp() +{ +} + +void BackupManagerServiceTest::TearDown() +{ +} + +void BackupManagerServiceTest::InitMetaData() +{ + metaData_.deviceId = DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid; + metaData_.bundleName = TEST_BACKUP_BUNDLE; + metaData_.appId = TEST_BACKUP_BUNDLE; + metaData_.user = "0"; + metaData_.area = OHOS::DistributedKv::EL1; + metaData_.instanceId = 0; + metaData_.isAutoSync = true; + metaData_.storeType = DistributedKv::KvStoreType::SINGLE_VERSION; + metaData_.storeId = TEST_BACKUP_STOREID; + metaData_.dataDir = "/data/service/el1/public/database/" + std::string(TEST_BACKUP_BUNDLE) + "/kvdb"; + metaData_.securityLevel = OHOS::DistributedKv::SecurityLevel::S2; +} + +std::vector BackupManagerServiceTest::Random(uint32_t len) +{ + std::random_device randomDevice; + std::uniform_int_distribution distribution(0, std::numeric_limits::max()); + std::vector key(len); + for (uint32_t i = 0; i < len; i++) { + key[i] = static_cast(distribution(randomDevice)); + } + return key; +} + +/** +* @tc.name: Init +* @tc.desc: Init testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, Init, TestSize.Level1) +{ + BackupManagerServiceTest::InitMetaData(); + StoreMetaData meta1; + meta1 = metaData_; + meta1.isBackup = false; + meta1.isDirty = false; + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta1, true)); + EXPECT_NO_FATAL_FAILURE(BackupManager::GetInstance().Init()); + + StoreMetaData meta2; + meta2 = metaData_; + meta2.isBackup = true; + meta2.isDirty = false; + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta2, true)); + EXPECT_NO_FATAL_FAILURE(BackupManager::GetInstance().Init()); + + StoreMetaData meta3; + meta3 = metaData_; + meta3.isBackup = false; + meta3.isDirty = true; + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta3, true)); + EXPECT_NO_FATAL_FAILURE(BackupManager::GetInstance().Init()); + + StoreMetaData meta4; + meta4 = metaData_; + meta4.isBackup = true; + meta4.isDirty = true; + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta4, true)); + EXPECT_NO_FATAL_FAILURE(BackupManager::GetInstance().Init()); +} + +/** +* @tc.name: RegisterExporter +* @tc.desc: RegisterExporter testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, RegisterExporter, TestSize.Level1) +{ + int32_t type = DistributedKv::KvStoreType::DEVICE_COLLABORATION; + BackupManager::Exporter exporter = + [](const StoreMetaData &meta, const std::string &backupPath, bool &result) + { result = true; }; + BackupManager instance; + EXPECT_NO_FATAL_FAILURE(instance.RegisterExporter(type, exporter)); + EXPECT_FALSE(instance.exporters_[type] == nullptr); + EXPECT_NO_FATAL_FAILURE(instance.RegisterExporter(type, exporter)); +} + +/** +* @tc.name: BackSchedule +* @tc.desc: BackSchedule testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, BackSchedule, TestSize.Level1) +{ + std::shared_ptr executors = std::make_shared(0, 1); + BackupManager instance; + instance.executors_ = nullptr; + EXPECT_NO_FATAL_FAILURE(instance.BackSchedule(executors)); +} + +/** +* @tc.name: CanBackup001 +* @tc.desc: CanBackup testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, CanBackup001, TestSize.Level1) +{ + BackupManager instance; + instance.backupSuccessTime_ = 0; + instance.backupInternal_ = 0; + bool status = instance.CanBackup(); // false false + EXPECT_TRUE(status); + + instance.backupInternal_ = MICROSEC_TO_SEC_TEST; + status = instance.CanBackup(); // true false + EXPECT_TRUE(status); + + instance.backupSuccessTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + instance.backupInternal_ = 0; + status = instance.CanBackup(); // false true + EXPECT_TRUE(status); + + instance.backupSuccessTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + instance.backupInternal_ = MICROSEC_TO_SEC_TEST; + status = instance.CanBackup(); // true true + EXPECT_FALSE(status); +} + +/** +* @tc.name: CanBackup +* @tc.desc: CanBackup testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, CanBackup, TestSize.Level1) +{ + BackupManagerServiceTest::TestRule(); + std::vector rule = { "TestRule" }; + BackupRuleManager::GetInstance().LoadBackupRules(rule); + ASSERT_FALSE(BackupRuleManager::GetInstance().CanBackup()); + bool status = BackupManager::GetInstance().CanBackup(); + EXPECT_FALSE(status); +} + +/** +* @tc.name: SaveData +* @tc.desc: SaveData testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, SaveData, TestSize.Level1) +{ + std::string path = "test"; + std::string key = "test"; + std::vector randomKey = BackupManagerServiceTest::Random(SKEY_SIZE); + SecretKeyMetaData secretKey; + secretKey.storeType = DistributedKv::KvStoreType::SINGLE_VERSION; + secretKey.sKey = randomKey; + EXPECT_EQ(secretKey.sKey.size(), SKEY_SIZE); + EXPECT_NO_FATAL_FAILURE(BackupManager::GetInstance().SaveData(path, key, secretKey)); + randomKey.assign(randomKey.size(), 0); +} + +/** +* @tc.name: GetClearType001 +* @tc.desc: GetClearType testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, GetClearType001, TestSize.Level1) +{ + StoreMetaData meta; + MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), metaData_, true); + BackupManager::ClearType status = BackupManager::GetInstance().GetClearType(meta); + EXPECT_EQ(status, BackupManager::ClearType::DO_NOTHING); +} + +/** +* @tc.name: GetClearType002 +* @tc.desc: GetClearType testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, GetClearType002, TestSize.Level1) +{ + BackupManagerServiceTest::InitMetaData(); + StoreMetaData meta; + meta = metaData_; + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(meta.GetSecretKey(), meta, true)); + + SecretKeyMetaData dbPassword; + EXPECT_TRUE(MetaDataManager::GetInstance().LoadMeta(meta.GetSecretKey(), dbPassword, true)); + SecretKeyMetaData backupPassword; + EXPECT_FALSE(MetaDataManager::GetInstance().LoadMeta(meta.GetBackupSecretKey(), backupPassword, true)); + EXPECT_FALSE(dbPassword.sKey != backupPassword.sKey); + BackupManager::ClearType status = BackupManager::GetInstance().GetClearType(meta); + EXPECT_EQ(status, BackupManager::ClearType::DO_NOTHING); +} + +/** +* @tc.name: GetPassWord +* @tc.desc: GetPassWord testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, GetPassWord, TestSize.Level1) +{ + StoreMetaData meta; + std::vector password; + bool status = BackupManager::GetInstance().GetPassWord(meta, password); + EXPECT_FALSE(status); +} + +/** +* @tc.name: IsFileExist +* @tc.desc: IsFileExist testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, IsFileExist, TestSize.Level1) +{ + std::string path; + bool status = BackupManager::GetInstance().IsFileExist(path); + EXPECT_FALSE(status); +} +} // namespace DistributedDataTest +} // namespace OHOS::Test \ No newline at end of file -- Gitee From 3d9e6f341e2a8097fd50de06f4c89260a15a6da3 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Tue, 18 Mar 2025 08:22:36 +0000 Subject: [PATCH 033/225] add BackupManagerServiceTest case-0318 Signed-off-by: suoqilong --- services/distributeddataservice/service/test/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 6f0a74f9e..4d16dc1f1 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -1771,6 +1771,7 @@ ohos_unittest("BackupManagerServiceTest") { "device_manager:devicemanagersdk", "googletest:gtest_main", "hilog:libhilog", + "hisysevent:libhisysevent", "ipc:ipc_core", "kv_store:distributeddata_inner", "kv_store:distributeddata_mgr", -- Gitee From d457052e2bf2f37da2c0a2806cf31658f0c69f25 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Tue, 18 Mar 2025 10:16:56 +0000 Subject: [PATCH 034/225] add BackupManagerServiceTest case-0318 Signed-off-by: suoqilong --- .../service/test/backup_manager_service_test.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/service/test/backup_manager_service_test.cpp b/services/distributeddataservice/service/test/backup_manager_service_test.cpp index 4a5a77664..82a953bee 100644 --- a/services/distributeddataservice/service/test/backup_manager_service_test.cpp +++ b/services/distributeddataservice/service/test/backup_manager_service_test.cpp @@ -127,7 +127,7 @@ HWTEST_F(BackupManagerServiceTest, Init, TestSize.Level1) meta1.isDirty = false; EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta1, true)); - EXPECT_NO_FATAL_FAILURE(BackupManager::GetInstance().Init()); + BackupManager::GetInstance().Init(); StoreMetaData meta2; meta2 = metaData_; @@ -135,7 +135,7 @@ HWTEST_F(BackupManagerServiceTest, Init, TestSize.Level1) meta2.isDirty = false; EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta2, true)); - EXPECT_NO_FATAL_FAILURE(BackupManager::GetInstance().Init()); + BackupManager::GetInstance().Init(); StoreMetaData meta3; meta3 = metaData_; @@ -143,7 +143,7 @@ HWTEST_F(BackupManagerServiceTest, Init, TestSize.Level1) meta3.isDirty = true; EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta3, true)); - EXPECT_NO_FATAL_FAILURE(BackupManager::GetInstance().Init()); + BackupManager::GetInstance().Init(); StoreMetaData meta4; meta4 = metaData_; @@ -151,7 +151,7 @@ HWTEST_F(BackupManagerServiceTest, Init, TestSize.Level1) meta4.isDirty = true; EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta4, true)); - EXPECT_NO_FATAL_FAILURE(BackupManager::GetInstance().Init()); + BackupManager::GetInstance().Init(); } /** -- Gitee From ae4f584f46e407f682989640ed909fefc85506f5 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Tue, 18 Mar 2025 11:33:51 +0000 Subject: [PATCH 035/225] add BackupManagerServiceTest case-0318 Signed-off-by: suoqilong --- .../service/test/backup_manager_service_test.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/services/distributeddataservice/service/test/backup_manager_service_test.cpp b/services/distributeddataservice/service/test/backup_manager_service_test.cpp index 82a953bee..56a0f27e1 100644 --- a/services/distributeddataservice/service/test/backup_manager_service_test.cpp +++ b/services/distributeddataservice/service/test/backup_manager_service_test.cpp @@ -168,9 +168,9 @@ HWTEST_F(BackupManagerServiceTest, RegisterExporter, TestSize.Level1) [](const StoreMetaData &meta, const std::string &backupPath, bool &result) { result = true; }; BackupManager instance; - EXPECT_NO_FATAL_FAILURE(instance.RegisterExporter(type, exporter)); + instance.RegisterExporter(type, exporter); EXPECT_FALSE(instance.exporters_[type] == nullptr); - EXPECT_NO_FATAL_FAILURE(instance.RegisterExporter(type, exporter)); + instance.RegisterExporter(type, exporter); } /** @@ -185,7 +185,8 @@ HWTEST_F(BackupManagerServiceTest, BackSchedule, TestSize.Level1) std::shared_ptr executors = std::make_shared(0, 1); BackupManager instance; instance.executors_ = nullptr; - EXPECT_NO_FATAL_FAILURE(instance.BackSchedule(executors)); + instance.BackSchedule(executors); + EXPECT_FALSE(instance.executors_ == nullptr); } /** @@ -230,7 +231,7 @@ HWTEST_F(BackupManagerServiceTest, CanBackup, TestSize.Level1) BackupManagerServiceTest::TestRule(); std::vector rule = { "TestRule" }; BackupRuleManager::GetInstance().LoadBackupRules(rule); - ASSERT_FALSE(BackupRuleManager::GetInstance().CanBackup()); + EXPECT_FALSE(BackupRuleManager::GetInstance().CanBackup()); bool status = BackupManager::GetInstance().CanBackup(); EXPECT_FALSE(status); } @@ -251,7 +252,8 @@ HWTEST_F(BackupManagerServiceTest, SaveData, TestSize.Level1) secretKey.storeType = DistributedKv::KvStoreType::SINGLE_VERSION; secretKey.sKey = randomKey; EXPECT_EQ(secretKey.sKey.size(), SKEY_SIZE); - EXPECT_NO_FATAL_FAILURE(BackupManager::GetInstance().SaveData(path, key, secretKey)); + BackupManager::GetInstance().SaveData(path, key, secretKey); + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(key, secretKey, true)); randomKey.assign(randomKey.size(), 0); } -- Gitee From 261b41c607f9f422df332142fd8f1456af8616dd Mon Sep 17 00:00:00 2001 From: wangbin Date: Wed, 19 Mar 2025 10:08:46 +0800 Subject: [PATCH 036/225] fix Signed-off-by: wangbin --- .../softbus_adapter_standard_test.cpp | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp index 6a434da15..44d3f97e5 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp @@ -78,6 +78,7 @@ void SoftbusAdapterStandardTest::TearDownTestCase() */ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange, TestSize.Level0) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(nullptr, {}); EXPECT_EQ(status, Status::INVALID_ARGUMENT); } @@ -91,6 +92,7 @@ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange, TestSize.Level0) */ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange01, TestSize.Level0) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo appId; appId.pipeId = "appId"; appId.userId = "groupId"; @@ -111,6 +113,7 @@ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange01, TestSize.Level0) */ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange02, TestSize.Level0) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo appId; appId.pipeId = ""; appId.userId = "groupId"; @@ -169,6 +172,7 @@ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange, TestSize.Level0) */ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange01, TestSize.Level0) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo appId; appId.pipeId = ""; appId.userId = "groupId"; @@ -187,11 +191,12 @@ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange01, TestSize.Level0) */ HWTEST_F(SoftbusAdapterStandardTest, GetExpireTime, TestSize.Level0) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo appId; appId.pipeId = "appId"; appId.userId = "groupId"; - DeviceId di = {"DeviceId"}; - std::shared_ptr conn = std::make_shared(appId, di, SoftBusClient::QoSType::QOS_HML); + DeviceId id = {"DeviceId"}; + std::shared_ptr conn = std::make_shared(appId, id, SoftBusClient::QoSType::QOS_HML); EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->GetExpireTime(conn)); } @@ -203,6 +208,7 @@ HWTEST_F(SoftbusAdapterStandardTest, GetExpireTime, TestSize.Level0) */ HWTEST_F(SoftbusAdapterStandardTest, SendData, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); PipeInfo id; id.pipeId = "appId"; @@ -254,6 +260,7 @@ HWTEST_F(SoftbusAdapterStandardTest, SendData01, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, StartCloseSessionTask, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); std::shared_ptr conn = nullptr; std::vector> clients; clients.emplace_back(conn); @@ -271,11 +278,12 @@ HWTEST_F(SoftbusAdapterStandardTest, StartCloseSessionTask, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, OnClientShutdown, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo appId; appId.pipeId = "appId"; appId.userId = "groupId"; - DeviceId di = {"DeviceId"}; - std::shared_ptr conn1 = std::make_shared(appId, di, SoftBusClient::QoSType::QOS_HML); + DeviceId id = {"DeviceId"}; + std::shared_ptr conn1 = std::make_shared(appId, id, SoftBusClient::QoSType::QOS_HML); std::shared_ptr conn2 = nullptr; std::vector> clients; clients.emplace_back(conn1); @@ -301,6 +309,7 @@ HWTEST_F(SoftbusAdapterStandardTest, OnClientShutdown, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, NotifyDataListeners, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo appId; appId.pipeId = "appId"; appId.userId = "groupId"; @@ -323,6 +332,7 @@ HWTEST_F(SoftbusAdapterStandardTest, NotifyDataListeners, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, ListenBroadcastMsg, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); SoftBusAdapter::GetInstance()->onBroadcast_= nullptr; PipeInfo appId; appId.pipeId = "appId"; @@ -345,16 +355,17 @@ HWTEST_F(SoftbusAdapterStandardTest, ListenBroadcastMsg, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, OnBroadcast, TestSize.Level1) { - DeviceId di = {"DeviceId"}; + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); + DeviceId id = {"DeviceId"}; LevelInfo level; level.dynamic = 1; level.statics = 1; level.switches = 1; level.switchesLen = 1; EXPECT_NE(SoftBusAdapter::GetInstance()->onBroadcast_, nullptr); - EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(di, level)); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(id, level)); SoftBusAdapter::GetInstance()->onBroadcast_ = nullptr; - EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(di, level)); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(id, level)); } /** @@ -384,6 +395,7 @@ HWTEST_F(SoftbusAdapterStandardTest, OnClientSocketChanged, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, OnServerBytesReceived, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PeerSocketInfo info; info.name = strdup(""); info.networkId = strdup("peertest01"); @@ -430,6 +442,7 @@ HWTEST_F(SoftbusAdapterStandardTest, GetPipeId, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, GetMtuSize, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); PipeInfo id; id.pipeId = "appId"; @@ -451,6 +464,7 @@ HWTEST_F(SoftbusAdapterStandardTest, GetMtuSize, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, GetTimeout, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); PipeInfo id; id.pipeId = "appId01"; @@ -471,6 +485,7 @@ HWTEST_F(SoftbusAdapterStandardTest, GetTimeout, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, IsSameStartedOnPeer, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo id; id.pipeId = "appId01"; id.userId = "groupId01"; @@ -510,6 +525,7 @@ HWTEST_F(SoftbusAdapterStandardTest, ReuseConnect, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, ReuseConnect01, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo pipe; pipe.pipeId = "appId"; pipe.userId = "groupId"; -- Gitee From af84cdff58dfafd091b26a7ac97f772a1c24f403 Mon Sep 17 00:00:00 2001 From: yangliu Date: Wed, 19 Mar 2025 10:25:58 +0800 Subject: [PATCH 037/225] update Signed-off-by: yangliu --- .../app/src/kvstore_meta_manager.cpp | 291 ++++++++---------- .../app/src/kvstore_meta_manager.h | 26 +- .../distributeddataservice/framework/BUILD.gn | 2 +- .../metadata/deviceid_pair_meta_data.h | 7 +- .../include/metadata/meta_data_manager.h | 1 - .../framework/include/utils/constant.h | 3 + .../framework/metadata/meta_data_manager.cpp | 28 -- .../framework/test/meta_data_test.cpp | 3 +- .../framework/utils/constant.cpp | 12 + .../service/kvdb/kvdb_service_impl.cpp | 1 - .../service/kvdb/upgrade.cpp | 37 +-- .../service/kvdb/upgrade.h | 1 - 12 files changed, 185 insertions(+), 227 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 647ae59ce..e23fc9f6f 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -33,8 +33,16 @@ #include "kv_radar_reporter.h" #include "log_print.h" #include "matrix_event.h" +#include "metadata/auto_launch_meta_data.h" +#include "metadata/capability_meta_data.h" +#include "metadata/deviceid_pair_meta_data.h" #include "metadata/meta_data_manager.h" +#include "metadata/matrix_meta_data.h" +#include "metadata/strategy_meta_data.h" #include "metadata/store_meta_data_local.h" +#include "metadata/stratery_meta_data.h" +#include "metadata/switches_meta_data.h" +#include "metadata/user_meta_data.h" #include "metadata/version_meta_data.h" #include "runtime_config.h" #include "safe_block_queue.h" @@ -46,12 +54,7 @@ #include "utils/crypto.h" #include "utils/ref_count.h" #include "utils/converter.h" -#include "metadata/matrix_meta_data.h" -#include "metadata/switches_meta_data.h" #include "utils/constant.h" -#include "metadata/user_meta_data.h" -#include "metadata/deviceid_pair_meta_data.h" -#include "metadata/strategy_meta_data.h" namespace OHOS { namespace DistributedKv { @@ -61,8 +64,8 @@ using namespace std::chrono; using namespace OHOS::DistributedData; using namespace DistributedDB; using namespace OHOS::AppDistributedKv; -constexpr const int UUID_LOC = 1; -constexpr const int MIN_SIZE = 1; +constexpr const int UUID_LOCATION = 1; +constexpr const int SPLITE_MIN_SIZE = 1; KvStoreMetaManager::MetaDeviceChangeListenerImpl KvStoreMetaManager::listener_; KvStoreMetaManager::DBInfoDeviceChangeListenerImpl KvStoreMetaManager::dbInfoListener_; @@ -141,11 +144,12 @@ void KvStoreMetaManager::InitMetaData() ZLOGI("get meta failed."); return; } - - CheckDeviceIDChanged(); + auto uuid = DmAdapter::GetInstance().GetLocalDevice().uuid; + if (IsMetaDeviceIdChanged(uuid)) { + UpdateMetaDeviceId(uuid); + } auto uid = getuid(); auto tokenId = IPCSkeleton::GetCallingTokenID(); - const std::string accountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); auto userId = AccountDelegate::GetInstance()->GetUserByToken(tokenId); StoreMetaData data; data.appId = label_; @@ -162,7 +166,7 @@ void KvStoreMetaManager::InitMetaData() data.dataType = DataType::TYPE_DYNAMICAL; data.schema = ""; data.storeId = Bootstrap::GetInstance().GetMetaDBName(); - data.account = accountId; + data.account = AccountDelegate::GetInstance()->GetCurrentAccountId(); data.uid = static_cast(uid); data.version = META_STORE_VERSION; data.securityLevel = SecurityLevel::S1; @@ -185,14 +189,6 @@ void KvStoreMetaManager::InitMetaData() ZLOGI("end."); } -void KvStoreMetaManager::CheckDeviceIDChanged() -{ - if (IsMetaDeviceIdChanged()) { - UpdateLocalMetaDeviceId(); - UpdateSyncMetaDeviceId(); - } -} - void KvStoreMetaManager::UpdateMetaData() { VersionMetaData versionMeta; @@ -572,176 +568,155 @@ AppDistributedKv::ChangeLevelType KvStoreMetaManager::DBInfoDeviceChangeListener return AppDistributedKv::ChangeLevelType::MIN; } -std::string KvStoreMetaManager::vectorToString(const std::vector &vec, const std::string separator) -{ - std::string result; - std::for_each(vec.begin(), vec.end(), [&](const std::string &info) { - if (!result.empty()) { - result += separator; - } - result += info; - }); - return result; -} - -bool KvStoreMetaManager::IsMetaDeviceIdChanged() +bool KvStoreMetaManager::IsMetaDeviceIdChanged(const std::string &localUUID) { DeviceIDMetaData meta; - auto localUUID = DmAdapter::GetInstance().GetLocalDevice().uuid; - if (!MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true)) { + if (localUUID.empty()) { + ZLOGW("get uuid failed"); + return false; + } + if (!MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true)) {\ meta.currentUUID = localUUID; MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); } else { - std::string currentUUID = localUUID; - if (!currentUUID.empty() && meta.currentUUID != currentUUID) { + if (meta.currentUUID != localUUID) { meta.oldUUID = meta.currentUUID; oldUUID_ = meta.currentUUID; - meta.currentUUID = currentUUID; + meta.currentUUID = localUUID; MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); ZLOGI("uuid changed! curruuid:%{public}s, olduuid:%{public}s, cache:%{public}s", - meta.currentUUID.c_str(), meta.oldUUID.c_str(), oldUUID_.c_str()); + Anonymous::Change(meta.currentUUID).c_str(), Anonymous::Change(meta.oldUUID).c_str(), + Anonymous::Change(oldUUID_).c_str()); return true; } } return false; } -void KvStoreMetaManager::UpdateLocalMetaDeviceId() +void KvStoreMetaManager::UpdateMetaDeviceId(const std::string ¤tUUID) { - std::vector localStoreMetas; - auto currentUuid = DmAdapter::GetInstance().GetLocalDevice().uuid; - MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({}), localStoreMetas, true); - for (auto &localStoreMeta : localStoreMetas) { - StoreMetaData oldMeta = localStoreMeta; - localStoreMeta.deviceId = currentUuid; - localStoreMeta.isNeedUpdateDeviceId = true; - MetaDataManager::GetInstance().SaveMeta(localStoreMeta.GetKey(), localStoreMeta, true); - MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey(), true); - } + UpdateStoreMetaData(currentUUID); + UpdateMatrixMetaData(currentUUID); + UpdateUserMetaData(currentUUID); + UpdateCapMetaData(currentUUID); + UpdateStrategyMetaData(currentUUID); - std::vector localMatrixMetas; - MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({}), localMatrixMetas, true); - for (auto &localMatrixMeta : localMatrixMetas) { - if (localMatrixMeta.deviceId != oldUUID_) { - continue; + UpdateStoreMetaData(currentUUID, true); + UpdateMatrixMetaData(currentUUID, true); + UpdateSwitchesMetaData(currentUUID, true); + UpdateLocalMetaData(currentUUID, true); + UpdateAutoLaunchMetaData(currentUUID, true); +} + +void KvStoreMetaManager::UpdateStoreMetaData(const std::string ¤tUUID, bool isLocal) +{ + std::vector storeMetas; + MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({oldUUID_}), storeMetas, isLocal); + for (auto &storeMeta : storeMetas) { + if (isLocal) { + storeMeta.isNeedUpdateDeviceId = true; } - MatrixMetaData oldMeta = localMatrixMeta; - localMatrixMeta.deviceId = currentUuid; - MetaDataManager::GetInstance().SaveMeta(localMatrixMeta.GetKey(), localMatrixMeta, true); - MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey(), true); + MetaDataManager::GetInstance().DelMeta(storeMeta.GetKey(), isLocal); + storeMeta.deviceId = currentUUID; + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), storeMeta, isLocal); } +} - std::vector localSwitchesMetaDatas; - MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({}), localSwitchesMetaDatas, true); - for (auto &localSwitchesMetaData : localSwitchesMetaDatas) { - if (localSwitchesMetaData.deviceId != oldUUID_) { - continue; - } - SwitchesMetaData oldMeta = localSwitchesMetaData; - localSwitchesMetaData.deviceId = currentUuid; - MetaDataManager::GetInstance().SaveMeta(localSwitchesMetaData.GetKey(), localSwitchesMetaData, true); - MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey(), true); - } - - std::string prefix = "AutoLaunchMetaData"; - std::vector localAutoLaunchMetaDatas; - MetaDataManager::GetInstance().LoadMetaPair(prefix, localAutoLaunchMetaDatas, true); - for (const auto &localautoLaunchMetaData : localAutoLaunchMetaDatas) { - std::string metaKey(localautoLaunchMetaData.key.begin(), localautoLaunchMetaData.key.end()); - std::string value(localautoLaunchMetaData.value.begin(), localautoLaunchMetaData.value.end()); - auto tokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); - if (tokens.size() > MIN_SIZE) { - tokens[UUID_LOC] = currentUuid; - } - auto newKey = vectorToString(tokens); - MetaDataManager::GetInstance().SaveMeta(newKey, value, true); - MetaDataManager::GetInstance().DelMeta(metaKey, true); - } - - prefix = "KvStoreMetaDataLocal"; - std::vector kvStoreMetaDataLocals; - MetaDataManager::GetInstance().LoadMetaPair(prefix, kvStoreMetaDataLocals, true); - for (const auto &kvStoreMetaDataLocal : kvStoreMetaDataLocals) { - std::string metaKey(kvStoreMetaDataLocal.key.begin(), kvStoreMetaDataLocal.key.end()); - std::string value(kvStoreMetaDataLocal.value.begin(), kvStoreMetaDataLocal.value.end()); - auto tokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); - if (tokens.size() > MIN_SIZE) { - tokens[UUID_LOC] = currentUuid; +void KvStoreMetaManager::UpdateLocalMetaData(const std::string ¤tUUID, bool isLocal) +{ + std::vector localMetaDatas; + MetaDataManager::GetInstance().LoadMetaPair("KvStoreMetaDataLocal", localMetaDatas, isLocal); + for (const auto &localMetaData : localMetaDatas) { + StoreMetaDataLocal storeMetaDataLocal; + std::string metaKey(localMetaData.key.begin(), localMetaData.key.end()); + Serializable::Unmarshall({ localMetaData.value.begin(), localMetaData.value.end() }, storeMetaDataLocal); + auto spliteTokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); + if (spliteTokens.size() > SPLITE_MIN_SIZE) { + spliteTokens[UUID_LOCATION] = currentUUID; } - auto newKey = vectorToString(tokens); - MetaDataManager::GetInstance().SaveMeta(newKey, value, true); - MetaDataManager::GetInstance().DelMeta(metaKey, true); + auto newKey = Constant::vectorToString(spliteTokens); + MetaDataManager::GetInstance().SaveMeta(newKey, storeMetaDataLocal, isLocal); + MetaDataManager::GetInstance().DelMeta(metaKey, isLocal); } } -void KvStoreMetaManager::UpdateSyncMetaDeviceId() +void KvStoreMetaManager::UpdateAutoLaunchMetaData(const std::string ¤tUUID, bool isLocal) { - std::vector syncStoreMetas; - auto currentUuid = DmAdapter::GetInstance().GetLocalDevice().uuid; - MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({}), syncStoreMetas); - for (auto &syncStoreMeta : syncStoreMetas) { - if (syncStoreMeta.deviceId != oldUUID_) { - continue; - } - StoreMetaData oldMeta = syncStoreMeta; - syncStoreMeta.deviceId = currentUuid; - MetaDataManager::GetInstance().SaveMeta(syncStoreMeta.GetKey(), syncStoreMeta); - MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); - } - - std::string prefix = "CapabilityMeta"; - std::vector syncCapabilityMetas; - MetaDataManager::GetInstance().LoadMetaPair(prefix, syncCapabilityMetas); - for (const auto &syncCapabilityMeta : syncCapabilityMetas) { - std::string metaKey(syncCapabilityMeta.key.begin(), syncCapabilityMeta.key.end()); - std::string value(syncCapabilityMeta.value.begin(), syncCapabilityMeta.value.end()); - auto tokens = Constant::Split(metaKey, Constant::KEY_SEPARATOR); - if (tokens.size() <= MIN_SIZE || tokens[1] != oldUUID_) { - continue; + std::vector autoLaunchMetaDatas; + MetaDataManager::GetInstance().LoadMetaPair("AutoLaunchMetaData", autoLaunchMetaDatas, isLocal); + for (const auto &metaData : autoLaunchMetaDatas) { + AutoLaunchMetaData autoLaunchMetaData; + std::string metaKey(metaData.key.begin(), metaData.key.end()); + Serializable::Unmarshall({ metaData.value.begin(), metaData.value.end() }, autoLaunchMetaData); + auto spliteTokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); + if (spliteTokens.size() > SPLITE_MIN_SIZE) { + spliteTokens[UUID_LOCATION] = currentUUID; } - tokens[UUID_LOC] = currentUuid; - auto newKey = vectorToString(tokens); - MetaDataManager::GetInstance().SaveMeta(newKey, value); - MetaDataManager::GetInstance().DelMeta(metaKey); + auto newKey = Constant::vectorToString(spliteTokens); + MetaDataManager::GetInstance().SaveMeta(newKey, autoLaunchMetaData, isLocal); + MetaDataManager::GetInstance().DelMeta(metaKey, isLocal); } +} - std::vector syncMatrixMetas; - MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({}), syncMatrixMetas); - for (auto &syncMatrixMeta : syncMatrixMetas) { - if (syncMatrixMeta.deviceId != oldUUID_) { - continue; - } - MatrixMetaData oldMeta = syncMatrixMeta; - syncMatrixMeta.deviceId = currentUuid; - MetaDataManager::GetInstance().SaveMeta(syncMatrixMeta.GetKey(), syncMatrixMeta); - MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); - } - - prefix = "StrategyMetaData"; - std::vector synctrategyMetas; - MetaDataManager::GetInstance().LoadMetaPair(prefix, synctrategyMetas); - for (const auto &synctrategyMeta : synctrategyMetas) { - std::string metaKey(synctrategyMeta.key.begin(), synctrategyMeta.key.end()); - std::string value(synctrategyMeta.value.begin(), synctrategyMeta.value.end()); - auto tokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); - if (tokens.size() <= MIN_SIZE || tokens[UUID_LOC] != oldUUID_) { - continue; +void KvStoreMetaManager::UpdateStrategyMetaData(const std::string ¤tUUID, bool isLocal) +{ + std::vector strategyMetaDatas; + MetaDataManager::GetInstance().LoadMetaPair("StrategyMetaData", strategyMetaDatas, isLocal); + for (const auto &metaData : strategyMetaDatas) { + StrategyMeta strategyMeta("", "", "", ""); + std::string metaKey(metaData.key.begin(), metaData.key.end()); + Serializable::Unmarshall({ metaData.value.begin(), metaData.value.end() }, strategyMeta); + auto spliteTokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); + if (spliteTokens.size() > SPLITE_MIN_SIZE) { + spliteTokens[UUID_LOCATION] = currentUUID; } - tokens[UUID_LOC] = currentUuid; - auto newKey = vectorToString(tokens); - MetaDataManager::GetInstance().SaveMeta(newKey, value); - MetaDataManager::GetInstance().DelMeta(metaKey); + auto newKey = Constant::vectorToString(spliteTokens); + MetaDataManager::GetInstance().SaveMeta(newKey, strategyMeta, isLocal); + MetaDataManager::GetInstance().DelMeta(metaKey, isLocal); } +} - std::vector syncUserMetas; - MetaDataManager::GetInstance().LoadMeta(UserMetaRow::GetKeyFor(""), syncUserMetas); - for (auto &syncUserMeta : syncUserMetas) { - if (syncUserMeta.deviceId != oldUUID_) { - continue; - } - syncUserMeta.deviceId = currentUuid; - MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor(currentUuid), syncUserMeta); - MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor(oldUUID_)); +void KvStoreMetaManager::UpdateMatrixMetaData(const std::string ¤tUUID, bool isLocal) +{ + MatrixMetaData matrixMetas; + bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({oldUUID_}), matrixMetas, isLocal); + if (isExist) { + MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({oldUUID_}), isLocal); + MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({currentUUID}), matrixMetas, isLocal); + } +} + +void KvStoreMetaManager::UpdateSwitchesMetaData(const std::string ¤tUUID, bool isLocal) +{ + SwitchesMetaData switchesMetaData; + bool isExist = MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({oldUUID_}), + switchesMetaData, isLocal); + if (isExist) { + MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({oldUUID_}), isLocal); + MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({currentUUID}), switchesMetaData, isLocal); + } +} + +void KvStoreMetaManager::UpdateUserMetaData(const std::string ¤tUUID, bool isLocal) +{ + UserMetaData userMetas; + bool isExist = MetaDataManager::GetInstance().LoadMeta(UserMetaRow::GetKeyFor(oldUUID_), userMetas, isLocal); + if (isExist) { + MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor(oldUUID_), isLocal); + MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor(currentUUID), userMetas, isLocal); + } +} + +void KvStoreMetaManager::UpdateCapMetaData(const std::string ¤tUUID, bool isLocal) +{ + CapMetaData capMetaData; + auto capKey = CapMetaRow::GetKeyFor(oldUUID_); + bool isExist = MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), + capMetaData, isLocal); + if (isExist) { + auto newCapKey = CapMetaRow::GetKeyFor(currentUUID); + MetaDataManager::GetInstance().DelMeta(std::string(capKey.begin(), capKey.end()), isLocal); + MetaDataManager::GetInstance().SaveMeta(std::string(newCapKey.begin(), newCapKey.end()), capMetaData, isLocal); } } } // namespace DistributedKv diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index 4b0e3d360..ce3267fc9 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -95,16 +95,26 @@ private: ExecutorPool::Task GetTask(uint32_t retry); DistributedDB::KvStoreNbDelegate::Option InitDBOption(); + + void UpdateMetaDeviceId(const std::string ¤tUUID); - std::string vectorToString(const std::vector &vec, const std::string separator = "###"); - - void UpdateSyncMetaDeviceId(); - - void UpdateLocalMetaDeviceId(); - - bool IsMetaDeviceIdChanged(); + bool IsMetaDeviceIdChanged(const std::string ¤tUUID); + + void UpdateStoreMetaData(const std::string ¤tUUID, bool isLocal = false); + + void UpdateLocalMetaData(const std::string ¤tUUID, bool isLocal = false); + + void UpdateAutoLaunchMetaData(const std::string ¤tUUID, bool isLocal = false); + + void UpdateStrategyMetaData(const std::string ¤tUUID, bool isLocal = false); + + void UpdateMatrixMetaData(const std::string ¤tUUID, bool isLocal = false); + + void UpdateSwitchesMetaData(const std::string ¤tUUID, bool isLocal = false); + + void UpdateUserMetaData(const std::string ¤tUUID, bool isLocal = false); - void CheckDeviceIDChanged(); + void UpdateCapMetaData(const std::string ¤tUUID, bool isLocal = false); static ExecutorPool::Task GetBackupTask( TaskQueue queue, std::shared_ptr executors, const NbDelegate store); diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index c528785aa..564140bf5 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -88,8 +88,8 @@ ohos_shared_library("distributeddatasvcfwk") { "metadata/capability_meta_data.cpp", "metadata/capability_range.cpp", "metadata/corrupted_meta_data.cpp", - "metadata/matrix_meta_data.cpp", "metadata/deviceid_pair_meta_data.cpp", + "metadata/matrix_meta_data.cpp", "metadata/meta_data.cpp", "metadata/meta_data_manager.cpp", "metadata/secret_key_meta_data.cpp", diff --git a/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h b/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h index 32a4e873a..581b3ece9 100644 --- a/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h @@ -21,17 +21,16 @@ namespace OHOS::DistributedData { class API_EXPORT DeviceIDMetaData final : public Serializable { public: - std::string currentUUID = ""; - std::string oldUUID = ""; - API_EXPORT DeviceIDMetaData(); API_EXPORT ~DeviceIDMetaData(); API_EXPORT bool Marshal(json &node) const override; API_EXPORT bool Unmarshal(const json &node) override; API_EXPORT std::string GetKey() const; + std::string currentUUID = ""; + std::string oldUUID = ""; private: - static constexpr const char *KEY_PREFIX = "DeviceIDKey"; + static constexpr const char *KEY_PREFIX = "DeviceIDMeta"; }; } // namespace OHOS::DistributedData #endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_APPID_META_DATA_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h index 7f631fff4..4eb76f0ee 100644 --- a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h +++ b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h @@ -85,7 +85,6 @@ public: API_EXPORT bool Sync(const std::vector &devices, OnComplete complete, bool wait = false); API_EXPORT bool LoadMetaPair(const std::string &prefix, std::vector &entries, bool isLocal = false); - API_EXPORT bool SaveMeta(const std::string &key, const std::string &value, bool isLocal = false); private: MetaDataManager(); ~MetaDataManager(); diff --git a/services/distributeddataservice/framework/include/utils/constant.h b/services/distributeddataservice/framework/include/utils/constant.h index b2c319b53..f98b8ceaf 100644 --- a/services/distributeddataservice/framework/include/utils/constant.h +++ b/services/distributeddataservice/framework/include/utils/constant.h @@ -45,6 +45,9 @@ public: API_EXPORT static std::vector Split(const std::string &str, const std::string &delim); API_EXPORT static std::vector SplitKeepSpace(const std::string &str, const std::string &delim); + + API_EXPORT static std::string vectorToString(const std::vector &vec, const std::string separator = "###"); + template inline static constexpr bool is_pod = (std::is_standard_layout_v && std::is_trivial_v); diff --git a/services/distributeddataservice/framework/metadata/meta_data_manager.cpp b/services/distributeddataservice/framework/metadata/meta_data_manager.cpp index b67b96f65..bb7641b7f 100644 --- a/services/distributeddataservice/framework/metadata/meta_data_manager.cpp +++ b/services/distributeddataservice/framework/metadata/meta_data_manager.cpp @@ -380,32 +380,4 @@ bool MetaDataManager::LoadMetaPair(const std::string &prefix, std::vector } return true; } - -bool MetaDataManager::SaveMeta(const std::string &key, const std::string &value, bool isLocal) -{ - if (!inited_) { - return false; - } - - auto status = isLocal ? metaStore_->PutLocal({ key.begin(), key.end() }, { value.begin(), value.end() }) - : metaStore_->Put({ key.begin(), key.end() }, { value.begin(), value.end() }); - if (status == DistributedDB::DBStatus::INVALID_PASSWD_OR_CORRUPTED_DB) { - ZLOGE("db corrupted! status:%{public}d isLocal:%{public}d, key:%{public}s", - status, isLocal, Anonymous::Change(key).c_str()); - CorruptReporter::CreateCorruptedFlag(DirectoryManager::GetInstance().GetMetaStorePath(), storeId_); - StopSA(); - return false; - } - if (status == DistributedDB::DBStatus::OK && backup_) { - backup_(metaStore_); - } - if (!isLocal && cloudSyncer_) { - cloudSyncer_(); - } - if (status != DistributedDB::DBStatus::OK) { - ZLOGE("failed! status:%{public}d isLocal:%{public}d, key:%{public}s", status, isLocal, - Anonymous::Change(key).c_str()); - } - return status == DistributedDB::DBStatus::OK; -} } // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 934f1d8a8..d770bed1e 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -847,7 +847,8 @@ HWTEST_F(ServiceMetaDataTest, LoadMatePair, TestSize.Level1) EXPECT_TRUE(result); EXPECT_EQ(entries.size(), 1); std::string key(entries[0].key.begin(), entries[0].key.end()); - std::string value(entries[0].value.begin(), entries[0].value.end()); + storeMetaData value; + Serializable::Unmarshall({ entries[0].value.begin(), entries[0].value.end() }, value); EXPECT_EQ(storeMetaData.GetKey(), key); auto tokens = Constant::SplitKeepSpace(key, Constant::KEY_SEPARATOR); diff --git a/services/distributeddataservice/framework/utils/constant.cpp b/services/distributeddataservice/framework/utils/constant.cpp index 084545743..93e84c1b4 100644 --- a/services/distributeddataservice/framework/utils/constant.cpp +++ b/services/distributeddataservice/framework/utils/constant.cpp @@ -89,6 +89,18 @@ std::vector Constant::SplitKeepSpace(const std::string &str, const return res; } +std::string Constant::vectorToString(const std::vector &vec, const std::string separator) +{ + std::string result; + std::for_each(vec.begin(), vec.end(), [&](const std::string &info) { + if (!result.empty()) { + result += separator; + } + result += info; + }); + return result; +} + bool Constant::Equal(bool first, bool second) { return (first && second) || (!first && !second); diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index 878c46597..87d7ba13f 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -740,7 +740,6 @@ Status KVDBServiceImpl::AfterCreate( auto isCreated = MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), oldMeta, true); Status status = SUCCESS; if (isCreated && oldMeta != metaData) { - Upgrade::GetInstance().UpdateDeviceId(oldMeta, metaData, password); auto dbStatus = Upgrade::GetInstance().UpdateStore(oldMeta, metaData, password); ZLOGI("update status:%{public}d appId:%{public}s storeId:%{public}s inst:%{public}d " "type:%{public}d->%{public}d dir:%{public}s dataType:%{public}d->%{public}d", diff --git a/services/distributeddataservice/service/kvdb/upgrade.cpp b/services/distributeddataservice/service/kvdb/upgrade.cpp index 094e34e21..654074066 100644 --- a/services/distributeddataservice/service/kvdb/upgrade.cpp +++ b/services/distributeddataservice/service/kvdb/upgrade.cpp @@ -40,7 +40,19 @@ Upgrade &Upgrade::GetInstance() Upgrade::DBStatus Upgrade::UpdateStore(const StoreMeta &old, const StoreMeta &meta, const std::vector &pwd) { - if (old.version < StoreMeta::UUID_CHANGED_TAG && old.storeType == DEVICE_COLLABORATION) { + if (old.isNeedUpdateDeviceId && !old.isEncrypt) { + auto store = GetDBStore(meta, pwd); + if (store == nullptr) { + ZLOGI("get store failed, appId:%{public}s storeId:%{public}s", old.appId.c_str(), + Anonymous::Change(old.storeId).c_str()); + return DBStatus::DB_ERROR; + } + store->OperateDataStatus(static_cast(DistributedDB::DataOperator::UPDATE_TIME) | + static_cast(DistributedDB::DataOperator::RESET_UPLOAD_CLOUD )); + } + + if ((old.version < StoreMeta::UUID_CHANGED_TAG || (old.isNeedUpdateDeviceId && !old.isEncrypt)) && + old.storeType == DEVICE_COLLABORATION) { auto upStatus = Upgrade::GetInstance().UpdateUuid(old, meta, pwd); if (upStatus != DBStatus::OK) { return DBStatus::DB_ERROR; @@ -70,29 +82,6 @@ Upgrade::DBStatus Upgrade::UpdateStore(const StoreMeta &old, const StoreMeta &me return DBStatus::OK; } -void Upgrade::UpdateDeviceId(const StoreMeta &oldMeta, const StoreMeta &meta, const std::vector &pwd) -{ - if (oldMeta.storeType < StoreMetaData::StoreType::STORE_KV_BEGIN || - oldMeta.storeType > StoreMetaData::StoreType::STORE_KV_END) { - return; - } - - if (oldMeta.isNeedUpdateDeviceId && !oldMeta.isEncrypt) { - auto store = GetDBStore(meta, pwd); - if (store == nullptr) { - ZLOGI("store is null appId:%{public}s storeId:%{public}s", oldMeta.appId.c_str(), - Anonymous::Change(oldMeta.storeId).c_str()); - return; - } - store->OperateDataStatus(static_cast(DistributedDB::DataOperator::UPDATE_TIME) | - static_cast(DistributedDB::DataOperator::RESET_UPLOAD_CLOUD)); - } - - if (oldMeta.isNeedUpdateDeviceId && oldMeta.storeType == DEVICE_COLLABORATION && !oldMeta.isEncrypt) { - Upgrade::GetInstance().UpdateUuid(oldMeta, meta, pwd); - } -} - Upgrade::DBStatus Upgrade::ExportStore(const StoreMeta &old, const StoreMeta &meta) { if (old.dataDir == meta.dataDir) { diff --git a/services/distributeddataservice/service/kvdb/upgrade.h b/services/distributeddataservice/service/kvdb/upgrade.h index d42788a7f..62458e235 100644 --- a/services/distributeddataservice/service/kvdb/upgrade.h +++ b/services/distributeddataservice/service/kvdb/upgrade.h @@ -42,7 +42,6 @@ public: DBStatus UpdateStore(const StoreMeta &old, const StoreMeta &meta, const std::vector &pwd); DBStatus ExportStore(const StoreMeta &old, const StoreMeta &meta); DBStatus UpdateUuid(const StoreMeta &old, const StoreMeta &meta, const std::vector &pwd); - void UpdateDeviceId(const StoreMeta &old, const StoreMeta &meta, const std::vector &pwd); API_EXPORT std::string GetEncryptedUuidByMeta(const StoreMeta &meta); private: -- Gitee From 14b34efc762be95b58aef8ee7cb46415c488aa91 Mon Sep 17 00:00:00 2001 From: yangliu Date: Wed, 19 Mar 2025 10:44:57 +0800 Subject: [PATCH 038/225] update Signed-off-by: yangliu --- .../app/src/kvstore_meta_manager.cpp | 31 +++++++------------ .../include/metadata/strategy_meta_data.h | 1 + 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index e23fc9f6f..8443ff73b 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -611,7 +611,7 @@ void KvStoreMetaManager::UpdateMetaDeviceId(const std::string ¤tUUID) void KvStoreMetaManager::UpdateStoreMetaData(const std::string ¤tUUID, bool isLocal) { std::vector storeMetas; - MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({oldUUID_}), storeMetas, isLocal); + MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ oldUUID_ }), storeMetas, isLocal); for (auto &storeMeta : storeMetas) { if (isLocal) { storeMeta.isNeedUpdateDeviceId = true; @@ -660,39 +660,32 @@ void KvStoreMetaManager::UpdateAutoLaunchMetaData(const std::string ¤tUUID void KvStoreMetaManager::UpdateStrategyMetaData(const std::string ¤tUUID, bool isLocal) { - std::vector strategyMetaDatas; - MetaDataManager::GetInstance().LoadMetaPair("StrategyMetaData", strategyMetaDatas, isLocal); - for (const auto &metaData : strategyMetaDatas) { - StrategyMeta strategyMeta("", "", "", ""); - std::string metaKey(metaData.key.begin(), metaData.key.end()); - Serializable::Unmarshall({ metaData.value.begin(), metaData.value.end() }, strategyMeta); - auto spliteTokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); - if (spliteTokens.size() > SPLITE_MIN_SIZE) { - spliteTokens[UUID_LOCATION] = currentUUID; - } - auto newKey = Constant::vectorToString(spliteTokens); - MetaDataManager::GetInstance().SaveMeta(newKey, strategyMeta, isLocal); - MetaDataManager::GetInstance().DelMeta(metaKey, isLocal); + std::vector strategyMetas; + MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ oldUUID_ }), strategyMetas, isLocal); + for (auto &strategyMeta : strategyMetas) { + MetaDataManager::GetInstance().DelMeta(strategyMeta.GetKey(), isLocal); + storeMeta.devId = currentUUID; + MetaDataManager::GetInstance().SaveMeta(strategyMeta.GetKey(), strategyMeta, isLocal); } } void KvStoreMetaManager::UpdateMatrixMetaData(const std::string ¤tUUID, bool isLocal) { MatrixMetaData matrixMetas; - bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({oldUUID_}), matrixMetas, isLocal); + bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), matrixMetas, isLocal); if (isExist) { - MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({oldUUID_}), isLocal); - MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({currentUUID}), matrixMetas, isLocal); + MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), isLocal); + MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({ currentUUID }), matrixMetas, isLocal); } } void KvStoreMetaManager::UpdateSwitchesMetaData(const std::string ¤tUUID, bool isLocal) { SwitchesMetaData switchesMetaData; - bool isExist = MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({oldUUID_}), + bool isExist = MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({ oldUUID_ }), switchesMetaData, isLocal); if (isExist) { - MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({oldUUID_}), isLocal); + MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({ oldUUID_ }), isLocal); MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({currentUUID}), switchesMetaData, isLocal); } } diff --git a/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h index a3cb9275b..25feaeded 100644 --- a/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h @@ -29,6 +29,7 @@ struct API_EXPORT StrategyMeta final : public Serializable { API_EXPORT StrategyMeta(const std::string &devId, const std::string &userId, const std::string &bundleName, const std::string &storeId); + API_EXPORT StrategyMeta() {}; API_EXPORT ~StrategyMeta() {}; API_EXPORT bool Marshal(json &node) const override; API_EXPORT bool Unmarshal(const json &node) override; -- Gitee From 770aecfe9d2457920718d2db4f332281bd1a5e8c Mon Sep 17 00:00:00 2001 From: yangliu Date: Wed, 19 Mar 2025 10:47:46 +0800 Subject: [PATCH 039/225] update Signed-off-by: yangliu --- .../distributeddataservice/app/src/kvstore_meta_manager.cpp | 3 +-- .../distributeddataservice/framework/include/utils/constant.h | 3 ++- services/distributeddataservice/service/kvdb/upgrade.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 8443ff73b..b4a640777 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -186,7 +186,6 @@ void KvStoreMetaManager::InitMetaData() } UpdateMetaData(); SetCloudSyncer(); - ZLOGI("end."); } void KvStoreMetaManager::UpdateMetaData() @@ -575,7 +574,7 @@ bool KvStoreMetaManager::IsMetaDeviceIdChanged(const std::string &localUUID) ZLOGW("get uuid failed"); return false; } - if (!MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true)) {\ + if (!MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true)) { meta.currentUUID = localUUID; MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); } else { diff --git a/services/distributeddataservice/framework/include/utils/constant.h b/services/distributeddataservice/framework/include/utils/constant.h index f98b8ceaf..965267623 100644 --- a/services/distributeddataservice/framework/include/utils/constant.h +++ b/services/distributeddataservice/framework/include/utils/constant.h @@ -46,7 +46,8 @@ public: API_EXPORT static std::vector SplitKeepSpace(const std::string &str, const std::string &delim); - API_EXPORT static std::string vectorToString(const std::vector &vec, const std::string separator = "###"); + API_EXPORT static std::string vectorToString(const std::vector &vec, + const std::string separator = "###"); template inline static constexpr bool is_pod = (std::is_standard_layout_v && std::is_trivial_v); diff --git a/services/distributeddataservice/service/kvdb/upgrade.cpp b/services/distributeddataservice/service/kvdb/upgrade.cpp index 654074066..7040dfb88 100644 --- a/services/distributeddataservice/service/kvdb/upgrade.cpp +++ b/services/distributeddataservice/service/kvdb/upgrade.cpp @@ -48,7 +48,7 @@ Upgrade::DBStatus Upgrade::UpdateStore(const StoreMeta &old, const StoreMeta &me return DBStatus::DB_ERROR; } store->OperateDataStatus(static_cast(DistributedDB::DataOperator::UPDATE_TIME) | - static_cast(DistributedDB::DataOperator::RESET_UPLOAD_CLOUD )); + static_cast(DistributedDB::DataOperator::RESET_UPLOAD_CLOUD)); } if ((old.version < StoreMeta::UUID_CHANGED_TAG || (old.isNeedUpdateDeviceId && !old.isEncrypt)) && -- Gitee From 4a4188ffe0761171d9fa35a94d4bed9538c1c95b Mon Sep 17 00:00:00 2001 From: yangliu Date: Wed, 19 Mar 2025 10:48:57 +0800 Subject: [PATCH 040/225] update Signed-off-by: yangliu --- .../distributeddataservice/app/src/kvstore_meta_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index b4a640777..f2fd5fb9b 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -40,7 +40,7 @@ #include "metadata/matrix_meta_data.h" #include "metadata/strategy_meta_data.h" #include "metadata/store_meta_data_local.h" -#include "metadata/stratery_meta_data.h" +#include "metadata/strategy_meta_data.h" #include "metadata/switches_meta_data.h" #include "metadata/user_meta_data.h" #include "metadata/version_meta_data.h" -- Gitee From e7625d61838ce6f9fe831578bb596d4d90b55449 Mon Sep 17 00:00:00 2001 From: yangliu Date: Wed, 19 Mar 2025 11:03:14 +0800 Subject: [PATCH 041/225] update Signed-off-by: yangliu --- .../app/src/kvstore_meta_manager.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index f2fd5fb9b..9a4ddffd1 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -629,7 +629,7 @@ void KvStoreMetaManager::UpdateLocalMetaData(const std::string ¤tUUID, boo StoreMetaDataLocal storeMetaDataLocal; std::string metaKey(localMetaData.key.begin(), localMetaData.key.end()); Serializable::Unmarshall({ localMetaData.value.begin(), localMetaData.value.end() }, storeMetaDataLocal); - auto spliteTokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); + auto spliteTokens = Constant::SplitKeepSpace(metaKey, Constant::KEY_SEPARATOR); if (spliteTokens.size() > SPLITE_MIN_SIZE) { spliteTokens[UUID_LOCATION] = currentUUID; } @@ -647,7 +647,7 @@ void KvStoreMetaManager::UpdateAutoLaunchMetaData(const std::string ¤tUUID AutoLaunchMetaData autoLaunchMetaData; std::string metaKey(metaData.key.begin(), metaData.key.end()); Serializable::Unmarshall({ metaData.value.begin(), metaData.value.end() }, autoLaunchMetaData); - auto spliteTokens = Constant::SplitWithSeparator(metaKey, Constant::KEY_SEPARATOR); + auto spliteTokens = Constant::SplitKeepSpace(metaKey, Constant::KEY_SEPARATOR); if (spliteTokens.size() > SPLITE_MIN_SIZE) { spliteTokens[UUID_LOCATION] = currentUUID; } @@ -671,7 +671,8 @@ void KvStoreMetaManager::UpdateStrategyMetaData(const std::string ¤tUUID, void KvStoreMetaManager::UpdateMatrixMetaData(const std::string ¤tUUID, bool isLocal) { MatrixMetaData matrixMetas; - bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), matrixMetas, isLocal); + bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), + matrixMetas, isLocal); if (isExist) { MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), isLocal); MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({ currentUUID }), matrixMetas, isLocal); -- Gitee From ce3500855e905279b6cd17faff4f92256e4e2e2c Mon Sep 17 00:00:00 2001 From: wangbin Date: Wed, 19 Mar 2025 15:24:38 +0800 Subject: [PATCH 042/225] fix SoftbusAdapterStandardTest Signed-off-by: wangbin --- .../adapter/communicator/test/BUILD.gn | 4 +- .../process_communicator_impl_test.cpp | 60 +++++++++++++++++-- .../softbus_adapter_standard_test.cpp | 34 +---------- 3 files changed, 57 insertions(+), 41 deletions(-) diff --git a/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/BUILD.gn index 64b50feef..db4a74a02 100755 --- a/services/distributeddataservice/adapter/communicator/test/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/BUILD.gn @@ -189,9 +189,9 @@ ohos_unittest("SoftbusAdapterStandardTest") { module_out_path = module_output_path sources = [ - "${data_service_path}/service/test/mock/device_manager_adapter_mock.cpp", "../src/communicator_context.cpp", "../src/data_buffer.cpp", + "../src/device_manager_adapter.cpp", "../src/process_communicator_impl.cpp", "../src/softbus_adapter.h", "../src/softbus_client.cpp", @@ -202,7 +202,6 @@ ohos_unittest("SoftbusAdapterStandardTest") { include_dirs = [ "${data_service_path}/adapter/include/communicator", "${data_service_path}/framework/include/dfx", - "${data_service_path}/service/test/mock", "../src", "../../include/communicator", "../../include/utils", @@ -215,7 +214,6 @@ ohos_unittest("SoftbusAdapterStandardTest") { "c_utils:utils", "device_manager:devicemanagersdk", "dsoftbus:softbus_client", - "googletest:gmock_main", "hilog:libhilog", "ipc:ipc_core", "json:nlohmann_json_static", diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp index 935ec97e2..f5c4cc30c 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp @@ -22,6 +22,8 @@ #include "communication_provider.h" #include "device_manager_adapter_mock.h" #include "process_communicator_impl.h" +#include "softbus_adapter.h" +#include "softbus_error_code.h" using namespace testing; using namespace testing::ext; @@ -31,7 +33,7 @@ using OnDeviceChange = DistributedDB::OnDeviceChange; using OnDataReceive = DistributedDB::OnDataReceive; using OnSendAble = DistributedDB::OnSendAble; using DeviceInfos = DistributedDB::DeviceInfos; -using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo; +using DeviceInfoo = OHOS::AppDistributedKv::DeviceInfo; using UserInfo = DistributedDB::UserInfo; namespace OHOS::AppDistributedKv { @@ -292,9 +294,9 @@ HWTEST_F(ProcessCommunicatorImplTest, GetRemoteOnlineDeviceInfosList, TestSize.L auto remoteDevInfos = communicator_->GetRemoteOnlineDeviceInfosList(); EXPECT_EQ(remoteDevInfos.empty(), true); - DeviceInfo deviceInfo; + DeviceInfoo deviceInfo; deviceInfo.uuid = "GetRemoteOnlineDeviceInfosList"; - std::vector devInfos; + std::vector devInfos; devInfos.push_back(deviceInfo); EXPECT_CALL(*deviceManagerAdapterMock, GetRemoteDevices()).WillRepeatedly(Return(devInfos)); remoteDevInfos = communicator_->GetRemoteOnlineDeviceInfosList(); @@ -311,7 +313,7 @@ HWTEST_F(ProcessCommunicatorImplTest, GetRemoteOnlineDeviceInfosList, TestSize.L HWTEST_F(ProcessCommunicatorImplTest, OnMessage, TestSize.Level0) { ASSERT_NE(communicator_, nullptr); - DeviceInfo deviceInfo; + DeviceInfoo deviceInfo; deviceInfo.uuid = "OnMessageTest"; uint8_t data[] = {0x10, 0x20, 0x30, 0x40, 0x50}; uint8_t *ptr = data; @@ -336,7 +338,7 @@ HWTEST_F(ProcessCommunicatorImplTest, OnMessage, TestSize.Level0) HWTEST_F(ProcessCommunicatorImplTest, OnDeviceChanged, TestSize.Level0) { ASSERT_NE(communicator_, nullptr); - DeviceInfo deviceInfo; + DeviceInfoo deviceInfo; deviceInfo.uuid = "cloudDeviceUuid"; EXPECT_NO_FATAL_FAILURE(communicator_->OnDeviceChanged(deviceInfo, DeviceChangeType::DEVICE_ONREADY)); EXPECT_NO_FATAL_FAILURE(communicator_->OnDeviceChanged(deviceInfo, DeviceChangeType::DEVICE_OFFLINE)); @@ -358,7 +360,7 @@ HWTEST_F(ProcessCommunicatorImplTest, OnDeviceChanged, TestSize.Level0) HWTEST_F(ProcessCommunicatorImplTest, OnSessionReady, TestSize.Level0) { ASSERT_NE(communicator_, nullptr); - DeviceInfo deviceInfo; + DeviceInfoo deviceInfo; deviceInfo.uuid = "OnSessionReadyTest"; communicator_->sessionListener_ = nullptr; EXPECT_NO_FATAL_FAILURE(communicator_->OnSessionReady(deviceInfo, 1)); @@ -455,4 +457,50 @@ HWTEST_F(ProcessCommunicatorImplTest, GetDataUserInfo, TestSize.Level0) userInfos.push_back(user3); status = communicator_->GetDataUserInfo(ptr, totalLen, label, userInfos); EXPECT_EQ(status, DistributedDB::OK); +} + +/** +* @tc.name: ReuseConnect01 +* @tc.desc: reuse connect +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin + */ +HWTEST_F(ProcessCommunicatorImplTest, ReuseConnect01, TestSize.Level0) +{ + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); + PipeInfo pipe; + pipe.pipeId = "appId"; + pipe.userId = "groupId"; + DeviceId device = {"DeviceId"}; + auto status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device); + EXPECT_EQ(status, Status::NOT_SUPPORT); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(testing::_)).WillOnce(testing::Return(true)) + .WillRepeatedly(testing::Return(true)); + status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device); + EXPECT_EQ(status, Status::NETWORK_ERROR); +} + +/** +* @tc.name: CloseSession +* @tc.desc: close session +* @tc.type: FUNC +* @tc.author: nhj +*/ +HWTEST_F(ProcessCommunicatorImplTest, CloseSession, TestSize.Level1) +{ + std::string networkId = "networkId"; + auto flag = SoftBusAdapter::GetInstance(); + ASSERT_NE(flag, nullptr); + std::string uuid = "CloseSessionTest"; + EXPECT_CALL(*deviceManagerAdapterMock, GetUuidByNetworkId(testing::_)).WillOnce(testing::Return(uuid)) + .WillRepeatedly(testing::Return(uuid)); + std::shared_ptr conn = nullptr; + std::vector> clients; + clients.emplace_back(conn); + auto result = SoftBusAdapter::GetInstance()->connects_.Insert(uuid, clients); + EXPECT_EQ(result, true); + auto status = SoftBusAdapter::GetInstance()->CloseSession(networkId); + SoftBusAdapter::GetInstance()->connects_.Clear(); + EXPECT_EQ(status, true); } \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp index 44d3f97e5..641166b94 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp @@ -15,9 +15,7 @@ #include "app_device_change_listener.h" #include #include "gtest/gtest.h" -#include #include -#include "device_manager_adapter_mock.h" #include "softbus_adapter.h" #include "softbus_adapter_standard.cpp" #include "softbus_error_code.h" @@ -47,9 +45,8 @@ void AppDataChangeListenerImpl::OnMessage(const OHOS::AppDistributedKv::DeviceIn class SoftbusAdapterStandardTest : public testing::Test { public: - static inline std::shared_ptr deviceManagerAdapterMock = nullptr; - static void SetUpTestCase(void); - static void TearDownTestCase(void); + static void SetUpTestCase(void) {} + static void TearDownTestCase(void) {} void SetUp() {} void TearDown() {} protected: @@ -57,18 +54,6 @@ protected: static constexpr uint32_t DEFAULT_TIMEOUT = 30 * 1000; }; -void SoftbusAdapterStandardTest::SetUpTestCase(void) -{ - deviceManagerAdapterMock = std::make_shared(); - BDeviceManagerAdapter::deviceManagerAdapter = deviceManagerAdapterMock; -} - -void SoftbusAdapterStandardTest::TearDownTestCase() -{ - deviceManagerAdapterMock = nullptr; - BDeviceManagerAdapter::deviceManagerAdapter = nullptr; -} - /** * @tc.name: StartWatchDeviceChange * @tc.desc: start watch data change @@ -532,10 +517,6 @@ HWTEST_F(SoftbusAdapterStandardTest, ReuseConnect01, TestSize.Level1) DeviceId device = {"DeviceId"}; auto status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device); EXPECT_EQ(status, Status::NOT_SUPPORT); - EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(testing::_)).WillOnce(testing::Return(true)) - .WillRepeatedly(testing::Return(true)); - status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device); - EXPECT_EQ(status, Status::NETWORK_ERROR); } /** @@ -615,17 +596,6 @@ HWTEST_F(SoftbusAdapterStandardTest, CloseSession, TestSize.Level1) ASSERT_NE(flag, nullptr); auto status = SoftBusAdapter::GetInstance()->CloseSession(networkId); EXPECT_EQ(status, false); - std::string uuid = "CloseSessionTest"; - EXPECT_CALL(*deviceManagerAdapterMock, GetUuidByNetworkId(testing::_)).WillOnce(testing::Return(uuid)) - .WillRepeatedly(testing::Return(uuid)); - std::shared_ptr conn = nullptr; - std::vector> clients; - clients.emplace_back(conn); - auto result = SoftBusAdapter::GetInstance()->connects_.Insert(uuid, clients); - EXPECT_EQ(result, true); - status = SoftBusAdapter::GetInstance()->CloseSession(networkId); - SoftBusAdapter::GetInstance()->connects_.Clear(); - EXPECT_EQ(status, true); } /** -- Gitee From 4d3db2e8b915500ce5ecbab34f23dd3f448735f5 Mon Sep 17 00:00:00 2001 From: ninghejuan Date: Tue, 18 Mar 2025 18:31:27 +0800 Subject: [PATCH 043/225] add kvdb_service_impl test Signed-off-by: ninghejuan --- .../service/test/kvdb_service_impl_test.cpp | 240 +++++++++++++++++- 1 file changed, 228 insertions(+), 12 deletions(-) diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index ba28f19a5..1d16a6562 100644 --- a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp @@ -28,10 +28,12 @@ #include "event_center.h" #include "ipc_skeleton.h" #include "kvdb_service_stub.h" +#include "kvdb_query.h" #include "kvstore_death_recipient.h" #include "kvstore_meta_manager.h" #include "kvstore_sync_manager.h" #include "log_print.h" +#include #include "mock/access_token_mock.h" #include "mock/meta_data_manager_mock.h" #include "network_delegate.h" @@ -63,9 +65,10 @@ using UserId = OHOS::DistributedKv::UserId; using StoreMetaData = OHOS::DistributedData::StoreMetaData; using SyncEnd = OHOS::DistributedKv::KvStoreSyncManager::SyncEnd; using DBResult = std::map; +using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; static OHOS::DistributedKv::StoreId storeId = { "kvdb_test_storeid" }; static OHOS::DistributedKv::AppId appId = { "ohos.test.kvdb" }; - +static constexpr const char *TEST_USER = "0"; namespace OHOS::Test { namespace DistributedDataTest { class KvdbServiceImplTest : public testing::Test { @@ -79,7 +82,7 @@ public: static UserId userId; std::shared_ptr kvStore; - + std::shared_ptr executors_; static AppId appId; static StoreId storeId64; static StoreId storeId65; @@ -95,6 +98,8 @@ public: protected: std::shared_ptr kvdbServiceImpl_; static NetworkDelegateMock delegate_; + StoreMetaData metaData_; + Options options_; }; class CloudServerMock : public CloudServer { @@ -165,6 +170,15 @@ void KvdbServiceImplTest::TearDownTestCase() void KvdbServiceImplTest::SetUp(void) { kvdbServiceImpl_ = std::make_shared(); + + options_.isNeedCompress = true; + metaData_.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + metaData_.bundleName = appId.appId; + metaData_.storeId = storeId.storeId; + metaData_.user = TEST_USER; + metaData_.tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + metaData_.version = 1; + MetaDataManager::GetInstance().DelMeta(metaData_.GetKey()); } void KvdbServiceImplTest::TearDown(void) @@ -1040,9 +1054,9 @@ HWTEST_F(KvdbServiceImplTest, OnReadyTest001, TestSize.Level0) */ HWTEST_F(KvdbServiceImplTest, ResolveAutoLaunch, TestSize.Level0) { - StoreId id1; - id1.storeId = "id1"; - Status status = manager.GetSingleKvStore(create, appId, id1, kvStore); + StoreId id; + id.storeId = "id"; + Status status = manager.GetSingleKvStore(create, appId, id, kvStore); EXPECT_NE(kvStore, nullptr); EXPECT_EQ(status, Status::SUCCESS); std::string identifier = "identifier"; @@ -1081,9 +1095,9 @@ HWTEST_F(KvdbServiceImplTest, IsRemoteChangeTest, TestSize.Level0) */ HWTEST_F(KvdbServiceImplTest, PutSwitch, TestSize.Level0) { - StoreId id1; - id1.storeId = "id1"; - Status status = manager.GetSingleKvStore(create, appId, id1, kvStore); + StoreId id; + id.storeId = "id1"; + Status status = manager.GetSingleKvStore(create, appId, id, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status, Status::SUCCESS); DistributedKv::SwitchData switchData; @@ -1118,9 +1132,9 @@ HWTEST_F(KvdbServiceImplTest, PutSwitch, TestSize.Level0) */ HWTEST_F(KvdbServiceImplTest, DoCloudSync, TestSize.Level0) { - StoreId id1; - id1.storeId = "id1"; - Status status = manager.GetSingleKvStore(create, appId, id1, kvStore); + StoreId id; + id.storeId = "id1"; + Status status = manager.GetSingleKvStore(create, appId, id, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status, Status::SUCCESS); StoreMetaData metaData; @@ -1273,5 +1287,207 @@ HWTEST_F(KvdbServiceImplTest, DoCloudSync02, TestSize.Level0) auto status = kvdbServiceImpl_->DoCloudSync(metaData, syncInfo); EXPECT_EQ(status, OHOS::DistributedKv::Status::NETWORK_ERROR); } + +/** +* @tc.name: DoCloudSync +* @tc.desc: DoCloudSync error function test. +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, DoCloudSync01, TestSize.Level0) +{ + StoreId id; + id.storeId = "id1"; + Status status = manager.GetSingleKvStore(create, appId, id, kvStore); + ASSERT_NE(kvStore, nullptr); + ASSERT_EQ(status, Status::SUCCESS); + StoreMetaData metaData; + metaData.enableCloud = false; + SyncInfo syncInfo; + status = kvdbServiceImpl_->DoCloudSync(metaData, syncInfo); + EXPECT_EQ(status, Status::NOT_SUPPORT); +} + +/** +* @tc.name: OnAsyncCompleteTest002 +* @tc.desc: OnAsyncComplete function test. +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, OnAsyncCompleteTest002, TestSize.Level0) +{ + DistributedKv::Statistic upload; + upload.failed = 1; // test + upload.success = 1; // test + upload.total = 1; // test + upload.untreated = 1; // test + DistributedKv::Statistic download; + download.failed = 1; // test + download.success = 1; // test + download.total = 1; // test + download.untreated = 1; // test + DistributedKv::TableDetail details; + details.download = download; + details.upload = upload; + DistributedKv::ProgressDetail detail; + detail.code = 1; // test + detail.progress = 1; // test + detail.details = details; + DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; + sptr notifier = nullptr; + syncAgent.pid_ = 1; // test + syncAgent.switchesObserverCount_ = 1; // test + syncAgent.appId_ = { "ohos.OnAsyncCompleteTest.kvdb" }; + syncAgent.notifier_ = notifier; + EXPECT_EQ(notifier, nullptr); + uint32_t tokenId = 2; + uint64_t seqNum = 1; + kvdbServiceImpl_->syncAgents_.Insert(tokenId, syncAgent); + kvdbServiceImpl_->OnAsyncComplete(tokenId, seqNum, std::move(detail)); + EXPECT_TRUE(kvdbServiceImpl_->syncAgents_.Find(tokenId).first); + kvdbServiceImpl_->OnAsyncComplete(0, 1, std::move(detail)); + EXPECT_TRUE(kvdbServiceImpl_->syncAgents_.Find(tokenId).first); +} + +/** +* @tc.name: OnAsyncCompleteTest003 +* @tc.desc: OnAsyncComplete function test. +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, OnAsyncCompleteTest003, TestSize.Level0) +{ + DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; + sptr notifier; + syncAgent.pid_ = 1; // test + syncAgent.switchesObserverCount_ = 1; // test + syncAgent.appId_ = { "ohos.OnAsyncCompleteTest001.kvdb" }; + syncAgent.notifier_ = notifier; + DistributedKv::ProgressDetail detail; + auto tokenId = IPCSkeleton::GetCallingTokenID(); + kvdbServiceImpl_->syncAgents_.Insert(tokenId, syncAgent); + kvdbServiceImpl_->OnAsyncComplete(tokenId, 1, std::move(detail)); + EXPECT_TRUE(kvdbServiceImpl_->syncAgents_.Find(tokenId).first); +} + +/** +* @tc.name: DeleteTest004 +* @tc.desc: Delete Test +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, DeleteTest004, TestSize.Level0) +{ + ZLOGI("DeleteTest004 start"); + AppId appId = { "ohos.kvdbserviceimpl.test" }; + StoreId storeId = { "meta_test_storeid" }; + DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; + syncAgent.pid_ = 1; + auto tokenId = IPCSkeleton::GetCallingTokenID(); + auto status = kvdbServiceImpl_->Delete(appId, storeId, 0); + ZLOGI("DeleteTest002 status = :%{public}d", status); + EXPECT_NE(tokenId, syncAgent.pid_); + ASSERT_EQ(status, Status::SUCCESS); +} + +/** +* @tc.name: syncTest002 +* @tc.desc: Sync +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, syncTest002, TestSize.Level0) +{ + ZLOGI("syncTest002 start"); + StoreMetaData metaData; + auto mm = std::numeric_limits::max(); + metaData.isAutoSync = true; + SyncInfo syncInfo; + syncInfo.devices = { "device1", "device2" }; + syncInfo.query = "query"; + syncInfo.seqId = mm; // test + auto status = kvdbServiceImpl_->Sync(appId, storeId, 0, syncInfo); + ASSERT_EQ(syncInfo.seqId, std::numeric_limits::max()); + ZLOGI("syncTest002 status = :%{public}d", status); + ASSERT_NE(status, Status::SUCCESS); +} + +/** +* @tc.name: syncTest003 +* @tc.desc: Sync +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, syncTest003, TestSize.Level0) +{ + ZLOGI("syncTest003 start"); + StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); + StoreMetaData metaData; + metaData.isAutoSync = true; + StoreMetaDataLocal localMeta; + PolicyValue value; + value.type = OHOS::DistributedKv::PolicyType::IMMEDIATE_SYNC_ON_ONLINE; + localMeta.policies = { std::move(value) }; + SyncInfo syncInfo; + syncInfo.seqId = std::numeric_limits::max(); + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(true)).WillRepeatedly(testing::Return(true)); + auto status = kvdbServiceImpl_->Sync(appId, storeId, 0, syncInfo); + EXPECT_EQ(localMeta.HasPolicy(DistributedKv::IMMEDIATE_SYNC_ON_CHANGE), false); + EXPECT_NE(status, Status::SUCCESS); + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(false)).WillRepeatedly(testing::Return(false)); + status = kvdbServiceImpl_->Sync(appId, storeId, 0, syncInfo); + EXPECT_EQ(localMeta.HasPolicy(DistributedKv::IMMEDIATE_SYNC_ON_ONLINE), true); +} + +/** +* @tc.name: GetSyncParamTest001 +* @tc.desc: GetStoreIds +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, GetSyncParamTest002, TestSize.Level0) +{ + ZLOGI("GetSyncParamTest001 start"); + Status status1 = manager.GetSingleKvStore(create, appId, storeId, kvStore); + ASSERT_NE(kvStore, nullptr); + ASSERT_EQ(status1, Status::SUCCESS); + OHOS::DistributedKv::KvSyncParam syncparam; + DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; + syncAgent.pid_ = 1; + auto tokenId = IPCSkeleton::GetCallingTokenID(); + EXPECT_NE(tokenId, syncAgent.pid_); + auto status = kvdbServiceImpl_->GetSyncParam(appId, storeId, 0, syncparam); + ZLOGI("GetSyncParamTest002 status = :%{public}d", status); + ASSERT_EQ(status, Status::SUCCESS); +} + +/** +* @tc.name: SubscribeSwitchData +* @tc.desc: SubscribeSwitchData function test. +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, SubscribeSwitchData, TestSize.Level0) +{ + options_.isNeedCompress = false; + std::vector password {}; + StoreMetaData metaData; + auto status = kvdbServiceImpl_->AfterCreate(appId, storeId, options_, password); + ASSERT_EQ(status, Status::SUCCESS); + auto tokenId = IPCSkeleton::GetCallingTokenID(); + DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; + syncAgent.switchesObserverCount_ = 1; + syncAgent.pid_ = tokenId; + syncAgent.notifier_ = nullptr; + status = kvdbServiceImpl_->SubscribeSwitchData(appId); + EXPECT_EQ(status, Status::SUCCESS); + ASSERT_FALSE(MetaDataManager::GetInstance().LoadMeta(metaData_.GetKey(), metaData)); + kvdbServiceImpl_->syncAgents_.Insert(IPCSkeleton::GetCallingTokenID(), syncAgent); + EXPECT_EQ(tokenId, syncAgent.pid_); + status = kvdbServiceImpl_->UnregServiceNotifier(appId); + ASSERT_EQ(status, Status::SUCCESS); +} } // namespace DistributedDataTest -} // namespace OHOS::Test \ No newline at end of file +} // namespace OHOS::Test -- Gitee From 2a3d4b807d08f644d4ec7c656f20dbc3b12c6ed2 Mon Sep 17 00:00:00 2001 From: wenjinchao Date: Thu, 20 Mar 2025 10:21:48 +0800 Subject: [PATCH 044/225] transfer to entries Signed-off-by: wenjinchao Change-Id: I7a8e77127069bc64c22a1a7025efbe2948039869 --- .../service/test/BUILD.gn | 9 +++ .../test/fuzztest/udmfservice_fuzzer/BUILD.gn | 2 + .../service/test/udmf_service_impl_test.cpp | 23 +++++++ .../service/udmf/BUILD.gn | 2 + .../service/udmf/udmf_service_impl.cpp | 64 +++++++++++++++++-- .../service/udmf/udmf_service_impl.h | 2 + 6 files changed, 96 insertions(+), 6 deletions(-) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 4d16dc1f1..70ece0588 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -931,6 +931,8 @@ ohos_unittest("UdmfRunTimeStoreTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "c_utils:utils", "dataclassification:data_transit_mgr", "dsoftbus:softbus_client", @@ -939,6 +941,7 @@ ohos_unittest("UdmfRunTimeStoreTest") { "image_framework:image", "ipc:ipc_core", "kv_store:distributeddata_inner", + "samgr:samgr_proxy", "udmf:udmf_client", ] @@ -1200,6 +1203,7 @@ ohos_unittest("UdmfServiceImplTest") { "ability_runtime:uri_permission_mgr", "access_token:libaccesstoken_sdk", "app_file_service:remote_file_share_native", + "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "device_manager:devicemanagersdk", @@ -1209,6 +1213,7 @@ ohos_unittest("UdmfServiceImplTest") { "kv_store:distributeddata_inner", "kv_store:distributeddb", "relational_store:native_rdb", + "samgr:samgr_proxy", "udmf:udmf_client", ] } @@ -1237,6 +1242,7 @@ ohos_unittest("UdmfServiceStubTest") { "ability_runtime:uri_permission_mgr", "access_token:libaccesstoken_sdk", "app_file_service:remote_file_share_native", + "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "device_manager:devicemanagersdk", @@ -1245,6 +1251,7 @@ ohos_unittest("UdmfServiceStubTest") { "kv_store:distributeddata_inner", "kv_store:distributeddb", "relational_store:native_rdb", + "samgr:samgr_proxy", "udmf:udmf_client", ] } @@ -1313,6 +1320,7 @@ ohos_unittest("UdmfServiceStubMockTest") { "access_token:libtoken_setproc", "access_token:libtokenid_sdk", "app_file_service:remote_file_share_native", + "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "device_manager:devicemanagersdk", @@ -1325,6 +1333,7 @@ ohos_unittest("UdmfServiceStubMockTest") { "kv_store:distributeddata_inner", "kv_store:distributeddb", "relational_store:native_rdb", + "samgr:samgr_proxy", "udmf:udmf_client", ] } diff --git a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn index 723fdfcc9..27778e7e3 100644 --- a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn @@ -57,6 +57,7 @@ ohos_fuzztest("UdmfServiceFuzzTest") { "ability_runtime:uri_permission_mgr", "access_token:libaccesstoken_sdk", "access_token:libtoken_setproc", + "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "hilog:libhilog", @@ -65,6 +66,7 @@ ohos_fuzztest("UdmfServiceFuzzTest") { "kv_store:distributeddata_inner", "kv_store:distributeddata_mgr", "kv_store:distributeddb", + "samgr:samgr_proxy", "udmf:udmf_client", ] } diff --git a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp index 55830d53b..258c27ca2 100644 --- a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp @@ -216,4 +216,27 @@ HWTEST_F(UdmfServiceImplTest, OnUserChangeTest001, TestSize.Level1) ASSERT_EQ(sizeAfter, 0); } +/** +* @tc.name: TransferToEntriesIfNeedTest001 +* @tc.desc: TransferToEntriesIfNeed test +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, TransferToEntriesIfNeedTest001, TestSize.Level1) +{ + UnifiedData data; + QueryOption query; + auto record1 = std::make_shared(); + auto record2 = std::make_shared(); + data.AddRecord(record1); + data.AddRecord(record2); + auto properties = std::make_shared(); + properties->tag = "records_to_entries_data_format"; + data.SetProperties(properties); + query.tokenId = 1; + UdmfServiceImpl udmfServiceImpl; + udmfServiceImpl.TransferToEntriesIfNeed(query, data); + EXPECT_TRUE(data.IsNeedTransferToEntries()); + EXPECT_EQ(data.GetRecords().size(), 2); +} }; // namespace UDMF \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/BUILD.gn b/services/distributeddataservice/service/udmf/BUILD.gn index 5d0f44c13..8176548a1 100644 --- a/services/distributeddataservice/service/udmf/BUILD.gn +++ b/services/distributeddataservice/service/udmf/BUILD.gn @@ -79,6 +79,8 @@ ohos_source_set("udmf_server") { "ability_runtime:uri_permission_mgr", "access_token:libtokenid_sdk", "app_file_service:remote_file_share_native", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "device_manager:devicemanagersdk", "hilog:libhilog", "hisysevent:libhisysevent", diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 2d0cdacbc..45c3bfeb6 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -21,20 +21,24 @@ #include "tokenid_kit.h" #include "accesstoken_kit.h" +#include "bootstrap.h" +#include "bundle_info.h" +#include "bundlemgr/bundle_mgr_proxy.h" #include "checker_manager.h" +#include "device_manager_adapter.h" +#include "iservice_registry.h" #include "lifecycle/lifecycle_manager.h" #include "log_print.h" +#include "metadata/store_meta_data.h" +#include "metadata/meta_data_manager.h" #include "preprocess_utils.h" #include "reporter.h" +#include "store_account_observer.h" +#include "system_ability_definition.h" #include "uri_permission_manager.h" #include "udmf_radar_reporter.h" -#include "device_manager_adapter.h" -#include "store_account_observer.h" -#include "utils/anonymous.h" -#include "bootstrap.h" -#include "metadata/store_meta_data.h" -#include "metadata/meta_data_manager.h" #include "unified_data_helper.h" +#include "utils/anonymous.h" namespace OHOS { namespace UDMF { @@ -51,6 +55,9 @@ constexpr const char *DATA_PREFIX = "udmf://"; constexpr const char *FILE_SCHEME = "file"; constexpr const char *PRIVILEGE_READ_AND_KEEP = "readAndKeep"; constexpr const char *MANAGE_UDMF_APP_SHARE_OPTION = "ohos.permission.MANAGE_UDMF_APP_SHARE_OPTION"; +constexpr const char *DEVICE_2IN1_TAG = "2in1"; +constexpr const char *DEVICE_PHONE_TAG = "phone"; +constexpr const char *DEVICE_DEFAULT_TAG = "default"; constexpr const char *HAP_LIST[] = {"com.ohos.pasteboarddialog"}; __attribute__((used)) UdmfServiceImpl::Factory UdmfServiceImpl::factory_; UdmfServiceImpl::Factory::Factory() @@ -168,6 +175,7 @@ int32_t UdmfServiceImpl::GetData(const QueryOption &query, UnifiedData &unifiedD msg.appId = bundleName; res = RetrieveData(query, unifiedData); } + TransferToEntriesIfNeed(query, unifiedData); auto errFind = ERROR_MAP.find(res); msg.result = errFind == ERROR_MAP.end() ? "E_ERROR" : errFind->second; for (const auto &record : unifiedData.GetRecords()) { @@ -831,5 +839,49 @@ int32_t UdmfServiceImpl::OnUserChange(uint32_t code, const std::string &user, co } return Feature::OnUserChange(code, user, account); } + +void UdmfServiceImpl::TransferToEntriesIfNeed(const QueryOption &query, UnifiedData &unifiedData) +{ + if (unifiedData.IsNeedTransferToEntries() && Is2In1DeviceType(query)) { + unifiedData.TransferToEntries(unifiedData); + } +} + +bool UdmfServiceImpl::Is2In1DeviceType(const QueryOption &query) +{ + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + ZLOGE("Failed to get system ability mgr."); + return false; + } + auto bundleMgrProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (bundleMgrProxy == nullptr) { + ZLOGE("Failed to Get BMS SA."); + return false; + } + auto bundleManager = iface_cast(bundleMgrProxy); + if (bundleManager == nullptr) { + ZLOGE("Failed to get bundle manager"); + return false; + } + std::string bundleName; + PreProcessUtils::GetHapBundleNameByToken(query.tokenId, bundleName); + int32_t userId = DistributedData::AccountDelegate::GetInstance()->GetUserByToken( + IPCSkeleton::GetCallingFullTokenID()); + AppExecFwk::BundleInfo bundleInfo; + bundleManager->GetBundleInfoV9(bundleName, static_cast( + AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE), bundleInfo, userId); + for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) { + if (std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), + DEVICE_PHONE_TAG) == hapModuleInfo.deviceTypes.end() + && std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), + DEVICE_DEFAULT_TAG) == hapModuleInfo.deviceTypes.end() + && std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), + DEVICE_2IN1_TAG) != hapModuleInfo.deviceTypes.end()) { + return true; + } + } + return false; +} } // namespace UDMF } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.h b/services/distributeddataservice/service/udmf/udmf_service_impl.h index 93082d45a..1a38c099a 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.h +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.h @@ -58,6 +58,8 @@ private: bool VerifyPermission(const std::string &permission, uint32_t callerTokenId); bool HasDatahubPriviledge(const std::string &bundleName); void RegisterAsyncProcessInfo(const std::string &businessUdKey); + void TransferToEntriesIfNeed(const QueryOption &query, UnifiedData &unifiedData); + bool Is2In1DeviceType(const QueryOption &query); class Factory { public: -- Gitee From d7142b9b0e3718409286272204c40d7c834e9e70 Mon Sep 17 00:00:00 2001 From: wangbin Date: Thu, 20 Mar 2025 11:13:41 +0800 Subject: [PATCH 045/225] =?UTF-8?q?=E8=A7=A3=E5=86=B3SoftbusAdapterStandar?= =?UTF-8?q?dTest=E7=BC=96=E8=AF=91libfuzz=E5=A4=B1=E8=B4=A5=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangbin --- .../adapter/communicator/test/BUILD.gn | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/BUILD.gn index db4a74a02..5e5a3489d 100755 --- a/services/distributeddataservice/adapter/communicator/test/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/BUILD.gn @@ -189,6 +189,13 @@ ohos_unittest("SoftbusAdapterStandardTest") { module_out_path = module_output_path sources = [ + "../src/app_pipe_handler.cpp", + "../src/app_pipe_handler.h", + "../src/app_pipe_mgr.cpp", + "../src/app_pipe_mgr.h", + "../src/ark_communication_provider.cpp", + "../src/communication_provider.cpp", + "../src/communication_provider_impl.cpp", "../src/communicator_context.cpp", "../src/data_buffer.cpp", "../src/device_manager_adapter.cpp", -- Gitee From 40e0e25ef208ca0ea14fee457c9db9f494218a79 Mon Sep 17 00:00:00 2001 From: wenjinchao Date: Thu, 20 Mar 2025 11:29:03 +0800 Subject: [PATCH 046/225] transfer to entries Signed-off-by: wenjinchao Change-Id: Ie67f91f3e27634fd3aae36d65022c1db0b3dc219 --- .../distributeddataservice/service/udmf/udmf_service_impl.cpp | 4 ++-- .../distributeddataservice/service/udmf/udmf_service_impl.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 45c3bfeb6..288a778a6 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -842,12 +842,12 @@ int32_t UdmfServiceImpl::OnUserChange(uint32_t code, const std::string &user, co void UdmfServiceImpl::TransferToEntriesIfNeed(const QueryOption &query, UnifiedData &unifiedData) { - if (unifiedData.IsNeedTransferToEntries() && Is2In1DeviceType(query)) { + if (unifiedData.IsNeedTransferToEntries() && IsNeedTransferDeviceType(query)) { unifiedData.TransferToEntries(unifiedData); } } -bool UdmfServiceImpl::Is2In1DeviceType(const QueryOption &query) +bool UdmfServiceImpl::IsNeedTransferDeviceType(const QueryOption &query) { auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgrProxy == nullptr) { diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.h b/services/distributeddataservice/service/udmf/udmf_service_impl.h index 1a38c099a..48a80b442 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.h +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.h @@ -59,7 +59,7 @@ private: bool HasDatahubPriviledge(const std::string &bundleName); void RegisterAsyncProcessInfo(const std::string &businessUdKey); void TransferToEntriesIfNeed(const QueryOption &query, UnifiedData &unifiedData); - bool Is2In1DeviceType(const QueryOption &query); + bool IsNeedTransferDeviceType(const QueryOption &query); class Factory { public: -- Gitee From 8bf12fee01ba53669963e6d2433ddff5acb7799a Mon Sep 17 00:00:00 2001 From: louzhihao Date: Wed, 12 Mar 2025 11:57:12 +0800 Subject: [PATCH 047/225] system Signed-off-by: louzhihao Change-Id: Ib7c2e44629b60aa20e64525665bfa1ae7d6f5327 --- .../data_share/data_share_service_stub.cpp | 29 +++++++++++++++++++ .../data_share/data_share_service_stub.h | 2 ++ .../service/data_share/idata_share_service.h | 26 ++++++++++++++++- 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp index 229afde95..d0b000ee9 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp @@ -18,6 +18,8 @@ #include "data_share_service_stub.h" #include +#include "accesstoken_kit.h" +#include "tokenid_kit.h" #include "data_share_obs_proxy.h" #include "hiview_adapter.h" #include "hiview_fault_adapter.h" @@ -325,6 +327,24 @@ int32_t DataShareServiceStub::OnNotifyConnectDone(MessageParcel &data, MessagePa return 0; } +bool DataShareServiceStub::CheckProxyCallingPermission(uint32_t tokenId) +{ + Security::AccessToken::ATokenTypeEnum tokenType = + Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId); + return (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE || + tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL); +} + +// GetTokenType use tokenId, and IsSystemApp use fullTokenId, these are different +bool DataShareServiceStub::CheckSystemUidCallingPermission(uint32_t tokenId, uint64_t fullTokenId) +{ + if (CheckProxyCallingPermission(tokenId)) { + return true; + } + // IsSystemAppByFullTokenID here is not IPC + return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); +} + int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply) { int tryTimes = TRY_TIMES; @@ -333,6 +353,15 @@ int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Me std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); } auto callingPid = IPCSkeleton::GetCallingPid(); + if (code >= DATA_SHARE_CMD_SYSTEM_CODE) { + auto fullTokenId = IPCSkeleton::GetCallingFullTokenID(); + if (!CheckSystemUidCallingPermission(IPCSkeleton::GetCallingTokenID(), fullTokenId)) { + ZLOGE("CheckSystemUidCallingPermission fail, token:%{public}" PRIx64 + ", callingPid:%{public}d, code:%{public}u", fullTokenId, callingPid, code); + return E_NOT_SYSTEM_APP; + } + code = code - DATA_SHARE_CMD_SYSTEM_CODE; + } if (code != DATA_SHARE_SERVICE_CMD_QUERY && code != DATA_SHARE_SERVICE_CMD_GET_SILENT_PROXY_STATUS) { ZLOGI("code:%{public}u, callingPid:%{public}d", code, callingPid); } diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.h b/services/distributeddataservice/service/data_share/data_share_service_stub.h index d13b20993..b84c26967 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_stub.h +++ b/services/distributeddataservice/service/data_share/data_share_service_stub.h @@ -29,6 +29,8 @@ public: private: static constexpr std::chrono::milliseconds TIME_THRESHOLD = std::chrono::milliseconds(500); static bool CheckInterfaceToken(MessageParcel& data); + bool CheckProxyCallingPermission(uint32_t tokenId); + bool CheckSystemUidCallingPermission(uint32_t tokenId, uint64_t fullTokenId); int32_t OnQuery(MessageParcel& data, MessageParcel& reply); int32_t OnAddTemplate(MessageParcel& data, MessageParcel& reply); int32_t OnDelTemplate(MessageParcel& data, MessageParcel& reply); diff --git a/services/distributeddataservice/service/data_share/idata_share_service.h b/services/distributeddataservice/service/data_share/idata_share_service.h index e57489fec..05e1fd155 100644 --- a/services/distributeddataservice/service/data_share/idata_share_service.h +++ b/services/distributeddataservice/service/data_share/idata_share_service.h @@ -29,6 +29,7 @@ namespace OHOS::DataShare { class IDataShareService { public: + static constexpr int DATA_SHARE_CMD_SYSTEM_CODE = 100; enum { DATA_SHARE_SERVICE_CMD_QUERY, DATA_SHARE_SERVICE_CMD_ADD_TEMPLATE, @@ -52,7 +53,30 @@ public: DATA_SHARE_SERVICE_CMD_INSERTEX, DATA_SHARE_SERVICE_CMD_DELETEEX, DATA_SHARE_SERVICE_CMD_UPDATEEX, - DATA_SHARE_SERVICE_CMD_MAX + DATA_SHARE_SERVICE_CMD_MAX, + DATA_SHARE_SERVICE_CMD_QUERY_SYSTEM = DATA_SHARE_CMD_SYSTEM_CODE, + DATA_SHARE_SERVICE_CMD_ADD_TEMPLATE_SYSTEM, + DATA_SHARE_SERVICE_CMD_DEL_TEMPLATE_SYSTEM, + DATA_SHARE_SERVICE_CMD_PUBLISH_SYSTEM, + DATA_SHARE_SERVICE_CMD_GET_DATA_SYSTEM, + DATA_SHARE_SERVICE_CMD_SUBSCRIBE_RDB_SYSTEM, + DATA_SHARE_SERVICE_CMD_UNSUBSCRIBE_RDB_SYSTEM, + DATA_SHARE_SERVICE_CMD_ENABLE_SUBSCRIBE_RDB_SYSTEM, + DATA_SHARE_SERVICE_CMD_DISABLE_SUBSCRIBE_RDB_SYSTEM, + DATA_SHARE_SERVICE_CMD_SUBSCRIBE_PUBLISHED_SYSTEM, + DATA_SHARE_SERVICE_CMD_UNSUBSCRIBE_PUBLISHED_SYSTEM, + DATA_SHARE_SERVICE_CMD_ENABLE_SUBSCRIBE_PUBLISHED_SYSTEM, + DATA_SHARE_SERVICE_CMD_DISABLE_SUBSCRIBE_PUBLISHED_SYSTEM, + DATA_SHARE_SERVICE_CMD_NOTIFY_SYSTEM, + DATA_SHARE_SERVICE_CMD_NOTIFY_OBSERVERS_SYSTEM, + DATA_SHARE_SERVICE_CMD_SET_SILENT_SWITCH_SYSTEM, + DATA_SHARE_SERVICE_CMD_GET_SILENT_PROXY_STATUS_SYSTEM, + DATA_SHARE_SERVICE_CMD_REGISTER_OBSERVER_SYSTEM, + DATA_SHARE_SERVICE_CMD_UNREGISTER_OBSERVER_SYSTEM, + DATA_SHARE_SERVICE_CMD_INSERTEX_SYSTEM, + DATA_SHARE_SERVICE_CMD_DELETEEX_SYSTEM, + DATA_SHARE_SERVICE_CMD_UPDATEEX_SYSTEM, + DATA_SHARE_SERVICE_CMD_MAX_SYSTEM }; enum { DATA_SHARE_ERROR = -1, DATA_SHARE_OK = 0 }; -- Gitee From f2fcb73e2390e4288c94f70b7f3af721b01c4861 Mon Sep 17 00:00:00 2001 From: wenjinchao Date: Thu, 20 Mar 2025 12:33:59 +0800 Subject: [PATCH 048/225] transfer to entries Signed-off-by: wenjinchao Change-Id: Ib05fdf9d52f2f96d28bbe6b867f06734602abba6 --- .../service/test/udmf_service_impl_test.cpp | 3 ++- .../service/udmf/udmf_service_impl.cpp | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp index 258c27ca2..d93a55905 100644 --- a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp @@ -237,6 +237,7 @@ HWTEST_F(UdmfServiceImplTest, TransferToEntriesIfNeedTest001, TestSize.Level1) UdmfServiceImpl udmfServiceImpl; udmfServiceImpl.TransferToEntriesIfNeed(query, data); EXPECT_TRUE(data.IsNeedTransferToEntries()); - EXPECT_EQ(data.GetRecords().size(), 2); + int recordSize = 2; + EXPECT_EQ(data.GetRecords().size(), recordSize); } }; // namespace UDMF \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 288a778a6..eb45d9334 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -872,11 +872,11 @@ bool UdmfServiceImpl::IsNeedTransferDeviceType(const QueryOption &query) bundleManager->GetBundleInfoV9(bundleName, static_cast( AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE), bundleInfo, userId); for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) { - if (std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), + if (std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), DEVICE_PHONE_TAG) == hapModuleInfo.deviceTypes.end() - && std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), + && std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), DEVICE_DEFAULT_TAG) == hapModuleInfo.deviceTypes.end() - && std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), + && std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), DEVICE_2IN1_TAG) != hapModuleInfo.deviceTypes.end()) { return true; } -- Gitee From 7b9e3470fe161603cdb988473ce776f8fac286ae Mon Sep 17 00:00:00 2001 From: wenjinchao Date: Thu, 20 Mar 2025 12:41:20 +0800 Subject: [PATCH 049/225] transfer to entries Signed-off-by: wenjinchao Change-Id: I18dbf5dbd62f1c384b6dbffd8a32fb43c0cfce61 --- .../distributeddataservice/service/udmf/udmf_service_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index eb45d9334..40027876c 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -873,7 +873,7 @@ bool UdmfServiceImpl::IsNeedTransferDeviceType(const QueryOption &query) AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE), bundleInfo, userId); for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) { if (std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), - DEVICE_PHONE_TAG) == hapModuleInfo.deviceTypes.end() + DEVICE_PHONE_TAG) == hapModuleInfo.deviceTypes.end() && std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), DEVICE_DEFAULT_TAG) == hapModuleInfo.deviceTypes.end() && std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), -- Gitee From 9da541af33c3ff5b1918335aa0c2d59e321c4076 Mon Sep 17 00:00:00 2001 From: yangliu Date: Thu, 20 Mar 2025 15:04:57 +0800 Subject: [PATCH 050/225] del code Signed-off-by: yangliu --- .../app/src/kvstore_meta_manager.cpp | 151 +++++++----------- .../app/src/kvstore_meta_manager.h | 16 +- .../distributeddataservice/framework/BUILD.gn | 2 +- ..._pair_meta_data.h => deviceid_meta_data.h} | 4 +- .../include/metadata/meta_data_manager.h | 2 - .../include/metadata/strategy_meta_data.h | 1 - .../framework/include/utils/constant.h | 5 - ...r_meta_data.cpp => deviceid_meta_data.cpp} | 2 +- .../framework/metadata/meta_data_manager.cpp | 27 ---- .../framework/test/meta_data_test.cpp | 43 +---- .../framework/utils/constant.cpp | 31 ---- 11 files changed, 74 insertions(+), 210 deletions(-) rename services/distributeddataservice/framework/include/metadata/{deviceid_pair_meta_data.h => deviceid_meta_data.h} (97%) rename services/distributeddataservice/framework/metadata/{deviceid_pair_meta_data.cpp => deviceid_meta_data.cpp} (96%) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 9a4ddffd1..5857b3add 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -35,7 +35,7 @@ #include "matrix_event.h" #include "metadata/auto_launch_meta_data.h" #include "metadata/capability_meta_data.h" -#include "metadata/deviceid_pair_meta_data.h" +#include "metadata/deviceid_meta_data.h" #include "metadata/meta_data_manager.h" #include "metadata/matrix_meta_data.h" #include "metadata/strategy_meta_data.h" @@ -595,16 +595,10 @@ bool KvStoreMetaManager::IsMetaDeviceIdChanged(const std::string &localUUID) void KvStoreMetaManager::UpdateMetaDeviceId(const std::string ¤tUUID) { UpdateStoreMetaData(currentUUID); - UpdateMatrixMetaData(currentUUID); - UpdateUserMetaData(currentUUID); - UpdateCapMetaData(currentUUID); - UpdateStrategyMetaData(currentUUID); + UpdateMetaData(currentUUID); UpdateStoreMetaData(currentUUID, true); - UpdateMatrixMetaData(currentUUID, true); - UpdateSwitchesMetaData(currentUUID, true); - UpdateLocalMetaData(currentUUID, true); - UpdateAutoLaunchMetaData(currentUUID, true); + UpdateMetaData(currentUUID, true); } void KvStoreMetaManager::UpdateStoreMetaData(const std::string ¤tUUID, bool isLocal) @@ -612,104 +606,81 @@ void KvStoreMetaManager::UpdateStoreMetaData(const std::string ¤tUUID, boo std::vector storeMetas; MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ oldUUID_ }), storeMetas, isLocal); for (auto &storeMeta : storeMetas) { + auto oldMeta = storeMeta; if (isLocal) { storeMeta.isNeedUpdateDeviceId = true; } MetaDataManager::GetInstance().DelMeta(storeMeta.GetKey(), isLocal); storeMeta.deviceId = currentUUID; MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), storeMeta, isLocal); - } -} - -void KvStoreMetaManager::UpdateLocalMetaData(const std::string ¤tUUID, bool isLocal) -{ - std::vector localMetaDatas; - MetaDataManager::GetInstance().LoadMetaPair("KvStoreMetaDataLocal", localMetaDatas, isLocal); - for (const auto &localMetaData : localMetaDatas) { - StoreMetaDataLocal storeMetaDataLocal; - std::string metaKey(localMetaData.key.begin(), localMetaData.key.end()); - Serializable::Unmarshall({ localMetaData.value.begin(), localMetaData.value.end() }, storeMetaDataLocal); - auto spliteTokens = Constant::SplitKeepSpace(metaKey, Constant::KEY_SEPARATOR); - if (spliteTokens.size() > SPLITE_MIN_SIZE) { - spliteTokens[UUID_LOCATION] = currentUUID; + + if (!isLocal) { + StrategyMeta strategyMeta("", "", "", ""); + if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetStrategyKey(), strategyMeta)) { + MetaDataManager::GetInstance().DelMeta(oldMeta.GetStrategyKey()); + strategyMeta.devId = currentUUID; + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetStrategyKey(), strategyMeta); + } } - auto newKey = Constant::vectorToString(spliteTokens); - MetaDataManager::GetInstance().SaveMeta(newKey, storeMetaDataLocal, isLocal); - MetaDataManager::GetInstance().DelMeta(metaKey, isLocal); - } -} -void KvStoreMetaManager::UpdateAutoLaunchMetaData(const std::string ¤tUUID, bool isLocal) -{ - std::vector autoLaunchMetaDatas; - MetaDataManager::GetInstance().LoadMetaPair("AutoLaunchMetaData", autoLaunchMetaDatas, isLocal); - for (const auto &metaData : autoLaunchMetaDatas) { - AutoLaunchMetaData autoLaunchMetaData; - std::string metaKey(metaData.key.begin(), metaData.key.end()); - Serializable::Unmarshall({ metaData.value.begin(), metaData.value.end() }, autoLaunchMetaData); - auto spliteTokens = Constant::SplitKeepSpace(metaKey, Constant::KEY_SEPARATOR); - if (spliteTokens.size() > SPLITE_MIN_SIZE) { - spliteTokens[UUID_LOCATION] = currentUUID; + if (isLocal) { + StoreMetaDataLocal metaDataLocal; + if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetKeyLocal(), metaDataLocal, isLocal)) { + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKeyLocal(), isLocal); + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKeyLocal(), metaDataLocal, isLocal); + } + + AutoLaunchMetaData autoLaunchMetaData; + bool isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, isLocal); + if (!isExist) { + oldMeta.storeId = ""; + isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, isLocal); + } + if (isExist) { + MetaDataManager::GetInstance().DelMeta(oldMeta.GetAutoLaunchKey(), isLocal); + oldMeta.deviceId = currentUUID; + MetaDataManager::GetInstance().SaveMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, isLocal); + } } - auto newKey = Constant::vectorToString(spliteTokens); - MetaDataManager::GetInstance().SaveMeta(newKey, autoLaunchMetaData, isLocal); - MetaDataManager::GetInstance().DelMeta(metaKey, isLocal); - } -} - -void KvStoreMetaManager::UpdateStrategyMetaData(const std::string ¤tUUID, bool isLocal) -{ - std::vector strategyMetas; - MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ oldUUID_ }), strategyMetas, isLocal); - for (auto &strategyMeta : strategyMetas) { - MetaDataManager::GetInstance().DelMeta(strategyMeta.GetKey(), isLocal); - storeMeta.devId = currentUUID; - MetaDataManager::GetInstance().SaveMeta(strategyMeta.GetKey(), strategyMeta, isLocal); } } -void KvStoreMetaManager::UpdateMatrixMetaData(const std::string ¤tUUID, bool isLocal) +void KvStoreMetaManager::UpdateMetaData(const std::string ¤tUUID, bool isLocal) { - MatrixMetaData matrixMetas; - bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), - matrixMetas, isLocal); + MatrixMetaData matrixMeta; + bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), matrixMeta, isLocal); if (isExist) { MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), isLocal); - MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({ currentUUID }), matrixMetas, isLocal); - } -} - -void KvStoreMetaManager::UpdateSwitchesMetaData(const std::string ¤tUUID, bool isLocal) -{ - SwitchesMetaData switchesMetaData; - bool isExist = MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({ oldUUID_ }), - switchesMetaData, isLocal); - if (isExist) { - MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({ oldUUID_ }), isLocal); - MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({currentUUID}), switchesMetaData, isLocal); - } -} - -void KvStoreMetaManager::UpdateUserMetaData(const std::string ¤tUUID, bool isLocal) -{ - UserMetaData userMetas; - bool isExist = MetaDataManager::GetInstance().LoadMeta(UserMetaRow::GetKeyFor(oldUUID_), userMetas, isLocal); - if (isExist) { - MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor(oldUUID_), isLocal); - MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor(currentUUID), userMetas, isLocal); + matrixMeta.deviceId = currentUUID; + MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({ currentUUID }), matrixMeta, isLocal); + } + + if (isLocal) { + SwitchesMetaData switchesMetaData; + if (MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({ oldUUID_ }), + switchesMetaData, isLocal)) { + MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({ oldUUID_ }), isLocal); + switchesMetaData.deviceId = currentUUID; + MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({ currentUUID }), + switchesMetaData, isLocal); + } } -} -void KvStoreMetaManager::UpdateCapMetaData(const std::string ¤tUUID, bool isLocal) -{ - CapMetaData capMetaData; - auto capKey = CapMetaRow::GetKeyFor(oldUUID_); - bool isExist = MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), - capMetaData, isLocal); - if (isExist) { - auto newCapKey = CapMetaRow::GetKeyFor(currentUUID); - MetaDataManager::GetInstance().DelMeta(std::string(capKey.begin(), capKey.end()), isLocal); - MetaDataManager::GetInstance().SaveMeta(std::string(newCapKey.begin(), newCapKey.end()), capMetaData, isLocal); + if (!isLocal) { + UserMetaData userMeta; + if (MetaDataManager::GetInstance().LoadMeta(UserMetaRow::GetKeyFor(oldUUID_), userMeta)) { + MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor(oldUUID_)); + userMeta.deviceId = currentUUID; + MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor(currentUUID), userMeta); + } + + CapMetaData capMetaData; + auto capKey = CapMetaRow::GetKeyFor(oldUUID_); + if (MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), capMetaData)) { + auto newCapKey = CapMetaRow::GetKeyFor(currentUUID); + MetaDataManager::GetInstance().DelMeta(std::string(capKey.begin(), capKey.end())); + MetaDataManager::GetInstance().SaveMeta(std::string(newCapKey.begin(), newCapKey.end()), capMetaData); + } } } } // namespace DistributedKv diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index ce3267fc9..0390259c3 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -101,20 +101,8 @@ private: bool IsMetaDeviceIdChanged(const std::string ¤tUUID); void UpdateStoreMetaData(const std::string ¤tUUID, bool isLocal = false); - - void UpdateLocalMetaData(const std::string ¤tUUID, bool isLocal = false); - - void UpdateAutoLaunchMetaData(const std::string ¤tUUID, bool isLocal = false); - - void UpdateStrategyMetaData(const std::string ¤tUUID, bool isLocal = false); - - void UpdateMatrixMetaData(const std::string ¤tUUID, bool isLocal = false); - - void UpdateSwitchesMetaData(const std::string ¤tUUID, bool isLocal = false); - - void UpdateUserMetaData(const std::string ¤tUUID, bool isLocal = false); - - void UpdateCapMetaData(const std::string ¤tUUID, bool isLocal = false); + + void UpdateMetaData(const std::string ¤tUUID, bool isLocal = false); static ExecutorPool::Task GetBackupTask( TaskQueue queue, std::shared_ptr executors, const NbDelegate store); diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index 564140bf5..4767b6d0a 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -88,7 +88,7 @@ ohos_shared_library("distributeddatasvcfwk") { "metadata/capability_meta_data.cpp", "metadata/capability_range.cpp", "metadata/corrupted_meta_data.cpp", - "metadata/deviceid_pair_meta_data.cpp", + "metadata/deviceid_meta_data.cpp", "metadata/matrix_meta_data.cpp", "metadata/meta_data.cpp", "metadata/meta_data_manager.cpp", diff --git a/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h b/services/distributeddataservice/framework/include/metadata/deviceid_meta_data.h similarity index 97% rename from services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h rename to services/distributeddataservice/framework/include/metadata/deviceid_meta_data.h index 581b3ece9..5212d2e5d 100644 --- a/services/distributeddataservice/framework/include/metadata/deviceid_pair_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/deviceid_meta_data.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_PAIR_META_DATA_H -#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_PAIR_META_DATA_H +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_META_DATA_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_META_DATA_H #include #include "serializable/serializable.h" diff --git a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h index 4eb76f0ee..8678a7614 100644 --- a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h +++ b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h @@ -83,8 +83,6 @@ public: API_EXPORT bool Subscribe(std::string prefix, Observer observer, bool isLocal = false); API_EXPORT bool Unsubscribe(std::string filter); API_EXPORT bool Sync(const std::vector &devices, OnComplete complete, bool wait = false); - API_EXPORT bool LoadMetaPair(const std::string &prefix, std::vector &entries, - bool isLocal = false); private: MetaDataManager(); ~MetaDataManager(); diff --git a/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h index 25feaeded..a3cb9275b 100644 --- a/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h @@ -29,7 +29,6 @@ struct API_EXPORT StrategyMeta final : public Serializable { API_EXPORT StrategyMeta(const std::string &devId, const std::string &userId, const std::string &bundleName, const std::string &storeId); - API_EXPORT StrategyMeta() {}; API_EXPORT ~StrategyMeta() {}; API_EXPORT bool Marshal(json &node) const override; API_EXPORT bool Unmarshal(const json &node) override; diff --git a/services/distributeddataservice/framework/include/utils/constant.h b/services/distributeddataservice/framework/include/utils/constant.h index 965267623..bfeaee6b3 100644 --- a/services/distributeddataservice/framework/include/utils/constant.h +++ b/services/distributeddataservice/framework/include/utils/constant.h @@ -44,11 +44,6 @@ public: API_EXPORT static std::vector Split(const std::string &str, const std::string &delim); - API_EXPORT static std::vector SplitKeepSpace(const std::string &str, const std::string &delim); - - API_EXPORT static std::string vectorToString(const std::vector &vec, - const std::string separator = "###"); - template inline static constexpr bool is_pod = (std::is_standard_layout_v && std::is_trivial_v); diff --git a/services/distributeddataservice/framework/metadata/deviceid_pair_meta_data.cpp b/services/distributeddataservice/framework/metadata/deviceid_meta_data.cpp similarity index 96% rename from services/distributeddataservice/framework/metadata/deviceid_pair_meta_data.cpp rename to services/distributeddataservice/framework/metadata/deviceid_meta_data.cpp index c8483699d..33f0aee46 100644 --- a/services/distributeddataservice/framework/metadata/deviceid_pair_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/deviceid_meta_data.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "metadata/deviceid_pair_meta_data.h" +#include "metadata/deviceid_meta_data.h" namespace OHOS { namespace DistributedData { diff --git a/services/distributeddataservice/framework/metadata/meta_data_manager.cpp b/services/distributeddataservice/framework/metadata/meta_data_manager.cpp index bb7641b7f..e7ade4b82 100644 --- a/services/distributeddataservice/framework/metadata/meta_data_manager.cpp +++ b/services/distributeddataservice/framework/metadata/meta_data_manager.cpp @@ -353,31 +353,4 @@ void MetaDataManager::StopSA() ZLOGE("stop distributeddata failed, errCode: %{public}d", err); } } - -bool MetaDataManager::LoadMetaPair(const std::string &prefix, std::vector &entries, bool isLocal) -{ - std::vector dbEntries; - auto status = isLocal ? metaStore_->GetLocalEntries({ prefix.begin(), prefix.end() }, dbEntries) - : metaStore_->GetEntries({ prefix.begin(), prefix.end() }, dbEntries); - if (status == DistributedDB::DBStatus::INVALID_PASSWD_OR_CORRUPTED_DB) { - ZLOGE("db corrupted! status:%{public}d isLocal:%{public}d", status, isLocal); - CorruptReporter::CreateCorruptedFlag(DirectoryManager::GetInstance().GetMetaStorePath(), storeId_); - StopSA(); - return false; - } - if (status != DistributedDB::DBStatus::OK && status != DistributedDB::DBStatus::NOT_FOUND) { - ZLOGE("failed! prefix:%{public}s status:%{public}d isLocal:%{public}d", Anonymous::Change(prefix).c_str(), - status, isLocal); - return false; - } - entries.resize(dbEntries.size()); - auto it = entries.begin(); - for (auto &dbEntry : dbEntries) { - auto &entry = *it; - entry.key = std::move(dbEntry.key); - entry.value = std::move(dbEntry.value); - ++it; - } - return true; -} } // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index d770bed1e..f093d159b 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -27,7 +27,7 @@ #include "metadata/store_meta_data_local.h" #include "metadata/strategy_meta_data.h" #include "metadata/user_meta_data.h" -#include "metadata/deviceid_pair_meta_data.h" +#include "metadata/deviceid_pair_data.h" #include "utils/constant.h" #include "gtest/gtest.h" #include @@ -832,41 +832,12 @@ HWTEST_F(ServiceMetaDataTest, DeviceIDMetaData, TestSize.Level1) * @tc.require: * @tc.author: yl */ -HWTEST_F(ServiceMetaDataTest, LoadMatePair, TestSize.Level1) +HWTEST_F(ServiceMetaDataTest, GetPrefixTest, TestSize.Level1) { - StoreMetaData storeMetaData("100", "appid", "test_store"); - storeMetaData.version = TEST_CURRENT_VERSION; - storeMetaData.instanceId = 1; - std::vector entries; - - std::string key = storeMetaData.GetKey(); - EXPECT_EQ(key, "KvStoreMetaData######100###default######test_store_001###1"); - auto result = MetaDataManager::GetInstance().SaveMeta(key, storeMetaData, true); - EXPECT_TRUE(result); - result = MetaDataManager::GetInstance().LoadMatePair(key, entries, true); - EXPECT_TRUE(result); - EXPECT_EQ(entries.size(), 1); - std::string key(entries[0].key.begin(), entries[0].key.end()); - storeMetaData value; - Serializable::Unmarshall({ entries[0].value.begin(), entries[0].value.end() }, value); - EXPECT_EQ(storeMetaData.GetKey(), key); - - auto tokens = Constant::SplitKeepSpace(key, Constant::KEY_SEPARATOR); - if (tokens.size() > 1) { - tokens[1] = "updateuuid"; - } - std::string newKey = ""; - std::string separator = "###"; - std::for_each(tokens.begin(), tokens.end(), [&](const std::string &info) { - if (!newKey.empty()) { - newKey += separator; - } - newKey += info; - }); - EXPECT_TRUE(!newKey.empty()); - result = MetaDataManager::GetInstance().SaveMeta(newKey, value, true); - EXPECT_TRUE(result); - result = MetaDataManager::GetInstance().DelMeta(key, true); - EXPECT_TRUE(result); + DeviceIDMetaData metaData; + std::string expectPrefix = "DeviceIDMeta"; + std::string prefix = metaData.GetKey(); + + EXPECT_EQ(prefix, expectPrefix); } } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/framework/utils/constant.cpp b/services/distributeddataservice/framework/utils/constant.cpp index 93e84c1b4..6fedf3f61 100644 --- a/services/distributeddataservice/framework/utils/constant.cpp +++ b/services/distributeddataservice/framework/utils/constant.cpp @@ -70,37 +70,6 @@ std::vector Constant::Split(const std::string &str, const std::stri return res; } -std::vector Constant::SplitKeepSpace(const std::string &str, const std::string &delim) -{ - if (str.empty()) { - return { str }; - } - std::vector res; - size_t pos = 0; - while (pos <= str.size()) { - size_t found = str.find(delim, pos); - if (found == std::string::npos) { - res.push_back(str.substr(pos)); - break; - } - res.push_back(str.substr(pos, found - pos)); - pos = found + delim.size(); - } - return res; -} - -std::string Constant::vectorToString(const std::vector &vec, const std::string separator) -{ - std::string result; - std::for_each(vec.begin(), vec.end(), [&](const std::string &info) { - if (!result.empty()) { - result += separator; - } - result += info; - }); - return result; -} - bool Constant::Equal(bool first, bool second) { return (first && second) || (!first && !second); -- Gitee From f0735f8dceb1f08eecbb452e0cac119e53a57f81 Mon Sep 17 00:00:00 2001 From: yangliu Date: Thu, 20 Mar 2025 15:07:55 +0800 Subject: [PATCH 051/225] del code Signed-off-by: yangliu --- .../framework/include/metadata/meta_data_manager.h | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h index 8678a7614..5a6153e16 100644 --- a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h +++ b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h @@ -51,10 +51,7 @@ public: using Backup = std::function &)>; using Bytes = std::vector; using OnComplete = std::function &)>; - struct Entry { - Bytes key; - Bytes value; - }; + API_EXPORT static MetaDataManager &GetInstance(); API_EXPORT void Initialize(std::shared_ptr metaStore, const Backup &backup, const std::string &storeId); API_EXPORT void SetSyncer(const Syncer &syncer); @@ -83,6 +80,7 @@ public: API_EXPORT bool Subscribe(std::string prefix, Observer observer, bool isLocal = false); API_EXPORT bool Unsubscribe(std::string filter); API_EXPORT bool Sync(const std::vector &devices, OnComplete complete, bool wait = false); + private: MetaDataManager(); ~MetaDataManager(); -- Gitee From 94eff829c377e8fa6ea2af494b469cf45d140457 Mon Sep 17 00:00:00 2001 From: yangliu Date: Thu, 20 Mar 2025 15:55:30 +0800 Subject: [PATCH 052/225] del code Signed-off-by: yangliu --- .../framework/include/metadata/meta_data_manager.h | 1 - .../distributeddataservice/framework/test/meta_data_test.cpp | 5 ++--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h index 5a6153e16..08a2465c4 100644 --- a/services/distributeddataservice/framework/include/metadata/meta_data_manager.h +++ b/services/distributeddataservice/framework/include/metadata/meta_data_manager.h @@ -51,7 +51,6 @@ public: using Backup = std::function &)>; using Bytes = std::vector; using OnComplete = std::function &)>; - API_EXPORT static MetaDataManager &GetInstance(); API_EXPORT void Initialize(std::shared_ptr metaStore, const Backup &backup, const std::string &storeId); API_EXPORT void SetSyncer(const Syncer &syncer); diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index f093d159b..3da0500fa 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -826,8 +826,8 @@ HWTEST_F(ServiceMetaDataTest, DeviceIDMetaData, TestSize.Level1) } /** - * @tc.name: LoadMatePair - * @tc.desc: test LoadMatePair function + * @tc.name: GetKeyTest + * @tc.desc: test GetKey function * @tc.type: FUNC * @tc.require: * @tc.author: yl @@ -837,7 +837,6 @@ HWTEST_F(ServiceMetaDataTest, GetPrefixTest, TestSize.Level1) DeviceIDMetaData metaData; std::string expectPrefix = "DeviceIDMeta"; std::string prefix = metaData.GetKey(); - EXPECT_EQ(prefix, expectPrefix); } } // namespace OHOS::Test \ No newline at end of file -- Gitee From f65e5c55b9b1655e0b6e6f035b3b3afee8ff174f Mon Sep 17 00:00:00 2001 From: yangliu Date: Thu, 20 Mar 2025 16:22:00 +0800 Subject: [PATCH 053/225] del code Signed-off-by: yangliu --- .../app/src/kvstore_meta_manager.cpp | 11 ++++++----- .../framework/include/metadata/deviceid_meta_data.h | 2 +- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 5857b3add..77210e5b8 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -64,8 +64,6 @@ using namespace std::chrono; using namespace OHOS::DistributedData; using namespace DistributedDB; using namespace OHOS::AppDistributedKv; -constexpr const int UUID_LOCATION = 1; -constexpr const int SPLITE_MIN_SIZE = 1; KvStoreMetaManager::MetaDeviceChangeListenerImpl KvStoreMetaManager::listener_; KvStoreMetaManager::DBInfoDeviceChangeListenerImpl KvStoreMetaManager::dbInfoListener_; @@ -631,10 +629,12 @@ void KvStoreMetaManager::UpdateStoreMetaData(const std::string ¤tUUID, boo } AutoLaunchMetaData autoLaunchMetaData; - bool isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, isLocal); + bool isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), + autoLaunchMetaData, isLocal); if (!isExist) { oldMeta.storeId = ""; - isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, isLocal); + isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), + autoLaunchMetaData, isLocal); } if (isExist) { MetaDataManager::GetInstance().DelMeta(oldMeta.GetAutoLaunchKey(), isLocal); @@ -648,7 +648,8 @@ void KvStoreMetaManager::UpdateStoreMetaData(const std::string ¤tUUID, boo void KvStoreMetaManager::UpdateMetaData(const std::string ¤tUUID, bool isLocal) { MatrixMetaData matrixMeta; - bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), matrixMeta, isLocal); + bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), + matrixMeta, isLocal); if (isExist) { MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), isLocal); matrixMeta.deviceId = currentUUID; diff --git a/services/distributeddataservice/framework/include/metadata/deviceid_meta_data.h b/services/distributeddataservice/framework/include/metadata/deviceid_meta_data.h index 5212d2e5d..b9e104f8a 100644 --- a/services/distributeddataservice/framework/include/metadata/deviceid_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/deviceid_meta_data.h @@ -33,4 +33,4 @@ private: static constexpr const char *KEY_PREFIX = "DeviceIDMeta"; }; } // namespace OHOS::DistributedData -#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_APPID_META_DATA_H \ No newline at end of file +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_META_DATA_H \ No newline at end of file -- Gitee From d8f2d36bc76ded8f6c7170d4ee9e60c07eba0613 Mon Sep 17 00:00:00 2001 From: archane Date: Thu, 20 Mar 2025 14:24:40 +0800 Subject: [PATCH 054/225] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=A4=87=E4=BB=BD?= =?UTF-8?q?=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: archane Change-Id: I75d3bb9b2cbf0a1513a419b9f3cbcb587c1f4125 --- .../service/data_share/common/db_delegate.h | 4 +-- .../service/data_share/common/kv_delegate.cpp | 34 ++++++++++++------- .../service/data_share/common/kv_delegate.h | 7 ++-- .../data_share/common/rdb_delegate.cpp | 2 +- .../data_share/data/published_data.cpp | 10 +++--- .../service/data_share/data/template_data.cpp | 18 ++++++---- .../data_share/data_share_service_impl.cpp | 2 +- .../data_share/dfx/hiview_fault_adapter.cpp | 18 +++++----- .../data_share/dfx/hiview_fault_adapter.h | 27 +++++++-------- .../strategies/publish_strategy.cpp | 2 +- 10 files changed, 69 insertions(+), 55 deletions(-) diff --git a/services/distributeddataservice/service/data_share/common/db_delegate.h b/services/distributeddataservice/service/data_share/common/db_delegate.h index 67bde3ade..0cb36808d 100644 --- a/services/distributeddataservice/service/data_share/common/db_delegate.h +++ b/services/distributeddataservice/service/data_share/common/db_delegate.h @@ -128,8 +128,8 @@ public: static std::shared_ptr GetInstance( bool reInit = false, const std::string &dir = "", const std::shared_ptr &executors = nullptr); virtual ~KvDBDelegate() = default; - virtual int32_t Upsert(const std::string &collectionName, const KvData &value) = 0; - virtual int32_t Delete(const std::string &collectionName, const std::string &filter) = 0; + virtual std::pair Upsert(const std::string &collectionName, const KvData &value) = 0; + virtual std::pair Delete(const std::string &collectionName, const std::string &filter) = 0; virtual int32_t Get(const std::string &collectionName, const Id &id, std::string &value) = 0; virtual int32_t Get(const std::string &collectionName, const std::string &filter, const std::string &projection, std::string &result) = 0; diff --git a/services/distributeddataservice/service/data_share/common/kv_delegate.cpp b/services/distributeddataservice/service/data_share/common/kv_delegate.cpp index 06f8cc6a2..be360b40b 100644 --- a/services/distributeddataservice/service/data_share/common/kv_delegate.cpp +++ b/services/distributeddataservice/service/data_share/common/kv_delegate.cpp @@ -40,7 +40,8 @@ const char* g_backupFiles[] = { "dataShare.db.safe", "dataShare.db.undo", }; -const char* BACKUP_SUFFIX = ".backup"; +constexpr const char* BACKUP_SUFFIX = ".backup"; +constexpr std::chrono::milliseconds COPY_TIME_OUT_MS = std::chrono::milliseconds(500); // If isBackUp is true, remove db backup files. Otherwise remove source db files. void KvDelegate::RemoveDbFile(bool isBackUp) const @@ -65,12 +66,15 @@ bool KvDelegate::CopyFile(bool isBackup) std::filesystem::copy_options options = std::filesystem::copy_options::overwrite_existing; std::error_code code; bool ret = true; + int index = 0; for (auto &fileName : g_backupFiles) { std::string src = path_ + "/" + fileName; std::string dst = src; isBackup ? dst.append(BACKUP_SUFFIX) : src.append(BACKUP_SUFFIX); + TimeoutReport timeoutReport({"", "", "", __FUNCTION__, 0}); // If src doesn't exist, error will be returned through `std::error_code` bool copyRet = std::filesystem::copy_file(src, dst, options, code); + timeoutReport.Report(("file index:" + std::to_string(index)), COPY_TIME_OUT_MS); if (!copyRet) { ZLOGE("failed to copy file %{public}s, isBackup %{public}d, err: %{public}s", fileName, isBackup, code.message().c_str()); @@ -78,6 +82,7 @@ bool KvDelegate::CopyFile(bool isBackup) RemoveDbFile(isBackup); break; } + index++; } return ret; } @@ -128,29 +133,30 @@ bool KvDelegate::RestoreIfNeed(int32_t dbStatus) return false; } -int64_t KvDelegate::Upsert(const std::string &collectionName, const std::string &filter, const std::string &value) +std::pair KvDelegate::Upsert(const std::string &collectionName, const std::string &filter, + const std::string &value) { std::lock_guard lock(mutex_); if (!Init()) { ZLOGE("init failed, %{public}s", collectionName.c_str()); - return E_ERROR; + return std::make_pair(E_ERROR, 0); } - int count = GRD_UpsertDoc(db_, collectionName.c_str(), filter.c_str(), value.c_str(), 0); + int32_t count = GRD_UpsertDoc(db_, collectionName.c_str(), filter.c_str(), value.c_str(), 0); if (count <= 0) { ZLOGE("GRD_UpSertDoc failed,status %{public}d", count); RestoreIfNeed(count); - return count; + return std::make_pair(count, 0); } Flush(); - return E_OK; + return std::make_pair(E_OK, count); } -int32_t KvDelegate::Delete(const std::string &collectionName, const std::string &filter) +std::pair KvDelegate::Delete(const std::string &collectionName, const std::string &filter) { std::lock_guard lock(mutex_); if (!Init()) { ZLOGE("init failed, %{public}s", collectionName.c_str()); - return E_ERROR; + return std::make_pair(E_ERROR, 0); } std::vector queryResults; @@ -158,23 +164,25 @@ int32_t KvDelegate::Delete(const std::string &collectionName, const std::string if (status != E_OK) { ZLOGE("db GetBatch failed, %{public}s %{public}d", filter.c_str(), status); // `GetBatch` should decide whether to restore before errors are returned, so skip restoration here. - return status; + return std::make_pair(status, 0); } + int32_t deleteCount = 0; for (auto &result : queryResults) { auto count = GRD_DeleteDoc(db_, collectionName.c_str(), result.c_str(), 0); if (count < 0) { ZLOGE("GRD_DeleteDoc failed,status %{public}d %{public}s", count, result.c_str()); if (RestoreIfNeed(count)) { - return count; + return std::make_pair(count, 0); } continue; } + deleteCount += count; } Flush(); if (queryResults.size() > 0) { ZLOGI("Delete, %{public}s, count %{public}zu", collectionName.c_str(), queryResults.size()); } - return E_OK; + return std::make_pair(E_OK, deleteCount); } bool KvDelegate::Init() @@ -232,7 +240,7 @@ KvDelegate::~KvDelegate() } } -int32_t KvDelegate::Upsert(const std::string &collectionName, const KvData &value) +std::pair KvDelegate::Upsert(const std::string &collectionName, const KvData &value) { std::string id = value.GetId(); if (value.HasVersion() && value.GetVersion() != 0) { @@ -241,7 +249,7 @@ int32_t KvDelegate::Upsert(const std::string &collectionName, const KvData &valu if (value.GetVersion() <= version) { ZLOGE("GetVersion failed,%{public}s id %{private}s %{public}d %{public}d", collectionName.c_str(), id.c_str(), value.GetVersion(), version); - return E_VERSION_NOT_NEWER; + return std::make_pair(E_VERSION_NOT_NEWER, 0); } } } diff --git a/services/distributeddataservice/service/data_share/common/kv_delegate.h b/services/distributeddataservice/service/data_share/common/kv_delegate.h index 3ec92c7cd..fce4ecf31 100644 --- a/services/distributeddataservice/service/data_share/common/kv_delegate.h +++ b/services/distributeddataservice/service/data_share/common/kv_delegate.h @@ -28,8 +28,8 @@ class KvDelegate final : public KvDBDelegate { public: KvDelegate(const std::string &path, const std::shared_ptr &executors); ~KvDelegate() override; - int32_t Upsert(const std::string &collectionName, const KvData &value) override; - int32_t Delete(const std::string &collectionName, const std::string &filter) override; + std::pair Upsert(const std::string &collectionName, const KvData &value) override; + std::pair Delete(const std::string &collectionName, const std::string &filter) override; int32_t Get(const std::string &collectionName, const Id &id, std::string &value) override; int32_t Get(const std::string &collectionName, const std::string &filter, const std::string &projection, @@ -41,7 +41,8 @@ public: private: bool Init(); bool GetVersion(const std::string &collectionName, const std::string &filter, int &version); - int64_t Upsert(const std::string &collectionName, const std::string &filter, const std::string &value); + std::pair Upsert(const std::string &collectionName, const std::string &filter, + const std::string &value); void Flush(); bool RestoreIfNeed(int32_t dbStatus); void Backup(); diff --git a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp index 9ccf69257..de1036ff2 100644 --- a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp +++ b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp @@ -341,7 +341,7 @@ bool RdbDelegate::IsLimit(int count, int32_t callingPid, uint32_t callingTokenId }); ZLOGE("resultSetCount is full, pid: %{public}d, owner is %{public}s", callingPid, logStr.c_str()); std::string appendix = "callingName:" + HiViewFaultAdapter::GetCallingName(callingTokenId).first; - DataShareFaultInfo faultInfo{RESULTSET_FULL, "callingTokenId:" + std::to_string(callingTokenId), + DataShareFaultInfo faultInfo{HiViewFaultAdapter::resultsetFull, "callingTokenId:" + std::to_string(callingTokenId), "Pid:" + std::to_string(callingPid), "owner:" + logStr, __FUNCTION__, E_RESULTSET_BUSY, appendix}; HiViewFaultAdapter::ReportDataFault(faultInfo); return true; diff --git a/services/distributeddataservice/service/data_share/data/published_data.cpp b/services/distributeddataservice/service/data_share/data/published_data.cpp index 894a8e583..0e73d871a 100644 --- a/services/distributeddataservice/service/data_share/data/published_data.cpp +++ b/services/distributeddataservice/service/data_share/data/published_data.cpp @@ -170,7 +170,7 @@ void PublishedData::Delete(const std::string &bundleName, const int32_t userId) ZLOGE("db open failed"); return; } - int32_t status = delegate->Delete(KvDBDelegate::DATA_TABLE, + auto [status, count] = delegate->Delete(KvDBDelegate::DATA_TABLE, "{\"bundleName\":\"" + bundleName + "\", \"userId\": " + std::to_string(userId) + "}"); if (status != E_OK) { ZLOGE("db Delete failed, %{public}s %{public}d", bundleName.c_str(), status); @@ -209,9 +209,9 @@ void PublishedData::ClearAging() } if (data.timestamp < lastValidTime && PublishedDataSubscriberManager::GetInstance() .GetCount(PublishedDataKey(data.key, data.bundleName, data.subscriberId)) == 0) { - status = delegate->Delete(KvDBDelegate::DATA_TABLE, + auto [errorCode, count] = delegate->Delete(KvDBDelegate::DATA_TABLE, Id(PublishedData::GenId(data.key, data.bundleName, data.subscriberId), data.userId)); - if (status != E_OK) { + if (errorCode != E_OK) { ZLOGE("db Delete failed, %{public}s %{public}s", data.key.c_str(), data.bundleName.c_str()); } agingSize++; @@ -249,8 +249,8 @@ void PublishedData::UpdateTimestamp( return; } data.timestamp = now; - status = delegate->Upsert(KvDBDelegate::DATA_TABLE, PublishedData(data)); - if (status == E_OK) { + auto [errorCode, count] = delegate->Upsert(KvDBDelegate::DATA_TABLE, PublishedData(data)); + if (errorCode == E_OK) { ZLOGI("update timestamp %{private}s", data.key.c_str()); } } diff --git a/services/distributeddataservice/service/data_share/data/template_data.cpp b/services/distributeddataservice/service/data_share/data/template_data.cpp index baf5dc4d5..79219aede 100644 --- a/services/distributeddataservice/service/data_share/data/template_data.cpp +++ b/services/distributeddataservice/service/data_share/data/template_data.cpp @@ -135,13 +135,15 @@ bool TemplateData::Delete(const std::string &bundleName, const int32_t userId) ZLOGE("db open failed"); return false; } - auto status = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE, + auto [status, count] = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE, "{\"bundleName\":\"" + bundleName + "\", \"userId\": " + std::to_string(userId) + "}"); if (status != E_OK) { ZLOGE("db DeleteById failed, %{public}d", status); return false; } - delegate->NotifyBackup(); + if (count > 0) { + delegate->NotifyBackup(); + } return true; } @@ -154,12 +156,14 @@ bool TemplateData::Add(const std::string &uri, const int32_t userId, const std:: return false; } TemplateData data(uri, bundleName, subscriberId, userId, aTemplate); - auto status = delegate->Upsert(KvDBDelegate::TEMPLATE_TABLE, data); + auto [status, count] = delegate->Upsert(KvDBDelegate::TEMPLATE_TABLE, data); if (status != E_OK) { ZLOGE("db Upsert failed, %{public}d", status); return false; } - delegate->NotifyBackup(); + if (count > 0) { + delegate->NotifyBackup(); + } return true; } @@ -171,13 +175,15 @@ bool TemplateData::Delete( ZLOGE("db open failed"); return false; } - auto status = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE, + auto [status, count] = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE, static_cast(Id(TemplateData::GenId(uri, bundleName, subscriberId), userId))); if (status != E_OK) { ZLOGE("db DeleteById failed, %{public}d", status); return false; } - delegate->NotifyBackup(); + if (count > 0) { + delegate->NotifyBackup(); + } return true; } diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp index a837f76f9..02b2ce855 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp @@ -1135,7 +1135,7 @@ void DataShareServiceImpl::ReportExcuteFault(uint32_t callingTokenId, DataProvid int32_t errCode, std::string &func) { std::string appendix = "callingName:" + HiViewFaultAdapter::GetCallingName(callingTokenId).first; - DataShareFaultInfo faultInfo = {CURD_FAILED, providerInfo.bundleName, providerInfo.moduleName, + DataShareFaultInfo faultInfo = {HiViewFaultAdapter::curdFailed, providerInfo.bundleName, providerInfo.moduleName, providerInfo.storeName, func, errCode, appendix}; HiViewFaultAdapter::ReportDataFault(faultInfo); } diff --git a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp index 6f8713521..5b6bdc45b 100644 --- a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp +++ b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp @@ -86,19 +86,19 @@ std::pair HiViewFaultAdapter::GetCallingName(uint32_t callingT return std::make_pair(callingName, result); } -void TimeoutReport::Report() +void TimeoutReport::Report(const std::string &timeoutAppendix, const std::chrono::milliseconds timeoutms) { auto end = std::chrono::steady_clock::now(); std::chrono::milliseconds duration = std::chrono::duration_cast(end - start); // Used to report DFX timeout faults - if (needFaultReport && duration > DFX_TIME_OUT_MS) { + if (needFaultReport && duration > HiViewFaultAdapter::dfxTimeOutMs) { DFXReport(duration); } // Used to report log timeout - if (duration > TIME_OUT_MS) { + if (duration > timeoutms) { int64_t milliseconds = duration.count(); - ZLOGE("over time when doing %{public}s, cost:%{public}" PRIi64 "ms", dfxInfo.businessType.c_str(), - milliseconds); + ZLOGE("over time when doing %{public}s, %{public}s, cost:%{public}" PRIi64 "ms", + dfxInfo.businessType.c_str(), timeoutAppendix.c_str(), milliseconds); } } @@ -107,11 +107,11 @@ void TimeoutReport::Report(const std::string &user, uint32_t callingPid, int32_t auto end = std::chrono::steady_clock::now(); std::chrono::milliseconds duration = std::chrono::duration_cast(end - start); // Used to report DFX timeout faults - if (needFaultReport && duration > DFX_TIME_OUT_MS) { + if (needFaultReport && duration > HiViewFaultAdapter::dfxTimeOutMs) { DFXReport(duration); } // Used to report log timeout - if (duration > TIME_OUT_MS) { + if (duration > HiViewFaultAdapter::timeOutMs) { int64_t milliseconds = duration.count(); std::string timeoutAppendix = "bundleName: " + dfxInfo.bundleName + ", user: " + user + ", callingPid: " + std::to_string(callingPid); @@ -134,8 +134,8 @@ void TimeoutReport::DFXReport(const std::chrono::milliseconds &duration) int64_t milliseconds = duration.count(); std::string appendix = "callingName:" + HiViewFaultAdapter::GetCallingName(dfxInfo.callingTokenId).first; appendix += ",cost:" + std::to_string(milliseconds) + "ms"; - DataShareFaultInfo faultInfo{TIME_OUT, dfxInfo.bundleName, dfxInfo.moduleName, dfxInfo.storeName, - dfxInfo.businessType, errorCode, appendix}; + DataShareFaultInfo faultInfo{HiViewFaultAdapter::timeOut, dfxInfo.bundleName, dfxInfo.moduleName, + dfxInfo.storeName, dfxInfo.businessType, errorCode, appendix}; HiViewFaultAdapter::ReportDataFault(faultInfo); } } diff --git a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h index 00cb42a58..3b001e62d 100644 --- a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h +++ b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h @@ -34,6 +34,17 @@ struct DataShareFaultInfo { std::string appendix; }; +class HiViewFaultAdapter { +public: + static constexpr const std::chrono::milliseconds timeOutMs = std::chrono::milliseconds(300); + static constexpr const std::chrono::milliseconds dfxTimeOutMs = std::chrono::milliseconds(2000); + static constexpr const char* timeOut = "TIME_OUT"; + static constexpr const char* resultsetFull = "RESULTSET_FULL"; + static constexpr const char* curdFailed = "CURD_FAILED"; + static void ReportDataFault(const DataShareFaultInfo &faultInfo); + static std::pair GetCallingName(uint32_t callingTokenid); +}; + // TimeoutReport is used for recording the time usage of multiple interfaces; // It can set up a timeout threshold, and when the time usage exceeds this threshold, will print log; // If want to record DFX fault report, need to set needFaultReport to true (default is false); @@ -54,24 +65,12 @@ struct TimeoutReport { explicit TimeoutReport(const DfxInfo &dfxInfo, bool needFaultReport = false) : dfxInfo(dfxInfo), needFaultReport(needFaultReport) {} - void Report(); + void Report(const std::string &timeoutAppendix = "", + const std::chrono::milliseconds timeoutms = HiViewFaultAdapter::timeOutMs); void Report(const std::string &user, uint32_t callingPid, int32_t appIndex = -1, int32_t instanceId = -1); void DFXReport(const std::chrono::milliseconds &duration); ~TimeoutReport() = default; }; - - -class HiViewFaultAdapter { -public: - static void ReportDataFault(const DataShareFaultInfo &faultInfo); - static std::pair GetCallingName(uint32_t callingTokenid); -}; - -inline const char* TIME_OUT = "TIME_OUT"; -inline const char* RESULTSET_FULL = "RESULTSET_FULL"; -inline const char* CURD_FAILED = "CURD_FAILED"; -inline const std::chrono::milliseconds TIME_OUT_MS = std::chrono::milliseconds(300); -inline const std::chrono::milliseconds DFX_TIME_OUT_MS = std::chrono::milliseconds(2000); } } #endif \ No newline at end of file diff --git a/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp index 26b116d48..b0b7ca77a 100644 --- a/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp @@ -45,7 +45,7 @@ int32_t PublishStrategy::Execute(std::shared_ptr context, const Publish PublishedDataNode node(context->uri, context->calledBundleName, item.subscriberId_, context->currentUserId, PublishedDataNode::MoveTo(value)); PublishedData data(node, context->version); - int32_t status = delegate->Upsert(KvDBDelegate::DATA_TABLE, data); + auto [status, count] = delegate->Upsert(KvDBDelegate::DATA_TABLE, data); if (status != E_OK) { ZLOGE("db Upsert failed, %{public}s %{public}s %{public}d", context->calledBundleName.c_str(), DistributedData::Anonymous::Change(context->uri).c_str(), status); -- Gitee From ebb923764ea3d4f1a6be13b3a53afe74de794024 Mon Sep 17 00:00:00 2001 From: yangliu Date: Thu, 20 Mar 2025 16:44:58 +0800 Subject: [PATCH 055/225] del code Signed-off-by: yangliu --- .../distributeddataservice/framework/test/meta_data_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 3da0500fa..217aa3a82 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -27,7 +27,7 @@ #include "metadata/store_meta_data_local.h" #include "metadata/strategy_meta_data.h" #include "metadata/user_meta_data.h" -#include "metadata/deviceid_pair_data.h" +#include "metadata/deviceid_meta_data.h" #include "utils/constant.h" #include "gtest/gtest.h" #include -- Gitee From 97361606e6b1e928f33fdcf8b683bfb605598466 Mon Sep 17 00:00:00 2001 From: yangliu Date: Thu, 20 Mar 2025 17:44:51 +0800 Subject: [PATCH 056/225] update Signed-off-by: yangliu --- .../distributeddataservice/framework/test/meta_data_test.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 217aa3a82..589afa669 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -805,10 +805,7 @@ HWTEST_F(ServiceMetaDataTest, MatrixMetaData, TestSize.Level1) */ HWTEST_F(ServiceMetaDataTest, DeviceIDMetaData, TestSize.Level1) { - DeviceIDMetaData metaData; - std::string expectedPrefix = "DeviceIDKey"; - std::string prefix = metaData.GetKey(); - + DeviceIDMetaData metaData; ASSERT_EQ(prefix, expectedPrefix); std::string currentUUID = "newuuid"; std::string oldUUID = "olduuid"; -- Gitee From cc5cbb832458ef5e5483ea1e49cbc4254c82c74a Mon Sep 17 00:00:00 2001 From: l30005037 Date: Thu, 20 Mar 2025 21:10:03 +0800 Subject: [PATCH 057/225] Security and privacy compliance requirements Signed-off-by: l30005037 --- .../distributeddataservice/adapter/dfx/test/BUILD.gn | 12 +++++++++--- .../distributeddataservice/adapter/utils/BUILD.gn | 4 +++- services/distributeddataservice/app/BUILD.gn | 4 +++- .../distributeddataservice/app/src/checker/BUILD.gn | 4 +++- services/distributeddataservice/app/test/BUILD.gn | 4 +++- services/distributeddataservice/framework/BUILD.gn | 4 +++- .../distributeddataservice/framework/test/BUILD.gn | 4 +++- services/distributeddataservice/service/BUILD.gn | 4 +++- 8 files changed, 30 insertions(+), 10 deletions(-) diff --git a/services/distributeddataservice/adapter/dfx/test/BUILD.gn b/services/distributeddataservice/adapter/dfx/test/BUILD.gn index 78a3fa45b..e7ee9c851 100755 --- a/services/distributeddataservice/adapter/dfx/test/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/test/BUILD.gn @@ -42,7 +42,9 @@ ohos_unittest("DistributeddataDfxMSTTest") { "kv_store:distributeddata_inner", "openssl:libcrypto_shared", ] - ldflags = [ "-Wl,--exclude-libs,ALL" ] + ldflags = [ + "-Wl,-z,relro,-z,now,--exclude-libs,ALL" + ] deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx", "//third_party/googletest:gtest_main", @@ -83,7 +85,9 @@ ohos_unittest("DistributeddataDfxUTTest") { "kv_store:distributeddata_inner", "openssl:libcrypto_shared", ] - ldflags = [ "-Wl,--exclude-libs,ALL" ] + ldflags = [ + "-Wl,-z,relro,-z,now,--exclude-libs,ALL" + ] deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx", "${data_service_path}/adapter/utils:distributeddata_utils", @@ -115,7 +119,9 @@ ohos_unittest("HiViewAdapterDfxTest") { "kv_store:distributeddata_mgr", "openssl:libcrypto_shared", ] - ldflags = [ "-Wl,--exclude-libs,ALL" ] + ldflags = [ + "-Wl,-z,relro,-z,now,--exclude-libs,ALL" + ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/adapter/dfx:distributeddata_dfx", diff --git a/services/distributeddataservice/adapter/utils/BUILD.gn b/services/distributeddataservice/adapter/utils/BUILD.gn index bf5b815f0..2c6bbb08a 100755 --- a/services/distributeddataservice/adapter/utils/BUILD.gn +++ b/services/distributeddataservice/adapter/utils/BUILD.gn @@ -31,7 +31,9 @@ ohos_source_set("distributeddata_utils") { } include_dirs = [ "../include/utils" ] - ldflags = [ "-Wl,--exclude-libs,ALL" ] + ldflags = [ + "-Wl,-z,relro,-z,now,--exclude-libs,ALL" + ] external_deps = [ "c_utils:utils", diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index 084cbb75e..55b8a8ac4 100644 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -83,7 +83,9 @@ config("module_private_config") { "-Oz", ] - ldflags = [ "-Wl,--gc-sections" ] + ldflags = [ + "-Wl,-z,relro,-z,now,--gc-sections" + ] } ohos_shared_library("distributeddataservice") { diff --git a/services/distributeddataservice/app/src/checker/BUILD.gn b/services/distributeddataservice/app/src/checker/BUILD.gn index f0fa8dd25..544f496ac 100644 --- a/services/distributeddataservice/app/src/checker/BUILD.gn +++ b/services/distributeddataservice/app/src/checker/BUILD.gn @@ -37,7 +37,9 @@ ohos_source_set("distributeddata_checker") { if (build_public_version) { cflags_cc += [ "-DCONFIG_PUBLIC_VERSION" ] } - ldflags = [ "-Wl,--exclude-libs,ALL" ] + ldflags = [ + "-Wl,-z,relro,-z,now,--exclude-libs,ALL" + ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils" ] cflags = [ "-Oz" ] external_deps = [ diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index f3f912893..774e98288 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -65,7 +65,9 @@ config("module_private_config") { "-Dprivate=public", "-Dprotected=public", ] - ldflags = [ "-Wl,--whole-archive" ] + ldflags = [ + "-Wl,-z,relro,-z,now,--whole-archive" + ] defines = [ "TEST_ON_DEVICE", "OPENSSL_SUPPRESS_DEPRECATED", diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index f85d7b550..7d6ae6b90 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -125,7 +125,9 @@ ohos_shared_library("distributeddatasvcfwk") { "-ffunction-sections", ] - ldflags = [ "-Wl,--gc-sections" ] + ldflags = [ + "-Wl,-z,relro,-z,now,--gc-sections" + ] cflags_cc = [ "-fvisibility=hidden" ] diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn index 728d05f26..8b3706750 100644 --- a/services/distributeddataservice/framework/test/BUILD.gn +++ b/services/distributeddataservice/framework/test/BUILD.gn @@ -47,7 +47,9 @@ config("module_private_config") { "//third_party/json/single_include", ] cflags = [ "-Werror" ] - ldflags = [ "-Wl,--whole-archive" ] + ldflags = [ + "-Wl,-z,relro,-z,now,--whole-archive" + ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } diff --git a/services/distributeddataservice/service/BUILD.gn b/services/distributeddataservice/service/BUILD.gn index 952c92895..683dede32 100644 --- a/services/distributeddataservice/service/BUILD.gn +++ b/services/distributeddataservice/service/BUILD.gn @@ -65,7 +65,9 @@ ohos_shared_library("distributeddatasvc") { "-ffunction-sections", ] - ldflags = [ "-Wl,--gc-sections" ] + ldflags = [ + "-Wl,-z,relro,-z,now,--gc-sections" + ] cflags_cc = [ "-fvisibility=hidden", -- Gitee From f57aab520d329e441b47ced8dc61d8c03f772c26 Mon Sep 17 00:00:00 2001 From: l30005037 Date: Thu, 20 Mar 2025 22:07:28 +0800 Subject: [PATCH 058/225] Security and privacy compliance requirements Signed-off-by: l30005037 --- .../distributeddataservice/adapter/dfx/test/BUILD.gn | 12 +++--------- .../distributeddataservice/adapter/utils/BUILD.gn | 4 +--- services/distributeddataservice/app/BUILD.gn | 4 +--- .../distributeddataservice/app/src/checker/BUILD.gn | 4 +--- services/distributeddataservice/app/test/BUILD.gn | 4 +--- services/distributeddataservice/framework/BUILD.gn | 4 +--- .../distributeddataservice/framework/test/BUILD.gn | 4 +--- services/distributeddataservice/service/BUILD.gn | 4 +--- 8 files changed, 10 insertions(+), 30 deletions(-) diff --git a/services/distributeddataservice/adapter/dfx/test/BUILD.gn b/services/distributeddataservice/adapter/dfx/test/BUILD.gn index e7ee9c851..ff7b5fe6b 100755 --- a/services/distributeddataservice/adapter/dfx/test/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/test/BUILD.gn @@ -42,9 +42,7 @@ ohos_unittest("DistributeddataDfxMSTTest") { "kv_store:distributeddata_inner", "openssl:libcrypto_shared", ] - ldflags = [ - "-Wl,-z,relro,-z,now,--exclude-libs,ALL" - ] + ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx", "//third_party/googletest:gtest_main", @@ -85,9 +83,7 @@ ohos_unittest("DistributeddataDfxUTTest") { "kv_store:distributeddata_inner", "openssl:libcrypto_shared", ] - ldflags = [ - "-Wl,-z,relro,-z,now,--exclude-libs,ALL" - ] + ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx", "${data_service_path}/adapter/utils:distributeddata_utils", @@ -119,9 +115,7 @@ ohos_unittest("HiViewAdapterDfxTest") { "kv_store:distributeddata_mgr", "openssl:libcrypto_shared", ] - ldflags = [ - "-Wl,-z,relro,-z,now,--exclude-libs,ALL" - ] + ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/adapter/dfx:distributeddata_dfx", diff --git a/services/distributeddataservice/adapter/utils/BUILD.gn b/services/distributeddataservice/adapter/utils/BUILD.gn index 2c6bbb08a..f96b7fe3e 100755 --- a/services/distributeddataservice/adapter/utils/BUILD.gn +++ b/services/distributeddataservice/adapter/utils/BUILD.gn @@ -31,9 +31,7 @@ ohos_source_set("distributeddata_utils") { } include_dirs = [ "../include/utils" ] - ldflags = [ - "-Wl,-z,relro,-z,now,--exclude-libs,ALL" - ] + ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] external_deps = [ "c_utils:utils", diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index 55b8a8ac4..7748c2fda 100644 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -83,9 +83,7 @@ config("module_private_config") { "-Oz", ] - ldflags = [ - "-Wl,-z,relro,-z,now,--gc-sections" - ] + ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] } ohos_shared_library("distributeddataservice") { diff --git a/services/distributeddataservice/app/src/checker/BUILD.gn b/services/distributeddataservice/app/src/checker/BUILD.gn index 544f496ac..575e9fad2 100644 --- a/services/distributeddataservice/app/src/checker/BUILD.gn +++ b/services/distributeddataservice/app/src/checker/BUILD.gn @@ -37,9 +37,7 @@ ohos_source_set("distributeddata_checker") { if (build_public_version) { cflags_cc += [ "-DCONFIG_PUBLIC_VERSION" ] } - ldflags = [ - "-Wl,-z,relro,-z,now,--exclude-libs,ALL" - ] + ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils" ] cflags = [ "-Oz" ] external_deps = [ diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index 774e98288..f8ae56963 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -65,9 +65,7 @@ config("module_private_config") { "-Dprivate=public", "-Dprotected=public", ] - ldflags = [ - "-Wl,-z,relro,-z,now,--whole-archive" - ] + ldflags = [ "-Wl,-z,relro,-z,now,--whole-archive" ] defines = [ "TEST_ON_DEVICE", "OPENSSL_SUPPRESS_DEPRECATED", diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index 7d6ae6b90..a4b707a6e 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -125,9 +125,7 @@ ohos_shared_library("distributeddatasvcfwk") { "-ffunction-sections", ] - ldflags = [ - "-Wl,-z,relro,-z,now,--gc-sections" - ] + ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] cflags_cc = [ "-fvisibility=hidden" ] diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn index 8b3706750..2cd08bc3d 100644 --- a/services/distributeddataservice/framework/test/BUILD.gn +++ b/services/distributeddataservice/framework/test/BUILD.gn @@ -47,9 +47,7 @@ config("module_private_config") { "//third_party/json/single_include", ] cflags = [ "-Werror" ] - ldflags = [ - "-Wl,-z,relro,-z,now,--whole-archive" - ] + ldflags = [ "-Wl,-z,relro,-z,now,--whole-archive" ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } diff --git a/services/distributeddataservice/service/BUILD.gn b/services/distributeddataservice/service/BUILD.gn index 683dede32..6274b1d1c 100644 --- a/services/distributeddataservice/service/BUILD.gn +++ b/services/distributeddataservice/service/BUILD.gn @@ -65,9 +65,7 @@ ohos_shared_library("distributeddatasvc") { "-ffunction-sections", ] - ldflags = [ - "-Wl,-z,relro,-z,now,--gc-sections" - ] + ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] cflags_cc = [ "-fvisibility=hidden", -- Gitee From fded23dad91e60da6541af78f1e0916186f9045a Mon Sep 17 00:00:00 2001 From: lvcong_oh Date: Tue, 18 Mar 2025 11:03:05 +0800 Subject: [PATCH 059/225] add error detail for dfx Signed-off-by: lvcong_oh --- .../framework/include/store/general_value.h | 1 + .../service/cloud/sync_manager.cpp | 91 +++++++++++-------- .../service/cloud/sync_manager.h | 7 +- 3 files changed, 59 insertions(+), 40 deletions(-) diff --git a/services/distributeddataservice/framework/include/store/general_value.h b/services/distributeddataservice/framework/include/store/general_value.h index e1f9b3a18..888c9f7c1 100644 --- a/services/distributeddataservice/framework/include/store/general_value.h +++ b/services/distributeddataservice/framework/include/store/general_value.h @@ -115,6 +115,7 @@ struct ReportParam { std::string prepareTraceId; SyncStage syncStage = SyncStage::PREPARE; int32_t errCode = 0; + std::string message = ""; }; using Assets = std::vector; diff --git a/services/distributeddataservice/service/cloud/sync_manager.cpp b/services/distributeddataservice/service/cloud/sync_manager.cpp index 139179622..de09414b2 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.cpp +++ b/services/distributeddataservice/service/cloud/sync_manager.cpp @@ -300,14 +300,14 @@ std::function SyncManager::GetPostEventTask(const std::vectorsecond, SyncStage::END, - E_ERROR }); + E_ERROR, "!IsOn:" + schema.bundleName }); continue; } for (const auto &database : schema.databases) { if (!info.Contains(database.name)) { UpdateFinishSyncInfo({ cloud.user, cloud.id, schema.bundleName, database.name }, syncId, E_ERROR); Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second, SyncStage::END, - E_ERROR }); + E_ERROR, "!Contains:" + database.name }); continue; } StoreInfo storeInfo = { 0, schema.bundleName, database.name, cloud.apps[schema.bundleName].instanceId, @@ -318,7 +318,7 @@ std::function SyncManager::GetPostEventTask(const std::vectorsecond, SyncStage::END, - status }); + status, "CheckSyncAction" }); info.SetError(status); continue; } @@ -359,7 +359,7 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount auto code = IsValid(info, cloud); if (code != E_OK) { BatchUpdateFinishState(cloudSyncInfos, code); - BatchReport(info.user_, traceIds, SyncStage::END, code); + BatchReport(info.user_, traceIds, SyncStage::END, code, "!IsValid"); return; } @@ -373,7 +373,7 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount retryer(RETRY_INTERVAL, E_RETRY_TIMEOUT, GenStore::CLOUD_ERR_OFFSET + E_CLOUD_DISABLED, it == traceIds.end() ? "" : it->second); BatchUpdateFinishState(cloudSyncInfos, E_CLOUD_DISABLED); - BatchReport(info.user_, traceIds, SyncStage::END, E_CLOUD_DISABLED); + BatchReport(info.user_, traceIds, SyncStage::END, E_CLOUD_DISABLED, "empty schema:" + info.bundleName_); return; } } @@ -386,6 +386,34 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount }; } +void SyncManager::StartCloudSync(const DistributedData::SyncEvent &evt, const StoreMetaData &meta, + const AutoCache::Store &store, Retryer retryer, DistributedData::GenDetails &details) +{ + auto &storeInfo = evt.GetStoreInfo(); + GenAsync async = evt.GetAsyncDetail(); + auto prepareTraceId = evt.GetPrepareTraceId(); + auto user = evt.GetUser(); + auto &detail = details[SyncInfo::DEFAULT_ID]; + ReportSyncEvent(evt, BizState::BEGIN, E_OK); + SyncParam syncParam = { evt.GetMode(), evt.GetWait(), evt.IsCompensation(), MODE_DEFAULT, prepareTraceId }; + syncParam.asyncDownloadAsset = meta.asyncDownloadAsset; + auto [status, dbCode] = store->Sync({ SyncInfo::DEFAULT_ID }, *(evt.GetQuery()), + evt.AutoRetry() ? RetryCallback(storeInfo, retryer, evt.GetTriggerMode(), prepareTraceId, user) + : GetCallback(async, storeInfo, evt.GetTriggerMode(), prepareTraceId, user), syncParam); + if (status != E_OK) { + if (async) { + detail.code = status; + async(std::move(details)); + } + UpdateFinishSyncInfo({ storeInfo.user, GetAccountId(storeInfo.user), storeInfo.bundleName, + storeInfo.storeName }, storeInfo.syncId, E_ERROR); + if (status != GeneralError::E_NOT_SUPPORT) { + auto code = dbCode == 0 ? GenStore::CLOUD_ERR_OFFSET + status : dbCode; + ReportSyncEvent(evt, BizState::END, code); + } + } +} + std::function SyncManager::GetSyncHandler(Retryer retryer) { return [this, retryer](const Event &event) { @@ -393,13 +421,13 @@ std::function SyncManager::GetSyncHandler(Retryer retryer) auto &storeInfo = evt.GetStoreInfo(); GenAsync async = evt.GetAsyncDetail(); auto prepareTraceId = evt.GetPrepareTraceId(); - auto user = evt.GetUser(); GenDetails details; auto &detail = details[SyncInfo::DEFAULT_ID]; detail.progress = GenProgress::SYNC_FINISH; auto [hasMeta, meta] = GetMetaData(storeInfo); if (!hasMeta) { - return DoExceptionalCallback(async, details, storeInfo, prepareTraceId); + return DoExceptionalCallback(async, details, storeInfo, + {0, "", prepareTraceId, SyncStage::END, GeneralError::E_ERROR, "no meta"}); } auto [code, store] = GetStore(meta, storeInfo.user); if (code == E_SCREEN_LOCKED) { @@ -408,34 +436,19 @@ std::function SyncManager::GetSyncHandler(Retryer retryer) if (store == nullptr) { ZLOGE("store null, storeId:%{public}s, prepareTraceId:%{public}s", meta.GetStoreAlias().c_str(), prepareTraceId.c_str()); - return DoExceptionalCallback(async, details, storeInfo, prepareTraceId); + return DoExceptionalCallback(async, details, storeInfo, + {0, "", prepareTraceId, SyncStage::END, GeneralError::E_ERROR, "store null"}); } if (!meta.enableCloud) { ZLOGW("meta.enableCloud is false, storeId:%{public}s, prepareTraceId:%{public}s", meta.GetStoreAlias().c_str(), prepareTraceId.c_str()); - return DoExceptionalCallback(async, details, storeInfo, prepareTraceId, E_CLOUD_DISABLED); + return DoExceptionalCallback(async, details, storeInfo, + {0, "", prepareTraceId, SyncStage::END, E_CLOUD_DISABLED, "disable cloud"}); } ZLOGI("database:<%{public}d:%{public}s:%{public}s:%{public}s> sync start, asyncDownloadAsset?[%{public}d]", storeInfo.user, storeInfo.bundleName.c_str(), meta.GetStoreAlias().c_str(), prepareTraceId.c_str(), meta.asyncDownloadAsset); - ReportSyncEvent(evt, BizState::BEGIN, E_OK); - SyncParam syncParam = { evt.GetMode(), evt.GetWait(), evt.IsCompensation(), MODE_DEFAULT, prepareTraceId }; - syncParam.asyncDownloadAsset = meta.asyncDownloadAsset; - auto [status, dbCode] = store->Sync({ SyncInfo::DEFAULT_ID }, *(evt.GetQuery()), - evt.AutoRetry() ? RetryCallback(storeInfo, retryer, evt.GetTriggerMode(), prepareTraceId, user) - : GetCallback(async, storeInfo, evt.GetTriggerMode(), prepareTraceId, user), syncParam); - if (status != E_OK) { - if (async) { - detail.code = status; - async(std::move(details)); - } - UpdateFinishSyncInfo({ storeInfo.user, GetAccountId(storeInfo.user), storeInfo.bundleName, - storeInfo.storeName }, storeInfo.syncId, E_ERROR); - if (status != GeneralError::E_NOT_SUPPORT) { - auto code = dbCode == 0 ? GenStore::CLOUD_ERR_OFFSET + status : dbCode; - ReportSyncEvent(evt, BizState::END, code); - } - } + StartCloudSync(evt, meta, store, retryer, details); }; } @@ -452,7 +465,7 @@ void SyncManager::ReportSyncEvent(const SyncEvent &evt, BizState bizState, int32 RadarReporter::Report({storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC, storeInfo.syncId, evt.GetTriggerMode(), code}, "GetSyncHandler", bizState); } - Report({evt.GetUser(), storeInfo.bundleName, evt.GetPrepareTraceId(), syncStage, code}); + Report({evt.GetUser(), storeInfo.bundleName, evt.GetPrepareTraceId(), syncStage, code, "GetSyncHandler"}); } std::function SyncManager::GetClientChangeHandler() @@ -496,7 +509,7 @@ SyncManager::Retryer SyncManager::GetRetryer(int32_t times, const SyncInfo &sync dbCode }, "GetRetryer", BizState::END); Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, - dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode }); + 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; @@ -513,7 +526,7 @@ SyncManager::Retryer SyncManager::GetRetryer(int32_t times, const SyncInfo &sync dbCode }, "GetRetryer", BizState::END); Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, - dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode }); + dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode, "GetRetryer continue" }); 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; @@ -831,7 +844,7 @@ std::function SyncManager::GetCallback(const Gen RadarReporter::Report({ storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC, storeInfo.syncId, triggerMode, dbCode, result.begin()->second.changeCount }, "GetCallback", BizState::END); - Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, dbCode }); + Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, dbCode, "GetCallback" }); if (dbCode != 0) { Report(FT_CALLBACK, storeInfo.bundleName, static_cast(Fault::CSF_GS_CLOUD_SYNC), "callback failed, dbCode=" + std::to_string(dbCode)); @@ -878,15 +891,16 @@ std::vector SyncManager::GetSchemaMeta(const CloudInfo &cloud, const } void SyncManager::DoExceptionalCallback(const GenAsync &async, GenDetails &details, const StoreInfo &storeInfo, - const std::string &prepareTraceId, int32_t code) + const ReportParam ¶m) { if (async) { - details[SyncInfo::DEFAULT_ID].code = code; + details[SyncInfo::DEFAULT_ID].code = param.errCode; async(details); } QueryKey queryKey{ storeInfo.user, GetAccountId(storeInfo.user), storeInfo.bundleName, storeInfo.storeName }; - UpdateFinishSyncInfo(queryKey, storeInfo.syncId, code); - Report({ storeInfo.user, storeInfo.bundleName, prepareTraceId, SyncStage::END, code }); + UpdateFinishSyncInfo(queryKey, storeInfo.syncId, param.errCode); + Report({ storeInfo.user, storeInfo.bundleName, param.prepareTraceId, SyncStage::END, + param.errCode, param.message }); } bool SyncManager::InitDefaultUser(int32_t &user) @@ -921,7 +935,7 @@ std::function SyncManager::Retr triggerMode, code, details.begin()->second.changeCount }, "RetryCallback", BizState::END); Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, - dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode }); + dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode, "RetryCallback" }); } } retryer(GetInterval(code), code, dbCode, prepareTraceId); @@ -936,10 +950,11 @@ void SyncManager::BatchUpdateFinishState(const std::vector GetPostEventTask(const std::vector &schemas, CloudInfo &cloud, SyncInfo &info, bool retry, const TraceIds &traceIds); void DoExceptionalCallback(const GenAsync &async, GenDetails &details, const StoreInfo &storeInfo, - const std::string &prepareTraceId, int32_t code = GeneralError::E_ERROR); + const ReportParam ¶m); bool InitDefaultUser(int32_t &user); std::function RetryCallback(const StoreInfo &storeInfo, Retryer retryer, int32_t triggerMode, const std::string &prepareTraceId, int32_t user); @@ -159,7 +159,10 @@ private: void BatchUpdateFinishState(const std::vector> &cloudSyncInfos, int32_t code); bool NeedSaveSyncInfo(const QueryKey &queryKey); std::function GetLockChangeHandler(); - void BatchReport(int32_t userId, const TraceIds &traceIds, SyncStage syncStage, int32_t errCode); + void BatchReport(int32_t userId, const TraceIds &traceIds, SyncStage syncStage, int32_t errCode, + const std::string &message = ""); + void StartCloudSync(const DistributedData::SyncEvent &evt, const StoreMetaData &meta, + const AutoCache::Store &store, Retryer retryer, DistributedData::GenDetails &details); TraceIds GetPrepareTraceId(const SyncInfo &info, const CloudInfo &cloud); std::pair GetMetaData(const StoreInfo &storeInfo); void AddCompensateSync(const StoreMetaData &meta); -- Gitee From 9cd14bb0561fd4a0d98f63075233e8969befb6d6 Mon Sep 17 00:00:00 2001 From: yangliu Date: Fri, 21 Mar 2025 19:58:22 +0800 Subject: [PATCH 060/225] update Signed-off-by: yangliu --- .../app/src/kvstore_meta_manager.cpp | 195 +++++++++--------- .../app/src/kvstore_meta_manager.h | 11 +- .../distributeddataservice/framework/BUILD.gn | 2 +- ...eviceid_meta_data.h => device_meta_data.h} | 18 +- .../include/metadata/strategy_meta_data.h | 1 + ...eid_meta_data.cpp => device_meta_data.cpp} | 21 +- .../framework/test/meta_data_test.cpp | 30 +-- .../service/kvdb/kvdb_service_impl.cpp | 5 +- 8 files changed, 143 insertions(+), 140 deletions(-) rename services/distributeddataservice/framework/include/metadata/{deviceid_meta_data.h => device_meta_data.h} (77%) rename services/distributeddataservice/framework/metadata/{deviceid_meta_data.cpp => device_meta_data.cpp} (61%) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 77210e5b8..5e7aa9829 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -35,7 +35,7 @@ #include "matrix_event.h" #include "metadata/auto_launch_meta_data.h" #include "metadata/capability_meta_data.h" -#include "metadata/deviceid_meta_data.h" +#include "metadata/device_meta_data.h" #include "metadata/meta_data_manager.h" #include "metadata/matrix_meta_data.h" #include "metadata/strategy_meta_data.h" @@ -64,6 +64,7 @@ using namespace std::chrono; using namespace OHOS::DistributedData; using namespace DistributedDB; using namespace OHOS::AppDistributedKv; + KvStoreMetaManager::MetaDeviceChangeListenerImpl KvStoreMetaManager::listener_; KvStoreMetaManager::DBInfoDeviceChangeListenerImpl KvStoreMetaManager::dbInfoListener_; @@ -143,9 +144,8 @@ void KvStoreMetaManager::InitMetaData() return; } auto uuid = DmAdapter::GetInstance().GetLocalDevice().uuid; - if (IsMetaDeviceIdChanged(uuid)) { - UpdateMetaDeviceId(uuid); - } + CheckMetaDeviceId(uuid); + auto uid = getuid(); auto tokenId = IPCSkeleton::GetCallingTokenID(); auto userId = AccountDelegate::GetInstance()->GetUserByToken(tokenId); @@ -184,6 +184,7 @@ void KvStoreMetaManager::InitMetaData() } UpdateMetaData(); SetCloudSyncer(); + ZLOGI("end."); } void KvStoreMetaManager::UpdateMetaData() @@ -565,123 +566,125 @@ AppDistributedKv::ChangeLevelType KvStoreMetaManager::DBInfoDeviceChangeListener return AppDistributedKv::ChangeLevelType::MIN; } -bool KvStoreMetaManager::IsMetaDeviceIdChanged(const std::string &localUUID) +void KvStoreMetaManager::CheckMetaDeviceId(const std::string &localUuid) { - DeviceIDMetaData meta; - if (localUUID.empty()) { + DeviceMetaData deviceMeta; + if (localUuid.empty()) { ZLOGW("get uuid failed"); - return false; + return; } - if (!MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true)) { - meta.currentUUID = localUUID; - MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); + if (!MetaDataManager::GetInstance().LoadMeta(deviceMeta.GetKey(), deviceMeta, true)) { + deviceMeta.currentUuid = localUuid; + MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true); } else { - if (meta.currentUUID != localUUID) { - meta.oldUUID = meta.currentUUID; - oldUUID_ = meta.currentUUID; - meta.currentUUID = localUUID; - MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); - ZLOGI("uuid changed! curruuid:%{public}s, olduuid:%{public}s, cache:%{public}s", - Anonymous::Change(meta.currentUUID).c_str(), Anonymous::Change(meta.oldUUID).c_str(), - Anonymous::Change(oldUUID_).c_str()); - return true; + if (deviceMeta.currentUuid != localUuid) { + deviceMeta.oldUuid = deviceMeta.currentUuid; + deviceMeta.currentUuid = localUuid; + MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true); + ZLOGI("meta changed! curruuid:%{public}s, olduuid:%{public}s", + deviceMeta.currentUuid.c_str(), deviceMeta.oldUuid.c_str()); + UpdateMetaDeviceId(localUuid, deviceMeta.oldUuid); } } - return false; } -void KvStoreMetaManager::UpdateMetaDeviceId(const std::string ¤tUUID) +void KvStoreMetaManager::UpdateMetaDeviceId(const std::string &newUuid, const std::string &oldUuid) { - UpdateStoreMetaData(currentUUID); - UpdateMetaData(currentUUID); - - UpdateStoreMetaData(currentUUID, true); - UpdateMetaData(currentUUID, true); + //update meta like prefix###uuid###user###default#bundleName#storeid + UpdateStoreMetaData(newUuid, oldUuid); + //update meta like prefix###uuid + UpdateMetaDatas(newUuid, oldUuid); } -void KvStoreMetaManager::UpdateStoreMetaData(const std::string ¤tUUID, bool isLocal) +void KvStoreMetaManager::UpdateStoreMetaData(const std::string &newUuid, const std::string &oldUuid) { std::vector storeMetas; - MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ oldUUID_ }), storeMetas, isLocal); + MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({oldUuid}), storeMetas, true); for (auto &storeMeta : storeMetas) { + // update storeMeta in local table auto oldMeta = storeMeta; - if (isLocal) { - storeMeta.isNeedUpdateDeviceId = true; + storeMeta.isNeedUpdateDeviceId = true; + MetaDataManager::GetInstance().DelMeta(storeMeta.GetKey(), true); + storeMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), storeMeta, true); + // update storeMetaLocal in local table + StoreMetaDataLocal metaDataLocal; + if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetKeyLocal(), metaDataLocal, true)) { + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKeyLocal(), true); + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKeyLocal(), metaDataLocal, true); } - MetaDataManager::GetInstance().DelMeta(storeMeta.GetKey(), isLocal); - storeMeta.deviceId = currentUUID; - MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), storeMeta, isLocal); - - if (!isLocal) { - StrategyMeta strategyMeta("", "", "", ""); - if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetStrategyKey(), strategyMeta)) { - MetaDataManager::GetInstance().DelMeta(oldMeta.GetStrategyKey()); - strategyMeta.devId = currentUUID; - MetaDataManager::GetInstance().SaveMeta(storeMeta.GetStrategyKey(), strategyMeta); - } + // update autoLaunchMeta in local table + AutoLaunchMetaData autoLaunchMetaData; + bool isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, true); + if (!isExist) { + oldMeta.storeId = ""; + isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, true); } - - if (isLocal) { - StoreMetaDataLocal metaDataLocal; - if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetKeyLocal(), metaDataLocal, isLocal)) { - MetaDataManager::GetInstance().DelMeta(oldMeta.GetKeyLocal(), isLocal); - MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKeyLocal(), metaDataLocal, isLocal); - } - - AutoLaunchMetaData autoLaunchMetaData; - bool isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), - autoLaunchMetaData, isLocal); - if (!isExist) { - oldMeta.storeId = ""; - isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), - autoLaunchMetaData, isLocal); - } - if (isExist) { - MetaDataManager::GetInstance().DelMeta(oldMeta.GetAutoLaunchKey(), isLocal); - oldMeta.deviceId = currentUUID; - MetaDataManager::GetInstance().SaveMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, isLocal); - } + if (isExist) { + MetaDataManager::GetInstance().DelMeta(oldMeta.GetAutoLaunchKey(), true); + oldMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, true); + } + } + + storeMetas.clear(); + MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({oldUuid}), storeMetas); + for (auto &storeMeta : storeMetas) { + // update storeMeta in sync table + auto oldMeta = storeMeta; + MetaDataManager::GetInstance().DelMeta(storeMeta.GetKey()); + storeMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), storeMeta); + // update strategyMeta in sync table + StrategyMeta strategyMeta; + if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetStrategyKey(), strategyMeta)) { + MetaDataManager::GetInstance().DelMeta(oldMeta.GetStrategyKey()); + strategyMeta.devId = newUuid; + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetStrategyKey(), strategyMeta); } } } -void KvStoreMetaManager::UpdateMetaData(const std::string ¤tUUID, bool isLocal) +void KvStoreMetaManager::UpdateMetaDatas(const std::string &newUuid, const std::string &oldUuid) { + // update storeMeta in local table MatrixMetaData matrixMeta; - bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), - matrixMeta, isLocal); + bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({oldUuid}), matrixMeta, true); if (isExist) { - MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ oldUUID_ }), isLocal); - matrixMeta.deviceId = currentUUID; - MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({ currentUUID }), matrixMeta, isLocal); - } - - if (isLocal) { - SwitchesMetaData switchesMetaData; - if (MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({ oldUUID_ }), - switchesMetaData, isLocal)) { - MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({ oldUUID_ }), isLocal); - switchesMetaData.deviceId = currentUUID; - MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({ currentUUID }), - switchesMetaData, isLocal); - } + MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({oldUuid}), true); + matrixMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({newUuid}), matrixMeta, true); } - - if (!isLocal) { - UserMetaData userMeta; - if (MetaDataManager::GetInstance().LoadMeta(UserMetaRow::GetKeyFor(oldUUID_), userMeta)) { - MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor(oldUUID_)); - userMeta.deviceId = currentUUID; - MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor(currentUUID), userMeta); - } - - CapMetaData capMetaData; - auto capKey = CapMetaRow::GetKeyFor(oldUUID_); - if (MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), capMetaData)) { - auto newCapKey = CapMetaRow::GetKeyFor(currentUUID); - MetaDataManager::GetInstance().DelMeta(std::string(capKey.begin(), capKey.end())); - MetaDataManager::GetInstance().SaveMeta(std::string(newCapKey.begin(), newCapKey.end()), capMetaData); - } + // update storeMeta in sync table + isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({oldUuid}), matrixMeta); + if (isExist) { + MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({oldUuid})); + matrixMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({newUuid}), matrixMeta); + } + // update switchesMeta in local table + SwitchesMetaData switchesMetaData; + if (MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({oldUuid}), + switchesMetaData, true)) { + MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({oldUuid}), true); + switchesMetaData.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({newUuid}), + switchesMetaData, true); + } + // update userMeta in sync table + UserMetaData userMeta; + if (MetaDataManager::GetInstance().LoadMeta(UserMetaRow::GetKeyFor(oldUuid), userMeta)) { + MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor(oldUuid)); + userMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor(newUuid), userMeta); + } + // update capMeta in sync table + CapMetaData capMetaData; + auto capKey = CapMetaRow::GetKeyFor(oldUuid); + if (MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), capMetaData)) { + auto newCapKey = CapMetaRow::GetKeyFor(newUuid); + MetaDataManager::GetInstance().DelMeta(std::string(capKey.begin(), capKey.end())); + MetaDataManager::GetInstance().SaveMeta(std::string(newCapKey.begin(), newCapKey.end()), capMetaData); } } } // namespace DistributedKv diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index 0390259c3..a80459b1b 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -96,13 +96,13 @@ private: DistributedDB::KvStoreNbDelegate::Option InitDBOption(); - void UpdateMetaDeviceId(const std::string ¤tUUID); + void CheckMetaDeviceId(const std::string &localUuid); - bool IsMetaDeviceIdChanged(const std::string ¤tUUID); + void UpdateMetaDeviceId(const std::string &newUuid, const std::string &oldUuid); - void UpdateStoreMetaData(const std::string ¤tUUID, bool isLocal = false); - - void UpdateMetaData(const std::string ¤tUUID, bool isLocal = false); + void UpdateStoreMetaData(const std::string &newUuid, const std::string &oldUuid); + + void UpdateMetaDatas(const std::string &newUuid, const std::string &oldUuid); static ExecutorPool::Task GetBackupTask( TaskQueue queue, std::shared_ptr executors, const NbDelegate store); @@ -141,7 +141,6 @@ private: TaskId delaySyncTaskId_ = ExecutorPool::INVALID_TASK_ID; static constexpr int32_t META_VERSION = 4; static constexpr int32_t MAX_TASK_COUNT = 1; - std::string oldUUID_; }; } // namespace DistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index 4767b6d0a..344f08426 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -88,7 +88,7 @@ ohos_shared_library("distributeddatasvcfwk") { "metadata/capability_meta_data.cpp", "metadata/capability_range.cpp", "metadata/corrupted_meta_data.cpp", - "metadata/deviceid_meta_data.cpp", + "metadata/device_meta_data.cpp", "metadata/matrix_meta_data.cpp", "metadata/meta_data.cpp", "metadata/meta_data_manager.cpp", diff --git a/services/distributeddataservice/framework/include/metadata/deviceid_meta_data.h b/services/distributeddataservice/framework/include/metadata/device_meta_data.h similarity index 77% rename from services/distributeddataservice/framework/include/metadata/deviceid_meta_data.h rename to services/distributeddataservice/framework/include/metadata/device_meta_data.h index b9e104f8a..7df8c5564 100644 --- a/services/distributeddataservice/framework/include/metadata/deviceid_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/device_meta_data.h @@ -13,24 +13,22 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_META_DATA_H -#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_META_DATA_H +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICE_META_DATA_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICE_META_DATA_H #include #include "serializable/serializable.h" namespace OHOS::DistributedData { -class API_EXPORT DeviceIDMetaData final : public Serializable { +class API_EXPORT DeviceMetaData final : public Serializable { public: - API_EXPORT DeviceIDMetaData(); - API_EXPORT ~DeviceIDMetaData(); + API_EXPORT DeviceMetaData(); + API_EXPORT ~DeviceMetaData(); API_EXPORT bool Marshal(json &node) const override; API_EXPORT bool Unmarshal(const json &node) override; API_EXPORT std::string GetKey() const; - std::string currentUUID = ""; - std::string oldUUID = ""; -private: - static constexpr const char *KEY_PREFIX = "DeviceIDMeta"; + std::string newUuid = ""; + std::string oldUuid = ""; }; } // namespace OHOS::DistributedData -#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICEID_META_DATA_H \ No newline at end of file +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICE_META_DATA_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h index a3cb9275b..25feaeded 100644 --- a/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h @@ -29,6 +29,7 @@ struct API_EXPORT StrategyMeta final : public Serializable { API_EXPORT StrategyMeta(const std::string &devId, const std::string &userId, const std::string &bundleName, const std::string &storeId); + API_EXPORT StrategyMeta() {}; API_EXPORT ~StrategyMeta() {}; API_EXPORT bool Marshal(json &node) const override; API_EXPORT bool Unmarshal(const json &node) override; diff --git a/services/distributeddataservice/framework/metadata/deviceid_meta_data.cpp b/services/distributeddataservice/framework/metadata/device_meta_data.cpp similarity index 61% rename from services/distributeddataservice/framework/metadata/deviceid_meta_data.cpp rename to services/distributeddataservice/framework/metadata/device_meta_data.cpp index 33f0aee46..c16c6400f 100644 --- a/services/distributeddataservice/framework/metadata/deviceid_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/device_meta_data.cpp @@ -12,33 +12,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "metadata/deviceid_meta_data.h" +#include "metadata/device_meta_data.h" namespace OHOS { namespace DistributedData { -bool DeviceIDMetaData::Marshal(json &node) const +static constexpr const char *KEY_PREFIX = "DeviceMeta"; +bool DeviceMetaData::Marshal(json &node) const { - SetValue(node[GET_NAME(currentUUID)], currentUUID); - SetValue(node[GET_NAME(oldUUID)], oldUUID); + SetValue(node[GET_NAME(newUuid)], newUuid); + SetValue(node[GET_NAME(oldUuid)], oldUuid); return true; } -bool DeviceIDMetaData::Unmarshal(const json &node) +bool DeviceMetaData::Unmarshal(const json &node) { - GetValue(node, GET_NAME(currentUUID), currentUUID); - GetValue(node, GET_NAME(oldUUID), oldUUID); + GetValue(node, GET_NAME(newUuid), newUuid); + GetValue(node, GET_NAME(oldUuid), oldUuid); return true; } -DeviceIDMetaData::DeviceIDMetaData() +DeviceMetaData::DeviceMetaData() { } -DeviceIDMetaData::~DeviceIDMetaData() +DeviceMetaData::~DeviceMetaData() { } -std::string DeviceIDMetaData::GetKey() const +std::string DeviceMetaData::GetKey() const { return KEY_PREFIX; } diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 589afa669..642c57954 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -27,7 +27,7 @@ #include "metadata/store_meta_data_local.h" #include "metadata/strategy_meta_data.h" #include "metadata/user_meta_data.h" -#include "metadata/deviceid_meta_data.h" +#include "metadata/device_meta_data.h" #include "utils/constant.h" #include "gtest/gtest.h" #include @@ -797,29 +797,29 @@ HWTEST_F(ServiceMetaDataTest, MatrixMetaData, TestSize.Level1) } /** - * @tc.name: DeviceIDMetaData - * @tc.desc: test DeviceIDMetaData function + * @tc.name: DeviceMetaData + * @tc.desc: test DeviceMetaData function * @tc.type: FUNC * @tc.require: * @tc.author: yl */ -HWTEST_F(ServiceMetaDataTest, DeviceIDMetaData, TestSize.Level1) +HWTEST_F(ServiceMetaDataTest, DeviceMetaData, TestSize.Level1) { - DeviceIDMetaData metaData; + DeviceMetaData metaData; ASSERT_EQ(prefix, expectedPrefix); - std::string currentUUID = "newuuid"; - std::string oldUUID = "olduuid"; - metaData.currentUUID = currentUUID; - metaData.oldUUID = oldUUID; + std::string newUuid = "newuuid"; + std::string oldUuid = "olduuid"; + metaData.newUuid = newUuid; + metaData.oldUuid = oldUuid; Serializable::json node1; metaData.Marshal(node1); - EXPECT_EQ(node1["currentUUID"], currentUUID); - EXPECT_EQ(node1["oldUUID"], oldUUID); + EXPECT_EQ(node1["newUuid"], newUuid); + EXPECT_EQ(node1["oldUuid"], oldUuid); - DeviceIDMetaData newMetaData; + DeviceMetaData newMetaData; newMetaData.Unmarshal(node1); - EXPECT_EQ(newMetaData.currentUUID, currentUUID); - EXPECT_EQ(newMetaData.oldUUID, oldUUID); + EXPECT_EQ(newMetaData.newUuid, newUuid); + EXPECT_EQ(newMetaData.oldUuid, oldUuid); } /** @@ -831,7 +831,7 @@ HWTEST_F(ServiceMetaDataTest, DeviceIDMetaData, TestSize.Level1) */ HWTEST_F(ServiceMetaDataTest, GetPrefixTest, TestSize.Level1) { - DeviceIDMetaData metaData; + DeviceMetaData metaData; std::string expectPrefix = "DeviceIDMeta"; std::string prefix = metaData.GetKey(); EXPECT_EQ(prefix, expectPrefix); diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index 87d7ba13f..0cbd8215e 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -623,9 +623,10 @@ Status KVDBServiceImpl::GetBackupPassword(const AppId &appId, const StoreId &sto StoreMetaData meta; MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), meta, true); if (meta.isNeedUpdateDeviceId) { - ZLOGW("device already update uuid, appId:%{public}s, storeId:%{public}s", + MetaDataManager::GetInstance().DelMeta(metaData.GetSecretKey(), true); + MetaDataManager::GetInstance().DelMeta(metaData.GetCloneSecretKey(), true); + ZLOGW("device already update uuid, del secretkey. appId:%{public}s, storeId:%{public}s", appId.appId.c_str(), Anonymous::Change(storeId.storeId).c_str()); - return ERROR; } passwords.reserve(SECRET_KEY_COUNT); SecretKeyMetaData secretKey; -- Gitee From f18abae190af6395ccc5a06df008a9a3cc31cbed Mon Sep 17 00:00:00 2001 From: yangliu Date: Fri, 21 Mar 2025 20:22:45 +0800 Subject: [PATCH 061/225] update Signed-off-by: yangliu --- .../app/src/kvstore_meta_manager.cpp | 10 +++++----- .../framework/test/meta_data_test.cpp | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 5e7aa9829..3abb91c6e 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -574,15 +574,15 @@ void KvStoreMetaManager::CheckMetaDeviceId(const std::string &localUuid) return; } if (!MetaDataManager::GetInstance().LoadMeta(deviceMeta.GetKey(), deviceMeta, true)) { - deviceMeta.currentUuid = localUuid; + deviceMeta.newUuid = localUuid; MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true); } else { - if (deviceMeta.currentUuid != localUuid) { - deviceMeta.oldUuid = deviceMeta.currentUuid; - deviceMeta.currentUuid = localUuid; + if (deviceMeta.newUuid != localUuid) { + deviceMeta.oldUuid = deviceMeta.newUuid; + deviceMeta.newUuid = localUuid; MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true); ZLOGI("meta changed! curruuid:%{public}s, olduuid:%{public}s", - deviceMeta.currentUuid.c_str(), deviceMeta.oldUuid.c_str()); + deviceMeta.newUuid.c_str(), deviceMeta.oldUuid.c_str()); UpdateMetaDeviceId(localUuid, deviceMeta.oldUuid); } } diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 642c57954..e1236fc98 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -805,7 +805,7 @@ HWTEST_F(ServiceMetaDataTest, MatrixMetaData, TestSize.Level1) */ HWTEST_F(ServiceMetaDataTest, DeviceMetaData, TestSize.Level1) { - DeviceMetaData metaData; + DeviceMetaData metaData; ASSERT_EQ(prefix, expectedPrefix); std::string newUuid = "newuuid"; std::string oldUuid = "olduuid"; -- Gitee From 654546f0733bd4c0db1fd429962656949dd49af9 Mon Sep 17 00:00:00 2001 From: yangliu Date: Fri, 21 Mar 2025 21:03:59 +0800 Subject: [PATCH 062/225] update Signed-off-by: yangliu --- .../distributeddataservice/framework/test/meta_data_test.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index e1236fc98..b2dbdb05a 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -805,8 +805,7 @@ HWTEST_F(ServiceMetaDataTest, MatrixMetaData, TestSize.Level1) */ HWTEST_F(ServiceMetaDataTest, DeviceMetaData, TestSize.Level1) { - DeviceMetaData metaData; - ASSERT_EQ(prefix, expectedPrefix); + DeviceMetaData metaData; std::string newUuid = "newuuid"; std::string oldUuid = "olduuid"; metaData.newUuid = newUuid; @@ -832,7 +831,7 @@ HWTEST_F(ServiceMetaDataTest, DeviceMetaData, TestSize.Level1) HWTEST_F(ServiceMetaDataTest, GetPrefixTest, TestSize.Level1) { DeviceMetaData metaData; - std::string expectPrefix = "DeviceIDMeta"; + std::string expectPrefix = "DeviceMeta"; std::string prefix = metaData.GetKey(); EXPECT_EQ(prefix, expectPrefix); } -- Gitee From 6a867f0d127508e71ed68022df3c1427fb00c11d Mon Sep 17 00:00:00 2001 From: l30005037 Date: Sat, 22 Mar 2025 09:48:47 +0800 Subject: [PATCH 063/225] Security and privacy compliance requirements Signed-off-by: l30005037 --- .../adapter/account/BUILD.gn | 5 ++- .../adapter/account/test/BUILD.gn | 1 + .../adapter/communicator/BUILD.gn | 5 ++- .../adapter/communicator/test/BUILD.gn | 7 +++++ .../fuzztest/softbusadapter_fuzzer/BUILD.gn | 1 + .../adapter/dfx/BUILD.gn | 5 ++- .../adapter/dfx/test/BUILD.gn | 1 + .../adapter/network/BUILD.gn | 2 ++ .../adapter/network/test/BUILD.gn | 2 ++ .../adapter/schema_helper/BUILD.gn | 5 ++- .../adapter/screenlock/BUILD.gn | 5 ++- .../adapter/screenlock/test/BUILD.gn | 1 + .../adapter/utils/BUILD.gn | 5 ++- services/distributeddataservice/app/BUILD.gn | 2 ++ .../app/src/checker/BUILD.gn | 6 +++- .../app/src/installer/BUILD.gn | 6 +++- .../distributeddataservice/app/test/BUILD.gn | 7 ++++- .../fuzztest/dataservicestub_fuzzer/BUILD.gn | 1 + .../distributeddataservice/framework/BUILD.gn | 6 +++- .../framework/test/BUILD.gn | 7 ++++- .../rust/connect_adapter/BUILD.gn | 10 ++++-- .../rust/extension/BUILD.gn | 6 +++- .../distributeddataservice/service/BUILD.gn | 7 ++++- .../service/backup/BUILD.gn | 2 ++ .../service/bootstrap/BUILD.gn | 2 ++ .../service/cloud/BUILD.gn | 2 ++ .../service/common/BUILD.gn | 2 ++ .../service/config/BUILD.gn | 2 ++ .../service/crypto/BUILD.gn | 2 ++ .../service/data_share/BUILD.gn | 2 ++ .../service/dumper/BUILD.gn | 2 ++ .../service/kvdb/BUILD.gn | 2 ++ .../service/matrix/BUILD.gn | 2 ++ .../service/object/BUILD.gn | 2 ++ .../service/permission/BUILD.gn | 2 ++ .../service/rdb/BUILD.gn | 2 ++ .../service/test/BUILD.gn | 31 ++++++++++++++++++- .../fuzztest/cloudservicestub_fuzzer/BUILD.gn | 1 + .../datashareservicestub_fuzzer/BUILD.gn | 1 + .../test/fuzztest/dumphelper_fuzzer/BUILD.gn | 1 + .../fuzztest/kvdbservicestub_fuzzer/BUILD.gn | 1 + .../objectservicestub_fuzzer/BUILD.gn | 1 + .../fuzztest/rdbresultsetstub_fuzzer/BUILD.gn | 1 + .../fuzztest/rdbservicestub_fuzzer/BUILD.gn | 1 + .../test/fuzztest/udmfservice_fuzzer/BUILD.gn | 1 + .../service/udmf/BUILD.gn | 2 ++ 46 files changed, 154 insertions(+), 16 deletions(-) diff --git a/services/distributeddataservice/adapter/account/BUILD.gn b/services/distributeddataservice/adapter/account/BUILD.gn index 85697b11b..fc643f996 100755 --- a/services/distributeddataservice/adapter/account/BUILD.gn +++ b/services/distributeddataservice/adapter/account/BUILD.gn @@ -35,7 +35,10 @@ ohos_source_set("distributeddata_account") { "${data_service_path}/framework/include/account", ] - cflags_cc = [ "-fvisibility=hidden" ] + cflags_cc = [ + "-fvisibility=hidden", + "-fstack-protector-strong", + ] remove_configs = [ "//build/config/compiler:no_exceptions" ] diff --git a/services/distributeddataservice/adapter/account/test/BUILD.gn b/services/distributeddataservice/adapter/account/test/BUILD.gn index 39c09ee55..5340c802a 100755 --- a/services/distributeddataservice/adapter/account/test/BUILD.gn +++ b/services/distributeddataservice/adapter/account/test/BUILD.gn @@ -32,6 +32,7 @@ ohos_unittest("AccountDelegateTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ "../:distributeddata_account" ] diff --git a/services/distributeddataservice/adapter/communicator/BUILD.gn b/services/distributeddataservice/adapter/communicator/BUILD.gn index ff2d7cf86..522a20c21 100755 --- a/services/distributeddataservice/adapter/communicator/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/BUILD.gn @@ -49,7 +49,10 @@ ohos_source_set("distributeddata_communicator") { "${data_service_path}/framework/include/utils", ] - cflags_cc = [ "-fvisibility=hidden" ] + cflags_cc = [ + "-fvisibility=hidden", + "-fstack-protector-strong", + ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", diff --git a/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/BUILD.gn index 5e5a3489d..c18e1b084 100755 --- a/services/distributeddataservice/adapter/communicator/test/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/BUILD.gn @@ -65,6 +65,7 @@ ohos_unittest("CommunicatorContextTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", @@ -88,6 +89,7 @@ ohos_unittest("CommunicatorDataBufferTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", @@ -118,6 +120,7 @@ ohos_unittest("DeviceManagerAdapterTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", @@ -174,6 +177,7 @@ ohos_unittest("ProcessCommunicatorImplTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ @@ -231,6 +235,7 @@ ohos_unittest("SoftbusAdapterStandardTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", @@ -262,6 +267,7 @@ ohos_unittest("SoftbusClientTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", @@ -292,6 +298,7 @@ ohos_unittest("AppPipeMgrServiceTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", diff --git a/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn index cc55d56d7..01c09fe7b 100644 --- a/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn @@ -33,6 +33,7 @@ ohos_fuzztest("SoftBusAdapterFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-fstack-protector-strong", ] sources = [ "softbusadapter_fuzzer.cpp" ] diff --git a/services/distributeddataservice/adapter/dfx/BUILD.gn b/services/distributeddataservice/adapter/dfx/BUILD.gn index dc2a52cb3..483c45449 100644 --- a/services/distributeddataservice/adapter/dfx/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/BUILD.gn @@ -50,7 +50,10 @@ ohos_source_set("distributeddata_dfx") { "${data_service_path}/framework/include/utils", ] - cflags_cc = [ "-fvisibility=hidden" ] + cflags_cc = [ + "-fvisibility=hidden", + "-fstack-protector-strong", + ] external_deps = [ "c_utils:utils", diff --git a/services/distributeddataservice/adapter/dfx/test/BUILD.gn b/services/distributeddataservice/adapter/dfx/test/BUILD.gn index ff7b5fe6b..bc4d53b77 100755 --- a/services/distributeddataservice/adapter/dfx/test/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/test/BUILD.gn @@ -100,6 +100,7 @@ ohos_unittest("HiViewAdapterDfxTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] configs = [ ":module_dfx_config" ] diff --git a/services/distributeddataservice/adapter/network/BUILD.gn b/services/distributeddataservice/adapter/network/BUILD.gn index fb25666a3..f120004b8 100644 --- a/services/distributeddataservice/adapter/network/BUILD.gn +++ b/services/distributeddataservice/adapter/network/BUILD.gn @@ -37,6 +37,7 @@ ohos_source_set("distributeddata_network") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] configs = [ ":network_public_config" ] @@ -48,6 +49,7 @@ ohos_source_set("distributeddata_network") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] external_deps = [ "kv_store:datamgr_common" ] diff --git a/services/distributeddataservice/adapter/network/test/BUILD.gn b/services/distributeddataservice/adapter/network/test/BUILD.gn index c1b564cc8..14277e488 100755 --- a/services/distributeddataservice/adapter/network/test/BUILD.gn +++ b/services/distributeddataservice/adapter/network/test/BUILD.gn @@ -32,6 +32,7 @@ ohos_unittest("NetworkDelegateTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ "../:distributeddata_network" ] @@ -66,6 +67,7 @@ ohos_unittest("NetworkDelegateNormalImplTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/adapter/schema_helper/BUILD.gn b/services/distributeddataservice/adapter/schema_helper/BUILD.gn index 26095037d..4bfbe3be2 100644 --- a/services/distributeddataservice/adapter/schema_helper/BUILD.gn +++ b/services/distributeddataservice/adapter/schema_helper/BUILD.gn @@ -29,7 +29,10 @@ ohos_source_set("distributeddata_schema_helper") { } sources = [ "src/get_schema_helper.cpp" ] - cflags_cc = [ "-fvisibility=hidden" ] + cflags_cc = [ + "-fvisibility=hidden", + "-fstack-protector-strong", + ] include_dirs = [ "../include/schema_helper" ] diff --git a/services/distributeddataservice/adapter/screenlock/BUILD.gn b/services/distributeddataservice/adapter/screenlock/BUILD.gn index ed1fd3913..28f3b0b78 100644 --- a/services/distributeddataservice/adapter/screenlock/BUILD.gn +++ b/services/distributeddataservice/adapter/screenlock/BUILD.gn @@ -24,7 +24,10 @@ ohos_source_set("distributeddata_screenlock") { } sources = [ "src/screen_lock.cpp" ] - cflags_cc = [ "-fvisibility=hidden" ] + cflags_cc = [ + "-fvisibility=hidden", + "-fstack-protector-strong", + ] include_dirs = [ "../include/screenlock", diff --git a/services/distributeddataservice/adapter/screenlock/test/BUILD.gn b/services/distributeddataservice/adapter/screenlock/test/BUILD.gn index f1f16b53b..962f8d9bc 100755 --- a/services/distributeddataservice/adapter/screenlock/test/BUILD.gn +++ b/services/distributeddataservice/adapter/screenlock/test/BUILD.gn @@ -33,6 +33,7 @@ ohos_unittest("ScreenLockTest") { "-Dprivate=public", "-Dprotected=public", "-Werror", + "-fstack-protector-strong", ] external_deps = [ diff --git a/services/distributeddataservice/adapter/utils/BUILD.gn b/services/distributeddataservice/adapter/utils/BUILD.gn index f96b7fe3e..8325bf050 100755 --- a/services/distributeddataservice/adapter/utils/BUILD.gn +++ b/services/distributeddataservice/adapter/utils/BUILD.gn @@ -24,7 +24,10 @@ ohos_source_set("distributeddata_utils") { } sources = [ "src/kvstore_utils.cpp" ] - cflags_cc = [ "-fvisibility=hidden" ] + cflags_cc = [ + "-fvisibility=hidden", + "-fstack-protector-strong", + ] if (build_public_version) { cflags_cc += [ "-DCONFIG_PUBLIC_VERSION" ] diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index 7748c2fda..b66d01341 100644 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -76,11 +76,13 @@ config("module_private_config") { "-Oz", "-fdata-sections", "-ffunction-sections", + "-fstack-protector-strong", ] cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] diff --git a/services/distributeddataservice/app/src/checker/BUILD.gn b/services/distributeddataservice/app/src/checker/BUILD.gn index 575e9fad2..6695b0d65 100644 --- a/services/distributeddataservice/app/src/checker/BUILD.gn +++ b/services/distributeddataservice/app/src/checker/BUILD.gn @@ -30,6 +30,7 @@ ohos_source_set("distributeddata_checker") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] include_dirs = [ "${data_service_path}/framework/include" ] @@ -39,7 +40,10 @@ ohos_source_set("distributeddata_checker") { } ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils" ] - cflags = [ "-Oz" ] + cflags = [ + "-Oz", + "-fstack-protector-strong", + ] external_deps = [ "ability_base:base", "ability_base:want", diff --git a/services/distributeddataservice/app/src/installer/BUILD.gn b/services/distributeddataservice/app/src/installer/BUILD.gn index 0ccfc73e8..49eb62d2f 100644 --- a/services/distributeddataservice/app/src/installer/BUILD.gn +++ b/services/distributeddataservice/app/src/installer/BUILD.gn @@ -40,9 +40,13 @@ ohos_source_set("distributeddata_installer") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] - cflags = [ "-Oz" ] + cflags = [ + "-Oz", + "-fstack-protector-strong", + ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk", diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index f8ae56963..9b82df489 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -64,6 +64,7 @@ config("module_private_config") { "-Werror", "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] ldflags = [ "-Wl,-z,relro,-z,now,--whole-archive" ] defines = [ @@ -155,7 +156,10 @@ ohos_unittest("SessionManagerTest") { debug = false } - cflags_cc = [ "-DUT_TEST" ] + cflags_cc = [ + "-DUT_TEST", + "-fstack-protector-strong", + ] configs = [ ":module_private_config" ] external_deps = [ @@ -313,6 +317,7 @@ ohos_unittest("FeatureStubImplTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] if (datamgr_service_power) { diff --git a/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn index a04a1d620..55528a3c1 100644 --- a/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn @@ -59,6 +59,7 @@ ohos_fuzztest("DataServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index a4b707a6e..fafa407a3 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -123,11 +123,15 @@ ohos_shared_library("distributeddatasvcfwk") { "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-fdata-sections", "-ffunction-sections", + "-fstack-protector-strong", ] ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] - cflags_cc = [ "-fvisibility=hidden" ] + cflags_cc = [ + "-fvisibility=hidden", + "-fstack-protector-strong", + ] configs = [ ":module_config" ] diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn index 2cd08bc3d..e814574a7 100644 --- a/services/distributeddataservice/framework/test/BUILD.gn +++ b/services/distributeddataservice/framework/test/BUILD.gn @@ -46,7 +46,10 @@ config("module_private_config") { "${data_service_path}/service/matrix/include", "//third_party/json/single_include", ] - cflags = [ "-Werror" ] + cflags = [ + "-Werror", + "-fstack-protector-strong", + ] ldflags = [ "-Wl,-z,relro,-z,now,--whole-archive" ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } @@ -127,6 +130,7 @@ ohos_unittest("ServiceUtilsTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] external_deps = [ @@ -163,6 +167,7 @@ ohos_unittest("StoreTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] external_deps = [ diff --git a/services/distributeddataservice/rust/connect_adapter/BUILD.gn b/services/distributeddataservice/rust/connect_adapter/BUILD.gn index 49162568b..292dc2003 100644 --- a/services/distributeddataservice/rust/connect_adapter/BUILD.gn +++ b/services/distributeddataservice/rust/connect_adapter/BUILD.gn @@ -34,8 +34,14 @@ ohos_shared_library("conn_adapter") { "src/connect_wrapper.cpp", ] configs = [ ":export_connect" ] - cflags = [ "-Werror" ] - cflags_cc = [ "-fvisibility=hidden" ] + cflags = [ + "-Werror", + "-fstack-protector-strong", + ] + cflags_cc = [ + "-fvisibility=hidden", + "-fstack-protector-strong", + ] external_deps = [ "ability_base:want", diff --git a/services/distributeddataservice/rust/extension/BUILD.gn b/services/distributeddataservice/rust/extension/BUILD.gn index d1c0fdc1d..6730b9901 100644 --- a/services/distributeddataservice/rust/extension/BUILD.gn +++ b/services/distributeddataservice/rust/extension/BUILD.gn @@ -47,9 +47,13 @@ ohos_shared_library("opencloudextension") { cflags = [ "-Werror", "-Wno-multichar", + "-fstack-protector-strong", ] - cflags_cc = [ "-fvisibility=hidden" ] + cflags_cc = [ + "-fvisibility=hidden", + "-fstack-protector-strong", + ] configs = [ ":module_public_config" ] diff --git a/services/distributeddataservice/service/BUILD.gn b/services/distributeddataservice/service/BUILD.gn index 6274b1d1c..b07724a03 100644 --- a/services/distributeddataservice/service/BUILD.gn +++ b/services/distributeddataservice/service/BUILD.gn @@ -42,7 +42,10 @@ config("module_public_config") { "${kv_store_distributeddb_path}/interfaces/include/", "${kv_store_distributeddb_path}/interfaces/include/relational", ] - cflags = [ "-Wno-c99-designator" ] + cflags = [ + "-Wno-c99-designator", + "-fstack-protector-strong", + ] } ohos_shared_library("distributeddatasvc") { @@ -63,6 +66,7 @@ ohos_shared_library("distributeddatasvc") { "-Oz", "-fdata-sections", "-ffunction-sections", + "-fstack-protector-strong", ] ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] @@ -70,6 +74,7 @@ ohos_shared_library("distributeddatasvc") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] configs = [ ":module_public_config" ] diff --git a/services/distributeddataservice/service/backup/BUILD.gn b/services/distributeddataservice/service/backup/BUILD.gn index 6b90fa32f..6a492ef4b 100755 --- a/services/distributeddataservice/service/backup/BUILD.gn +++ b/services/distributeddataservice/service/backup/BUILD.gn @@ -32,6 +32,7 @@ ohos_source_set("distributeddata_backup") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] include_dirs = [ @@ -46,6 +47,7 @@ ohos_source_set("distributeddata_backup") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/bootstrap/BUILD.gn b/services/distributeddataservice/service/bootstrap/BUILD.gn index ff48eaece..70b1c24c0 100644 --- a/services/distributeddataservice/service/bootstrap/BUILD.gn +++ b/services/distributeddataservice/service/bootstrap/BUILD.gn @@ -32,6 +32,7 @@ ohos_source_set("distributeddata_bootstrap") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] include_dirs = [ "${data_service_path}/service/config/include" ] @@ -43,6 +44,7 @@ ohos_source_set("distributeddata_bootstrap") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/cloud/BUILD.gn b/services/distributeddataservice/service/cloud/BUILD.gn index b36909c07..3c592276d 100755 --- a/services/distributeddataservice/service/cloud/BUILD.gn +++ b/services/distributeddataservice/service/cloud/BUILD.gn @@ -39,6 +39,7 @@ ohos_source_set("distributeddata_cloud") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] include_dirs = [ @@ -59,6 +60,7 @@ ohos_source_set("distributeddata_cloud") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/common/BUILD.gn b/services/distributeddataservice/service/common/BUILD.gn index 3a8e1990d..7a493bd1b 100644 --- a/services/distributeddataservice/service/common/BUILD.gn +++ b/services/distributeddataservice/service/common/BUILD.gn @@ -31,6 +31,7 @@ ohos_source_set("distributeddata_common") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] include_dirs = [ "include" ] @@ -40,6 +41,7 @@ ohos_source_set("distributeddata_common") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] diff --git a/services/distributeddataservice/service/config/BUILD.gn b/services/distributeddataservice/service/config/BUILD.gn index a2ea71cf4..9349f8113 100644 --- a/services/distributeddataservice/service/config/BUILD.gn +++ b/services/distributeddataservice/service/config/BUILD.gn @@ -39,6 +39,7 @@ ohos_source_set("distributeddata_config") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] include_dirs = [ @@ -52,6 +53,7 @@ ohos_source_set("distributeddata_config") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] diff --git a/services/distributeddataservice/service/crypto/BUILD.gn b/services/distributeddataservice/service/crypto/BUILD.gn index 2b8003be8..18b166a96 100644 --- a/services/distributeddataservice/service/crypto/BUILD.gn +++ b/services/distributeddataservice/service/crypto/BUILD.gn @@ -32,6 +32,7 @@ ohos_source_set("distributeddata_crypto") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] include_dirs = [ "include" ] @@ -42,6 +43,7 @@ ohos_source_set("distributeddata_crypto") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] configs = [ ":crypto_public_config" ] public_configs = [ ":crypto_public_config" ] diff --git a/services/distributeddataservice/service/data_share/BUILD.gn b/services/distributeddataservice/service/data_share/BUILD.gn index 5f435aa5e..2964c14db 100644 --- a/services/distributeddataservice/service/data_share/BUILD.gn +++ b/services/distributeddataservice/service/data_share/BUILD.gn @@ -94,11 +94,13 @@ ohos_source_set("data_share_service") { "-Wno-multichar", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] configs = [ ":module_public_config" ] diff --git a/services/distributeddataservice/service/dumper/BUILD.gn b/services/distributeddataservice/service/dumper/BUILD.gn index 72b194d79..9ba04db73 100644 --- a/services/distributeddataservice/service/dumper/BUILD.gn +++ b/services/distributeddataservice/service/dumper/BUILD.gn @@ -27,6 +27,7 @@ ohos_source_set("distributeddata_dumper") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] include_dirs = [ "include" ] @@ -37,6 +38,7 @@ ohos_source_set("distributeddata_dumper") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] diff --git a/services/distributeddataservice/service/kvdb/BUILD.gn b/services/distributeddataservice/service/kvdb/BUILD.gn index 874dc361c..9f1d96dae 100644 --- a/services/distributeddataservice/service/kvdb/BUILD.gn +++ b/services/distributeddataservice/service/kvdb/BUILD.gn @@ -55,6 +55,7 @@ ohos_source_set("distributeddata_kvdb") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] cflags = [ @@ -63,6 +64,7 @@ ohos_source_set("distributeddata_kvdb") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/matrix/BUILD.gn b/services/distributeddataservice/service/matrix/BUILD.gn index e7f2d0a63..3499cbe6c 100755 --- a/services/distributeddataservice/service/matrix/BUILD.gn +++ b/services/distributeddataservice/service/matrix/BUILD.gn @@ -35,6 +35,7 @@ ohos_source_set("distributeddata_matrix") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] include_dirs = [ @@ -49,6 +50,7 @@ ohos_source_set("distributeddata_matrix") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/object/BUILD.gn b/services/distributeddataservice/service/object/BUILD.gn index e76a7510e..29056fe07 100644 --- a/services/distributeddataservice/service/object/BUILD.gn +++ b/services/distributeddataservice/service/object/BUILD.gn @@ -49,6 +49,7 @@ ohos_source_set("distributeddata_object") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] include_dirs = [ "include" ] @@ -61,6 +62,7 @@ ohos_source_set("distributeddata_object") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/permission/BUILD.gn b/services/distributeddataservice/service/permission/BUILD.gn index 2795bda98..0f28d2778 100644 --- a/services/distributeddataservice/service/permission/BUILD.gn +++ b/services/distributeddataservice/service/permission/BUILD.gn @@ -36,6 +36,7 @@ ohos_source_set("distributeddata_permit") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] include_dirs = [ @@ -51,6 +52,7 @@ ohos_source_set("distributeddata_permit") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", + "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/rdb/BUILD.gn b/services/distributeddataservice/service/rdb/BUILD.gn index 9c126c795..ad693d92d 100644 --- a/services/distributeddataservice/service/rdb/BUILD.gn +++ b/services/distributeddataservice/service/rdb/BUILD.gn @@ -63,6 +63,7 @@ ohos_source_set("distributeddata_rdb") { "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Werror", "-Oz", + "-fstack-protector-strong", ] deps = [ @@ -96,6 +97,7 @@ ohos_source_set("distributeddata_rdb") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] subsystem_name = "distributeddatamgr" diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 4d16dc1f1..32c82ccab 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -52,7 +52,10 @@ config("module_private_config") { "${relational_store_path}/interfaces/inner_api/common_type/include", "${data_service_path}/adapter/include/communicator", ] - cflags = [ "-Werror" ] + cflags = [ + "-Werror", + "-fstack-protector-strong", + ] defines = [ "TEST_ON_DEVICE", "OPENSSL_SUPPRESS_DEPRECATED", @@ -150,6 +153,7 @@ ohos_unittest("CloudDataTest") { cflags = [ "-fno-access-control", # Ignore Private Member Access Control + "-fstack-protector-strong", ] cflags_cc = cflags @@ -246,6 +250,7 @@ ohos_unittest("CloudServiceImplTest") { cflags = [ "-fno-access-control", # Ignore Private Member Access Control + "-fstack-protector-strong", ] cflags_cc = cflags @@ -294,6 +299,7 @@ ohos_unittest("ValueProxyServiceTest") { "-Dprotected=public", "-Wno-multichar", "-Wno-c99-designator", + "-fstack-protector-strong", ] external_deps = [ @@ -399,6 +405,7 @@ ohos_unittest("DeviceMatrixTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] external_deps = [ @@ -449,6 +456,7 @@ ohos_unittest("KVDBGeneralStoreTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] external_deps = [ @@ -517,6 +525,7 @@ ohos_unittest("KVDBGeneralStoreAbnormalTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] external_deps = [ @@ -566,6 +575,7 @@ ohos_unittest("RdbResultSetImplTest") { "-Dprotected=public", "-Wno-multichar", "-Wno-c99-designator", + "-fstack-protector-strong", ] external_deps = [ @@ -625,6 +635,7 @@ ohos_unittest("RdbServiceTest") { "-Wno-multichar", "-Wno-c99-designator", "-fno-access-control", # Ignore Private Member Access Control + "-fstack-protector-strong", ] external_deps = [ @@ -686,6 +697,7 @@ ohos_unittest("ObjectAssetLoaderTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] } @@ -756,6 +768,7 @@ ohos_unittest("ObjectDmsHandlerTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] } @@ -817,6 +830,7 @@ ohos_unittest("ObjectManagerTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] } @@ -1040,6 +1054,7 @@ ohos_unittest("DataShareServiceImplTest") { "-Wno-c99-designator", "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] external_deps = [ @@ -1114,6 +1129,7 @@ ohos_unittest("KvdbServiceImplTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] external_deps = [ @@ -1156,6 +1172,7 @@ ohos_unittest("DumpHelperTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] external_deps = [ @@ -1189,6 +1206,7 @@ ohos_unittest("UdmfServiceImplTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ @@ -1226,6 +1244,7 @@ ohos_unittest("UdmfServiceStubTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ @@ -1301,6 +1320,7 @@ ohos_unittest("UdmfServiceStubMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ "${data_service_path}/service:distributeddatasvc" ] @@ -1350,6 +1370,7 @@ ohos_unittest("UdmfCheckerManagerTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ @@ -1428,6 +1449,7 @@ ohos_unittest("PermissionValidatorMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ @@ -1469,6 +1491,7 @@ ohos_unittest("PermitDelegateMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] cflags_cc = cflags @@ -1544,6 +1567,7 @@ ohos_unittest("BootStrapMockTest") { "-Werror", "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] cflags_cc = cflags @@ -1571,6 +1595,7 @@ ohos_unittest("QueryHelperUnitTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] deps = [ @@ -1630,6 +1655,7 @@ ohos_unittest("AuthDelegateMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] cflags_cc = cflags @@ -1688,6 +1714,7 @@ ohos_unittest("UpgradeMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] cflags_cc = cflags @@ -1727,6 +1754,7 @@ ohos_unittest("UserDelegateMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] cflags_cc = cflags @@ -1759,6 +1787,7 @@ ohos_unittest("BackupManagerServiceTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", + "-fstack-protector-strong", ] external_deps = [ diff --git a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn index 3cb8f10bd..1202e1210 100644 --- a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn @@ -59,6 +59,7 @@ ohos_fuzztest("CloudServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn index 67dd09415..081de015c 100644 --- a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn @@ -48,6 +48,7 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn index 2fd165553..75a5eea34 100644 --- a/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("DumpHelperFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn index 458b5897b..3f9651228 100644 --- a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn @@ -55,6 +55,7 @@ ohos_fuzztest("KvdbServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn index 336b0dbfc..459739baa 100755 --- a/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn @@ -55,6 +55,7 @@ ohos_fuzztest("ObjectServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn index 984eddf37..effc420c1 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn @@ -47,6 +47,7 @@ ohos_fuzztest("RdbResultSetStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn index e51d78511..89c31f950 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn @@ -59,6 +59,7 @@ ohos_fuzztest("RdbServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn index 723fdfcc9..0449b7bd0 100644 --- a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn @@ -40,6 +40,7 @@ ohos_fuzztest("UdmfServiceFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-fstack-protector-strong", ] sources = [ "udmfservice_fuzzer.cpp" ] diff --git a/services/distributeddataservice/service/udmf/BUILD.gn b/services/distributeddataservice/service/udmf/BUILD.gn index 5d0f44c13..6a51944f7 100644 --- a/services/distributeddataservice/service/udmf/BUILD.gn +++ b/services/distributeddataservice/service/udmf/BUILD.gn @@ -70,6 +70,7 @@ ohos_source_set("udmf_server") { "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Werror", "-Oz", + "-fstack-protector-strong", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] @@ -92,6 +93,7 @@ ohos_source_set("udmf_server") { cflags_cc = [ "-fvisibility=hidden", "-Oz", + "-fstack-protector-strong", ] subsystem_name = "distributeddatamgr" -- Gitee From 447ad4edc2f8a586f83a1afd7806975030688991 Mon Sep 17 00:00:00 2001 From: l30005037 Date: Sat, 22 Mar 2025 10:39:19 +0800 Subject: [PATCH 064/225] Security and privacy compliance requirements Signed-off-by: l30005037 --- .../adapter/account/test/BUILD.gn | 1 - .../adapter/communicator/test/BUILD.gn | 7 ----- .../fuzztest/softbusadapter_fuzzer/BUILD.gn | 1 - .../adapter/dfx/test/BUILD.gn | 7 ++--- .../adapter/network/test/BUILD.gn | 2 -- .../adapter/screenlock/test/BUILD.gn | 1 - .../distributeddataservice/app/test/BUILD.gn | 9 ++---- .../fuzztest/dataservicestub_fuzzer/BUILD.gn | 1 - .../framework/test/BUILD.gn | 9 ++---- .../service/test/BUILD.gn | 31 +------------------ .../fuzztest/cloudservicestub_fuzzer/BUILD.gn | 1 - .../datashareservicestub_fuzzer/BUILD.gn | 1 - .../test/fuzztest/dumphelper_fuzzer/BUILD.gn | 1 - .../fuzztest/kvdbservicestub_fuzzer/BUILD.gn | 1 - .../objectservicestub_fuzzer/BUILD.gn | 1 - .../fuzztest/rdbresultsetstub_fuzzer/BUILD.gn | 1 - .../fuzztest/rdbservicestub_fuzzer/BUILD.gn | 1 - .../test/fuzztest/udmfservice_fuzzer/BUILD.gn | 1 - 18 files changed, 8 insertions(+), 69 deletions(-) diff --git a/services/distributeddataservice/adapter/account/test/BUILD.gn b/services/distributeddataservice/adapter/account/test/BUILD.gn index 5340c802a..39c09ee55 100755 --- a/services/distributeddataservice/adapter/account/test/BUILD.gn +++ b/services/distributeddataservice/adapter/account/test/BUILD.gn @@ -32,7 +32,6 @@ ohos_unittest("AccountDelegateTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ "../:distributeddata_account" ] diff --git a/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/BUILD.gn index c18e1b084..5e5a3489d 100755 --- a/services/distributeddataservice/adapter/communicator/test/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/BUILD.gn @@ -65,7 +65,6 @@ ohos_unittest("CommunicatorContextTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", @@ -89,7 +88,6 @@ ohos_unittest("CommunicatorDataBufferTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", @@ -120,7 +118,6 @@ ohos_unittest("DeviceManagerAdapterTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", @@ -177,7 +174,6 @@ ohos_unittest("ProcessCommunicatorImplTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ @@ -235,7 +231,6 @@ ohos_unittest("SoftbusAdapterStandardTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", @@ -267,7 +262,6 @@ ohos_unittest("SoftbusClientTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", @@ -298,7 +292,6 @@ ohos_unittest("AppPipeMgrServiceTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", diff --git a/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn index 01c09fe7b..cc55d56d7 100644 --- a/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn @@ -33,7 +33,6 @@ ohos_fuzztest("SoftBusAdapterFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", - "-fstack-protector-strong", ] sources = [ "softbusadapter_fuzzer.cpp" ] diff --git a/services/distributeddataservice/adapter/dfx/test/BUILD.gn b/services/distributeddataservice/adapter/dfx/test/BUILD.gn index bc4d53b77..78a3fa45b 100755 --- a/services/distributeddataservice/adapter/dfx/test/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/test/BUILD.gn @@ -42,7 +42,7 @@ ohos_unittest("DistributeddataDfxMSTTest") { "kv_store:distributeddata_inner", "openssl:libcrypto_shared", ] - ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] + ldflags = [ "-Wl,--exclude-libs,ALL" ] deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx", "//third_party/googletest:gtest_main", @@ -83,7 +83,7 @@ ohos_unittest("DistributeddataDfxUTTest") { "kv_store:distributeddata_inner", "openssl:libcrypto_shared", ] - ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] + ldflags = [ "-Wl,--exclude-libs,ALL" ] deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx", "${data_service_path}/adapter/utils:distributeddata_utils", @@ -100,7 +100,6 @@ ohos_unittest("HiViewAdapterDfxTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] configs = [ ":module_dfx_config" ] @@ -116,7 +115,7 @@ ohos_unittest("HiViewAdapterDfxTest") { "kv_store:distributeddata_mgr", "openssl:libcrypto_shared", ] - ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] + ldflags = [ "-Wl,--exclude-libs,ALL" ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/adapter/dfx:distributeddata_dfx", diff --git a/services/distributeddataservice/adapter/network/test/BUILD.gn b/services/distributeddataservice/adapter/network/test/BUILD.gn index 14277e488..c1b564cc8 100755 --- a/services/distributeddataservice/adapter/network/test/BUILD.gn +++ b/services/distributeddataservice/adapter/network/test/BUILD.gn @@ -32,7 +32,6 @@ ohos_unittest("NetworkDelegateTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ "../:distributeddata_network" ] @@ -67,7 +66,6 @@ ohos_unittest("NetworkDelegateNormalImplTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/adapter/screenlock/test/BUILD.gn b/services/distributeddataservice/adapter/screenlock/test/BUILD.gn index 962f8d9bc..f1f16b53b 100755 --- a/services/distributeddataservice/adapter/screenlock/test/BUILD.gn +++ b/services/distributeddataservice/adapter/screenlock/test/BUILD.gn @@ -33,7 +33,6 @@ ohos_unittest("ScreenLockTest") { "-Dprivate=public", "-Dprotected=public", "-Werror", - "-fstack-protector-strong", ] external_deps = [ diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index 9b82df489..f3f912893 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -64,9 +64,8 @@ config("module_private_config") { "-Werror", "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] - ldflags = [ "-Wl,-z,relro,-z,now,--whole-archive" ] + ldflags = [ "-Wl,--whole-archive" ] defines = [ "TEST_ON_DEVICE", "OPENSSL_SUPPRESS_DEPRECATED", @@ -156,10 +155,7 @@ ohos_unittest("SessionManagerTest") { debug = false } - cflags_cc = [ - "-DUT_TEST", - "-fstack-protector-strong", - ] + cflags_cc = [ "-DUT_TEST" ] configs = [ ":module_private_config" ] external_deps = [ @@ -317,7 +313,6 @@ ohos_unittest("FeatureStubImplTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] if (datamgr_service_power) { diff --git a/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn index 55528a3c1..a04a1d620 100644 --- a/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn @@ -59,7 +59,6 @@ ohos_fuzztest("DataServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", - "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn index e814574a7..728d05f26 100644 --- a/services/distributeddataservice/framework/test/BUILD.gn +++ b/services/distributeddataservice/framework/test/BUILD.gn @@ -46,11 +46,8 @@ config("module_private_config") { "${data_service_path}/service/matrix/include", "//third_party/json/single_include", ] - cflags = [ - "-Werror", - "-fstack-protector-strong", - ] - ldflags = [ "-Wl,-z,relro,-z,now,--whole-archive" ] + cflags = [ "-Werror" ] + ldflags = [ "-Wl,--whole-archive" ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } @@ -130,7 +127,6 @@ ohos_unittest("ServiceUtilsTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] external_deps = [ @@ -167,7 +163,6 @@ ohos_unittest("StoreTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] external_deps = [ diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 32c82ccab..4d16dc1f1 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -52,10 +52,7 @@ config("module_private_config") { "${relational_store_path}/interfaces/inner_api/common_type/include", "${data_service_path}/adapter/include/communicator", ] - cflags = [ - "-Werror", - "-fstack-protector-strong", - ] + cflags = [ "-Werror" ] defines = [ "TEST_ON_DEVICE", "OPENSSL_SUPPRESS_DEPRECATED", @@ -153,7 +150,6 @@ ohos_unittest("CloudDataTest") { cflags = [ "-fno-access-control", # Ignore Private Member Access Control - "-fstack-protector-strong", ] cflags_cc = cflags @@ -250,7 +246,6 @@ ohos_unittest("CloudServiceImplTest") { cflags = [ "-fno-access-control", # Ignore Private Member Access Control - "-fstack-protector-strong", ] cflags_cc = cflags @@ -299,7 +294,6 @@ ohos_unittest("ValueProxyServiceTest") { "-Dprotected=public", "-Wno-multichar", "-Wno-c99-designator", - "-fstack-protector-strong", ] external_deps = [ @@ -405,7 +399,6 @@ ohos_unittest("DeviceMatrixTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] external_deps = [ @@ -456,7 +449,6 @@ ohos_unittest("KVDBGeneralStoreTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] external_deps = [ @@ -525,7 +517,6 @@ ohos_unittest("KVDBGeneralStoreAbnormalTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] external_deps = [ @@ -575,7 +566,6 @@ ohos_unittest("RdbResultSetImplTest") { "-Dprotected=public", "-Wno-multichar", "-Wno-c99-designator", - "-fstack-protector-strong", ] external_deps = [ @@ -635,7 +625,6 @@ ohos_unittest("RdbServiceTest") { "-Wno-multichar", "-Wno-c99-designator", "-fno-access-control", # Ignore Private Member Access Control - "-fstack-protector-strong", ] external_deps = [ @@ -697,7 +686,6 @@ ohos_unittest("ObjectAssetLoaderTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] } @@ -768,7 +756,6 @@ ohos_unittest("ObjectDmsHandlerTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] } @@ -830,7 +817,6 @@ ohos_unittest("ObjectManagerTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] } @@ -1054,7 +1040,6 @@ ohos_unittest("DataShareServiceImplTest") { "-Wno-c99-designator", "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] external_deps = [ @@ -1129,7 +1114,6 @@ ohos_unittest("KvdbServiceImplTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] external_deps = [ @@ -1172,7 +1156,6 @@ ohos_unittest("DumpHelperTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] external_deps = [ @@ -1206,7 +1189,6 @@ ohos_unittest("UdmfServiceImplTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ @@ -1244,7 +1226,6 @@ ohos_unittest("UdmfServiceStubTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ @@ -1320,7 +1301,6 @@ ohos_unittest("UdmfServiceStubMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ "${data_service_path}/service:distributeddatasvc" ] @@ -1370,7 +1350,6 @@ ohos_unittest("UdmfCheckerManagerTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ @@ -1449,7 +1428,6 @@ ohos_unittest("PermissionValidatorMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ @@ -1491,7 +1469,6 @@ ohos_unittest("PermitDelegateMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] cflags_cc = cflags @@ -1567,7 +1544,6 @@ ohos_unittest("BootStrapMockTest") { "-Werror", "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] cflags_cc = cflags @@ -1595,7 +1571,6 @@ ohos_unittest("QueryHelperUnitTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] deps = [ @@ -1655,7 +1630,6 @@ ohos_unittest("AuthDelegateMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] cflags_cc = cflags @@ -1714,7 +1688,6 @@ ohos_unittest("UpgradeMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] cflags_cc = cflags @@ -1754,7 +1727,6 @@ ohos_unittest("UserDelegateMockTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] cflags_cc = cflags @@ -1787,7 +1759,6 @@ ohos_unittest("BackupManagerServiceTest") { cflags = [ "-Dprivate=public", "-Dprotected=public", - "-fstack-protector-strong", ] external_deps = [ diff --git a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn index 1202e1210..3cb8f10bd 100644 --- a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn @@ -59,7 +59,6 @@ ohos_fuzztest("CloudServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", - "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn index 081de015c..67dd09415 100644 --- a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn @@ -48,7 +48,6 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", - "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn index 75a5eea34..2fd165553 100644 --- a/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn @@ -44,7 +44,6 @@ ohos_fuzztest("DumpHelperFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", - "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn index 3f9651228..458b5897b 100644 --- a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn @@ -55,7 +55,6 @@ ohos_fuzztest("KvdbServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", - "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn index 459739baa..336b0dbfc 100755 --- a/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn @@ -55,7 +55,6 @@ ohos_fuzztest("ObjectServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", - "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn index effc420c1..984eddf37 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn @@ -47,7 +47,6 @@ ohos_fuzztest("RdbResultSetStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", - "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn index 89c31f950..e51d78511 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn @@ -59,7 +59,6 @@ ohos_fuzztest("RdbServiceStubFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", - "-fstack-protector-strong", ] sources = [ diff --git a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn index 0449b7bd0..723fdfcc9 100644 --- a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn @@ -40,7 +40,6 @@ ohos_fuzztest("UdmfServiceFuzzTest") { "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", - "-fstack-protector-strong", ] sources = [ "udmfservice_fuzzer.cpp" ] -- Gitee From 847dfa2121d7c2f678bec38e70fb55451d28ad19 Mon Sep 17 00:00:00 2001 From: yangliu Date: Sat, 22 Mar 2025 19:10:44 +0800 Subject: [PATCH 065/225] update Signed-off-by: yangliu --- .../framework/test/BUILD.gn | 5 + .../framework/test/meta_data_test.cpp | 233 ++++++++++++++---- .../service/rdb/rdb_general_store.h | 2 +- .../service/test/cloud_data_test.cpp | 104 ++++++++ .../service/test/kvdb_service_impl_test.cpp | 20 ++ .../service/test/kvdb_service_test.cpp | 20 ++ 6 files changed, 337 insertions(+), 47 deletions(-) diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn index 619dc289a..9075b5bf4 100644 --- a/services/distributeddataservice/framework/test/BUILD.gn +++ b/services/distributeddataservice/framework/test/BUILD.gn @@ -300,6 +300,11 @@ ohos_unittest("ServiceMetaDataTest") { cfi_cross_dso = true debug = false } + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] configs = [ ":module_private_config" ] diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index b2dbdb05a..32285e1e5 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -770,69 +770,210 @@ HWTEST_F(ServiceMetaDataTest, CapabilityRange, TestSize.Level1) } /** - * @tc.name: MatrixMetaData - * @tc.desc: test MatrixMetaData operator!= function - * @tc.type: FUNC - * @tc.require: - * @tc.author: nhj - */ -HWTEST_F(ServiceMetaDataTest, MatrixMetaData, TestSize.Level1) -{ - MatrixMetaData matrixMetaData1; - matrixMetaData1.version = 0; - matrixMetaData1.deviceId = "PEER_DEVICE_ID"; - - MatrixMetaData matrixMetaData2; - matrixMetaData2.version = 0; - matrixMetaData2.deviceId = "PEER_DEVICE_ID"; - - MatrixMetaData matrixMetaData3; - matrixMetaData3.version = 1; - matrixMetaData3.deviceId = "DEVICE_ID"; - EXPECT_TRUE(matrixMetaData1 != matrixMetaData3); - EXPECT_FALSE(matrixMetaData1 != matrixMetaData2); - - std::string key = matrixMetaData3.GetConsistentKey(); - EXPECT_EQ(key, "MatrixMeta###DEVICE_ID###Consistent"); -} - -/** - * @tc.name: DeviceMetaData - * @tc.desc: test DeviceMetaData function + * @tc.name: DeviceMetaData + * @tc.desc: test DeviceMetaData function * @tc.type: FUNC * @tc.require: * @tc.author: yl */ -HWTEST_F(ServiceMetaDataTest, DeviceMetaData, TestSize.Level1) +HWTEST_F(ServiceMetaDataTest, DeviceMetaData , TestSize.Level1) { - DeviceMetaData metaData; - std::string newUuid = "newuuid"; + DeviceMetaData metaData; + std::string currentUuid = "newuuid"; std::string oldUuid = "olduuid"; - metaData.newUuid = newUuid; + metaData.currentUuid = currentUuid; metaData.oldUuid = oldUuid; Serializable::json node1; metaData.Marshal(node1); - EXPECT_EQ(node1["newUuid"], newUuid); + EXPECT_EQ(node1["currentUuid"], currentUuid); EXPECT_EQ(node1["oldUuid"], oldUuid); - - DeviceMetaData newMetaData; + + DeviceIDMetaData newMetaData; newMetaData.Unmarshal(node1); - EXPECT_EQ(newMetaData.newUuid, newUuid); + EXPECT_EQ(newMetaData.currentUuid, currentUuid); EXPECT_EQ(newMetaData.oldUuid, oldUuid); } /** - * @tc.name: GetKeyTest - * @tc.desc: test GetKey function - * @tc.type: FUNC - * @tc.require: - * @tc.author: yl - */ -HWTEST_F(ServiceMetaDataTest, GetPrefixTest, TestSize.Level1) +* @tc.name: InitMeta +* @tc.desc: test Init TestMeta +* @tc.type: FUNC +* @tc.require: +* @tc.author: yl +*/ +HWTEST_F(ServiceMetaDataTest, InitTestMeta, TestSize.Level1) +{ + StoreMetaData oldMeta; + oldMeta.deviceId = "mockOldUuid"; + oldMeta.user = "200"; + oldMeta.bundleName = "test_appid_001"; + oldMeta.storeId = "test_storeid_001"; + bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta, true); + EXPECT_TRUE(isSuccess); + StoreMetaDataLocal metaDataLocal; + isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKeyLocal(), metaDataLocal, true); + EXPECT_TRUE(isSuccess); + SwitchesMetaData switchesMetaData; + isSuccess = MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({"mockOldUuid"}), + switchesMetaData, true); + EXPECT_TRUE(isSuccess); + AutoLaunchMetaData autoLaunchMetaData; + MetaDataManager::GetInstance().SaveMeta(AutoLaunchMetaData::GetPrefix({ oldMeta.deviceId, oldMeta.user, + "default", oldMeta.bundleName, "" }), autoLaunchMetaData, true); + EXPECT_TRUE(isSuccess); + MatrixMetaData matrixMeta0; + isSuccess = MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({"mockOldUuid"}), matrixMeta0, true); + EXPECT_TRUE(isSuccess); + + isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta); + EXPECT_TRUE(isSuccess); + MatrixMetaData matrixMeta; + isSuccess = MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({"mockOldUuid"}), matrixMeta); + EXPECT_TRUE(isSuccess); + UserMetaData userMeta; + isSuccess = MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor("mockOldUuid"), userMeta); + EXPECT_TRUE(isSuccess); + CapMetaData capMetaData; + auto capKey = CapMetaRow::GetKeyFor("mockOldUuid"); + isSuccess = MetaDataManager::GetInstance().SaveMeta(std::string(capKey.begin(), capKey.end()), capMetaData); + EXPECT_TRUE(isSuccess); + StrategyMeta strategyMeta; + isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetStrategyKey(), strategyMeta); + EXPECT_TRUE(isSuccess); +} + +/** +* @tc.name: UpdateStoreMetaData +* @tc.desc: test UpdateStoreMetaData function +* @tc.type: FUNC +* @tc.require: +* @tc.author: yl +*/ +HWTEST_F(ServiceMetaDataTest, UpdateStoreMetaData, TestSize.Level1) +{ + std::string mockNewUuid = "mockNewUuid"; + std::string mockOldUuid = "mockOldUuid"; + StoreMetaData newMeta; + newMeta.deviceId = "mockNewUuid"; + newMeta.user = "200"; + newMeta.bundleName = "test_appid_001"; + newMeta.storeId = "test_storeid_001"; + KvStoreMetaManager::GetInstance().UpdateStoreMetaData(mockNewUuid, mockOldUuid); + bool isSuccess = MetaDataManager::GetInstance().LoadMeta(newMeta.GetKey(), newMeta, true); + EXPECT_TRUE(isSuccess); + EXPECT_TRUE(newMeta.isNeedUpdateDeviceId); + isSuccess = MetaDataManager::GetInstance().LoadMeta(newMeta.GetKey(), newMeta); + EXPECT_TRUE(isSuccess); + AutoLaunchMetaData autoLaunchMetaData; + isSuccess = MetaDataManager::GetInstance().LoadMeta(AutoLaunchMetaData::GetPrefix({ newMeta.deviceId, newMeta.user, + "default", newMeta.bundleName, "" }), autoLaunchMetaData, true); + EXPECT_TRUE(isSuccess); + StrategyMeta strategyMeta; + isSuccess = MetaDataManager::GetInstance().LoadMeta(newMeta.GetStrategyKey(), strategyMeta); + EXPECT_TRUE(isSuccess); +} + +/** +* @tc.name: UpdateMetaDatas +* @tc.desc: test UpdateMetaDatas function +* @tc.type: FUNC +* @tc.require: +* @tc.author: yl +*/ +HWTEST_F(ServiceMetaDataTest, UpdateMetaDatas, TestSize.Level1) +{ + std::string mockNewUuid = "mockNewUuid"; + std::string mockOldUuid = "mockOldUuid"; + StoreMetaData newMeta; + newMeta.deviceId = "mockNewUuid"; + newMeta.user = "200"; + newMeta.bundleName = "test_appid_001"; + newMeta.storeId = "test_storeid_001"; + KvStoreMetaManager::GetInstance().UpdateMetaDatas(mockNewUuid, mockOldUuid); + MatrixMetaData matrixMeta; + bool isSuccess = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }), + matrixMeta, true); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }), matrixMeta); + EXPECT_TRUE(isSuccess); + UserMetaData userMeta; + isSuccess = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }), userMeta); + EXPECT_TRUE(isSuccess); + CapMetaData capMetaData; + auto capKey = CapMetaRow::GetKeyFor("mockNewUuid"); + isSuccess = MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), capMetaData); + EXPECT_TRUE(isSuccess); + SwitchesMetaData switchesMetaData; + isSuccess = MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({ "mockNewUuid" }), + switchesMetaData, true); + EXPECT_TRUE(isSuccess); +} + +/** +* @tc.name: DelInitTestMeta +* @tc.desc: test Del TestMeta +* @tc.type: FUNC +* @tc.require: +* @tc.author: yl +*/ +HWTEST_F(ServiceMetaDataTest, DelTestMeta, TestSize.Level1) +{ + StoreMetaData newMeta; + newMeta.deviceId = "mockNewUuid"; + newMeta.user = "200"; + newMeta.bundleName = "test_appid_001"; + newMeta.storeId = "test_storeid_001"; + bool isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetKey(), true); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetKeyLocal(), true); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({ "mockNewUuid" }), true); + EXPECT_TRUE(isSuccess); + MetaDataManager::GetInstance().DelMeta(AutoLaunchMetaData::GetPrefix({ "mockNewUuid", newMeta.user, + "default", newMeta.bundleName, "" }), true); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }), true); + EXPECT_TRUE(isSuccess); + + isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetKey()); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({"mockNewUuid"})); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor("mockNewUuid")); + EXPECT_TRUE(isSuccess); + auto capKey = CapMetaRow::GetKeyFor("mockNewUuid"); + isSuccess = MetaDataManager::GetInstance().DelMeta(std::string(capKey.begin(), capKey.end())); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetStrategyKey()); + EXPECT_TRUE(isSuccess); +} + +/** +* @tc.name: CheckMetaDeviceId +* @tc.desc: test CheckMetaDeviceId function +* @tc.type: FUNC +* @tc.require: +* @tc.author: yl +*/ +HWTEST_F(ServiceMetaDataTest, CheckMetaDeviceId, TestSize.Level1) +{ + std::string localUuid = ""; + KvStoreMetaManager::GetInstance().CheckMetaDeviceId(localUuid); + EXPECT_TRUE(localUuid.empty()); +} + +/** +* @tc.name: GetKeyTest +* @tc.desc: GetKey +* @tc.type: FUNC +* @tc.require: +* @tc.author: yl +*/ +HWTEST_F(ServiceMetaDataTest, GetKey, TestSize.Level1) { DeviceMetaData metaData; - std::string expectPrefix = "DeviceMeta"; + std::string expectedPrefix = "DeviceMeta"; std::string prefix = metaData.GetKey(); - EXPECT_EQ(prefix, expectPrefix); + EXPECT_EQ(prefix, expectedPrefix); } } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.h b/services/distributeddataservice/service/rdb/rdb_general_store.h index 3b34b4d06..3de5f3c37 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.h +++ b/services/distributeddataservice/service/rdb/rdb_general_store.h @@ -88,7 +88,7 @@ public: int32_t CleanTrackerData(const std::string &tableName, int64_t cursor) override; std::pair LockCloudDB() override; int32_t UnLockCloudDB() override; - int32_t OperateDataStatus() override;; + int32_t OperateDataStatus() override; private: RdbGeneralStore(const RdbGeneralStore& rdbGeneralStore); diff --git a/services/distributeddataservice/service/test/cloud_data_test.cpp b/services/distributeddataservice/service/test/cloud_data_test.cpp index 107a81cf9..bc316e505 100644 --- a/services/distributeddataservice/service/test/cloud_data_test.cpp +++ b/services/distributeddataservice/service/test/cloud_data_test.cpp @@ -2703,5 +2703,109 @@ HWTEST_F(CloudDataTest, GetPrepareTraceId, TestSize.Level0) EXPECT_EQ(evt.GetUser(), EVT_USER); EXPECT_EQ(evt.GetPrepareTraceId(), TEST_TRACE_ID); } + +/** +* @tc.name: TryUpdateDeviceId001 +* @tc.desc: TryUpdateDeviceId test +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudDataTest, TryUpdateDeviceId001, TestSize.Level1) +{ + DistributedRdb::RdbServiceImpl rdbServiceImpl; + DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; + StoreMetaData oldMeta; + oldMeta.deviceId = "oldUuidtest"; + oldMeta.user = "100"; + oldMeta.bundleName = "test_appid_001"; + oldMeta.storeId = "test_storeid_001"; + oldMeta.isNeedUpdateDeviceId = true; + oldMeta.storeType = StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN; + bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta); + EXPECT_EQ(isSuccess, true); + StoreMetaData meta1 = oldMeta; + auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); + EXPECT_EQ(ret, DistributedRdb::RDB_OK); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); +} + +/** +* @tc.name: TryUpdateDeviceId002 +* @tc.desc: TryUpdateDeviceId test +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudDataTest, TryUpdateDeviceId002, TestSize.Level1) +{ + DistributedRdb::RdbServiceImpl rdbServiceImpl; + DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; + StoreMetaData oldMeta; + oldMeta.deviceId = "oldUuidtest"; + oldMeta.user = "100"; + oldMeta.bundleName = "test_appid_001"; + oldMeta.storeId = "test_storeid_001"; + oldMeta.isNeedUpdateDeviceId = false; + oldMeta.storeType = StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN; + bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta); + EXPECT_EQ(isSuccess, true); + StoreMetaData meta1 = oldMeta; + auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); + EXPECT_EQ(ret, DistributedRdb::RDB_OK); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); +} + +/** +* @tc.name: TryUpdateDeviceId003 +* @tc.desc: TryUpdateDeviceId test +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudDataTest, TryUpdateDeviceId003, TestSize.Level1) +{ + DistributedRdb::RdbServiceImpl rdbServiceImpl; + DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; + StoreMetaData oldMeta; + oldMeta.deviceId = "oldUuidtest"; + oldMeta.user = "100"; + oldMeta.bundleName = "test_appid_001"; + oldMeta.storeId = "test_storeid_001"; + oldMeta.isNeedUpdateDeviceId = true; + oldMeta.storeType = StoreMetaData::StoreType::STORE_RELATIONAL_END; + bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta); + EXPECT_EQ(isSuccess, true); + StoreMetaData meta1 = oldMeta; + auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); + EXPECT_EQ(ret, DistributedRdb::RDB_OK); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); +} + +/** +* @tc.name: TryUpdateDeviceId004 +* @tc.desc: TryUpdateDeviceId test +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudDataTest, TryUpdateDeviceId004, TestSize.Level1) +{ + DistributedRdb::RdbServiceImpl rdbServiceImpl; + DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; + StoreMetaData oldMeta; + oldMeta.deviceId = "oldUuidtest"; + oldMeta.user = "100"; + oldMeta.bundleName = "test_appid_001"; + oldMeta.storeId = "test_storeid_001"; + oldMeta.isNeedUpdateDeviceId = false; + oldMeta.storeType = StoreMetaData::StoreType::STORE_RELATIONAL_END; + bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta); + EXPECT_EQ(isSuccess, true); + StoreMetaData meta1 = oldMeta; + auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); + EXPECT_EQ(ret, DistributedRdb::RDB_OK); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); +} } // namespace DistributedDataTest } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index ba28f19a5..aca82c982 100644 --- a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp @@ -893,6 +893,26 @@ HWTEST_F(KvdbServiceImplTest, GetBackupPasswordTest001, TestSize.Level0) ASSERT_EQ(status, Status::ERROR); } +/** +* @tc.name: GetBackupPasswordTest002 +* @tc.desc: GetBackupPassword test +* @tc.type: FUNC +* @tc.author: yl +*/ +HWTEST_F(KvdbServiceImplTest, GetBackupPasswordTest002, TestSize.Level0) +{ + AppId appId; + StoreId storeId; + appId.appId = "test_appid_100"; + storeId.storeId = "test_appid_100"; + StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); + meta.isNeedUpdateDeviceId = true; + std::vector> password; + auto status = kvdbServiceImpl_->GetBackupPassword + (appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::SECRET_KEY); + ASSERT_EQ(status, Status::ERROR); +} + /** * @tc.name: BeforeCreateTest001 * @tc.desc: BeforeCreate test diff --git a/services/distributeddataservice/service/test/kvdb_service_test.cpp b/services/distributeddataservice/service/test/kvdb_service_test.cpp index a017163e2..80990d179 100644 --- a/services/distributeddataservice/service/test/kvdb_service_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_test.cpp @@ -211,6 +211,26 @@ HWTEST_F(UpgradeTest, UpdateStore, TestSize.Level0) EXPECT_EQ(dbStatus, DBStatus::OK); } +/** +* @tc.name: UpdateStore002 +* @tc.desc: UpdateStore test the return result of input with different values. +* @tc.type: FUNC +* @tc.author: yl +*/ +HWTEST_F(UpgradeTest, UpdateStore002, TestSize.Level0) +{ + DistributedKv::Upgrade upgrade; + StoreMetaData oldMeta = metaData_; + oldMeta.isNeedUpdateDeviceId = true; + std::vector password; + auto dbStatus = upgrade.UpdateStore(oldMeta, metaData_, password); + EXPECT_EQ(dbStatus, DBStatus::DB_ERROR); + + oldMeta.isEncrypt = true; + dbStatus = upgrade.UpdateStore(oldMeta, metaData_, password); + EXPECT_EQ(dbStatus, DBStatus::OK); +} + /** * @tc.name: ExportStore * @tc.desc: ExportStore test the return result of input with different values. -- Gitee From a075bd393c1fc7eed4ef384ece77c9237839aeb6 Mon Sep 17 00:00:00 2001 From: yangliu Date: Sat, 22 Mar 2025 19:20:52 +0800 Subject: [PATCH 066/225] update Signed-off-by: yangliu --- .../framework/test/meta_data_test.cpp | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 32285e1e5..15a46489b 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -769,9 +769,36 @@ HWTEST_F(ServiceMetaDataTest, CapabilityRange, TestSize.Level1) EXPECT_EQ(capRange.remoteLabel, remote); } +/** + * @tc.name: MatrixMetaData + * @tc.desc: test MatrixMetaData operator!= function + * @tc.type: FUNC + * @tc.require: + * @tc.author: nhj + */ +HWTEST_F(ServiceMetaDataTest, MatrixMetaData, TestSize.Level1) +{ + MatrixMetaData matrixMetaData1; + matrixMetaData1.version = 0; + matrixMetaData1.deviceId = "PEER_DEVICE_ID"; + + MatrixMetaData matrixMetaData2; + matrixMetaData2.version = 0; + matrixMetaData2.deviceId = "PEER_DEVICE_ID"; + + MatrixMetaData matrixMetaData3; + matrixMetaData3.version = 1; + matrixMetaData3.deviceId = "DEVICE_ID"; + EXPECT_TRUE(matrixMetaData1 != matrixMetaData3); + EXPECT_FALSE(matrixMetaData1 != matrixMetaData2); + + std::string key = matrixMetaData3.GetConsistentKey(); + EXPECT_EQ(key, "MatrixMeta###DEVICE_ID###Consistent"); +} + /** * @tc.name: DeviceMetaData - * @tc.desc: test DeviceMetaData function + * @tc.desc: test DeviceMetaData function * @tc.type: FUNC * @tc.require: * @tc.author: yl -- Gitee From d6b136458a96f475db474df2498d8b86834e8888 Mon Sep 17 00:00:00 2001 From: yangliu Date: Sat, 22 Mar 2025 20:53:22 +0800 Subject: [PATCH 067/225] update Signed-off-by: yangliu --- .../framework/test/BUILD.gn | 2 +- .../framework/test/meta_data_test.cpp | 16 ++++++++++------ .../service/test/kvdb_service_impl_test.cpp | 5 +++++ 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn index 9075b5bf4..36aac8d74 100644 --- a/services/distributeddataservice/framework/test/BUILD.gn +++ b/services/distributeddataservice/framework/test/BUILD.gn @@ -300,7 +300,7 @@ ohos_unittest("ServiceMetaDataTest") { cfi_cross_dso = true debug = false } - + cflags = [ "-Dprivate=public", "-Dprotected=public", diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 15a46489b..e46db4dc3 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -15,6 +15,9 @@ #include "bootstrap.h" #include "kvstore_meta_manager.h" + +#include "metadata/appid_meta_data.h" +#include "metadata/auto_launch_meta_data.h" #include "metadata/appid_meta_data.h" #include "metadata/capability_meta_data.h" #include "metadata/capability_range.h" @@ -26,6 +29,7 @@ #include "metadata/store_meta_data.h" #include "metadata/store_meta_data_local.h" #include "metadata/strategy_meta_data.h" +#include "metadata/switches_meta_data.h" #include "metadata/user_meta_data.h" #include "metadata/device_meta_data.h" #include "utils/constant.h" @@ -797,27 +801,27 @@ HWTEST_F(ServiceMetaDataTest, MatrixMetaData, TestSize.Level1) } /** - * @tc.name: DeviceMetaData + * @tc.name: DeviceMetaData * @tc.desc: test DeviceMetaData function * @tc.type: FUNC * @tc.require: * @tc.author: yl */ -HWTEST_F(ServiceMetaDataTest, DeviceMetaData , TestSize.Level1) +HWTEST_F(ServiceMetaDataTest, DeviceMetaData, TestSize.Level1) { DeviceMetaData metaData; - std::string currentUuid = "newuuid"; + std::string newUuid = "newuuid"; std::string oldUuid = "olduuid"; - metaData.currentUuid = currentUuid; + metaData.newUuid = newUuid; metaData.oldUuid = oldUuid; Serializable::json node1; metaData.Marshal(node1); - EXPECT_EQ(node1["currentUuid"], currentUuid); + EXPECT_EQ(node1["newUuid"], newUuid); EXPECT_EQ(node1["oldUuid"], oldUuid); DeviceIDMetaData newMetaData; newMetaData.Unmarshal(node1); - EXPECT_EQ(newMetaData.currentUuid, currentUuid); + EXPECT_EQ(newMetaData.newUuid, newUuid); EXPECT_EQ(newMetaData.oldUuid, oldUuid); } diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index aca82c982..5db1eb62e 100644 --- a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp @@ -911,6 +911,11 @@ HWTEST_F(KvdbServiceImplTest, GetBackupPasswordTest002, TestSize.Level0) auto status = kvdbServiceImpl_->GetBackupPassword (appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::SECRET_KEY); ASSERT_EQ(status, Status::ERROR); + + meta.isNeedUpdateDeviceId = false; + auto status = kvdbServiceImpl_->GetBackupPassword + (appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::SECRET_KEY); + ASSERT_EQ(status, Status::ERROR); } /** -- Gitee From 949899ae68e80b037d36c9ae78d1ad2e77400f98 Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 23 Mar 2025 14:38:51 +0800 Subject: [PATCH 068/225] update Signed-off-by: yangliu --- .../app/src/kvstore_meta_manager.cpp | 110 ++++++++---------- .../app/src/kvstore_meta_manager.h | 4 +- .../framework/include/store/general_store.h | 2 +- .../framework/test/meta_data_test.cpp | 1 + .../service/kvdb/kvdb_service_impl.cpp | 6 - .../service/rdb/rdb_general_store.cpp | 7 +- .../service/rdb/rdb_general_store.h | 2 +- .../service/rdb/rdb_service_impl.cpp | 6 +- .../service/test/kvdb_service_impl_test.cpp | 25 ---- 9 files changed, 63 insertions(+), 100 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 3abb91c6e..105486adc 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -143,9 +143,8 @@ void KvStoreMetaManager::InitMetaData() ZLOGI("get meta failed."); return; } - auto uuid = DmAdapter::GetInstance().GetLocalDevice().uuid; - CheckMetaDeviceId(uuid); + CheckMetaDeviceId(); auto uid = getuid(); auto tokenId = IPCSkeleton::GetCallingTokenID(); auto userId = AccountDelegate::GetInstance()->GetUserByToken(tokenId); @@ -566,9 +565,10 @@ AppDistributedKv::ChangeLevelType KvStoreMetaManager::DBInfoDeviceChangeListener return AppDistributedKv::ChangeLevelType::MIN; } -void KvStoreMetaManager::CheckMetaDeviceId(const std::string &localUuid) +void KvStoreMetaManager::CheckMetaDeviceId() { DeviceMetaData deviceMeta; + auto localUuid = DmAdapter::GetInstance().GetLocalDevice().uuid; if (localUuid.empty()) { ZLOGW("get uuid failed"); return; @@ -576,44 +576,50 @@ void KvStoreMetaManager::CheckMetaDeviceId(const std::string &localUuid) if (!MetaDataManager::GetInstance().LoadMeta(deviceMeta.GetKey(), deviceMeta, true)) { deviceMeta.newUuid = localUuid; MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true); - } else { - if (deviceMeta.newUuid != localUuid) { - deviceMeta.oldUuid = deviceMeta.newUuid; - deviceMeta.newUuid = localUuid; - MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true); - ZLOGI("meta changed! curruuid:%{public}s, olduuid:%{public}s", - deviceMeta.newUuid.c_str(), deviceMeta.oldUuid.c_str()); - UpdateMetaDeviceId(localUuid, deviceMeta.oldUuid); - } + return; + } + if (deviceMeta.newUuid != localUuid) { + UpdateStoreMetaData(localUuid, deviceMeta.newUuid); + UpdateMetaDatas(localUuid, deviceMeta.newUuid); + deviceMeta.oldUuid = deviceMeta.newUuid; + deviceMeta.newUuid = localUuid; + MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true); + ZLOGI("meta changed! curruuid:%{public}s, olduuid:%{public}s", + deviceMeta.newUuid.c_str(), deviceMeta.oldUuid.c_str()); } -} - -void KvStoreMetaManager::UpdateMetaDeviceId(const std::string &newUuid, const std::string &oldUuid) -{ - //update meta like prefix###uuid###user###default#bundleName#storeid - UpdateStoreMetaData(newUuid, oldUuid); - //update meta like prefix###uuid - UpdateMetaDatas(newUuid, oldUuid); } void KvStoreMetaManager::UpdateStoreMetaData(const std::string &newUuid, const std::string &oldUuid) { std::vector storeMetas; - MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({oldUuid}), storeMetas, true); + MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ oldUuid }), storeMetas, true); for (auto &storeMeta : storeMetas) { - // update storeMeta in local table auto oldMeta = storeMeta; storeMeta.isNeedUpdateDeviceId = true; - MetaDataManager::GetInstance().DelMeta(storeMeta.GetKey(), true); storeMeta.deviceId = newUuid; MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), storeMeta, true); - // update storeMetaLocal in local table + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey(), true); + + StoreMetaData syncStoreMeta; + if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetKey(), syncStoreMeta)) { + syncStoreMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), syncStoreMeta); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); + } + + StrategyMeta strategyMeta; + if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetStrategyKey(), strategyMeta)) { + strategyMeta.devId = newUuid; + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetStrategyKey(), strategyMeta); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetStrategyKey()); + } + StoreMetaDataLocal metaDataLocal; if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetKeyLocal(), metaDataLocal, true)) { - MetaDataManager::GetInstance().DelMeta(oldMeta.GetKeyLocal(), true); MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKeyLocal(), metaDataLocal, true); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKeyLocal(), true); } - // update autoLaunchMeta in local table + AutoLaunchMetaData autoLaunchMetaData; bool isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, true); if (!isExist) { @@ -625,60 +631,44 @@ void KvStoreMetaManager::UpdateStoreMetaData(const std::string &newUuid, const s oldMeta.deviceId = newUuid; MetaDataManager::GetInstance().SaveMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, true); } - } - - storeMetas.clear(); - MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({oldUuid}), storeMetas); - for (auto &storeMeta : storeMetas) { - // update storeMeta in sync table - auto oldMeta = storeMeta; - MetaDataManager::GetInstance().DelMeta(storeMeta.GetKey()); - storeMeta.deviceId = newUuid; - MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), storeMeta); - // update strategyMeta in sync table - StrategyMeta strategyMeta; - if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetStrategyKey(), strategyMeta)) { - MetaDataManager::GetInstance().DelMeta(oldMeta.GetStrategyKey()); - strategyMeta.devId = newUuid; - MetaDataManager::GetInstance().SaveMeta(storeMeta.GetStrategyKey(), strategyMeta); + if (storeMeta.isEncrypt) { + MetaDataManager::GetInstance().DelMeta(storeMeta.GetSecretKey(), true); + MetaDataManager::GetInstance().DelMeta(storeMeta.GetCloneSecretKey(), true); } } } void KvStoreMetaManager::UpdateMetaDatas(const std::string &newUuid, const std::string &oldUuid) { - // update storeMeta in local table MatrixMetaData matrixMeta; - bool isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({oldUuid}), matrixMeta, true); - if (isExist) { - MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({oldUuid}), true); + if (MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUuid }), matrixMeta, true)) { + MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ oldUuid }), true); matrixMeta.deviceId = newUuid; - MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({newUuid}), matrixMeta, true); + MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({ newUuid }), matrixMeta, true); } - // update storeMeta in sync table - isExist = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({oldUuid}), matrixMeta); - if (isExist) { - MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({oldUuid})); + + if (MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUuid }), matrixMeta)) { + MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ oldUuid })); matrixMeta.deviceId = newUuid; - MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({newUuid}), matrixMeta); + MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({ newUuid }), matrixMeta); } - // update switchesMeta in local table + SwitchesMetaData switchesMetaData; - if (MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({oldUuid}), + if (MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({ oldUuid }), switchesMetaData, true)) { - MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({oldUuid}), true); - switchesMetaData.deviceId = newUuid; - MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({newUuid}), - switchesMetaData, true); + MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({ oldUuid }), true); + switchesMetaData.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({ newUuid }), + switchesMetaData, true); } - // update userMeta in sync table + UserMetaData userMeta; if (MetaDataManager::GetInstance().LoadMeta(UserMetaRow::GetKeyFor(oldUuid), userMeta)) { MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor(oldUuid)); userMeta.deviceId = newUuid; MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor(newUuid), userMeta); } - // update capMeta in sync table + CapMetaData capMetaData; auto capKey = CapMetaRow::GetKeyFor(oldUuid); if (MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), capMetaData)) { diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index a80459b1b..f7b28e1cd 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -96,10 +96,8 @@ private: DistributedDB::KvStoreNbDelegate::Option InitDBOption(); - void CheckMetaDeviceId(const std::string &localUuid); + void CheckMetaDeviceId(); - void UpdateMetaDeviceId(const std::string &newUuid, const std::string &oldUuid); - void UpdateStoreMetaData(const std::string &newUuid, const std::string &oldUuid); void UpdateMetaDatas(const std::string &newUuid, const std::string &oldUuid); diff --git a/services/distributeddataservice/framework/include/store/general_store.h b/services/distributeddataservice/framework/include/store/general_store.h index 47cb37975..dd4e27e7d 100644 --- a/services/distributeddataservice/framework/include/store/general_store.h +++ b/services/distributeddataservice/framework/include/store/general_store.h @@ -198,7 +198,7 @@ public: virtual int32_t UnLockCloudDB() = 0; - virtual int32_t OperateDataStatus() + virtual int32_t UpdateDBStatus() { return 0; } diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index e46db4dc3..71aab549a 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -839,6 +839,7 @@ HWTEST_F(ServiceMetaDataTest, InitTestMeta, TestSize.Level1) oldMeta.user = "200"; oldMeta.bundleName = "test_appid_001"; oldMeta.storeId = "test_storeid_001"; + oldMeta.isEncrypt = true; bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta, true); EXPECT_TRUE(isSuccess); StoreMetaDataLocal metaDataLocal; diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index 0cbd8215e..d93388844 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -622,12 +622,6 @@ Status KVDBServiceImpl::GetBackupPassword(const AppId &appId, const StoreId &sto if (passwordType == KVDBService::PasswordType::SECRET_KEY) { StoreMetaData meta; MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), meta, true); - if (meta.isNeedUpdateDeviceId) { - MetaDataManager::GetInstance().DelMeta(metaData.GetSecretKey(), true); - MetaDataManager::GetInstance().DelMeta(metaData.GetCloneSecretKey(), true); - ZLOGW("device already update uuid, del secretkey. appId:%{public}s, storeId:%{public}s", - appId.appId.c_str(), Anonymous::Change(storeId.storeId).c_str()); - } passwords.reserve(SECRET_KEY_COUNT); SecretKeyMetaData secretKey; std::vector password; diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.cpp b/services/distributeddataservice/service/rdb/rdb_general_store.cpp index 556de1dda..b8dc6345e 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.cpp +++ b/services/distributeddataservice/service/rdb/rdb_general_store.cpp @@ -1339,8 +1339,13 @@ RdbGeneralStore::DBProcessCB RdbGeneralStore::GetCB(SyncId syncId) }; } -int32_t RdbGeneralStore::OperateDataStatus() +int32_t RdbGeneralStore::UpdateDBStatus() { + std::shared_lock lock(rwMutex_); + if (delegate_ == nullptr) { + ZLOGE("Database already closed! database:%{public}s", Anonymous::Change(storeInfo_.storeName).c_str()); + return GeneralError::E_ALREADY_CLOSED; + } return delegate_->OperateDataStatus(static_cast(DataOperator::UPDATE_TIME)); } } // namespace OHOS::DistributedRdb \ No newline at end of file diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.h b/services/distributeddataservice/service/rdb/rdb_general_store.h index 3de5f3c37..98b5d2ed6 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.h +++ b/services/distributeddataservice/service/rdb/rdb_general_store.h @@ -88,7 +88,7 @@ public: int32_t CleanTrackerData(const std::string &tableName, int64_t cursor) override; std::pair LockCloudDB() override; int32_t UnLockCloudDB() override; - int32_t OperateDataStatus() override; + int32_t UpdateDBStatus() override; private: RdbGeneralStore(const RdbGeneralStore& rdbGeneralStore); diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index bfcd88c35..7cf464f28 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -828,7 +828,7 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) ZLOGI("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " "area:%{public}d->%{public}d", meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), old.storeType, meta.storeType, old.isEncrypt, meta.isEncrypt, old.area, meta.area); - TryUpdateDeviceId(param, old, meta); + meta.isNeedUpdateDeviceId = isCreated && !tryupdatedeviceid(); MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); AutoLaunchMetaData launchData; if (!MetaDataManager::GetInstance().LoadMeta(meta.GetAutoLaunchKey(), launchData, true)) { @@ -1664,12 +1664,12 @@ int32_t RdbServiceImpl::TryUpdateDeviceId(const RdbSyncerParam ¶m, const Sto Anonymous::Change(param.storeName_).c_str()); return RDB_ERROR; } - auto errCode = store->OperateDataStatus(); + auto errCode = store->UpdateDBStatus(); if (errCode == RDB_OK) { meta.isNeedUpdateDeviceId = false; } else { meta.isNeedUpdateDeviceId = true; - ZLOGE("OperateDataStatus failed errCode %{public}d", errCode); + ZLOGE("UpdateDBStatus failed errCode %{public}d", errCode); } } return RDB_OK; diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index 5db1eb62e..ba28f19a5 100644 --- a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp @@ -893,31 +893,6 @@ HWTEST_F(KvdbServiceImplTest, GetBackupPasswordTest001, TestSize.Level0) ASSERT_EQ(status, Status::ERROR); } -/** -* @tc.name: GetBackupPasswordTest002 -* @tc.desc: GetBackupPassword test -* @tc.type: FUNC -* @tc.author: yl -*/ -HWTEST_F(KvdbServiceImplTest, GetBackupPasswordTest002, TestSize.Level0) -{ - AppId appId; - StoreId storeId; - appId.appId = "test_appid_100"; - storeId.storeId = "test_appid_100"; - StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); - meta.isNeedUpdateDeviceId = true; - std::vector> password; - auto status = kvdbServiceImpl_->GetBackupPassword - (appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::SECRET_KEY); - ASSERT_EQ(status, Status::ERROR); - - meta.isNeedUpdateDeviceId = false; - auto status = kvdbServiceImpl_->GetBackupPassword - (appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::SECRET_KEY); - ASSERT_EQ(status, Status::ERROR); -} - /** * @tc.name: BeforeCreateTest001 * @tc.desc: BeforeCreate test -- Gitee From 4c41bdc47d9d17560d3a2835e126456e5f25647a Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 23 Mar 2025 15:07:07 +0800 Subject: [PATCH 069/225] update Signed-off-by: yangliu --- .../distributeddataservice/app/src/kvstore_meta_manager.cpp | 2 +- .../distributeddataservice/service/kvdb/kvdb_service_impl.cpp | 2 -- .../distributeddataservice/service/rdb/rdb_service_impl.cpp | 2 +- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 105486adc..06b07a9c1 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -659,7 +659,7 @@ void KvStoreMetaManager::UpdateMetaDatas(const std::string &newUuid, const std:: MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({ oldUuid }), true); switchesMetaData.deviceId = newUuid; MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({ newUuid }), - switchesMetaData, true); + switchesMetaData, true); } UserMetaData userMeta; diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index d93388844..f04980ccc 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -620,8 +620,6 @@ Status KVDBServiceImpl::GetBackupPassword(const AppId &appId, const StoreId &sto return res ? SUCCESS : ERROR; } if (passwordType == KVDBService::PasswordType::SECRET_KEY) { - StoreMetaData meta; - MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), meta, true); passwords.reserve(SECRET_KEY_COUNT); SecretKeyMetaData secretKey; std::vector password; diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 7cf464f28..ce9980c06 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -828,7 +828,7 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) ZLOGI("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " "area:%{public}d->%{public}d", meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), old.storeType, meta.storeType, old.isEncrypt, meta.isEncrypt, old.area, meta.area); - meta.isNeedUpdateDeviceId = isCreated && !tryupdatedeviceid(); + meta.isNeedUpdateDeviceId = isCreated && !TryUpdateDeviceId(); MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); AutoLaunchMetaData launchData; if (!MetaDataManager::GetInstance().LoadMeta(meta.GetAutoLaunchKey(), launchData, true)) { -- Gitee From 0807b0e5079b2a7602b9af0de1886e6dab373086 Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 23 Mar 2025 15:23:33 +0800 Subject: [PATCH 070/225] update Signed-off-by: yangliu --- .../distributeddataservice/service/rdb/rdb_service_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index ce9980c06..ea64cf7ed 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -828,7 +828,7 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) ZLOGI("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " "area:%{public}d->%{public}d", meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), old.storeType, meta.storeType, old.isEncrypt, meta.isEncrypt, old.area, meta.area); - meta.isNeedUpdateDeviceId = isCreated && !TryUpdateDeviceId(); + meta.isNeedUpdateDeviceId = isCreated && !TryUpdateDeviceId(param, old, meta); MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); AutoLaunchMetaData launchData; if (!MetaDataManager::GetInstance().LoadMeta(meta.GetAutoLaunchKey(), launchData, true)) { -- Gitee From b27dbd93707777212b860db830e6b8e219c1093c Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 23 Mar 2025 15:43:05 +0800 Subject: [PATCH 071/225] update Signed-off-by: yangliu --- .../framework/test/meta_data_test.cpp | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 71aab549a..7e57d044f 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -980,20 +980,6 @@ HWTEST_F(ServiceMetaDataTest, DelTestMeta, TestSize.Level1) EXPECT_TRUE(isSuccess); } -/** -* @tc.name: CheckMetaDeviceId -* @tc.desc: test CheckMetaDeviceId function -* @tc.type: FUNC -* @tc.require: -* @tc.author: yl -*/ -HWTEST_F(ServiceMetaDataTest, CheckMetaDeviceId, TestSize.Level1) -{ - std::string localUuid = ""; - KvStoreMetaManager::GetInstance().CheckMetaDeviceId(localUuid); - EXPECT_TRUE(localUuid.empty()); -} - /** * @tc.name: GetKeyTest * @tc.desc: GetKey -- Gitee From 51eb8206b6ae7792faa4f44e92555ff5460e0a5c Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 23 Mar 2025 16:01:15 +0800 Subject: [PATCH 072/225] update Signed-off-by: yangliu --- .../distributeddataservice/framework/test/meta_data_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 7e57d044f..952990503 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -819,7 +819,7 @@ HWTEST_F(ServiceMetaDataTest, DeviceMetaData, TestSize.Level1) EXPECT_EQ(node1["newUuid"], newUuid); EXPECT_EQ(node1["oldUuid"], oldUuid); - DeviceIDMetaData newMetaData; + DeviceMetaData newMetaData; newMetaData.Unmarshal(node1); EXPECT_EQ(newMetaData.newUuid, newUuid); EXPECT_EQ(newMetaData.oldUuid, oldUuid); -- Gitee From 02f99facfe3e2f3ac022ad088275817fb3881bc1 Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 23 Mar 2025 19:05:02 +0800 Subject: [PATCH 073/225] fix Signed-off-by: yangliu --- .../service/rdb/rdb_service_impl.cpp | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index ea64cf7ed..62f11adf9 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -1664,13 +1664,7 @@ int32_t RdbServiceImpl::TryUpdateDeviceId(const RdbSyncerParam ¶m, const Sto Anonymous::Change(param.storeName_).c_str()); return RDB_ERROR; } - auto errCode = store->UpdateDBStatus(); - if (errCode == RDB_OK) { - meta.isNeedUpdateDeviceId = false; - } else { - meta.isNeedUpdateDeviceId = true; - ZLOGE("UpdateDBStatus failed errCode %{public}d", errCode); - } + return store->UpdateDBStatus(); } return RDB_OK; } -- Gitee From 56cd54fb357f7414d81f3810cc2b24ac0fe20acf Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 23 Mar 2025 21:26:40 +0800 Subject: [PATCH 074/225] update Signed-off-by: yangliu --- .../service/rdb/rdb_service_impl.cpp | 10 +++++++--- .../service/test/cloud_data_test.cpp | 8 ++++---- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 62f11adf9..bf753d398 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -1662,10 +1662,14 @@ int32_t RdbServiceImpl::TryUpdateDeviceId(const RdbSyncerParam ¶m, const Sto if (store == nullptr) { ZLOGE("store is null, bundleName:%{public}s storeName:%{public}s", param.bundleName_.c_str(), Anonymous::Change(param.storeName_).c_str()); - return RDB_ERROR; + return false; + } + auto errCode store->UpdateDBStatus(); + if (errCode != RDB_OK) { + ZLOGE("Update failed errCode %{public}d", errCode); + return false; } - return store->UpdateDBStatus(); } - return RDB_OK; + return true; } } // namespace OHOS::DistributedRdb \ 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 bc316e505..8b5655a44 100644 --- a/services/distributeddataservice/service/test/cloud_data_test.cpp +++ b/services/distributeddataservice/service/test/cloud_data_test.cpp @@ -2726,7 +2726,7 @@ HWTEST_F(CloudDataTest, TryUpdateDeviceId001, TestSize.Level1) EXPECT_EQ(isSuccess, true); StoreMetaData meta1 = oldMeta; auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); - EXPECT_EQ(ret, DistributedRdb::RDB_OK); + EXPECT_EQ(ret, true); MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); } @@ -2752,7 +2752,7 @@ HWTEST_F(CloudDataTest, TryUpdateDeviceId002, TestSize.Level1) EXPECT_EQ(isSuccess, true); StoreMetaData meta1 = oldMeta; auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); - EXPECT_EQ(ret, DistributedRdb::RDB_OK); + EXPECT_EQ(ret, true); MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); } @@ -2778,7 +2778,7 @@ HWTEST_F(CloudDataTest, TryUpdateDeviceId003, TestSize.Level1) EXPECT_EQ(isSuccess, true); StoreMetaData meta1 = oldMeta; auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); - EXPECT_EQ(ret, DistributedRdb::RDB_OK); + EXPECT_EQ(ret, true); MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); } @@ -2804,7 +2804,7 @@ HWTEST_F(CloudDataTest, TryUpdateDeviceId004, TestSize.Level1) EXPECT_EQ(isSuccess, true); StoreMetaData meta1 = oldMeta; auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); - EXPECT_EQ(ret, DistributedRdb::RDB_OK); + EXPECT_EQ(ret, true); MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); } } // namespace DistributedDataTest -- Gitee From d665d53f3f104af134d915de30311100c1b73f56 Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 23 Mar 2025 21:27:30 +0800 Subject: [PATCH 075/225] update Signed-off-by: yangliu --- .../distributeddataservice/service/rdb/rdb_service_impl.cpp | 2 +- services/distributeddataservice/service/rdb/rdb_service_impl.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index bf753d398..3085f98fb 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -1651,7 +1651,7 @@ std::string RdbServiceImpl::GetSubUser(const int32_t subUser) return userId; } -int32_t RdbServiceImpl::TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, +bool RdbServiceImpl::TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, StoreMetaData &meta) { StoreMetaData syncMeta; diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.h b/services/distributeddataservice/service/rdb/rdb_service_impl.h index 96b11236e..b876a2f40 100755 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -241,7 +241,7 @@ private: bool UpgradeCloneSecretKey(const StoreMetaData &meta); - int32_t TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, StoreMetaData &meta); + bool TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, StoreMetaData &meta); static Factory factory_; ConcurrentMap syncAgents_; -- Gitee From 350a048cfb780edc1e4894cb075555d5035a435f Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 23 Mar 2025 21:43:45 +0800 Subject: [PATCH 076/225] update Signed-off-by: yangliu --- .../distributeddataservice/service/rdb/rdb_service_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 3085f98fb..61bff0d76 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -1664,7 +1664,7 @@ bool RdbServiceImpl::TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreM Anonymous::Change(param.storeName_).c_str()); return false; } - auto errCode store->UpdateDBStatus(); + auto errCode = store->UpdateDBStatus(); if (errCode != RDB_OK) { ZLOGE("Update failed errCode %{public}d", errCode); return false; -- Gitee From 9c5501a569937d098722edaa6ed0ba5b59a0e7cf Mon Sep 17 00:00:00 2001 From: Axi_Beft Date: Tue, 18 Mar 2025 15:59:34 +0800 Subject: [PATCH 077/225] object add service UT Signed-off-by: Axi_Beft --- .../service/test/object_manager_test.cpp | 86 ++++++++++++++++ .../service/test/object_service_impl_test.cpp | 22 ++++- .../service/test/value_proxy_test.cpp | 99 +++++++++++++++++++ 3 files changed, 203 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/service/test/object_manager_test.cpp b/services/distributeddataservice/service/test/object_manager_test.cpp index db1ed7c89..835dca5b6 100644 --- a/services/distributeddataservice/service/test/object_manager_test.cpp +++ b/services/distributeddataservice/service/test/object_manager_test.cpp @@ -978,5 +978,91 @@ HWTEST_F(ObjectManagerTest, OnFinished001, TestSize.Level1) ObjectAssetsRecvListener listener; int32_t ret = listener.OnFinished(srcNetworkId, assetObj, result); EXPECT_NE(ret, DistributedObject::OBJECT_SUCCESS); + + sptr assetObj_1 = new AssetObj(); + assetObj_1->dstBundleName_ = bundleName_; + assetObj_1->srcBundleName_ = bundleName_; + assetObj_1->dstNetworkId_ = "1"; + assetObj_1->sessionId_ = "123"; + ret = listener.OnFinished(srcNetworkId, assetObj_1, result); + EXPECT_EQ(ret, DistributedObject::OBJECT_SUCCESS); +} + +/** +* @tc.name: GetObjectData001 +* @tc.desc: GetObjectData test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, GetObjectData001, TestSize.Level1) +{ + auto manager = ObjectStoreManager::GetInstance(); + + std::string bundleName = bundleName_; + std::string sessionId = sessionId_; + std::string source = "sourceDeviceId"; + std::string target = "targetDeviceId"; + std::string timestamp = "1234567890"; + ObjectStoreManager::SaveInfo saveInfo(bundleName, sessionId, source, target, timestamp); + std::string prefix = saveInfo.ToPropertyPrefix(); + EXPECT_FALSE(prefix.empty()); + + // p_name not asset key + std::string p_name = "p_namejpg"; + std::string key = bundleName + "_" + sessionId + "_" + source + "_" + target + "_" + timestamp + "_" + p_name; + std::map> changedData = {{ key, data_ }}; + bool hasAsset = false; + auto ret = manager->GetObjectData(changedData, saveInfo, hasAsset); + EXPECT_FALSE(ret.empty()); + EXPECT_FALSE(hasAsset); +} + +/** +* @tc.name: GetObjectData002 +* @tc.desc: GetObjectData test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, GetObjectData002, TestSize.Level1) +{ + auto manager = ObjectStoreManager::GetInstance(); + + std::string bundleName = ""; + std::string sessionId = ""; + std::string source = ""; + std::string target = ""; + std::string timestamp = ""; + ObjectStoreManager::SaveInfo saveInfo(bundleName, sessionId, source, target, timestamp); + std::string prefix = saveInfo.ToPropertyPrefix(); + EXPECT_TRUE(prefix.empty()); + + // saveInfo.bundleName, sourceDeviceId, targetDeviceId empty + saveInfo.sessionId = sessionId_; + saveInfo.timestamp = "1234567890"; + + bundleName = bundleName_; + sessionId = sessionId_; + source = "sourceDeviceId"; + target = "targetDeviceId"; + timestamp = "1234567890"; + std::string p_name = "p_name.jpg"; + std::string key = bundleName + "_" + sessionId + "_" + source + "_" + target + "_" + timestamp + "_" + p_name; + std::map> changedData = {{ key, data_ }}; + bool hasAsset = false; + auto ret = manager->GetObjectData(changedData, saveInfo, hasAsset); + EXPECT_FALSE(ret.empty()); + EXPECT_EQ(saveInfo.bundleName, bundleName); + EXPECT_TRUE(hasAsset); + + // only targetDeviceId empty + saveInfo.bundleName = "test_bundleName"; + saveInfo.sourceDeviceId = "test_source"; + // p_name not asset key + p_name = "p_namejpg"; + std::string key_1 = bundleName + "_" + sessionId + "_" + source + "_" + target + "_" + timestamp + "_" + p_name; + std::map> changedData_1 = {{ key_1, data_ }}; + hasAsset = false; + ret = manager->GetObjectData(changedData_1, saveInfo, hasAsset); + EXPECT_FALSE(ret.empty()); + EXPECT_NE(saveInfo.bundleName, bundleName); + EXPECT_FALSE(hasAsset); } } // namespace OHOS::Test diff --git a/services/distributeddataservice/service/test/object_service_impl_test.cpp b/services/distributeddataservice/service/test/object_service_impl_test.cpp index 7497b04dd..e67f493ab 100644 --- a/services/distributeddataservice/service/test/object_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/object_service_impl_test.cpp @@ -94,8 +94,6 @@ HWTEST_F(ObjectServiceImplTest, OnAssetChanged001, TestSize.Level1) // bundleName not equal tokenId auto ret = objectServiceImpl->OnAssetChanged(bundleName_, sessionId_, deviceId_, asset_); EXPECT_EQ(ret, OBJECT_PERMISSION_DENIED); - ret = objectServiceImpl->OnAssetChanged(bundleName, sessionId_, deviceId_, asset_); - EXPECT_NE(ret, OBJECT_SUCCESS); } /** @@ -115,8 +113,6 @@ HWTEST_F(ObjectServiceImplTest, BindAssetStore001, TestSize.Level1) // bundleName not equal tokenId auto ret = objectServiceImpl->BindAssetStore(bundleName_, sessionId_, asset_, assetBindInfo_); EXPECT_EQ(ret, OBJECT_PERMISSION_DENIED); - ret = objectServiceImpl->BindAssetStore(bundleName, sessionId_, asset_, assetBindInfo_); - EXPECT_NE(ret, OBJECT_SUCCESS); } /** @@ -137,4 +133,22 @@ HWTEST_F(ObjectServiceImplTest, DeleteSnapshot001, TestSize.Level1) auto ret = objectServiceImpl->DeleteSnapshot(bundleName_, sessionId_); EXPECT_EQ(ret, OBJECT_PERMISSION_DENIED); } + +/** + * @tc.name: ResolveAutoLaunch001 + * @tc.desc: ResolveAutoLaunch test. + * @tc.type: FUNC + */ +HWTEST_F(ObjectServiceImplTest, ResolveAutoLaunch001, TestSize.Level1) +{ + DistributedDB::AutoLaunchParam param { + .userId = userId_, + .appId = appId_, + .storeId = "storeId", + }; + std::string identifier = "identifier"; + std::shared_ptr objectServiceImpl = std::make_shared(); + int32_t ret = objectServiceImpl->ResolveAutoLaunch(identifier, param); + EXPECT_EQ(ret, OBJECT_STORE_NOT_FOUND); +} } \ No newline at end of file diff --git a/services/distributeddataservice/service/test/value_proxy_test.cpp b/services/distributeddataservice/service/test/value_proxy_test.cpp index 8ada4d4c9..469d2230d 100644 --- a/services/distributeddataservice/service/test/value_proxy_test.cpp +++ b/services/distributeddataservice/service/test/value_proxy_test.cpp @@ -362,4 +362,103 @@ HWTEST_F(ValueProxyServiceTest, TempAssetConvertToDataStatus, TestSize.Level0) result = ValueProxy::TempAsset::ConvertToDataStatus(status); EXPECT_NE(result, DistributedData::Asset::STATUS_NORMAL); } + +/** +* @tc.name: AssetsOperator001 +* @tc.desc: AssetsOperator test. +* @tc.type: FUNC +*/ +HWTEST_F(ValueProxyServiceTest, AssetsOperator001, TestSize.Level0) +{ + ValueProxy::Assets proxy1; + ValueProxy::Assets proxy2; + ValueProxy::Assets proxy3; + proxy1.assets_.push_back(ValueProxy::Asset(DistributedDB::Asset { + .version = 1, + .status = DistributedData::Asset::Status::STATUS_INSERT, + .name = "Asset1", + .uri = "uri1", + .size = "1", + .hash = "hash1", + })); + proxy2.assets_.push_back(ValueProxy::Asset(DistributedDB::Asset { + .version = 2, + .status = DistributedData::Asset::Status::STATUS_NORMAL, + .name = "Asset2", + .uri = "uri2", + .size = "2", + .hash = "hash2", + })); + proxy2.assets_.push_back(ValueProxy::Asset(DistributedDB::Asset { + .version = 3, + .status = DistributedData::Asset::Status::STATUS_NORMAL, + .name = "Asset3", + .uri = "uri3", + .size = "3", + .hash = "hash3", + })); + // operator "=" same asset case + proxy3 = proxy1; + proxy1 = proxy3; + + // operator "=" different aseet case + proxy1 = proxy2; + EXPECT_EQ(proxy1.assets_.size(), 2); + + // operator Distributeddata Asset() + DistributedData::Asset asset = proxy1.assets_[0]; + EXPECT_EQ(asset.version, 2); + + // operator "=" noexcept same asset case + proxy2 = std::move(proxy1); + // operator "=" noexcept different asset case + proxy1 = std::move(proxy3); + EXPECT_EQ(proxy1.assets_.size(), 1); + asset = proxy1.assets_[0]; + EXPECT_EQ(asset.version, 1); +} + +/** +* @tc.name: AssetOperator001 +* @tc.desc: AssetOperator test. +* @tc.type: FUNC +*/ +HWTEST_F(ValueProxyServiceTest, AssetOperator001, TestSize.Level0) +{ + ValueProxy::Asset asset1 = DistributedDB::Asset { + .version = 1, + .status = DistributedData::Asset::Status::STATUS_INSERT, + .name = "Asset1", + .uri = "uri1", + .size = "1", + .hash = "hash1", + }; + ValueProxy::Asset asset2 = DistributedDB::Asset { + .version = 2, + .status = DistributedData::Asset::Status::STATUS_NORMAL, + .name = "Asset2", + .uri = "uri2", + .size = "2", + .hash = "hash2", + }; + ValueProxy::Asset asset3 = asset1; + DistributedData::Asset asset = asset3; + EXPECT_EQ(asset.version, 1); + + // operator "=" same asset case + asset1 = asset3; + EXPECT_EQ(asset.version, 1); + // operator "=" different aseet case + asset1 = asset2; + asset = asset1; + EXPECT_EQ(asset.version, 2); + + // operator "=" noexcept same asset case + asset2 = std::move(asset1); + EXPECT_EQ(asset.version, 2); + // operator "=" noexcept different asset case + asset1 = std::move(asset3); + asset = asset1; + EXPECT_EQ(asset.version, 1); +} } // namespace OHOS::Test \ No newline at end of file -- Gitee From 7fc07214d3ee0be9d8af614573d5f71abf15781b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E5=AD=90=E6=9D=8E?= Date: Mon, 17 Mar 2025 22:11:56 +0800 Subject: [PATCH 078/225] service MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 木子李 --- .../service/udmf/preprocess/data_handler.cpp | 20 ++++++++++++++++++- .../service/udmf/store/runtime_store.cpp | 5 +++-- .../service/udmf/udmf_service_impl.cpp | 2 +- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp index 94d6ad7f1..d772d9998 100644 --- a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp @@ -21,6 +21,7 @@ namespace OHOS::UDMF { constexpr const char *UD_KEY_SEPARATOR = "/"; constexpr const char *UD_KEY_ENTRY_SEPARATOR = "#"; +constexpr const char *UD_KEY_PROPERTIES_SEPARATOR = "#properties"; Status DataHandler::MarshalToEntries(const UnifiedData &unifiedData, std::vector &entries) { @@ -34,6 +35,16 @@ Status DataHandler::MarshalToEntries(const UnifiedData &unifiedData, std::vector std::vector udKeyBytes = { unifiedKey.begin(), unifiedKey.end() }; Entry entry = { udKeyBytes, runtimeBytes }; entries.emplace_back(entry); + std::string propsKey = unifiedData.GetRuntime()->key.GetPropertyKey() + UD_KEY_PROPERTIES_SEPARATOR; + std::vector propsBytes; + auto propsTlv = TLVObject(propsBytes); + if (!TLVUtil::Writing(*unifiedData.GetProperties(), propsTlv, TAG::TAG_PROPERTIES)) { + ZLOGE("Properties info marshalling failed:%{public}s", propsKey.c_str()); + return E_WRITE_PARCEL_ERROR; + } + std::vector propsKeyBytes = { propsKey.begin(), propsKey.end() }; + Entry propsEntry = { propsKeyBytes, propsBytes }; + entries.emplace_back(std::move(propsEntry)); return BuildEntries(unifiedData.GetRecords(), unifiedKey, entries); } @@ -75,7 +86,14 @@ Status DataHandler::UnmarshalEntryItem(UnifiedData &unifiedData, const std::vect continue; } auto isStartWithKey = keyStr.find(key) == 0; - if (!isStartWithKey) { + std::string propsKey = UnifiedKey(key).GetPropertyKey() + UD_KEY_PROPERTIES_SEPARATOR; + if (!isStartWithKey && (keyStr == propsKey)) { + std::shared_ptr properties; + if (!TLVUtil::ReadTlv(properties, data, TAG::TAG_PROPERTIES)) { + ZLOGE("Unmarshall unified properties failed."); + return E_READ_PARCEL_ERROR; + } + unifiedData.SetProperties(std::move(properties)); continue; } auto isEntryItem = keyStr.rfind(UD_KEY_ENTRY_SEPARATOR) != std::string::npos; diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index ae7fac872..942cfcb92 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -113,7 +113,7 @@ Status RuntimeStore::Get(const std::string &key, UnifiedData &unifiedData) { UpdateTime(); std::vector entries; - if (GetEntries(key, entries) != E_OK) { + if (GetEntries(UnifiedKey(key).GetPropertyKey(), entries) != E_OK) { ZLOGE("GetEntries failed, dataPrefix: %{public}s.", key.c_str()); return E_DB_ERROR; } @@ -371,7 +371,8 @@ Status RuntimeStore::GetBatchData(const std::string &dataPrefix, std::vector keySet; for (const auto &entry : entries) { std::string keyStr = {entry.key.begin(), entry.key.end()}; - if (std::count(keyStr.begin(), keyStr.end(), '/') == SLASH_COUNT_IN_KEY) { + if (std::count(keyStr.begin(), keyStr.end(), '/') == SLASH_COUNT_IN_KEY && + std::count(keyStr.begin(), keyStr.end(), '#') == 0) { keySet.emplace_back(keyStr); } } diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 2d0cdacbc..584be8814 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -700,7 +700,7 @@ int32_t UdmfServiceImpl::QueryDataCommon( UnifiedKey key(query.key); key.IsValid(); if (intention.empty()) { - dataPrefix = key.key; + dataPrefix = UnifiedKey(key.key).GetPropertyKey(); intention = key.intention; } ZLOGD("dataPrefix = %{public}s, intention: %{public}s.", dataPrefix.c_str(), intention.c_str()); -- Gitee From 37f497f78ba9e968b2a17adc4f5ea60b60aee9bc Mon Sep 17 00:00:00 2001 From: xuwenqi Date: Mon, 17 Mar 2025 20:48:00 +0800 Subject: [PATCH 079/225] =?UTF-8?q?=E6=B7=BB=E5=8A=A0data=20share=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E7=AB=AF=E6=B5=8B=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: xuwenqi Change-Id: I29d6b1cbc01fb9eb0012da2837d31a55b8bf6b77 --- .../service/test/BUILD.gn | 2 + .../service/test/data_share_common_test.cpp | 92 ++++++++++++++ .../test/data_share_service_impl_test.cpp | 43 +++---- .../service/test/kv_dalegate_test.cpp | 115 ++++++++++++++++++ 4 files changed, 229 insertions(+), 23 deletions(-) create mode 100644 services/distributeddataservice/service/test/data_share_common_test.cpp create mode 100644 services/distributeddataservice/service/test/kv_dalegate_test.cpp diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 3ad470925..3b0071df4 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -996,11 +996,13 @@ ohos_unittest("DataShareServiceImplTest") { "${data_service_path}/service/kvdb/user_delegate.cpp", "${data_service_path}/service/permission/src/permission_validator.cpp", "${data_service_path}/service/permission/src/permit_delegate.cpp", + "data_share_common_test.cpp", "data_share_obs_proxy_test.cpp", "data_share_profile_config_test.cpp", "data_share_service_impl_test.cpp", "data_share_service_stub_test.cpp", "data_share_subscriber_managers_test.cpp", + "kv_dalegate_test.cpp", ] configs = [ ":module_private_config" ] diff --git a/services/distributeddataservice/service/test/data_share_common_test.cpp b/services/distributeddataservice/service/test/data_share_common_test.cpp new file mode 100644 index 000000000..ad14f7d37 --- /dev/null +++ b/services/distributeddataservice/service/test/data_share_common_test.cpp @@ -0,0 +1,92 @@ +/* +* 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 "DataShareCommonTest" + +#include +#include +#include "data_share_profile_config.h" +#include "div_strategy.h" +#include "log_print.h" +#include "strategy.h" + +namespace OHOS::Test { +using namespace testing::ext; +using namespace OHOS::DataShare; +class DataShareCommonTest : public testing::Test { +public: + static constexpr int64_t USER_TEST = 100; + static void SetUpTestCase(void){}; + static void TearDownTestCase(void){}; + void SetUp(){}; + void TearDown(){}; +}; + +/** +* @tc.name: DivStrategy001 +* @tc.desc: test DivStrategy function when three parameters are all nullptr +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(DataShareCommonTest, DivStrategy001, TestSize.Level1) +{ + ZLOGI("DataShareCommonTest DivStrategy001 start"); + std::shared_ptr check = nullptr; + std::shared_ptr trueAction = nullptr; + std::shared_ptr falseAction = nullptr; + DivStrategy divStrategy(check, trueAction, falseAction); + auto context = std::make_shared(); + bool result = divStrategy.operator()(context); + EXPECT_EQ(result, false); + ZLOGI("DataShareCommonTest DivStrategy001 end"); +} + +/** +* @tc.name: DivStrategy002 +* @tc.desc: test DivStrategy function when trueAction and falseAction are nullptr +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(DataShareCommonTest, DivStrategy002, TestSize.Level1) +{ + ZLOGI("DataShareCommonTest DivStrategy002 start"); + std::shared_ptr check = std::make_shared(); + std::shared_ptr trueAction = nullptr; + std::shared_ptr falseAction = nullptr; + DivStrategy divStrategy(check, trueAction, falseAction); + auto context = std::make_shared(); + bool result = divStrategy.operator()(context); + EXPECT_EQ(result, false); + ZLOGI("DataShareCommonTest DivStrategy002 end"); +} + +/** +* @tc.name: DivStrategy003 +* @tc.desc: test DivStrategy function when only falseAction is nullptr +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(DataShareCommonTest, DivStrategy003, TestSize.Level1) +{ + ZLOGI("DataShareCommonTest DivStrategy003 start"); + std::shared_ptr check = std::make_shared(); + std::shared_ptr trueAction = std::make_shared(); + std::shared_ptr falseAction = nullptr; + DivStrategy divStrategy(check, trueAction, falseAction); + auto context = std::make_shared(); + bool result = divStrategy.operator()(context); + EXPECT_EQ(result, false); + ZLOGI("DataShareCommonTest DivStrategy003 end"); +} +} // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/data_share_service_impl_test.cpp b/services/distributeddataservice/service/test/data_share_service_impl_test.cpp index 9c9595bc0..58efb56e4 100644 --- a/services/distributeddataservice/service/test/data_share_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/data_share_service_impl_test.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2024 Huawei Device Co., Ltd. +* 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 @@ -38,6 +38,7 @@ std::string TBL_NAME0 = "name0"; std::string TBL_NAME1 = "name1"; std::string BUNDLE_NAME = "ohos.datasharetest.demo"; namespace OHOS::Test { +using OHOS::DataShare::LogLabel; class DataShareServiceImplTest : public testing::Test { public: static constexpr int64_t USER_TEST = 100; @@ -458,40 +459,36 @@ HWTEST_F(DataShareServiceImplTest, OnInitialize, TestSize.Level1) } /** -* @tc.name: NotifyObserver -* @tc.desc: test NotifyObserver no GetCallerBundleName scene +* @tc.name: GetCallerInfo001 +* @tc.desc: test GetCallerInfo function when succeeded in getting tokenID * @tc.type: FUNC * @tc.require:SQL */ -HWTEST_F(DataShareServiceImplTest, NotifyObserver, TestSize.Level1) +HWTEST_F(DataShareServiceImplTest, GetCallerInfo001, TestSize.Level1) { + ZLOGI("DataShareServiceImplTest GetCallerInfo001 start"); DataShareServiceImpl dataShareServiceImpl; - std::string uri = SLIENT_ACCESS_URI; - sptr remoteObj; - auto tokenId = AccessTokenKit::GetHapTokenID(USER_TEST, "ohos.datasharetest.demo", 0); - AccessTokenKit::DeleteToken(tokenId); - - auto result = dataShareServiceImpl.RegisterObserver(uri, remoteObj); - EXPECT_EQ(result, ERR_INVALID_VALUE); - dataShareServiceImpl.NotifyObserver(uri); - result = dataShareServiceImpl.UnregisterObserver(uri, remoteObj); - EXPECT_EQ(result, ERR_INVALID_VALUE); + int32_t appIndex = 1; + auto result = dataShareServiceImpl.GetCallerInfo(BUNDLE_NAME, appIndex); + EXPECT_EQ(result.first, true); + ZLOGI("DataShareServiceImplTest GetCallerInfo001 end"); } /** -* @tc.name: RegisterObserver -* @tc.desc: test RegisterObserver abnormal scene +* @tc.name: GetCallerInfo002 +* @tc.desc: test GetCallerInfo function when failed to get tokenID * @tc.type: FUNC * @tc.require:SQL */ -HWTEST_F(DataShareServiceImplTest, RegisterObserver, TestSize.Level1) +HWTEST_F(DataShareServiceImplTest, GetCallerInfo002, TestSize.Level1) { + ZLOGI("DataShareServiceImplTest GetCallerInfo002 start"); DataShareServiceImpl dataShareServiceImpl; - sptr remoteObj; - auto result = dataShareServiceImpl.RegisterObserver("", remoteObj); - EXPECT_EQ(result, ERR_INVALID_VALUE); - dataShareServiceImpl.NotifyObserver(""); - result = dataShareServiceImpl.UnregisterObserver("", remoteObj); - EXPECT_EQ(result, ERR_INVALID_VALUE); + int32_t appIndex = 1; + auto tokenId = AccessTokenKit::GetHapTokenID(USER_TEST, "ohos.datasharetest.demo", 0); + AccessTokenKit::DeleteToken(tokenId); + auto result = dataShareServiceImpl.GetCallerInfo(BUNDLE_NAME, appIndex); + EXPECT_EQ(result.first, false); + ZLOGI("DataShareServiceImplTest GetCallerInfo002 end"); } } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/kv_dalegate_test.cpp b/services/distributeddataservice/service/test/kv_dalegate_test.cpp new file mode 100644 index 000000000..2de190483 --- /dev/null +++ b/services/distributeddataservice/service/test/kv_dalegate_test.cpp @@ -0,0 +1,115 @@ +/* +* Copyright (c) 2024 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 "KvDelegateTest" + +#include +#include +#include "data_share_profile_config.h" +#include "executor_pool.h" +#include "grd_error.h" +#include "kv_delegate.h" +#include "log_print.h" + +namespace OHOS::Test { +using namespace testing::ext; +using namespace OHOS::DataShare; +class KvDelegateTest : public testing::Test { +public: + static constexpr int64_t USER_TEST = 100; + static void SetUpTestCase(void){}; + static void TearDownTestCase(void){}; + void SetUp(){}; + void TearDown(){}; +}; + +const char* g_backupFiles[] = { + "dataShare.db", + "dataShare.db.redo", + "dataShare.db.safe", + "dataShare.db.undo", +}; +const char* BACKUP_SUFFIX = ".backup"; +std::shared_ptr executors = std::make_shared(5, 3); + +/** +* @tc.name: RestoreIfNeedt001 +* @tc.desc: test RestoreIfNeed function when dbstatus is GRD_INVALID_FILE_FORMAT +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(KvDelegateTest, RestoreIfNeed001, TestSize.Level1) +{ + ZLOGI("KvDelegateTest RestoreIfNeed001 start"); + int32_t dbstatus = GRD_INVALID_FILE_FORMAT; + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + bool result = kvDelegate.RestoreIfNeed(dbstatus); + EXPECT_EQ(result, true); + ZLOGI("KvDelegateTest RestoreIfNeed001 end"); +} + +/** +* @tc.name: RestoreIfNeedt002 +* @tc.desc: test RestoreIfNeed function when dbstatus is GRD_REBUILD_DATABASE +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(KvDelegateTest, RestoreIfNeed002, TestSize.Level1) +{ + ZLOGI("KvDelegateTest RestoreIfNeed002 start"); + int32_t dbstatus = GRD_REBUILD_DATABASE; + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + bool result = kvDelegate.RestoreIfNeed(dbstatus); + EXPECT_EQ(result, true); + ZLOGI("KvDelegateTest RestoreIfNeed002 end"); +} + +/** +* @tc.name: RestoreIfNeedt003 +* @tc.desc: test RestoreIfNeed function when dbstatus is GRD_TIME_OUT +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(KvDelegateTest, RestoreIfNeed003, TestSize.Level1) +{ + ZLOGI("KvDelegateTest RestoreIfNeed003 start"); + int32_t dbstatus = GRD_TIME_OUT; + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + bool result = kvDelegate.RestoreIfNeed(dbstatus); + EXPECT_EQ(result, false); + ZLOGI("KvDelegateTest RestoreIfNeed003 end"); +} + +/** +* @tc.name: GetVersion001 +* @tc.desc: test GetVersion function when get version failed +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(KvDelegateTest, GetVersion001, TestSize.Level1) +{ + ZLOGI("KvDelegateTest GetVersion001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + std::string collectionname = "testname"; + std::string filter = "testfilter"; + int version = 0; + bool result = kvDelegate.GetVersion(collectionname, filter, version); + EXPECT_EQ(result, false); + ZLOGI("KvDelegateTest GetVersion001 end"); +} +} // namespace OHOS::Test \ No newline at end of file -- Gitee From b7e019746b3a577b3572acbd60c927421cb31889 Mon Sep 17 00:00:00 2001 From: xuwenqi Date: Mon, 24 Mar 2025 21:33:03 +0800 Subject: [PATCH 080/225] =?UTF-8?q?=E6=B7=BB=E5=8A=A0data=20share=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E7=AB=AF=E6=B5=8B=E8=AF=95=E7=94=A8=E4=BE=8B02?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xuwenqi Change-Id: I0a740f3341e14ed4f1a9e870b9e502e06071ca25 --- .../distributeddataservice/service/test/kv_dalegate_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/test/kv_dalegate_test.cpp b/services/distributeddataservice/service/test/kv_dalegate_test.cpp index 2de190483..26bba5c02 100644 --- a/services/distributeddataservice/service/test/kv_dalegate_test.cpp +++ b/services/distributeddataservice/service/test/kv_dalegate_test.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2024 Huawei Device Co., Ltd. +* 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 -- Gitee From e9679077a6deb256549ea6d9bc45c1d633e6f35b Mon Sep 17 00:00:00 2001 From: z30053452 Date: Tue, 25 Mar 2025 17:31:11 +0800 Subject: [PATCH 081/225] add water level Signed-off-by: z30053452 --- .../service/kvdb/kvdb_service_impl.cpp | 52 +++++++++---------- .../service/kvdb/kvdb_service_impl.h | 2 +- 2 files changed, 26 insertions(+), 28 deletions(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index f04980ccc..d7d19c917 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -245,17 +245,16 @@ Status KVDBServiceImpl::Sync(const AppId &appId, const StoreId &storeId, int32_t { StoreMetaData metaData = GetStoreMetaData(appId, storeId, subUser); MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData); - auto delay = GetSyncDelayTime(syncInfo.delay, storeId, metaData.user); - if (metaData.isAutoSync && syncInfo.seqId == std::numeric_limits::max()) { - DeviceMatrix::GetInstance().OnChanged(metaData); - StoreMetaDataLocal localMeta; - MetaDataManager::GetInstance().LoadMeta(metaData.GetKeyLocal(), localMeta, true); - if (!localMeta.HasPolicy(IMMEDIATE_SYNC_ON_CHANGE)) { - ZLOGW("appId:%{public}s storeId:%{public}s no IMMEDIATE_SYNC_ON_CHANGE ", appId.appId.c_str(), - Anonymous::Change(storeId.storeId).c_str()); - return Status::SUCCESS; + if (DeviceMatrix::GetInstance().IsStatics(metaData) || DeviceMatrix::GetInstance().IsDynamic(metaData)) { + if (!IsNeedSync(metaData, syncInfo.devices)) { + ZLOGW("no change, do not need sync, appId:%{public}s storeId:%{public}s", metaData.bundleName.c_str(), + Anonymous::Change(metaData.storeId).c_str()); + DBResult dbResult = { {syncInfo.devices[0], DBStatus::OK} }; + DoComplete(metaData, syncInfo, RefCount(), std::move(dbResult)); + return SUCCESS; } } + auto delay = GetSyncDelayTime(syncInfo.delay, storeId, metaData.user); syncInfo.syncId = ++syncId_; RADAR_REPORT(STANDARD_DEVICE_SYNC, ADD_SYNC_TASK, RADAR_SUCCESS, BIZ_STATE, START, SYNC_STORE_ID, Anonymous::Change(storeId.storeId), SYNC_APP_ID, appId.appId, CONCURRENT_ID, @@ -266,6 +265,23 @@ Status KVDBServiceImpl::Sync(const AppId &appId, const StoreId &storeId, int32_t std::bind(&KVDBServiceImpl::DoComplete, this, metaData, syncInfo, RefCount(), std::placeholders::_1)); } +bool KVDBServiceImpl::IsNeedSync(const StoreMetaData &metaData, std::vector &devices) +{ + auto uuids = ConvertDevices(devices); + if (uuids.empty()) { + ZLOGW("no device, appId:%{public}s, storeId:%{public}s", metaData.bundleName.c_str(), + Anonymous::Change(metaData.storeId).c_str()); + return false; + } + auto code = DeviceMatrix::GetInstance().GetCode(metaData); + auto [exist, mask] = DeviceMatrix::GetInstance().GetRemoteMask(uuids[0]); + auto [existLocal, localMask] = DeviceMatrix::GetInstance().GetMask(uuids[0]); + if ((mask & code) == code || (localMask & code) == code) { + return true; + } + return false; +} + Status KVDBServiceImpl::NotifyDataChange(const AppId &appId, const StoreId &storeId, uint64_t delay) { StoreMetaData meta = GetStoreMetaData(appId, storeId); @@ -857,24 +873,6 @@ int32_t KVDBServiceImpl::OnUserChange(uint32_t code, const std::string &user, co return SUCCESS; } -bool KVDBServiceImpl::IsRemoteChange(const StoreMetaData &metaData, const std::string &device) -{ - auto code = DeviceMatrix::GetInstance().GetCode(metaData); - if (code == DeviceMatrix::INVALID_MASK) { - return true; - } - auto [dynamic, statics] = DeviceMatrix::GetInstance().IsConsistent(device); - if (metaData.dataType == DataType::TYPE_STATICS && statics) { - return false; - } - if (metaData.dataType == DataType::TYPE_DYNAMICAL && dynamic) { - return false; - } - auto [exist, mask] = DeviceMatrix::GetInstance().GetRemoteMask( - device, static_cast(metaData.dataType)); - return (mask & code) == code; -} - void KVDBServiceImpl::AddOptions(const Options &options, StoreMetaData &metaData) { metaData.isAutoSync = options.autoSync; diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.h b/services/distributeddataservice/service/kvdb/kvdb_service_impl.h index 4604f8b56..df132cf20 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.h +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.h @@ -155,7 +155,7 @@ private: void RegisterHandler(); void DumpKvServiceInfo(int fd, std::map> ¶ms); void TryToSync(const StoreMetaData &metaData, bool force = false); - bool IsRemoteChange(const StoreMetaData &metaData, const std::string &device); + bool IsNeedSync(const StoreMetaData &metaData, std::vector &devices); bool IsOHOSType(const std::vector &ids); Status ConvertDbStatusNative(DBStatus status); bool CompareTripleIdentifier(const std::string &accountId, const std::string &identifier, -- Gitee From eb970d689321dda6b1ea39769a1667956eb1da40 Mon Sep 17 00:00:00 2001 From: z30053452 Date: Tue, 25 Mar 2025 20:20:49 +0800 Subject: [PATCH 082/225] code fix Signed-off-by: z30053452 --- .../service/test/kvdb_service_impl_test.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index 1d16a6562..ed12553a6 100644 --- a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp @@ -1074,16 +1074,16 @@ HWTEST_F(KvdbServiceImplTest, ResolveAutoLaunch, TestSize.Level0) } /** -* @tc.name: IsRemoteChange -* @tc.desc: IsRemoteChange function test. +* @tc.name: IsNeedSync +* @tc.desc: IsNeedSync function test. * @tc.type: FUNC * @tc.author: wangbin */ -HWTEST_F(KvdbServiceImplTest, IsRemoteChangeTest, TestSize.Level0) +HWTEST_F(KvdbServiceImplTest, IsNeedSyncTest, TestSize.Level0) { StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); - std::string devices= "IsRemoteChangeTest"; - auto changes = kvdbServiceImpl_->IsRemoteChange(meta, devices); + std::vector devices= {"IsNeedSyncTest"}; + auto changes = kvdbServiceImpl_->IsNeedSync(meta, devices); EXPECT_EQ(changes, true); } -- Gitee From 935a1e8336d3e825c72637b090129d7f6973c4d1 Mon Sep 17 00:00:00 2001 From: wenjinchao Date: Tue, 25 Mar 2025 20:40:31 +0800 Subject: [PATCH 083/225] fix file uri Signed-off-by: wenjinchao Change-Id: Ifaed7b25a68dcc997ebb0d436da72fc3c5b9f201 --- .../distributeddataservice/service/udmf/udmf_service_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 28bdac177..6804c1b9e 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -843,7 +843,7 @@ int32_t UdmfServiceImpl::OnUserChange(uint32_t code, const std::string &user, co void UdmfServiceImpl::TransferToEntriesIfNeed(const QueryOption &query, UnifiedData &unifiedData) { if (unifiedData.IsNeedTransferToEntries() && IsNeedTransferDeviceType(query)) { - unifiedData.TransferToEntries(unifiedData); + unifiedData.TransferToEntries(); } } -- Gitee From 2709bd6b4adc626d7e9b0966bf5da0d3ba75289f Mon Sep 17 00:00:00 2001 From: wanxiaoqing Date: Tue, 18 Mar 2025 09:19:00 +0800 Subject: [PATCH 084/225] add test case Signed-off-by: wanxiaoqing --- .../service/test/BUILD.gn | 80 ++++++++ .../test/udmf_preprocess_utils_mock_test.cpp | 78 ++++++++ .../test/udmf_preprocess_utils_test.cpp | 182 ++++++++++++++++++ .../service/test/udmf_run_time_store_test.cpp | 95 +++++++++ 4 files changed, 435 insertions(+) create mode 100644 services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp create mode 100644 services/distributeddataservice/service/test/udmf_preprocess_utils_test.cpp diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 121c04da4..76fa919ed 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -1312,6 +1312,84 @@ ohos_unittest("UdmfServiceStubMockTest") { ] } +ohos_unittest("UdmfPreProcessUtilsTest") { + module_out_path = module_output_path + sources = [ "udmf_preprocess_utils_test.cpp" ] + + include_dirs = [ + "${data_service_path}/service/udmf/permission", + "${data_service_path}/service/udmf/preprocess", + ] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + deps = [ + "${data_service_path}/service:distributeddatasvc", + "${data_service_path}/service/udmf:udmf_server", + ] + + external_deps = [ + "ability_runtime:uri_permission_mgr", + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "device_manager:devicemanagersdk", + "googletest:gtest_main", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "kv_store:distributeddata_inner", + "kv_store:distributeddb", + "relational_store:native_rdb", + "udmf:udmf_client", + ] +} + +ohos_unittest("UdmfPreProcessUtilsMockTest") { + module_out_path = module_output_path + sources = [ + "${data_service_path}/service/test/mock/access_token_mock.cpp", + "${data_service_path}/service/udmf/preprocess/preprocess_utils.cpp", + "udmf_preprocess_utils_mock_test.cpp", + ] + + include_dirs = [ + "${data_service_path}/service/udmf/preprocess", + "${data_service_path}/service/test/mock", + "${data_service_path}/service/udmf/store", + "${data_service_path}/framework/include/account", + "${data_service_path}/adapter/include/communicator", + ] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + deps = [ + "${data_service_path}/service:distributeddatasvc", + "mock:distributeddata_mock_static", + ] + + external_deps = [ + "ability_runtime:uri_permission_mgr", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "access_token:libtokenid_sdk", + "app_file_service:remote_file_share_native", + "c_utils:utils", + "device_manager:devicemanagersdk", + "googletest:gmock_main", + "googletest:gtest_main", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "udmf:udmf_client", + ] +} + ohos_unittest("UdmfCheckerManagerTest") { module_out_path = module_output_path sources = [ @@ -1738,6 +1816,8 @@ group("unittest") { if (datamgr_service_udmf) { deps += [ ":UdmfCheckerManagerTest", + ":UdmfPreProcessUtilsMockTest", + ":UdmfPreProcessUtilsTest", ":UdmfRunTimeStoreTest", ":UdmfServiceImplTest", ":UdmfServiceStubMockTest", diff --git a/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp b/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp new file mode 100644 index 000000000..ddebf513d --- /dev/null +++ b/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp @@ -0,0 +1,78 @@ +/* +* 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 "preprocess_utils.h" +#include "gtest/gtest.h" +#include "access_token_mock.h" + +namespace OHOS::UDMF { +using namespace testing; +using namespace std; +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; +class UdmfPreProcessUtilsMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() {} + void TearDown() {} + static inline shared_ptr accessTokenKitMock = nullptr; +}; + +void UdmfPreProcessUtilsMockTest::SetUpTestCase(void) +{ + accessTokenKitMock = make_shared(); + BAccessTokenKit::accessTokenkit = accessTokenKitMock; +} + +void UdmfPreProcessUtilsMockTest::TearDownTestCase(void) +{ + BAccessTokenKit::accessTokenkit = nullptr; + accessTokenKitMock = nullptr; +} + +/** +* @tc.name: GetHapUidByToken001 +* @tc.desc: Abnormal test of GetHapUidByToken, AccessTokenKit GetHapTokenInfo failed +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsMockTest, GetHapUidByToken001, TestSize.Level1) +{ + uint32_t tokenId = 0; + int userId = 0; + PreProcessUtils preProcessUtils; + EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillOnce(Return(RET_SUCCESS)); + int32_t ret = preProcessUtils.GetHapUidByToken(tokenId, userId); + EXPECT_EQ(ret, E_OK); +} + +/** +* @tc.name: GetInstIndex001 +* @tc.desc: Abnormal test of GetInstIndex, AccessTokenKit GetInstIndex failed +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsMockTest, GetInstIndex001, TestSize.Level1) +{ + uint32_t tokenId = 0; + int32_t instIndex = 0; + PreProcessUtils preProcessUtils; + EXPECT_CALL(*accessTokenKitMock, GetTokenTypeFlag(_)).WillOnce(Return(TOKEN_HAP)); + EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillOnce(Return(RET_SUCCESS)); + bool ret = preProcessUtils.GetInstIndex(tokenId, instIndex); + EXPECT_EQ(ret, true); +} +}; // namespace UDMF \ No newline at end of file diff --git a/services/distributeddataservice/service/test/udmf_preprocess_utils_test.cpp b/services/distributeddataservice/service/test/udmf_preprocess_utils_test.cpp new file mode 100644 index 000000000..38a85bdfa --- /dev/null +++ b/services/distributeddataservice/service/test/udmf_preprocess_utils_test.cpp @@ -0,0 +1,182 @@ +/* +* 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 "preprocess_utils.h" +#include "gtest/gtest.h" +#include "text.h" + +namespace OHOS::UDMF { +using namespace testing::ext; +class UdmfPreProcessUtilsTest : public testing::Test { +public: + static void SetUpTestCase(void) {} + static void TearDownTestCase(void) {} + void SetUp() {} + void TearDown() {} +}; + +/** +* @tc.name: RuntimeDataImputation001 +* @tc.desc: Abnormal test of RuntimeDataImputation, option is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, RuntimeDataImputation001, TestSize.Level1) +{ + UnifiedData data; + CustomOption option; + PreProcessUtils preProcessUtils; + int32_t ret = preProcessUtils.RuntimeDataImputation(data, option); + EXPECT_EQ(ret, E_ERROR); +} + +/** +* @tc.name: GetHapUidByToken001 +* @tc.desc: Abnormal test of GetHapUidByToken, tokenId is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, GetHapUidByToken001, TestSize.Level1) +{ + uint32_t tokenId = 0; + int userId = 0; + PreProcessUtils preProcessUtils; + int32_t ret = preProcessUtils.GetHapUidByToken(tokenId, userId); + EXPECT_EQ(ret, E_ERROR); +} + +/** +* @tc.name: SetRemoteData001 +* @tc.desc: Abnormal test of SetRemoteData, data is null +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, SetRemoteData001, TestSize.Level1) +{ + UnifiedData data; + PreProcessUtils preProcessUtils; + EXPECT_NO_FATAL_FAILURE(preProcessUtils.SetRemoteData(data)); +} + +/** +* @tc.name: SetRemoteData002 +* @tc.desc: Normal test of SetRemoteData +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, SetRemoteData002, TestSize.Level1) +{ + UnifiedData data; + std::vector> inputRecords; + for (int32_t i = 0; i < 512; ++i) { + inputRecords.emplace_back(std::make_shared()); + } + data.SetRecords(inputRecords); + data.runtime_ = std::make_shared(); + PreProcessUtils preProcessUtils; + EXPECT_NO_FATAL_FAILURE(preProcessUtils.SetRemoteData(data)); +} + +/** +* @tc.name: IsFileType001 +* @tc.desc: Abnormal test of IsFileType, record is nullptr +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, IsFileType001, TestSize.Level1) +{ + std::shared_ptr record = nullptr; + PreProcessUtils preProcessUtils; + bool ret = preProcessUtils.IsFileType(record); + EXPECT_EQ(ret, false); +} + +/** +* @tc.name: GetDfsUrisFromLocal001 +* @tc.desc: Abnormal test of GetDfsUrisFromLocal, uris is null +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, GetDfsUrisFromLocal001, TestSize.Level1) +{ + const std::vector uris; + int32_t userId = 0; + UnifiedData data; + PreProcessUtils preProcessUtils; + int32_t ret = preProcessUtils.GetDfsUrisFromLocal(uris, userId, data); + EXPECT_EQ(ret, E_FS_ERROR); +} + +/** +* @tc.name: CheckUriAuthorization001 +* @tc.desc: Abnormal test of CheckUriAuthorization, uris is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, CheckUriAuthorization001, TestSize.Level1) +{ + const std::vector uris = {"test"}; + uint32_t tokenId = 0; + PreProcessUtils preProcessUtils; + bool ret = preProcessUtils.CheckUriAuthorization(uris, tokenId); + EXPECT_EQ(ret, false); +} + +/** +* @tc.name: GetInstIndex001 +* @tc.desc: Normal test of GetInstIndex +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, GetInstIndex001, TestSize.Level1) +{ + uint32_t tokenId = 0; + int32_t instIndex = 0; + PreProcessUtils preProcessUtils; + bool ret = preProcessUtils.GetInstIndex(tokenId, instIndex); + EXPECT_EQ(instIndex, 0); + EXPECT_EQ(ret, true); +} + +/** +* @tc.name: ProcessFileType001 +* @tc.desc: Abnormal test of ProcessFileType, records is nullptr +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, ProcessFileType001, TestSize.Level1) +{ + std::vector> records = { nullptr }; + std::function)> callback; + PreProcessUtils preProcessUtils; + EXPECT_NO_FATAL_FAILURE(preProcessUtils.ProcessFileType(records, callback)); +} + +/** +* @tc.name: GetHtmlFileUris001 +* @tc.desc: Abnormal test of GetHtmlFileUris, uris is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, GetHtmlFileUris001, TestSize.Level1) +{ + uint32_t tokenId = 0; + UnifiedData data; + bool isLocal = false; + std::vector uris = {"test"}; + PreProcessUtils preProcessUtils; + EXPECT_NO_FATAL_FAILURE(preProcessUtils.GetHtmlFileUris(tokenId, data, isLocal, uris)); +} +}; // namespace UDMF \ No newline at end of file diff --git a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp index ec7fb210a..13c760a20 100644 --- a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp +++ b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp @@ -552,6 +552,101 @@ HWTEST_F(UdmfRunTimeStoreTest, GetDetailsFromUData01, TestSize.Level1) EXPECT_FALSE(status); } +/** +* @tc.name: Sync01 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Sync01, TestSize.Level1) +{ + std::vector devices = {"device"}; + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + Status ret = store->Sync(devices); + EXPECT_EQ(ret, E_DB_ERROR); +} + +/** +* @tc.name: Sync02 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Sync02, TestSize.Level1) +{ + std::vector devices = { }; + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + Status ret = store->Sync(devices); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: Sync03 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Sync03, TestSize.Level1) +{ + std::vector devices = { "device" }; + ProcessCallback callback; + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + Status ret = store->Sync(devices, callback); + EXPECT_EQ(ret, E_DB_ERROR); +} + +/** +* @tc.name: Sync04 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Sync04, TestSize.Level1) +{ + std::vector devices = { }; + ProcessCallback callback; + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + Status ret = store->Sync(devices, callback); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: Clear01 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Clear01, TestSize.Level1) +{ + static constexpr const char *DATA_PREFIX = "udmf://"; + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + Status ret = store->Clear(); + EXPECT_EQ(ret, store->Delete(DATA_PREFIX)); +} + +/** +* @tc.name: Close01 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Close01, TestSize.Level1) +{ + auto store = std::make_shared(STORE_ID); + EXPECT_NO_FATAL_FAILURE(store->Close()); +} + + /** * @tc.name: GetSummary * @tc.desc: check for legal parameters, delete entries error. -- Gitee From aca9f48e50efd7f45ae71e774da899fbccda1903 Mon Sep 17 00:00:00 2001 From: gecheng Date: Tue, 25 Mar 2025 20:23:47 +0800 Subject: [PATCH 085/225] =?UTF-8?q?=E5=91=8A=E8=AD=A6=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gecheng --- .../service/cloud/cloud_data_translate.cpp | 2 +- .../service/cloud/sync_manager.cpp | 39 +++++++++---------- .../service/cloud/sync_manager.h | 19 +++++---- 3 files changed, 29 insertions(+), 31 deletions(-) diff --git a/services/distributeddataservice/service/cloud/cloud_data_translate.cpp b/services/distributeddataservice/service/cloud/cloud_data_translate.cpp index 80762e387..b1e0983fe 100644 --- a/services/distributeddataservice/service/cloud/cloud_data_translate.cpp +++ b/services/distributeddataservice/service/cloud/cloud_data_translate.cpp @@ -50,7 +50,7 @@ std::vector RdbCloudDataTranslate::AssetsToBlob(const Assets &assets) auto magicU8 = reinterpret_cast(const_cast(&leMagic)); rawData.insert(rawData.end(), magicU8, magicU8 + sizeof(ASSETS_MAGIC)); rawData.insert(rawData.end(), reinterpret_cast(&num), reinterpret_cast(&num) + sizeof(num)); - for (auto &asset : assets) { + for (const auto &asset : assets) { auto data = AssetToBlob(asset); rawData.insert(rawData.end(), data.begin(), data.end()); } diff --git a/services/distributeddataservice/service/cloud/sync_manager.cpp b/services/distributeddataservice/service/cloud/sync_manager.cpp index 139179622..f57013052 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.cpp +++ b/services/distributeddataservice/service/cloud/sync_manager.cpp @@ -201,8 +201,8 @@ std::function SyncManager::GetLockChangeHandler() SyncManager::SyncManager() { - EventCenter::GetInstance().Subscribe(CloudEvent::LOCK_CLOUD_CONTAINER, GetLockChangeHandler()); - EventCenter::GetInstance().Subscribe(CloudEvent::UNLOCK_CLOUD_CONTAINER, GetLockChangeHandler()); + EventCenter::GetInstance().Subscribe(CloudEvent::LOCK_CLOUD_CONTAINER, SyncManager::GetLockChangeHandler()); + EventCenter::GetInstance().Subscribe(CloudEvent::UNLOCK_CLOUD_CONTAINER, SyncManager::GetLockChangeHandler()); EventCenter::GetInstance().Subscribe(CloudEvent::LOCAL_CHANGE, GetClientChangeHandler()); syncStrategy_ = std::make_shared(); auto metaName = Bootstrap::GetInstance().GetProcessLabel(); @@ -299,15 +299,15 @@ std::function SyncManager::GetPostEventTask(const std::vectorsecond, SyncStage::END, - E_ERROR }); + SyncManager::Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second, + SyncStage::END, E_ERROR }); continue; } for (const auto &database : schema.databases) { if (!info.Contains(database.name)) { UpdateFinishSyncInfo({ cloud.user, cloud.id, schema.bundleName, database.name }, syncId, E_ERROR); - Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second, SyncStage::END, - E_ERROR }); + SyncManager::Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second, + SyncStage::END, E_ERROR }); continue; } StoreInfo storeInfo = { 0, schema.bundleName, database.name, cloud.apps[schema.bundleName].instanceId, @@ -317,8 +317,8 @@ std::function SyncManager::GetPostEventTask(const std::vectorsecond, SyncStage::END, - status }); + SyncManager::Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second, + SyncStage::END, status }); info.SetError(status); continue; } @@ -353,7 +353,7 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount info.SetError(E_CLOUD_DISABLED); return; } - auto traceIds = GetPrepareTraceId(info, cloud); + auto traceIds = SyncManager::GetPrepareTraceId(info, cloud); BatchReport(info.user_, traceIds, SyncStage::PREPARE, E_OK); UpdateStartSyncInfo(cloudSyncInfos); auto code = IsValid(info, cloud); @@ -432,8 +432,7 @@ std::function SyncManager::GetSyncHandler(Retryer retryer) UpdateFinishSyncInfo({ storeInfo.user, GetAccountId(storeInfo.user), storeInfo.bundleName, storeInfo.storeName }, storeInfo.syncId, E_ERROR); if (status != GeneralError::E_NOT_SUPPORT) { - auto code = dbCode == 0 ? GenStore::CLOUD_ERR_OFFSET + status : dbCode; - ReportSyncEvent(evt, BizState::END, code); + ReportSyncEvent(evt, BizState::END, dbCode == 0 ? GenStore::CLOUD_ERR_OFFSET + status : dbCode); } } }; @@ -441,7 +440,7 @@ std::function SyncManager::GetSyncHandler(Retryer retryer) void SyncManager::ReportSyncEvent(const SyncEvent &evt, BizState bizState, int32_t code) { - SyncStage syncStage = SyncStage::START; + SyncStage syncStage; auto &storeInfo = evt.GetStoreInfo(); if (bizState == BizState::BEGIN) { syncStage = SyncStage::START; @@ -452,7 +451,7 @@ void SyncManager::ReportSyncEvent(const SyncEvent &evt, BizState bizState, int32 RadarReporter::Report({storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC, storeInfo.syncId, evt.GetTriggerMode(), code}, "GetSyncHandler", bizState); } - Report({evt.GetUser(), storeInfo.bundleName, evt.GetPrepareTraceId(), syncStage, code}); + SyncManager::Report({evt.GetUser(), storeInfo.bundleName, evt.GetPrepareTraceId(), syncStage, code}); } std::function SyncManager::GetClientChangeHandler() @@ -495,7 +494,7 @@ SyncManager::Retryer SyncManager::GetRetryer(int32_t times, const SyncInfo &sync RadarReporter::Report({ info.bundleName_.c_str(), CLOUD_SYNC, FINISH_SYNC, info.syncId_, info.triggerMode_, dbCode }, "GetRetryer", BizState::END); - Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, + SyncManager::Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode }); Report(FT_CALLBACK, info.bundleName_, static_cast(Fault::CSF_GS_CLOUD_SYNC), "code=" + std::to_string(code) + ",dbCode=" + std::to_string(static_cast(dbCode))); @@ -512,7 +511,7 @@ SyncManager::Retryer SyncManager::GetRetryer(int32_t times, const SyncInfo &sync RadarReporter::Report({ info.bundleName_.c_str(), CLOUD_SYNC, FINISH_SYNC, info.syncId_, info.triggerMode_, dbCode }, "GetRetryer", BizState::END); - Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, + SyncManager::Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode }); Report(FT_CALLBACK, info.bundleName_, static_cast(Fault::CSF_GS_CLOUD_SYNC), "code=" + std::to_string(code) + ",dbCode=" + std::to_string(static_cast(dbCode))); @@ -757,7 +756,7 @@ std::pair> SyncManager::QueryL if (lastSyncInfoMap.find(queryKey.storeId) != lastSyncInfoMap.end()) { continue; } - auto [status, syncInfo] = GetLastSyncInfoFromMeta(queryKey); + auto [status, syncInfo] = SyncManager::GetLastSyncInfoFromMeta(queryKey); if (status == SUCCESS) { lastSyncInfoMap.insert(std::make_pair(std::move(syncInfo.storeId), std::move(syncInfo))); } @@ -831,7 +830,7 @@ std::function SyncManager::GetCallback(const Gen RadarReporter::Report({ storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC, storeInfo.syncId, triggerMode, dbCode, result.begin()->second.changeCount }, "GetCallback", BizState::END); - Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, dbCode }); + SyncManager::Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, dbCode }); if (dbCode != 0) { Report(FT_CALLBACK, storeInfo.bundleName, static_cast(Fault::CSF_GS_CLOUD_SYNC), "callback failed, dbCode=" + std::to_string(dbCode)); @@ -886,7 +885,7 @@ void SyncManager::DoExceptionalCallback(const GenAsync &async, GenDetails &detai } QueryKey queryKey{ storeInfo.user, GetAccountId(storeInfo.user), storeInfo.bundleName, storeInfo.storeName }; UpdateFinishSyncInfo(queryKey, storeInfo.syncId, code); - Report({ storeInfo.user, storeInfo.bundleName, prepareTraceId, SyncStage::END, code }); + SyncManager::Report({ storeInfo.user, storeInfo.bundleName, prepareTraceId, SyncStage::END, code }); } bool SyncManager::InitDefaultUser(int32_t &user) @@ -920,7 +919,7 @@ std::function SyncManager::Retr RadarReporter::Report({ storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC, storeInfo.syncId, triggerMode, code, details.begin()->second.changeCount }, "RetryCallback", BizState::END); - Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, + SyncManager::Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode }); } } @@ -939,7 +938,7 @@ void SyncManager::BatchUpdateFinishState(const std::vector; using SyncStage = DistributedData::SyncStage; using ReportParam = DistributedData::ReportParam; - static std::pair GetStore(const StoreMetaData &meta, int32_t user, bool mustBind = true); class SyncInfo final { public: using Store = std::string; @@ -95,12 +94,13 @@ public: }; SyncManager(); ~SyncManager(); + static void Report(const ReportParam &reportParam); + static std::pair GetStore(const StoreMetaData &meta, int32_t user, bool mustBind = true); int32_t Bind(std::shared_ptr executor); int32_t DoCloudSync(SyncInfo syncInfo); int32_t StopCloudSync(int32_t user = 0); std::pair> QueryLastSyncInfo( const std::vector &queryKeys); - void Report(const ReportParam &reportParam); void OnScreenUnlocked(int32_t user); void CleanCompensateSync(int32_t userId); @@ -137,6 +137,13 @@ private: static std::vector GetSchemaMeta(const CloudInfo &cloud, const std::string &bundleName); static bool NeedGetCloudInfo(CloudInfo &cloud); static GeneralError IsValid(SyncInfo &info, CloudInfo &cloud); + static std::function GetLockChangeHandler(); + static TraceIds GetPrepareTraceId(const SyncInfo &info, const CloudInfo &cloud); + static void Report( + const std::string &faultType, const std::string &bundleName, int32_t errCode, const std::string &appendix); + static std::pair GetLastResults(std::map &infos); + static std::pair GetLastSyncInfoFromMeta(const QueryKey &queryKey); + static void SaveLastSyncInfo(const QueryKey &queryKey, CloudLastSyncInfo &&info); Task GetSyncTask(int32_t times, bool retry, RefCount ref, SyncInfo &&syncInfo); void UpdateSchema(const SyncInfo &syncInfo); std::function GetSyncHandler(Retryer retryer); @@ -155,20 +162,12 @@ private: bool InitDefaultUser(int32_t &user); std::function RetryCallback(const StoreInfo &storeInfo, Retryer retryer, int32_t triggerMode, const std::string &prepareTraceId, int32_t user); - static std::pair GetLastResults(std::map &infos); void BatchUpdateFinishState(const std::vector> &cloudSyncInfos, int32_t code); bool NeedSaveSyncInfo(const QueryKey &queryKey); - std::function GetLockChangeHandler(); void BatchReport(int32_t userId, const TraceIds &traceIds, SyncStage syncStage, int32_t errCode); - TraceIds GetPrepareTraceId(const SyncInfo &info, const CloudInfo &cloud); std::pair GetMetaData(const StoreInfo &storeInfo); void AddCompensateSync(const StoreMetaData &meta); - static void Report( - const std::string &faultType, const std::string &bundleName, int32_t errCode, const std::string &appendix); void ReportSyncEvent(const DistributedData::SyncEvent &evt, DistributedDataDfx::BizState bizState, int32_t code); - std::pair GetLastSyncInfoFromMeta(const QueryKey &queryKey); - static void SaveLastSyncInfo(const QueryKey &queryKey, CloudLastSyncInfo &&info); - static std::atomic genId_; std::shared_ptr executor_; ConcurrentMap actives_; -- Gitee From a711bc30ba07f359d709b89e2ea3aec967641a01 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Wed, 26 Mar 2025 02:19:06 +0000 Subject: [PATCH 086/225] update .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md. Signed-off-by: suoqilong --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 50 ++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index a76fddfde..ceef331b8 100755 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -7,4 +7,52 @@ * **FUZZ**:Pass/Fail/NA * **ACTS**:Pass/Fail/NA * **DCTS**:Pass/Fail/NA -* **DST**:Pass/Fail/NA \ No newline at end of file +* **DST**:Pass/Fail/NA +**稳定性排查:** + +| 自检项 | 自检结果 | +| ------------------------------------------------------------ | -------- | +| 禁止在锁内,向其他进程发送IPC | | +| 禁止将捕获**栈变量引用**的lambda函数**异步到其他线程执行** | | +| 禁止存储string的c_str()方法获取到的指针 | | + +**日志打印排查:** + +| 自检项 | 自检结果 | +| ------------------------------------------------------------ | -------- | +| 禁止打印内存地址,如:%p | | +| 禁止打印密钥、文件路径、数据库名称、udidhash、设备名称、账号id等敏感信息 | | +| 禁止不作匿名化直接打印udid/networkid/uuid/ip/mac等敏感信息 | | + +**安全编码自检:** + +| 自检项 | 自检结果 | +| -------------------------------------------------------------- | -------- | +| 【内存管理】内存申请前必须对内存大小进行合法性校验 | | +| 【内存管理】内存申请后必须判空,判断内存申请是否成功 | | +| 【内存管理】分配和释放内存的函数需要成对出现 | | +| 【内存管理】申请内存后异常退出前需要及时进行内存释放 | | +| 【内存管理】禁止使用realloc、alloca函数 | | +| 【内存管理】strdup使用需要注意内存释放 | | +| 【内存管理】正则表达式构造后需释放资源,regcomp/regexec与regfree必须成对使用 | | +| 【内存管理】realpath使用时如果resolved_path为NULL需要注意内存释放 | | +| 【外部输入校验】外部传入的路径要做规范化校验,对路径中的.、..、../等特殊字符严格校验 | | +| 【外部输入校验】按TLV格式解析时需校验解析长度值是否小于等于缓冲区实际值,并校验是否符合业务数据范围 | | +| 【外部输入校验】解析数据后拷贝时需校验源buffer实际缓冲区大小,避免越界读写 | | +| 【外部输入校验】使用外部输入作为循环变量时,需要校验循环变量上限是否合理,防止出现超大循环 | | +| 【外部输入校验】禁止直接使用使用外部输入作为数组下标,防止出现内存越界 | | +| 【敏感信息】堆、栈中保存密钥、口令(包括加密后的变量)变量使用完后必须显式覆盖或清空 | | +| 【加密算法】禁止使用私有加密算法或不安全加密算法 | | +| 【变量初始化】指针变量、表示资源描述符的变量、bool变量必须赋初值 | | +| 【指针】IPC流程中ReadCString、ReadRawData、readParcelable等结果必须判空; | | +| 【整数运算】整数之间运算时必须严格检查,确保不会出现溢出、反转、除0 | | +| 【整数运算】禁止对有符号整数进行位操作符运算 | | +| 【循环变量】循环次数如果受外部数据控制,需要检验其合法性 | | +| 【循环变量】循环变量和中止条件的数据类型定义保持一致 | | +| 【安全函数】安全函数必须检查返回值,并进行正确处理 | | +| 【安全函数】安全函数目标缓冲区大小入参与目标缓冲区实际大小必须一致 | | +| 【安全函数】禁止封装或者自定义安全函数 | | +| 【常见问题】修改单个函数时,如果涉及新增异常返回分支,必须排查是否需要释放锁、内存、fd等资源 | | +| 【常见问题】函数返回值需与函数签名相同,参数定义需在同一范畴(不能定义bool,返回int32_t),或同一枚举类型 | | +| 【常见问题】格式化打印类型需匹配,例如:int32_t %d; uint32_t %u; long %ld; unsigned long %lu; long long PRId64;
unsigned long long PRIu64; | | + -- Gitee From d2b5ea8b405ae08a5a1dd5eb517e74c5a82a9411 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Wed, 26 Mar 2025 02:21:34 +0000 Subject: [PATCH 087/225] update .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md. Signed-off-by: suoqilong --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index ceef331b8..434028b57 100755 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -8,6 +8,7 @@ * **ACTS**:Pass/Fail/NA * **DCTS**:Pass/Fail/NA * **DST**:Pass/Fail/NA + **稳定性排查:** | 自检项 | 自检结果 | -- Gitee From d3b9f1540d0bbf563068ece820866e43ea9326dc Mon Sep 17 00:00:00 2001 From: suoqilong Date: Wed, 26 Mar 2025 02:41:53 +0000 Subject: [PATCH 088/225] update .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md. Signed-off-by: suoqilong --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index 434028b57..affaa85ec 100755 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -13,9 +13,22 @@ | 自检项 | 自检结果 | | ------------------------------------------------------------ | -------- | -| 禁止在锁内,向其他进程发送IPC | | -| 禁止将捕获**栈变量引用**的lambda函数**异步到其他线程执行** | | +| 禁止在锁内向其他进程发送IPC | | +| 禁止将捕获栈变量引用的lambda函数异步到其他线程执行 | | +| 禁止传递this指针至其他模块或线程(特别是eventhandler任务) | 禁止存储string的c_str()方法获取到的指针 | | +|涉及跨进程调用的相关操作需要抛至主线程或加锁防止并发|| +|成员变量进行赋值或创建需要排查并发|| +|谨慎在未经拷贝的情况下使用外部传入的string、C字符串 +|map\vector\list\set等stl模板类使用时需要排查并发 +|谨慎考虑加锁范围,尽可能的小范围加锁 +|在IPC通信中谨慎使用同步通信方式 +|禁止将外部传入的裸指针在内部直接构造智能指针 +|禁止多个独立创建的智能指针管理同一地址 +|禁止在析构函数中抛异步任务 +|禁止js对象在非js线程(例如在IPC线程)创建、使用或销毁 +|禁止在对外接口中未经判空直接使用外部传入的指针 +|监听回调要确保,回调触发和取消注册并发时无生命周期问题 **日志打印排查:** @@ -56,4 +69,3 @@ | 【常见问题】修改单个函数时,如果涉及新增异常返回分支,必须排查是否需要释放锁、内存、fd等资源 | | | 【常见问题】函数返回值需与函数签名相同,参数定义需在同一范畴(不能定义bool,返回int32_t),或同一枚举类型 | | | 【常见问题】格式化打印类型需匹配,例如:int32_t %d; uint32_t %u; long %ld; unsigned long %lu; long long PRId64;
unsigned long long PRIu64; | | - -- Gitee From a132afd35a05606547c3566b36a731b11911344a Mon Sep 17 00:00:00 2001 From: suoqilong Date: Wed, 26 Mar 2025 02:59:36 +0000 Subject: [PATCH 089/225] update .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md. Signed-off-by: suoqilong --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index affaa85ec..7f647b075 100755 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -13,8 +13,8 @@ | 自检项 | 自检结果 | | ------------------------------------------------------------ | -------- | -| 禁止在锁内向其他进程发送IPC | | -| 禁止将捕获栈变量引用的lambda函数异步到其他线程执行 | | +| 禁止在锁内,向其他进程发送IPC | | +| 禁止将捕获**栈变量引用**的lambda函数**异步到其他线程执行** | | | 禁止传递this指针至其他模块或线程(特别是eventhandler任务) | 禁止存储string的c_str()方法获取到的指针 | | |涉及跨进程调用的相关操作需要抛至主线程或加锁防止并发|| @@ -29,6 +29,7 @@ |禁止js对象在非js线程(例如在IPC线程)创建、使用或销毁 |禁止在对外接口中未经判空直接使用外部传入的指针 |监听回调要确保,回调触发和取消注册并发时无生命周期问题 +|遍历容器进行删除或插入时注意迭代器失效问题 **日志打印排查:** @@ -37,6 +38,7 @@ | 禁止打印内存地址,如:%p | | | 禁止打印密钥、文件路径、数据库名称、udidhash、设备名称、账号id等敏感信息 | | | 禁止不作匿名化直接打印udid/networkid/uuid/ip/mac等敏感信息 | | +| 非必要不要在循环内打印日志,防止日志超限| | **安全编码自检:** @@ -44,7 +46,7 @@ | -------------------------------------------------------------- | -------- | | 【内存管理】内存申请前必须对内存大小进行合法性校验 | | | 【内存管理】内存申请后必须判空,判断内存申请是否成功 | | -| 【内存管理】分配和释放内存的函数需要成对出现 | | +| 【内存管理】分配和释放内存(or fd等资源)的函数需要成对出现 | | | 【内存管理】申请内存后异常退出前需要及时进行内存释放 | | | 【内存管理】禁止使用realloc、alloca函数 | | | 【内存管理】strdup使用需要注意内存释放 | | @@ -69,3 +71,4 @@ | 【常见问题】修改单个函数时,如果涉及新增异常返回分支,必须排查是否需要释放锁、内存、fd等资源 | | | 【常见问题】函数返回值需与函数签名相同,参数定义需在同一范畴(不能定义bool,返回int32_t),或同一枚举类型 | | | 【常见问题】格式化打印类型需匹配,例如:int32_t %d; uint32_t %u; long %ld; unsigned long %lu; long long PRId64;
unsigned long long PRIu64; | | + -- Gitee From 42b55ea803e769daf2ef99a07f91ad2e57eac387 Mon Sep 17 00:00:00 2001 From: Axi_Beft Date: Wed, 26 Mar 2025 11:05:21 +0800 Subject: [PATCH 090/225] object cppCheck fix Signed-off-by: Axi_Beft --- .../service/object/src/object_asset_machine.cpp | 8 ++++---- .../service/object/src/object_manager.cpp | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/services/distributeddataservice/service/object/src/object_asset_machine.cpp b/services/distributeddataservice/service/object/src/object_asset_machine.cpp index dcb034ad9..6d1d11fb7 100644 --- a/services/distributeddataservice/service/object/src/object_asset_machine.cpp +++ b/services/distributeddataservice/service/object/src/object_asset_machine.cpp @@ -57,12 +57,12 @@ static int32_t Recover(int32_t eventId, ChangedAssetInfo& changedAsset, Asset& a static int32_t UpdateStore(ChangedAssetInfo& changedAsset); -static AutoCache::Store GetStore(ChangedAssetInfo& changedAsset); +static AutoCache::Store GetStore(const ChangedAssetInfo& changedAsset); static VBuckets GetMigratedData(AutoCache::Store& store, AssetBindInfo& assetBindInfo, const Asset& newAsset); static void MergeAssetData(VBucket& record, const Asset& newAsset, const AssetBindInfo& assetBindInfo); static void MergeAsset(Asset& oldAsset, const Asset& newAsset); static std::string BuildSql(const AssetBindInfo& bindInfo, Values& args); -static BindEvent::BindEventInfo MakeBindInfo(ChangedAssetInfo& changedAsset); +static BindEvent::BindEventInfo MakeBindInfo(const ChangedAssetInfo& changedAsset); static const DFAAction AssetDFA[STATUS_BUTT][EVENT_BUTT] = { { @@ -287,7 +287,7 @@ static void MergeAsset(Asset& oldAsset, const Asset& newAsset) oldAsset.path = newAsset.path; } -static AutoCache::Store GetStore(ChangedAssetInfo& changedAsset) +static AutoCache::Store GetStore(const ChangedAssetInfo& changedAsset) { StoreMetaData meta; meta.storeId = changedAsset.bindInfo.storeName; @@ -347,7 +347,7 @@ static int32_t Recover(int32_t eventId, ChangedAssetInfo& changedAsset, Asset& a return E_OK; } -static BindEvent::BindEventInfo MakeBindInfo(ChangedAssetInfo& changedAsset) +static BindEvent::BindEventInfo MakeBindInfo(const ChangedAssetInfo& changedAsset) { BindEvent::BindEventInfo bindEventInfo; bindEventInfo.bundleName = changedAsset.storeInfo.bundleName; diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 3e3c554ff..63f90ce8c 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -847,7 +847,7 @@ int32_t ObjectStoreManager::SaveToStore(const std::string &appId, const std::str saveInfoEntry.value = std::vector(saveInfoValue.begin(), saveInfoValue.end()); std::vector entries; entries.emplace_back(saveInfoEntry); - for (auto &item : data) { + for (const auto &item : data) { DistributedDB::Entry entry; std::string key = GetPropertyPrefix(appId, sessionId, toDeviceId) + timestamp + SEPERATOR + item.first; entry.key = std::vector(key.begin(), key.end()); @@ -1110,7 +1110,7 @@ SequenceSyncManager::Result SequenceSyncManager::Process( return ERR_SID_NOT_EXIST; } std::map syncResults; - for (auto &item : results) { + for (const auto &item : results) { syncResults[item.first] = item.second == DistributedDB::DBStatus::OK ? 0 : -1; } seqIdCallbackRelations_[sequenceId](syncResults); -- Gitee From 1bd4dcc33fba4cd4354afadf9ddb9c4d72584773 Mon Sep 17 00:00:00 2001 From: archane Date: Wed, 26 Mar 2025 11:19:07 +0800 Subject: [PATCH 091/225] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E9=9D=99=E9=BB=98?= =?UTF-8?q?=E4=B8=ADext?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: archane Change-Id: I5f6af6c7fca50a063e54c6406f5e254403aa789d --- conf/config.json | 3 ++- .../service/config/include/config_factory.h | 1 + .../config/include/model/global_config.h | 1 + .../service/config/src/config_factory.cpp | 5 +++++ .../config/src/model/global_config.cpp | 2 ++ .../service/data_share/BUILD.gn | 1 + .../data_share/data_provider_config.cpp | 20 +++++++++++++++++++ .../service/data_share/data_provider_config.h | 1 + .../service/test/BUILD.gn | 1 + .../datashareservicestub_fuzzer/BUILD.gn | 2 ++ 10 files changed, 36 insertions(+), 1 deletion(-) diff --git a/conf/config.json b/conf/config.json index b1d053eb8..d03630732 100644 --- a/conf/config.json +++ b/conf/config.json @@ -86,5 +86,6 @@ "schedularInternal" : 1800, "backupInternal" : 36000, "backupNumber" : 20 - } + }, + "dataShareExtNames": [] } \ No newline at end of file diff --git a/services/distributeddataservice/service/config/include/config_factory.h b/services/distributeddataservice/service/config/include/config_factory.h index bce10b04a..b9cbebe7d 100644 --- a/services/distributeddataservice/service/config/include/config_factory.h +++ b/services/distributeddataservice/service/config/include/config_factory.h @@ -33,6 +33,7 @@ public: API_EXPORT CloudConfig *GetCloudConfig(); API_EXPORT std::vector *GetAppIdMappingConfig(); API_EXPORT ThreadConfig *GetThreadConfig(); + API_EXPORT std::vector GetDataShareExtNames(); private: static constexpr const char *CONF_PATH = "/system/etc/distributeddata/conf"; ConfigFactory(); diff --git a/services/distributeddataservice/service/config/include/model/global_config.h b/services/distributeddataservice/service/config/include/model/global_config.h index 91f5a237b..1b048b46e 100644 --- a/services/distributeddataservice/service/config/include/model/global_config.h +++ b/services/distributeddataservice/service/config/include/model/global_config.h @@ -40,6 +40,7 @@ public: CloudConfig *cloud = nullptr; std::vector *appIdMapping = nullptr; ThreadConfig *thread = nullptr; + std::vector dataShareExtNames; ~GlobalConfig(); bool Marshal(json &node) const override; bool Unmarshal(const json &node) override; diff --git a/services/distributeddataservice/service/config/src/config_factory.cpp b/services/distributeddataservice/service/config/src/config_factory.cpp index 3b05fce80..5936484a9 100644 --- a/services/distributeddataservice/service/config/src/config_factory.cpp +++ b/services/distributeddataservice/service/config/src/config_factory.cpp @@ -91,5 +91,10 @@ ThreadConfig *ConfigFactory::GetThreadConfig() { return config_.thread; } + +std::vector ConfigFactory::GetDataShareExtNames() +{ + return config_.dataShareExtNames; +} } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/global_config.cpp b/services/distributeddataservice/service/config/src/model/global_config.cpp index e64b01226..e5c4d2f67 100644 --- a/services/distributeddataservice/service/config/src/model/global_config.cpp +++ b/services/distributeddataservice/service/config/src/model/global_config.cpp @@ -30,6 +30,7 @@ bool GlobalConfig::Marshal(json &node) const SetValue(node[GET_NAME(cloud)], cloud); SetValue(node[GET_NAME(appIdMapping)], appIdMapping); SetValue(node[GET_NAME(thread)], thread); + SetValue(node[GET_NAME(dataShareExtNames)], dataShareExtNames); return true; } @@ -47,6 +48,7 @@ bool GlobalConfig::Unmarshal(const json &node) GetValue(node, GET_NAME(cloud), cloud); GetValue(node, GET_NAME(appIdMapping), appIdMapping); GetValue(node, GET_NAME(thread), thread); + GetValue(node, GET_NAME(dataShareExtNames), dataShareExtNames); return true; } diff --git a/services/distributeddataservice/service/data_share/BUILD.gn b/services/distributeddataservice/service/data_share/BUILD.gn index 2964c14db..3633536ec 100644 --- a/services/distributeddataservice/service/data_share/BUILD.gn +++ b/services/distributeddataservice/service/data_share/BUILD.gn @@ -28,6 +28,7 @@ config("module_public_config") { "${datashare_path}/interfaces/inner_api/common/include", "${datashare_path}/interfaces/inner_api/consumer/include", "${data_service_path}/adapter/include/communicator", + "${data_service_path}/service/config/include", "../common", "../crypto/include", "../permission/include", diff --git a/services/distributeddataservice/service/data_share/data_provider_config.cpp b/services/distributeddataservice/service/data_share/data_provider_config.cpp index e713b4acb..81eb0145f 100644 --- a/services/distributeddataservice/service/data_share/data_provider_config.cpp +++ b/services/distributeddataservice/service/data_share/data_provider_config.cpp @@ -20,10 +20,13 @@ #include "accesstoken_kit.h" #include "account/account_delegate.h" +#include "config_factory.h" #include "datashare_errno.h" #include "hap_token_info.h" +#include "ipc_skeleton.h" #include "log_print.h" #include "strategies/general/load_config_common_strategy.h" +#include "tokenid_kit.h" #include "uri_utils.h" #include "utils/anonymous.h" @@ -225,6 +228,17 @@ std::pair DataProviderConfig::GetProvider GetMetaDataFromUri(); return std::make_pair(ret, providerInfo_); } + if (ret != E_URI_NOT_EXIST) { + return std::make_pair(ret, providerInfo_); + } + auto fullTokenId = IPCSkeleton::GetCallingFullTokenID(); + Security::AccessToken::HapTokenInfo tokenInfo; + auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(IPCSkeleton::GetCallingTokenID(), tokenInfo); + if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId) + || (result == Security::AccessToken::RET_SUCCESS && !IsInExtList(tokenInfo.bundleName))) { + ZLOGE("The URI in the extension, is not allowed for silent access.! ret: %{public}d, bundleName: %{public}s," + "uri: %{public}s", ret, tokenInfo.bundleName.c_str(), providerInfo_.uri.c_str()); + } ret = GetFromExtension(); if (ret != E_OK) { ZLOGE("Get providerInfo failed! ret: %{public}d, uri: %{public}s", @@ -232,4 +246,10 @@ std::pair DataProviderConfig::GetProvider } return std::make_pair(ret, providerInfo_); } + +bool DataProviderConfig::IsInExtList(const std::string &bundleName) +{ + auto extNames = ConfigFactory::GetInstance().GetDataShareExtNames(); + return std::find(extNames.begin(), extNames.end(), bundleName) != extNames.end(); +} } // namespace OHOS::DataShare diff --git a/services/distributeddataservice/service/data_share/data_provider_config.h b/services/distributeddataservice/service/data_share/data_provider_config.h index 6b2770dfe..99099ce8a 100644 --- a/services/distributeddataservice/service/data_share/data_provider_config.h +++ b/services/distributeddataservice/service/data_share/data_provider_config.h @@ -63,6 +63,7 @@ private: int GetFromExtensionProperties(const ProfileInfo &profileInfo, const std::string &moduleName); void GetMetaDataFromUri(); std::pair GetBundleInfo(); + bool IsInExtList(const std::string &bundleName); enum class PATH_PARAM : int32_t { BUNDLE_NAME = 0, MODULE_NAME, diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index c4d836733..1a0d4a4d9 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -970,6 +970,7 @@ ohos_unittest("DataShareServiceImplTest") { module_out_path = module_output_path include_dirs = [ + "${data_service_path}/service/config/include", "${datashare_path}/frameworks/native/common/include", "${datashare_path}/interfaces/inner_api/common/include", "${datashare_path}/interfaces/inner_api/consumer/include", diff --git a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn index 67dd09415..a980b47de 100644 --- a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn @@ -24,6 +24,7 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "${data_service_path}/app/src", "${data_service_path}/framework/include", "${data_service_path}/service/common", + "${data_service_path}/service/config/include", "${data_service_path}/service/crypto/include", "${data_service_path}/service/data_share/common", "${data_service_path}/service/data_share/data", @@ -104,6 +105,7 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "${data_service_path}/adapter/account:distributeddata_account", "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", ] external_deps = [ -- Gitee From b5011ed7e579a13292293650afa54ad181ec793c Mon Sep 17 00:00:00 2001 From: Jeam_wang Date: Tue, 25 Mar 2025 20:03:22 +0800 Subject: [PATCH 092/225] =?UTF-8?q?=E6=B8=85=E7=90=86=E5=86=85=E5=AD=98?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jeam_wang --- .../distributeddataservice/service/cloud/sync_manager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/cloud/sync_manager.cpp b/services/distributeddataservice/service/cloud/sync_manager.cpp index 139179622..3aa151f0c 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.cpp +++ b/services/distributeddataservice/service/cloud/sync_manager.cpp @@ -723,7 +723,7 @@ std::pair SyncManager::GetLastResults(std::mapsecond.code != -1) { - return { SUCCESS, std::move(iter->second) }; + return { SUCCESS, iter->second }; } return { E_ERROR, {} }; } @@ -801,7 +801,7 @@ void SyncManager::UpdateFinishSyncInfo(const QueryKey &queryKey, uint64_t syncId iter->second.code = code; iter->second.syncStatus = SyncStatus::FINISHED; SaveLastSyncInfo(key, std::move(iter->second)); - iter = val.erase(iter); + return false; } else { iter++; } -- Gitee From 5939f63e7a13de8e0aa26b634230e3cca21d1a2c Mon Sep 17 00:00:00 2001 From: suoqilong Date: Wed, 26 Mar 2025 08:49:24 +0000 Subject: [PATCH 093/225] update .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md. Signed-off-by: suoqilong --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index 7f647b075..fed13f106 100755 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -17,7 +17,6 @@ | 禁止将捕获**栈变量引用**的lambda函数**异步到其他线程执行** | | | 禁止传递this指针至其他模块或线程(特别是eventhandler任务) | 禁止存储string的c_str()方法获取到的指针 | | -|涉及跨进程调用的相关操作需要抛至主线程或加锁防止并发|| |成员变量进行赋值或创建需要排查并发|| |谨慎在未经拷贝的情况下使用外部传入的string、C字符串 |map\vector\list\set等stl模板类使用时需要排查并发 @@ -71,4 +70,3 @@ | 【常见问题】修改单个函数时,如果涉及新增异常返回分支,必须排查是否需要释放锁、内存、fd等资源 | | | 【常见问题】函数返回值需与函数签名相同,参数定义需在同一范畴(不能定义bool,返回int32_t),或同一枚举类型 | | | 【常见问题】格式化打印类型需匹配,例如:int32_t %d; uint32_t %u; long %ld; unsigned long %lu; long long PRId64;
unsigned long long PRIu64; | | - -- Gitee From 6bea963675a6421267683796c0301a6e267b2002 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Thu, 27 Mar 2025 02:36:22 +0000 Subject: [PATCH 094/225] update .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md. Signed-off-by: suoqilong --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index fed13f106..eecc43c5e 100755 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -13,7 +13,7 @@ | 自检项 | 自检结果 | | ------------------------------------------------------------ | -------- | -| 禁止在锁内,向其他进程发送IPC | | +| 禁止在锁内向其他进程发送IPC(进程间通信) | | | 禁止将捕获**栈变量引用**的lambda函数**异步到其他线程执行** | | | 禁止传递this指针至其他模块或线程(特别是eventhandler任务) | 禁止存储string的c_str()方法获取到的指针 | | @@ -55,17 +55,17 @@ | 【外部输入校验】按TLV格式解析时需校验解析长度值是否小于等于缓冲区实际值,并校验是否符合业务数据范围 | | | 【外部输入校验】解析数据后拷贝时需校验源buffer实际缓冲区大小,避免越界读写 | | | 【外部输入校验】使用外部输入作为循环变量时,需要校验循环变量上限是否合理,防止出现超大循环 | | -| 【外部输入校验】禁止直接使用使用外部输入作为数组下标,防止出现内存越界 | | +| 【外部输入校验】禁止直接使用外部输入作为数组下标,防止出现内存越界 | | | 【敏感信息】堆、栈中保存密钥、口令(包括加密后的变量)变量使用完后必须显式覆盖或清空 | | | 【加密算法】禁止使用私有加密算法或不安全加密算法 | | | 【变量初始化】指针变量、表示资源描述符的变量、bool变量必须赋初值 | | -| 【指针】IPC流程中ReadCString、ReadRawData、readParcelable等结果必须判空; | | +| 【指针】IPC流程中ReadCString、ReadRawData、readParcelable等结果必须判空 | | | 【整数运算】整数之间运算时必须严格检查,确保不会出现溢出、反转、除0 | | | 【整数运算】禁止对有符号整数进行位操作符运算 | | | 【循环变量】循环次数如果受外部数据控制,需要检验其合法性 | | | 【循环变量】循环变量和中止条件的数据类型定义保持一致 | | | 【安全函数】安全函数必须检查返回值,并进行正确处理 | | -| 【安全函数】安全函数目标缓冲区大小入参与目标缓冲区实际大小必须一致 | | +| 【安全函数】安全函数目标缓冲区入参大小与目标缓冲区实际大小必须一致 | | | 【安全函数】禁止封装或者自定义安全函数 | | | 【常见问题】修改单个函数时,如果涉及新增异常返回分支,必须排查是否需要释放锁、内存、fd等资源 | | | 【常见问题】函数返回值需与函数签名相同,参数定义需在同一范畴(不能定义bool,返回int32_t),或同一枚举类型 | | -- Gitee From 0064479edfc6c0609ab627e043383f93b785ab15 Mon Sep 17 00:00:00 2001 From: z30053452 Date: Thu, 27 Mar 2025 10:42:52 +0800 Subject: [PATCH 095/225] code fix Signed-off-by: z30053452 --- .../service/kvdb/kvdb_service_impl.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index d7d19c917..d4ef62df1 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -245,14 +245,14 @@ Status KVDBServiceImpl::Sync(const AppId &appId, const StoreId &storeId, int32_t { StoreMetaData metaData = GetStoreMetaData(appId, storeId, subUser); MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData); - if (DeviceMatrix::GetInstance().IsStatics(metaData) || DeviceMatrix::GetInstance().IsDynamic(metaData)) { - if (!IsNeedSync(metaData, syncInfo.devices)) { - ZLOGW("no change, do not need sync, appId:%{public}s storeId:%{public}s", metaData.bundleName.c_str(), - Anonymous::Change(metaData.storeId).c_str()); - DBResult dbResult = { {syncInfo.devices[0], DBStatus::OK} }; - DoComplete(metaData, syncInfo, RefCount(), std::move(dbResult)); - return SUCCESS; - } + if ((DeviceMatrix::GetInstance().IsStatics(metaData) || DeviceMatrix::GetInstance().IsDynamic(metaData)) && + !IsNeedSync(metaData, syncInfo.devices)) + { + ZLOGW("no change, do not need sync, appId:%{public}s storeId:%{public}s", metaData.bundleName.c_str(), + Anonymous::Change(metaData.storeId).c_str()); + DBResult dbResult = { {syncInfo.devices[0], DBStatus::OK} }; + DoComplete(metaData, syncInfo, RefCount(), std::move(dbResult)); + return SUCCESS; } auto delay = GetSyncDelayTime(syncInfo.delay, storeId, metaData.user); syncInfo.syncId = ++syncId_; @@ -277,6 +277,8 @@ bool KVDBServiceImpl::IsNeedSync(const StoreMetaData &metaData, std::vector Date: Thu, 27 Mar 2025 11:47:35 +0800 Subject: [PATCH 096/225] code fix Signed-off-by: z30053452 --- .../distributeddataservice/service/kvdb/kvdb_service_impl.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index d4ef62df1..e195cbd18 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -246,8 +246,7 @@ Status KVDBServiceImpl::Sync(const AppId &appId, const StoreId &storeId, int32_t StoreMetaData metaData = GetStoreMetaData(appId, storeId, subUser); MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData); if ((DeviceMatrix::GetInstance().IsStatics(metaData) || DeviceMatrix::GetInstance().IsDynamic(metaData)) && - !IsNeedSync(metaData, syncInfo.devices)) - { + !IsNeedSync(metaData, syncInfo.devices)) { ZLOGW("no change, do not need sync, appId:%{public}s storeId:%{public}s", metaData.bundleName.c_str(), Anonymous::Change(metaData.storeId).c_str()); DBResult dbResult = { {syncInfo.devices[0], DBStatus::OK} }; -- Gitee From b729c71597ad3aaed9c48dfe7d8874d55b353983 Mon Sep 17 00:00:00 2001 From: Jeam_wang Date: Thu, 27 Mar 2025 11:50:44 +0800 Subject: [PATCH 097/225] =?UTF-8?q?=E6=B8=85=E7=90=86=E5=86=85=E5=AD=98?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jeam_wang --- services/distributeddataservice/service/cloud/sync_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/cloud/sync_manager.cpp b/services/distributeddataservice/service/cloud/sync_manager.cpp index 3aa151f0c..540bd37d4 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.cpp +++ b/services/distributeddataservice/service/cloud/sync_manager.cpp @@ -801,7 +801,7 @@ void SyncManager::UpdateFinishSyncInfo(const QueryKey &queryKey, uint64_t syncId iter->second.code = code; iter->second.syncStatus = SyncStatus::FINISHED; SaveLastSyncInfo(key, std::move(iter->second)); - return false; + iter = val.erase(iter); } else { iter++; } -- Gitee From 450400a574fe12d5c2bc4bc72e573011a51da662 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Thu, 27 Mar 2025 07:40:46 +0000 Subject: [PATCH 098/225] update .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md. Signed-off-by: suoqilong --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index eecc43c5e..f9521e327 100755 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -17,18 +17,18 @@ | 禁止将捕获**栈变量引用**的lambda函数**异步到其他线程执行** | | | 禁止传递this指针至其他模块或线程(特别是eventhandler任务) | 禁止存储string的c_str()方法获取到的指针 | | -|成员变量进行赋值或创建需要排查并发|| -|谨慎在未经拷贝的情况下使用外部传入的string、C字符串 -|map\vector\list\set等stl模板类使用时需要排查并发 -|谨慎考虑加锁范围,尽可能的小范围加锁 -|在IPC通信中谨慎使用同步通信方式 -|禁止将外部传入的裸指针在内部直接构造智能指针 -|禁止多个独立创建的智能指针管理同一地址 -|禁止在析构函数中抛异步任务 -|禁止js对象在非js线程(例如在IPC线程)创建、使用或销毁 -|禁止在对外接口中未经判空直接使用外部传入的指针 -|监听回调要确保,回调触发和取消注册并发时无生命周期问题 -|遍历容器进行删除或插入时注意迭代器失效问题 +|成员变量进行赋值或创建需要排查并发 | | +|谨慎在未经拷贝的情况下使用外部传入的string、C字符串 | | +|map\vector\list\set等stl模板类使用时需要排查并发 | | +|谨慎考虑加锁范围,尽可能的小范围加锁 | | +|在IPC通信中谨慎使用同步通信方式 | | +|禁止将外部传入的裸指针在内部直接构造智能指针 | | +|禁止多个独立创建的智能指针管理同一地址 | | +|禁止在析构函数中抛异步任务 | | +|禁止js对象在非js线程(例如在IPC线程)创建、使用或销毁 | | +|禁止在对外接口中未经判空直接使用外部传入的指针 | | +|监听回调要确保,回调触发和取消注册并发时无生命周期问题 | | +|遍历容器进行删除或插入时注意迭代器失效问题 | | **日志打印排查:** -- Gitee From bdf72632b99b7cf2b4d8c148226b35a2a82ffcbd Mon Sep 17 00:00:00 2001 From: z30053452 Date: Thu, 27 Mar 2025 16:12:01 +0800 Subject: [PATCH 099/225] code fix Signed-off-by: z30053452 --- .../service/test/kvdb_service_impl_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index ed12553a6..a59b778e2 100644 --- a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp @@ -1084,7 +1084,7 @@ HWTEST_F(KvdbServiceImplTest, IsNeedSyncTest, TestSize.Level0) StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); std::vector devices= {"IsNeedSyncTest"}; auto changes = kvdbServiceImpl_->IsNeedSync(meta, devices); - EXPECT_EQ(changes, true); + EXPECT_EQ(changes, false); } /** -- Gitee From 26cf2d69bc158115366f3b87ea364111d4af301d Mon Sep 17 00:00:00 2001 From: suoqilong Date: Thu, 27 Mar 2025 11:32:01 +0000 Subject: [PATCH 100/225] =?UTF-8?q?update=20=E5=AE=89=E5=85=A8=E7=BC=96?= =?UTF-8?q?=E7=A0=81=20checklist?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 109 ++++++++++++-------------- 1 file changed, 50 insertions(+), 59 deletions(-) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index f9521e327..648f36643 100755 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -9,64 +9,55 @@ * **DCTS**:Pass/Fail/NA * **DST**:Pass/Fail/NA -**稳定性排查:** +### 稳定性排查: +- [ ] 【规则】禁止在锁内向其他进程发送IPC(进程间通信); +- [ ] 【规则】禁止将捕获**栈变量引用**的lambda函数**异步到其他线程执行**; +- [ ] 【规则】禁止传递this指针至其他模块或线程(特别是eventhandler任务); +- [ ] 【规则】禁止存储string的c_str()方法获取到的指针; +- [ ] 【规则】成员变量进行赋值或创建需要排查并发; +- [ ] 【规则】谨慎在未经拷贝的情况下使用外部传入的string、C字符串; +- [ ] 【规则】map\vector\list\set等stl模板类使用时需要排查并发; +- [ ] 【规则】谨慎考虑加锁范围,尽可能的小范围加锁; +- [ ] 【规则】在IPC通信中谨慎使用同步通信方式; +- [ ] 【规则】禁止将外部传入的裸指针在内部直接构造智能指针; +- [ ] 【规则】禁止多个独立创建的智能指针管理同一地址; +- [ ] 【规则】禁止在析构函数中抛异步任务; +- [ ] 【规则】禁止js对象在非js线程(例如在IPC线程)创建、使用或销毁; +- [ ] 【规则】禁止在对外接口中未经判空直接使用外部传入的指针; +- [ ] 【规则】监听回调要确保,回调触发和取消注册并发时无生命周期问题; +- [ ] 【规则】遍历容器进行删除或插入时注意迭代器失效问题; -| 自检项 | 自检结果 | -| ------------------------------------------------------------ | -------- | -| 禁止在锁内向其他进程发送IPC(进程间通信) | | -| 禁止将捕获**栈变量引用**的lambda函数**异步到其他线程执行** | | -| 禁止传递this指针至其他模块或线程(特别是eventhandler任务) -| 禁止存储string的c_str()方法获取到的指针 | | -|成员变量进行赋值或创建需要排查并发 | | -|谨慎在未经拷贝的情况下使用外部传入的string、C字符串 | | -|map\vector\list\set等stl模板类使用时需要排查并发 | | -|谨慎考虑加锁范围,尽可能的小范围加锁 | | -|在IPC通信中谨慎使用同步通信方式 | | -|禁止将外部传入的裸指针在内部直接构造智能指针 | | -|禁止多个独立创建的智能指针管理同一地址 | | -|禁止在析构函数中抛异步任务 | | -|禁止js对象在非js线程(例如在IPC线程)创建、使用或销毁 | | -|禁止在对外接口中未经判空直接使用外部传入的指针 | | -|监听回调要确保,回调触发和取消注册并发时无生命周期问题 | | -|遍历容器进行删除或插入时注意迭代器失效问题 | | +### 日志打印排查: +- [ ] 【规则】禁止打印内存地址,如:%p; +- [ ] 【规则】禁止打印密钥、文件路径、数据库名称、udidhash、设备名称、账号id等敏感信息; +- [ ] 【规则】禁止不作匿名化直接打印udid/networkid/uuid/ip/mac等敏感信息; +- [ ] 【规则】非必要不要在循环内打印日志,防止日志超限; -**日志打印排查:** - -| 自检项 | 自检结果 | -| ------------------------------------------------------------ | -------- | -| 禁止打印内存地址,如:%p | | -| 禁止打印密钥、文件路径、数据库名称、udidhash、设备名称、账号id等敏感信息 | | -| 禁止不作匿名化直接打印udid/networkid/uuid/ip/mac等敏感信息 | | -| 非必要不要在循环内打印日志,防止日志超限| | - -**安全编码自检:** - -| 自检项 | 自检结果 | -| -------------------------------------------------------------- | -------- | -| 【内存管理】内存申请前必须对内存大小进行合法性校验 | | -| 【内存管理】内存申请后必须判空,判断内存申请是否成功 | | -| 【内存管理】分配和释放内存(or fd等资源)的函数需要成对出现 | | -| 【内存管理】申请内存后异常退出前需要及时进行内存释放 | | -| 【内存管理】禁止使用realloc、alloca函数 | | -| 【内存管理】strdup使用需要注意内存释放 | | -| 【内存管理】正则表达式构造后需释放资源,regcomp/regexec与regfree必须成对使用 | | -| 【内存管理】realpath使用时如果resolved_path为NULL需要注意内存释放 | | -| 【外部输入校验】外部传入的路径要做规范化校验,对路径中的.、..、../等特殊字符严格校验 | | -| 【外部输入校验】按TLV格式解析时需校验解析长度值是否小于等于缓冲区实际值,并校验是否符合业务数据范围 | | -| 【外部输入校验】解析数据后拷贝时需校验源buffer实际缓冲区大小,避免越界读写 | | -| 【外部输入校验】使用外部输入作为循环变量时,需要校验循环变量上限是否合理,防止出现超大循环 | | -| 【外部输入校验】禁止直接使用外部输入作为数组下标,防止出现内存越界 | | -| 【敏感信息】堆、栈中保存密钥、口令(包括加密后的变量)变量使用完后必须显式覆盖或清空 | | -| 【加密算法】禁止使用私有加密算法或不安全加密算法 | | -| 【变量初始化】指针变量、表示资源描述符的变量、bool变量必须赋初值 | | -| 【指针】IPC流程中ReadCString、ReadRawData、readParcelable等结果必须判空 | | -| 【整数运算】整数之间运算时必须严格检查,确保不会出现溢出、反转、除0 | | -| 【整数运算】禁止对有符号整数进行位操作符运算 | | -| 【循环变量】循环次数如果受外部数据控制,需要检验其合法性 | | -| 【循环变量】循环变量和中止条件的数据类型定义保持一致 | | -| 【安全函数】安全函数必须检查返回值,并进行正确处理 | | -| 【安全函数】安全函数目标缓冲区入参大小与目标缓冲区实际大小必须一致 | | -| 【安全函数】禁止封装或者自定义安全函数 | | -| 【常见问题】修改单个函数时,如果涉及新增异常返回分支,必须排查是否需要释放锁、内存、fd等资源 | | -| 【常见问题】函数返回值需与函数签名相同,参数定义需在同一范畴(不能定义bool,返回int32_t),或同一枚举类型 | | -| 【常见问题】格式化打印类型需匹配,例如:int32_t %d; uint32_t %u; long %ld; unsigned long %lu; long long PRId64;
unsigned long long PRIu64; | | +### 安全编码自检: +- [ ] 【内存管理】内存申请前必须对内存大小进行合法性校验; +- [ ] 【内存管理】内存申请后必须判空,判断内存申请是否成功; +- [ ] 【内存管理】分配和释放内存(or fd等资源)的函数需要成对出现; +- [ ] 【内存管理】申请内存后异常退出前需要及时进行内存释放; +- [ ] 【内存管理】禁止使用realloc、alloca函数; +- [ ] 【内存管理】strdup使用需要注意内存释放; +- [ ] 【内存管理】正则表达式构造后需释放资源,regcomp/regexec与regfree必须成对使用; +- [ ] 【内存管理】realpath使用时如果resolved_path为NULL需要注意内存释放; +- [ ] 【外部输入校验】外部传入的路径要做规范化校验,对路径中的.、..、../等特殊字符严格校验; +- [ ] 【外部输入校验】按TLV格式解析时需校验解析长度值是否小于等于缓冲区实际值,并校验是否符合业务数据范围; +- [ ] 【外部输入校验】解析数据后拷贝时需校验源buffer实际缓冲区大小,避免越界读写; +- [ ] 【外部输入校验】使用外部输入作为循环变量时,需要校验循环变量上限是否合理,防止出现超大循环; +- [ ] 【外部输入校验】禁止直接使用外部输入作为数组下标,防止出现内存越界; +- [ ] 【敏感信息】堆、栈中保存密钥、口令(包括加密后的变量)变量使用完后必须显式覆盖或清空; +- [ ] 【加密算法】禁止使用私有加密算法或不安全加密算法; +- [ ] 【变量初始化】指针变量、表示资源描述符的变量、bool变量必须赋初值; +- [ ] 【指针】IPC流程中ReadCString、ReadRawData、readParcelable等结果必须判空; +- [ ] 【整数运算】整数之间运算时必须严格检查,确保不会出现溢出、反转、除0; +- [ ] 【整数运算】禁止对有符号整数进行位操作符运算; +- [ ] 【循环变量】循环次数如果受外部数据控制,需要检验其合法性; +- [ ] 【循环变量】循环变量和中止条件的数据类型定义保持一致; +- [ ] 【安全函数】安全函数必须检查返回值,并进行正确处理; +- [ ] 【安全函数】安全函数目标缓冲区入参大小与目标缓冲区实际大小必须一致; +- [ ] 【安全函数】禁止封装或者自定义安全函数; +- [ ] 【常见问题】修改单个函数时,如果涉及新增异常返回分支,必须排查是否需要释放锁、内存、fd等资源; +- [ ] 【常见问题】函数返回值需与函数签名相同,参数定义需在同一范畴(不能定义bool,返回int32_t),或同一枚举类型; +- [ ] 【常见问题】格式化打印类型需匹配,例如:int32_t %d; uint32_t %u; long %ld; unsigned long %lu; long long PRId64;
unsigned long long PRIu64; -- Gitee From f95cee7b6f7f0197699fd23725497401c9163148 Mon Sep 17 00:00:00 2001 From: Jeam_wang Date: Thu, 27 Mar 2025 19:48:09 +0800 Subject: [PATCH 101/225] =?UTF-8?q?=E5=9C=A8=E7=BD=91=E7=BB=9C=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E4=B9=8B=E5=90=8E=E5=86=8D=E6=AC=A1=E8=A7=A6=E5=8F=91?= =?UTF-8?q?=E7=BD=91=E7=BB=9C=E7=9B=91=E5=90=AC=E6=B3=A8=E5=86=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jeam_wang --- .../distributeddataservice/app/src/kvstore_data_service.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index 8d732f7d0..aa42b9246 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -50,6 +50,7 @@ #include "mem_mgr_proxy.h" #include "metadata/appid_meta_data.h" #include "metadata/meta_data_manager.h" +#include "network/network_delegate.h" #include "permission_validator.h" #include "permit_delegate.h" #include "process_communicator_impl.h" @@ -319,6 +320,7 @@ void KvStoreDataService::OnStart() } AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); AddSystemAbilityListener(MEMORY_MANAGER_SA_ID); + AddSystemAbilityListener(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID); RegisterStoreInfo(); Handler handlerStoreInfo = std::bind(&KvStoreDataService::DumpStoreInfo, this, std::placeholders::_1, std::placeholders::_2); @@ -359,6 +361,8 @@ void KvStoreDataService::OnAddSystemAbility(int32_t systemAbilityId, const std:: } else if (systemAbilityId == MEMORY_MANAGER_SA_ID) { Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), 1, 1, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); + } else if (systemAbilityId == COMM_NET_CONN_MANAGER_SYS_ABILITY_ID) { + NetworkDelegate::GetInstance()->RegOnNetworkChange(); } return; } -- Gitee From eb4907889f336cb418d8cb736c03892a38e9e2b7 Mon Sep 17 00:00:00 2001 From: z30053452 Date: Thu, 27 Mar 2025 20:37:38 +0800 Subject: [PATCH 102/225] code fix Signed-off-by: z30053452 --- .../service/kvdb/kvdb_service_impl.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index e195cbd18..25a7d8b1c 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -245,6 +245,16 @@ Status KVDBServiceImpl::Sync(const AppId &appId, const StoreId &storeId, int32_t { StoreMetaData metaData = GetStoreMetaData(appId, storeId, subUser); MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData); + if (metaData.isAutoSync && syncInfo.seqId == std::numeric_limits::max()) { + DeviceMatrix::GetInstance().OnChanged(metaData); + StoreMetaDataLocal localMeta; + MetaDataManager::GetInstance().LoadMeta(metaData.GetKeyLocal(), localMeta, true); + if (!localMeta.HasPolicy(IMMEDIATE_SYNC_ON_CHANGE)) { + ZLOGW("appId:%{public}s storeId:%{public}s no IMMEDIATE_SYNC_ON_CHANGE ", appId.appId.c_str(), + Anonymous::Change(storeId.storeId).c_str()); + return Status::SUCCESS; + } + } if ((DeviceMatrix::GetInstance().IsStatics(metaData) || DeviceMatrix::GetInstance().IsDynamic(metaData)) && !IsNeedSync(metaData, syncInfo.devices)) { ZLOGW("no change, do not need sync, appId:%{public}s storeId:%{public}s", metaData.bundleName.c_str(), -- Gitee From bf2f139f8d63144039fa95558756811bfc5d3c76 Mon Sep 17 00:00:00 2001 From: z30053452 Date: Thu, 27 Mar 2025 20:44:00 +0800 Subject: [PATCH 103/225] code fix Signed-off-by: z30053452 --- .../distributeddataservice/service/kvdb/kvdb_service_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index 25a7d8b1c..1f6c2dd8d 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -251,7 +251,7 @@ Status KVDBServiceImpl::Sync(const AppId &appId, const StoreId &storeId, int32_t MetaDataManager::GetInstance().LoadMeta(metaData.GetKeyLocal(), localMeta, true); if (!localMeta.HasPolicy(IMMEDIATE_SYNC_ON_CHANGE)) { ZLOGW("appId:%{public}s storeId:%{public}s no IMMEDIATE_SYNC_ON_CHANGE ", appId.appId.c_str(), - Anonymous::Change(storeId.storeId).c_str()); + Anonymous::Change(storeId.storeId).c_str()); return Status::SUCCESS; } } -- Gitee From 1e27547dd2e53cee8183e694fa2442846fc6870a Mon Sep 17 00:00:00 2001 From: wenjinchao Date: Thu, 27 Mar 2025 22:29:16 +0800 Subject: [PATCH 104/225] fix Signed-off-by: wenjinchao Change-Id: Idf846ce0b342307a35ace6e57e8d8051f75e4d8f --- .../service/udmf/udmf_service_impl.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 6804c1b9e..ac715417a 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ +#include "dm_device_info.h" #define LOG_TAG "UdmfServiceImpl" #include "udmf_service_impl.h" @@ -43,6 +44,7 @@ namespace OHOS { namespace UDMF { using namespace Security::AccessToken; +using namespace OHOS::DistributedHardware; using FeatureSystem = DistributedData::FeatureSystem; using UdmfBehaviourMsg = OHOS::DistributedDataDfx::UdmfBehaviourMsg; using Reporter = OHOS::DistributedDataDfx::Reporter; @@ -849,6 +851,10 @@ void UdmfServiceImpl::TransferToEntriesIfNeed(const QueryOption &query, UnifiedD bool UdmfServiceImpl::IsNeedTransferDeviceType(const QueryOption &query) { + auto deviceInfo = DmAdapter::GetInstance().GetLocalDevice(); + if (deviceInfo.deviceType != DEVICE_TYPE_PC && deviceInfo.deviceType != DEVICE_TYPE_PAD) { + return false; + } auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgrProxy == nullptr) { ZLOGE("Failed to get system ability mgr."); -- Gitee From e04867a956ac4b7959fc3064ed28543317e3f4f2 Mon Sep 17 00:00:00 2001 From: wenjinchao Date: Thu, 27 Mar 2025 22:29:59 +0800 Subject: [PATCH 105/225] fix Signed-off-by: wenjinchao Change-Id: Ib3dd935cc9a94f559429488668d6e608b25d854a --- .../distributeddataservice/service/udmf/udmf_service_impl.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index ac715417a..555411604 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ -#include "dm_device_info.h" #define LOG_TAG "UdmfServiceImpl" #include "udmf_service_impl.h" -- Gitee From 7eb6f7652f4f3f00052210cf5004ec408296f13b Mon Sep 17 00:00:00 2001 From: wenjinchao Date: Fri, 28 Mar 2025 14:20:19 +0800 Subject: [PATCH 106/225] fix Signed-off-by: wenjinchao Change-Id: I96d6a338b77b1dedfa156808d5b0be4882609f17 --- .../distributeddataservice/service/udmf/udmf_service_impl.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 555411604..2b7daf788 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ +#include "dm_device_info.h" #define LOG_TAG "UdmfServiceImpl" #include "udmf_service_impl.h" @@ -851,7 +852,8 @@ void UdmfServiceImpl::TransferToEntriesIfNeed(const QueryOption &query, UnifiedD bool UdmfServiceImpl::IsNeedTransferDeviceType(const QueryOption &query) { auto deviceInfo = DmAdapter::GetInstance().GetLocalDevice(); - if (deviceInfo.deviceType != DEVICE_TYPE_PC && deviceInfo.deviceType != DEVICE_TYPE_PAD) { + if (deviceInfo.deviceType != DEVICE_TYPE_PC && deviceInfo.deviceType != DEVICE_TYPE_PAD + && deviceInfo.deviceType != DEVICE_TYPE_2IN1) { return false; } auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); -- Gitee From 4a7e4ee7f47bdd19c3fa5e5a5b2e605f599d352e Mon Sep 17 00:00:00 2001 From: wenjinchao Date: Fri, 28 Mar 2025 14:38:32 +0800 Subject: [PATCH 107/225] fix Signed-off-by: wenjinchao Change-Id: I9a81e266c3806a177c96a11506a6a2155e8b0a90 --- .../distributeddataservice/service/udmf/udmf_service_impl.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 2b7daf788..408c19a00 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ -#include "dm_device_info.h" #define LOG_TAG "UdmfServiceImpl" #include "udmf_service_impl.h" @@ -845,7 +844,7 @@ int32_t UdmfServiceImpl::OnUserChange(uint32_t code, const std::string &user, co void UdmfServiceImpl::TransferToEntriesIfNeed(const QueryOption &query, UnifiedData &unifiedData) { if (unifiedData.IsNeedTransferToEntries() && IsNeedTransferDeviceType(query)) { - unifiedData.TransferToEntries(); + unifiedData.ConvertRecordsToEntries(); } } -- Gitee From 5e477af0b8dd48fa755cd48880caa880d45b0000 Mon Sep 17 00:00:00 2001 From: z30053452 Date: Fri, 28 Mar 2025 16:13:24 +0800 Subject: [PATCH 108/225] code fix Signed-off-by: z30053452 --- .../distributeddataservice/service/kvdb/kvdb_service_impl.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index 1f6c2dd8d..eb1c1e63e 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -286,8 +286,7 @@ bool KVDBServiceImpl::IsNeedSync(const StoreMetaData &metaData, std::vector Date: Thu, 27 Mar 2025 17:58:14 +0800 Subject: [PATCH 109/225] =?UTF-8?q?=E9=87=8D=E6=96=B0=E5=BC=80=E5=BA=93?= =?UTF-8?q?=E8=AE=BE=E7=BD=AEenableCloud?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gecheng --- .../service/rdb/rdb_service_impl.cpp | 24 +++++++++++++------ .../service/rdb/rdb_service_impl.h | 2 ++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 61bff0d76..c4123e299 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -823,6 +823,7 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) auto meta = GetStoreMetaData(param); StoreMetaData old; auto isCreated = MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), old, true); + meta.enableCloud = isCreated ? old.enableCloud : meta.enableCloud; if (!isCreated || meta != old) { Upgrade(param, old); ZLOGI("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " @@ -845,15 +846,10 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) SavePromiseInfo(meta, param); SaveDfxInfo(meta, param); - AppIDMetaData appIdMeta; - appIdMeta.bundleName = meta.bundleName; - appIdMeta.appId = meta.appId; - if (!MetaDataManager::GetInstance().SaveMeta(appIdMeta.GetKey(), appIdMeta, true)) { - ZLOGE("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " - "area:%{public}d->%{public}d", meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), old.storeType, - meta.storeType, old.isEncrypt, meta.isEncrypt, old.area, meta.area); + if (!SaveAppIDMeta(meta, old)) { return RDB_ERROR; } + if (param.isEncrypt_ && !param.password_.empty()) { if (SetSecretKey(param, meta) != RDB_OK) { ZLOGE("Set secret key failed, bundle:%{public}s store:%{public}s", @@ -866,6 +862,20 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) return RDB_OK; } +bool RdbServiceImpl::SaveAppIDMeta(const StoreMetaData &meta, const StoreMetaData &old) +{ + AppIDMetaData appIdMeta; + appIdMeta.bundleName = meta.bundleName; + appIdMeta.appId = meta.appId; + if (!MetaDataManager::GetInstance().SaveMeta(appIdMeta.GetKey(), appIdMeta, true)) { + ZLOGE("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " + "area:%{public}d->%{public}d", meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), old.storeType, + meta.storeType, old.isEncrypt, meta.isEncrypt, old.area, meta.area); + return false; + } + return true; +} + int32_t RdbServiceImpl::ReportStatistic(const RdbSyncerParam& param, const RdbStatEvent &statEvent) { if (!CheckAccess(param.bundleName_, param.storeName_)) { diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.h b/services/distributeddataservice/service/rdb/rdb_service_impl.h index b876a2f40..da3d154cf 100755 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -215,6 +215,8 @@ private: static std::string GetSubUser(const int32_t subUser); static bool GetDBPassword(const StoreMetaData &metaData, DistributedDB::CipherPassword &password); + + static bool SaveAppIDMeta(const StoreMetaData &meta, const StoreMetaData &old); void GetSchema(const RdbSyncerParam ¶m); -- Gitee From 7b10d15a335d213090cbccc3749a17626a71a392 Mon Sep 17 00:00:00 2001 From: z30053452 Date: Sat, 29 Mar 2025 14:34:03 +0800 Subject: [PATCH 110/225] code fix Signed-off-by: z30053452 --- .../distributeddataservice/service/kvdb/kvdb_service_impl.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index eb1c1e63e..cd1b6b7ce 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -283,10 +283,12 @@ bool KVDBServiceImpl::IsNeedSync(const StoreMetaData &metaData, std::vector Date: Sat, 29 Mar 2025 16:55:59 +0800 Subject: [PATCH 111/225] code fix Signed-off-by: z30053452 --- .../distributeddataservice/service/kvdb/kvdb_service_impl.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index cd1b6b7ce..9bd6e680f 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -283,7 +283,6 @@ bool KVDBServiceImpl::IsNeedSync(const StoreMetaData &metaData, std::vector Date: Sat, 29 Mar 2025 17:24:29 +0800 Subject: [PATCH 112/225] code fix Signed-off-by: z30053452 --- .../distributeddataservice/service/kvdb/kvdb_service_impl.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index 9bd6e680f..d7120edbf 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -286,8 +286,7 @@ bool KVDBServiceImpl::IsNeedSync(const StoreMetaData &metaData, std::vector Date: Sat, 29 Mar 2025 18:29:46 +0800 Subject: [PATCH 113/225] code fix Signed-off-by: z30053452 --- .../service/kvdb/kvdb_service_impl.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index d7120edbf..fae485880 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -259,6 +259,9 @@ Status KVDBServiceImpl::Sync(const AppId &appId, const StoreId &storeId, int32_t !IsNeedSync(metaData, syncInfo.devices)) { ZLOGW("no change, do not need sync, appId:%{public}s storeId:%{public}s", metaData.bundleName.c_str(), Anonymous::Change(metaData.storeId).c_str()); + if (syncInfo.devices.empty()) { + return DEVICE_NOT_ONLINE; + } DBResult dbResult = { {syncInfo.devices[0], DBStatus::OK} }; DoComplete(metaData, syncInfo, RefCount(), std::move(dbResult)); return SUCCESS; @@ -286,7 +289,7 @@ bool KVDBServiceImpl::IsNeedSync(const StoreMetaData &metaData, std::vector Date: Sat, 29 Mar 2025 18:34:23 +0800 Subject: [PATCH 114/225] code fix Signed-off-by: z30053452 --- .../distributeddataservice/service/kvdb/kvdb_service_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index fae485880..859f9eb30 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -289,7 +289,7 @@ bool KVDBServiceImpl::IsNeedSync(const StoreMetaData &metaData, std::vector Date: Wed, 26 Mar 2025 17:55:02 +0800 Subject: [PATCH 115/225] add tesecase Signed-off-by: ZhaoJinghui Change-Id: I168b246d825f3bc63ff17fc1e9d9df2834ce6434 --- .../service/rdb/rdb_schema_config.cpp | 3 +- .../service/test/BUILD.gn | 65 ++++ .../service/test/rdb_service_impl_test.cpp | 281 ++++++++++++++++++ 3 files changed, 347 insertions(+), 2 deletions(-) create mode 100644 services/distributeddataservice/service/test/rdb_service_impl_test.cpp diff --git a/services/distributeddataservice/service/rdb/rdb_schema_config.cpp b/services/distributeddataservice/service/rdb/rdb_schema_config.cpp index 205a39db2..cf84b43fb 100644 --- a/services/distributeddataservice/service/rdb/rdb_schema_config.cpp +++ b/services/distributeddataservice/service/rdb/rdb_schema_config.cpp @@ -39,7 +39,6 @@ bool RdbSchemaConfig::GetDistributedSchema(const StoreMetaData &meta, Database & if (!InitBundleInfo(meta.bundleName, std::atoi(meta.user.c_str()), bundleInfo)) { return false; } - std::string storeName = meta.storeId; auto ret = GetSchemaFromHap(bundleInfo, meta.storeId, database); if (ret) { database.user = meta.user; @@ -99,7 +98,7 @@ bool RdbSchemaConfig::GetSchemaFromHap( std::string jsonData(fileContent.get(), fileContent.get() + length); DbSchema databases; databases.Unmarshall(jsonData); - for (auto &schema : databases.databases) { + for (const auto &schema : databases.databases) { if (schema.name == storeName) { database = schema; return true; diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 1a0d4a4d9..4cf45945b 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -649,6 +649,70 @@ ohos_unittest("RdbServiceTest") { ] } +ohos_unittest("RdbServiceImplTest") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + module_out_path = module_output_path + sources = [ + "mock/db_change_data_mock.cpp", + "mock/db_store_mock.cpp", + "rdb_service_impl_test.cpp", + ] + + include_dirs = [ + "${data_service_path}/adapter/include/communicator", + "${data_service_path}/service/test/mock", + ] + + defines = [ + "TEST_ON_DEVICE", + "OPENSSL_SUPPRESS_DEPRECATED", + ] + cflags = [ + "-Werror", + "-Dprivate=public", + "-Dprotected=public", + "-Wno-multichar", + "-Wno-c99-designator", + "-fno-access-control", # Ignore Private Member Access Control + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "data_share:datashare_common", + "data_share:datashare_consumer", + "device_manager:devicemanagersdk", + "dsoftbus:softbus_client", + "hicollie:libhicollie", + "hilog:libhilog", + "hisysevent:libhisysevent", + "huks:libhukssdk", + "ipc:ipc_core", + "kv_store:datamgr_common", + "kv_store:distributeddata_inner", + "kv_store:distributeddb", + "relational_store:native_rdb", + "resource_management:global_resmgr", + ] + + deps = [ + "${data_service_path}/adapter/utils:distributeddata_utils", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", + "${data_service_path}/service/rdb:distributeddata_rdb", + ] +} + ohos_unittest("ObjectAssetLoaderTest") { module_out_path = module_output_path sources = [ @@ -1922,6 +1986,7 @@ group("unittest") { if (datamgr_service_rdb) { deps += [ ":RdbResultSetImplTest", + ":RdbServiceImplTest", ":RdbServiceTest", ] } diff --git a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp new file mode 100644 index 000000000..a60ab06c9 --- /dev/null +++ b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp @@ -0,0 +1,281 @@ +/* + * 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 "account/account_delegate.h" +#include "device_manager_adapter.h" +#include "device_matrix.h" +#include "ipc_skeleton.h" +#include "metadata/meta_data_manager.h" +#include "metadata/store_meta_data.h" +#include "mock/db_store_mock.h" +#include "rdb_service_impl.h" +#include "relational_store_manager.h" +#include "gtest/gtest.h" + +using namespace OHOS::DistributedRdb; +using namespace OHOS::DistributedData; +using namespace DistributedDB; +using namespace testing::ext; +using namespace testing; +using namespace std; +using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; + +namespace OHOS::Test { +namespace DistributedRDBTest { + +static constexpr const char *TEST_BUNDLE = "test_rdb_service_impl_bundleName"; +static constexpr const char *TEST_APPID = "test_rdb_service_impl_appid"; +static constexpr const char *TEST_STORE = "test_rdb_service_impl_store"; + +class RdbServiceImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + static void InitMetaData(); + void SetUp(); + void TearDown(); +protected: + static std::shared_ptr dbStoreMock_; + static StoreMetaData metaData_; + static void InitMetaDataManager(); +}; + +std::shared_ptr RdbServiceImplTest::dbStoreMock_ = std::make_shared(); +StoreMetaData RdbServiceImplTest::metaData_; + +void RdbServiceImplTest::InitMetaData() +{ + metaData_.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + metaData_.appId = TEST_APPID; + metaData_.bundleName = TEST_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_STORE; +} + +void RdbServiceImplTest::InitMetaDataManager() +{ + MetaDataManager::GetInstance().Initialize(dbStoreMock_, nullptr, ""); + MetaDataManager::GetInstance().SetSyncer([](const auto &, auto) { + DeviceMatrix::GetInstance().OnChanged(DeviceMatrix::META_STORE_MASK); + }); +} + +void RdbServiceImplTest::SetUpTestCase() +{ + size_t max = 12; + size_t min = 5; + + auto dmExecutor = std::make_shared(max, min); + DeviceManagerAdapter::GetInstance().Init(dmExecutor); + InitMetaData(); +} + +void RdbServiceImplTest::TearDownTestCase() +{ +} + +void RdbServiceImplTest::SetUp() +{ +} + +void RdbServiceImplTest::TearDown() +{ +} + +/** +* @tc.name: OnRemoteRequest001 +* @tc.desc: ResolveAutoLaunch LoadMeta Failed. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch001, TestSize.Level0) +{ + auto localId = DmAdapter::GetInstance().GetLocalDevice().uuid; + DistributedDB::AutoLaunchParam param; + RdbServiceImpl service; + + std::string identifier = "test_identifier"; + int32_t result = service.ResolveAutoLaunch(identifier, param); + EXPECT_EQ(result, false); +} + +/** +* @tc.name: ResolveAutoLaunch002 +* @tc.desc: ResolveAutoLaunch no meta. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch002, TestSize.Level0) +{ + InitMetaDataManager(); + auto localId = DmAdapter::GetInstance().GetLocalDevice().uuid; + DistributedDB::AutoLaunchParam param; + RdbServiceImpl service; + + std::string identifier = "test_identifier"; + int32_t result = service.ResolveAutoLaunch(identifier, param); + EXPECT_EQ(result, false); +} + +/** +* @tc.name: ResolveAutoLaunch003 +* @tc.desc: ResolveAutoLaunch has meta, identifier not match. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch003, TestSize.Level0) +{ + auto ret = MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false); + EXPECT_EQ(ret, true); + StoreMetaData meta; + meta.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + meta.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(meta.tokenId)); + meta.bundleName = TEST_BUNDLE; + meta.storeId = "ResolveAutoLaunch003"; + meta.instanceId = 0; + meta.appId = TEST_APPID; + meta.tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + meta.area = OHOS::DistributedKv::EL1; + meta.isAutoSync = true; + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, false), true); + + DistributedDB::AutoLaunchParam param; + RdbServiceImpl service; + + std::string identifier = "test_identifier"; + int32_t result = service.ResolveAutoLaunch(identifier, param); + + EXPECT_EQ(result, false); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** +* @tc.name: ResolveAutoLaunch004 +* @tc.desc: ResolveAutoLaunch has meta, identifier match. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch004, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + DistributedDB::AutoLaunchParam param; + RdbServiceImpl service; + RelationalStoreManager userMgr(metaData_.appId, metaData_.user, metaData_.storeId); + auto identifier = userMgr.GetRelationalStoreIdentifier(metaData_.user, metaData_.appId, metaData_.storeId, true); + + int32_t result = service.ResolveAutoLaunch(identifier, param); + + EXPECT_EQ(result, true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** +* @tc.name: ResolveAutoLaunch005 +* @tc.desc: ResolveAutoLaunch has meta, identifier match, is encrypt. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch005, TestSize.Level0) +{ + auto meta = metaData_; + meta.isEncrypt = true; + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, false), true); + DistributedDB::AutoLaunchParam param; + RdbServiceImpl service; + RelationalStoreManager userMgr1(meta.appId, meta.user, meta.storeId); + auto identifier = userMgr1.GetRelationalStoreIdentifier(meta.user, meta.appId, meta.storeId, true); + + int32_t result = service.ResolveAutoLaunch(identifier, param); + + EXPECT_EQ(result, true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(meta.GetKey(), false), true); +} + +/** +* @tc.name: ResolveAutoLaunch006 +* @tc.desc: test ObtainDistributedTableName, uuid exist. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch006, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + RdbServiceImpl service; + auto deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + auto ret = service.ObtainDistributedTableName(deviceId, TEST_STORE); + EXPECT_GT(ret.length(), 0); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** +* @tc.name: ObtainDistributedTableName001 +* @tc.desc: test ObtainDistributedTableName, uuid invalid. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ObtainDistributedTableName001, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + RdbServiceImpl service; + auto ret = service.ObtainDistributedTableName("invalid_device_id", TEST_STORE); + EXPECT_EQ(ret.length(), 0); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** +* @tc.name: TransferStringToHex001 +* @tc.desc: test TransferStringToHex, param empty. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, TransferStringToHex001, TestSize.Level0) +{ + RdbServiceImpl service; + auto ret = service.TransferStringToHex(""); + EXPECT_EQ(ret.length(), 0); +} + +/** +* @tc.name: GetCallbacks001 +* @tc.desc: test GetCallbacks. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, GetCallbacks001, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + RdbServiceImpl service; + auto ret = service.GetCallbacks(metaData_.tokenId, metaData_.storeId); + EXPECT_EQ(ret, nullptr); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +} // namespace DistributedRDBTest +} // namespace OHOS::Test -- Gitee From bd0e173470712531ec42addbde415207c597eb95 Mon Sep 17 00:00:00 2001 From: Jeam_wang Date: Thu, 27 Mar 2025 19:48:09 +0800 Subject: [PATCH 116/225] =?UTF-8?q?=E5=9C=A8=E7=BD=91=E7=BB=9C=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E4=B9=8B=E5=90=8E=E5=86=8D=E6=AC=A1=E8=A7=A6=E5=8F=91?= =?UTF-8?q?=E7=BD=91=E7=BB=9C=E7=9B=91=E5=90=AC=E6=B3=A8=E5=86=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jeam_wang --- .../network/src/network_delegate_normal_impl.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp index 9389f8dcf..7769b8642 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp +++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp @@ -125,11 +125,19 @@ void NetworkDelegateNormalImpl::RegOnNetworkChange() flag.store(false); return; } - auto nRet = NetConnClient::GetInstance().RegisterNetConnCallback(observer); - if (nRet != NETMANAGER_SUCCESS) { + constexpr int32_t RETRY_MAX_TIMES = 3; + int32_t retryCount = 0; + constexpr int32_t RETRY_TIME_INTERVAL_MILLISECOND = 1 * 1000 * 1000; + do { + auto nRet = NetConnClient::GetInstance().RegisterNetConnCallback(observer); + if (nRet == E_OK) { + break; + } ZLOGE("RegisterNetConnCallback failed, ret = %{public}d", nRet); flag.store(false); - } + retryCount++; + usleep(RETRY_TIMEE_INTERVAL_MILLISECOND); + } while (retryCount < RETRY_MAX_TIMES); } bool NetworkDelegateNormalImpl::IsNetworkAvailable() -- Gitee From 9c64fbffbc0ceb648a5a41565369096275244df1 Mon Sep 17 00:00:00 2001 From: Jeam_wang Date: Thu, 27 Mar 2025 19:48:09 +0800 Subject: [PATCH 117/225] =?UTF-8?q?=E5=9C=A8=E7=BD=91=E7=BB=9C=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E4=B9=8B=E5=90=8E=E5=86=8D=E6=AC=A1=E8=A7=A6=E5=8F=91?= =?UTF-8?q?=E7=BD=91=E7=BB=9C=E7=9B=91=E5=90=AC=E6=B3=A8=E5=86=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jeam_wang --- .../adapter/network/src/network_delegate_normal_impl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp index 7769b8642..2e7736472 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp +++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp @@ -130,13 +130,13 @@ void NetworkDelegateNormalImpl::RegOnNetworkChange() constexpr int32_t RETRY_TIME_INTERVAL_MILLISECOND = 1 * 1000 * 1000; do { auto nRet = NetConnClient::GetInstance().RegisterNetConnCallback(observer); - if (nRet == E_OK) { + if (nRet == NETMANAGER_SUCCESS) { break; } ZLOGE("RegisterNetConnCallback failed, ret = %{public}d", nRet); flag.store(false); retryCount++; - usleep(RETRY_TIMEE_INTERVAL_MILLISECOND); + usleep(RETRY_TIME_INTERVAL_MILLISECOND); } while (retryCount < RETRY_MAX_TIMES); } -- Gitee From c0dded57e442dbd27a37ed81b57a045186eae9bf Mon Sep 17 00:00:00 2001 From: zph Date: Mon, 31 Mar 2025 20:31:30 +0800 Subject: [PATCH 118/225] update Signed-off-by: zph --- .../udmf/preprocess/preprocess_utils.cpp | 19 ++++++++++++++++++- .../udmf/preprocess/preprocess_utils.h | 1 + 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index 069609aba..6285e557e 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -22,6 +22,7 @@ #include "udmf_radar_reporter.h" #include "accesstoken_kit.h" #include "device_manager_adapter.h" +#include "ipc_skeleton.h" #include "log_print.h" #include "udmf_radar_reporter.h" #include "udmf_utils.h" @@ -71,7 +72,7 @@ int32_t PreProcessUtils::RuntimeDataImputation(UnifiedData &data, CustomOption & runtime.deviceId = GetLocalDeviceId(); runtime.recordTotalNum = static_cast(data.GetRecords().size()); runtime.tokenId = option.tokenId; - runtime.sdkVersion = data.GetSdkVersion(); + runtime.sdkVersion = GetSdkVersionByToken(option.tokenId); data.SetRuntime(runtime); return E_OK; } @@ -470,5 +471,21 @@ Status PreProcessUtils::GetSummaryFromDetails(const UDDetails &details, Summary } return E_OK; } + +std::string PreProcessUtils::GetSdkVersionByToken(uint32_t tokenId) +{ + if (Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) != + Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) { + ZLOGE("Caller is not application."); + return ""; + } + Security::AccessToken::HapTokenInfo hapTokenInfo; + auto ret = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, hapTokenInfo); + if (ret != 0) { + ZLOGE("GetHapTokenInfo fail, tokenid is %{public}u, ret is %{public}d.", tokenId, ret); + return ""; + } + return std::to_string(hapTokenInfo.apiVersion); +} } // namespace UDMF } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h index 6d6130078..1532f4c49 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h @@ -46,6 +46,7 @@ private: static bool CheckUriAuthorization(const std::vector& uris, uint32_t tokenId); static int32_t GetDfsUrisFromLocal(const std::vector &uris, int32_t userId, UnifiedData &data); static bool IsFileType(std::shared_ptr record); + static std::string GetSdkVersionByToken(uint32_t tokenId); }; } // namespace UDMF } // namespace OHOS -- Gitee From 2607afecb73eca69f56d153def13fdce2deebe9e Mon Sep 17 00:00:00 2001 From: zph Date: Tue, 1 Apr 2025 15:01:54 +0800 Subject: [PATCH 119/225] update Signed-off-by: zph --- .../udmf/permission/uri_permission_manager.cpp | 2 +- .../service/udmf/udmf_service_impl.cpp | 14 +++++--------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/services/distributeddataservice/service/udmf/permission/uri_permission_manager.cpp b/services/distributeddataservice/service/udmf/permission/uri_permission_manager.cpp index e9eb42a70..042325f49 100644 --- a/services/distributeddataservice/service/udmf/permission/uri_permission_manager.cpp +++ b/services/distributeddataservice/service/udmf/permission/uri_permission_manager.cpp @@ -22,7 +22,7 @@ namespace OHOS { namespace UDMF { -constexpr const std::uint32_t GRANT_URI_PERMISSION_MAX_SIZE = 500; +constexpr const std::uint32_t GRANT_URI_PERMISSION_MAX_SIZE = 10000; UriPermissionManager &UriPermissionManager::GetInstance() { static UriPermissionManager instance; diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 408c19a00..2310e1e31 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -580,19 +580,15 @@ int32_t UdmfServiceImpl::IsRemoteData(const QueryOption &query, bool &result) return E_DB_ERROR; } - UnifiedData unifiedData; - if (store->Get(query.key, unifiedData) != E_OK) { - ZLOGE("Store get unifiedData failed:%{public}s", key.intention.c_str()); - return E_DB_ERROR; - } - std::shared_ptr runtime = unifiedData.GetRuntime(); - if (runtime == nullptr) { - ZLOGE("Store get runtime failed, key: %{public}s.", query.key.c_str()); + Runtime runtime; + auto res = store->GetRuntime(query.key, runtime); + if (res != E_OK) { + ZLOGE("Get runtime failed, res:%{public}d, key:%{public}s.", res, query.key.c_str()); return E_DB_ERROR; } std::string localDeviceId = PreProcessUtils::GetLocalDeviceId(); - if (localDeviceId != runtime->deviceId) { + if (localDeviceId != runtime.deviceId) { result = true; } return E_OK; -- Gitee From f9f68dcbdb7ea8f298d92ea37a37231deb516dff Mon Sep 17 00:00:00 2001 From: wTong6 Date: Mon, 31 Mar 2025 10:30:12 +0800 Subject: [PATCH 120/225] fix Signed-off-by: wTong6 --- .../service/rdb/rdb_general_store.cpp | 12 ++++++++---- .../service/rdb/rdb_general_store.h | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.cpp b/services/distributeddataservice/service/rdb/rdb_general_store.cpp index b8dc6345e..ce24e6ac5 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.cpp +++ b/services/distributeddataservice/service/rdb/rdb_general_store.cpp @@ -62,6 +62,7 @@ constexpr const char *INSERT = "INSERT INTO "; constexpr const char *REPLACE = "REPLACE INTO "; constexpr const char *VALUES = " VALUES "; constexpr const char *LOGOUT_DELETE_FLAG = "DELETE#ALL_CLOUDDATA"; +constexpr const char *LOGOUT_RESERVE_FLAG = "RESERVE#ALL_CLOUDDATA"; constexpr const LockAction LOCK_ACTION = static_cast(static_cast(LockAction::INSERT) | static_cast(LockAction::UPDATE) | static_cast(LockAction::DELETE) | static_cast(LockAction::DOWNLOAD)); @@ -1191,8 +1192,8 @@ void RdbGeneralStore::ObserverProxy::OnChange(DBOrigin origin, const std::string info.push_back(std::move(value)); continue; } - auto deleteKey = std::get_if(&value); - if (deleteKey != nullptr && (*deleteKey == LOGOUT_DELETE_FLAG)) { + auto key = std::get_if(&value); + if (key != nullptr && (*key == LOGOUT_DELETE_FLAG || *key == LOGOUT_RESERVE_FLAG)) { // notify to start app notifyFlag = true; } @@ -1200,8 +1201,11 @@ void RdbGeneralStore::ObserverProxy::OnChange(DBOrigin origin, const std::string } } if (notifyFlag) { - ZLOGI("post data change for cleaning cloud data"); - PostDataChange(meta_, {}, CLOUD_DATA_CLEAN); + ZLOGI("post data change for cleaning cloud data. store:%{public}s table:%{public}s data change from " + ":%{public}s", + Anonymous::Change(storeId_).c_str(), Anonymous::Change(data.tableName).c_str(), + Anonymous::Change(originalId).c_str()); + PostDataChange(meta_, {}, CLOUD_LOGOUT); } if (!data.field.empty()) { fields[std::move(data.tableName)] = std::move(*(data.field.begin())); diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.h b/services/distributeddataservice/service/rdb/rdb_general_store.h index 98b5d2ed6..3f2d394ef 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.h +++ b/services/distributeddataservice/service/rdb/rdb_general_store.h @@ -130,7 +130,7 @@ private: private: enum ChangeType { CLOUD_DATA_CHANGE = 0, - CLOUD_DATA_CLEAN + CLOUD_LOGOUT, }; void PostDataChange(const StoreMetaData &meta, const std::vector &tables, ChangeType type); friend RdbGeneralStore; -- Gitee From 71936fb13653aac58b17a4d16af304434620ce6f Mon Sep 17 00:00:00 2001 From: zph Date: Wed, 2 Apr 2025 19:42:35 +0800 Subject: [PATCH 121/225] update Signed-off-by: zph --- .../service/udmf/preprocess/preprocess_utils.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index 6285e557e..145727a2a 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -425,7 +425,7 @@ bool PreProcessUtils::GetDetailsFromUData(const UnifiedData &data, UDDetails &de { auto records = data.GetRecords(); if (records.size() != TEMP_UDATA_RECORD_SIZE) { - ZLOGE("Records size error.size:%{public}zu", records.size()); + ZLOGI("Records size:%{public}zu", records.size()); return false; } if (records[0] == nullptr) { @@ -476,7 +476,7 @@ std::string PreProcessUtils::GetSdkVersionByToken(uint32_t tokenId) { if (Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) != Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) { - ZLOGE("Caller is not application."); + ZLOGE("Caller is not application, tokenid is %{public}u", tokenId); return ""; } Security::AccessToken::HapTokenInfo hapTokenInfo; -- Gitee From 759edd1e8f0784a64a8dfbceaa08dcad73925e35 Mon Sep 17 00:00:00 2001 From: zph Date: Wed, 2 Apr 2025 21:13:07 +0800 Subject: [PATCH 122/225] update Signed-off-by: zph --- .../service/udmf/preprocess/preprocess_utils.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index 145727a2a..0cf277aa7 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -22,7 +22,6 @@ #include "udmf_radar_reporter.h" #include "accesstoken_kit.h" #include "device_manager_adapter.h" -#include "ipc_skeleton.h" #include "log_print.h" #include "udmf_radar_reporter.h" #include "udmf_utils.h" -- Gitee From bd32be9aa4a2957df9078dc858574071b96ba91d Mon Sep 17 00:00:00 2001 From: Jeam_wang Date: Thu, 27 Mar 2025 19:48:09 +0800 Subject: [PATCH 123/225] =?UTF-8?q?=E5=9C=A8=E7=BD=91=E7=BB=9C=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E4=B9=8B=E5=90=8E=E5=86=8D=E6=AC=A1=E8=A7=A6=E5=8F=91?= =?UTF-8?q?=E7=BD=91=E7=BB=9C=E7=9B=91=E5=90=AC=E6=B3=A8=E5=86=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jeam_wang --- .../src/network_delegate_default_impl.cpp | 4 ++ .../src/network_delegate_default_impl.h | 2 +- .../src/network_delegate_normal_impl.cpp | 49 ++++++++++++------- .../src/network_delegate_normal_impl.h | 5 ++ .../app/src/kvstore_data_service.cpp | 1 + .../include/network/network_delegate.h | 2 + .../service/cloud/cloud_service_impl.cpp | 1 - 7 files changed, 44 insertions(+), 20 deletions(-) diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp index 0372dc5b6..192c32cb6 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp +++ b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp @@ -40,6 +40,10 @@ NetworkDelegate::NetworkType NetworkDelegateDefaultImpl::GetNetworkType(bool ret return NetworkType::NONE; } +void NetworkDelegateDefaultImpl::BindExecutor(std::shared_ptr executors) +{ +} + bool NetworkDelegateDefaultImpl::Init() { static NetworkDelegateDefaultImpl delegate; diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h index db00f8d75..b3ddd1a17 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h +++ b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h @@ -25,7 +25,7 @@ public: bool IsNetworkAvailable() override; void RegOnNetworkChange() override; NetworkType GetNetworkType(bool retrieve = false) override; - + void BindExecutor(std::shared_ptr executors) override; private: NetworkDelegateDefaultImpl(); ~NetworkDelegateDefaultImpl(); diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp index 2e7736472..8e1b4a4ca 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp +++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp @@ -114,30 +114,43 @@ NetworkDelegateNormalImpl::~NetworkDelegateNormalImpl() void NetworkDelegateNormalImpl::RegOnNetworkChange() { - static std::atomic_bool flag = false; - if (flag.exchange(true)) { - ZLOGW("run only one"); - return; + if (executors_ != nullptr) { + executors_->Execute(GetTask(0)); } - sptr observer = new (std::nothrow) NetConnCallbackObserver(*this); - if (observer == nullptr) { - ZLOGE("new operator error.observer is nullptr"); - flag.store(false); - return; - } - constexpr int32_t RETRY_MAX_TIMES = 3; - int32_t retryCount = 0; - constexpr int32_t RETRY_TIME_INTERVAL_MILLISECOND = 1 * 1000 * 1000; - do { +} + +void NetworkDelegateNormalImpl::BindExecutor(std::shared_ptr executors) +{ + executors_ = executors; +} + +ExecutorPool::Task NetworkDelegateNormalImpl::GetTask(uint32_t retry) +{ + return [this, retry] { + static std::atomic_bool flag = false; + if (flag.exchange(true)) { + ZLOGW("run only one"); + return; + } + sptr observer = new (std::nothrow) NetConnCallbackObserver(*this); + if (observer == nullptr) { + ZLOGE("new operator error.observer is nullptr"); + flag.store(false); + return; + } auto nRet = NetConnClient::GetInstance().RegisterNetConnCallback(observer); - if (nRet == NETMANAGER_SUCCESS) { break; + return; } ZLOGE("RegisterNetConnCallback failed, ret = %{public}d", nRet); flag.store(false); - retryCount++; - usleep(RETRY_TIME_INTERVAL_MILLISECOND); - } while (retryCount < RETRY_MAX_TIMES); + if (retry + 1 > MAX_RETRY_TIME) { + flag.store(false); + ZLOGE("fail to register subscriber!"); + return; + } + executors_->Schedule(std::chrono::seconds(RETRY_WAIT_TIME_S), GetTask(retry + 1)); + }; } bool NetworkDelegateNormalImpl::IsNetworkAvailable() diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h index c403f8497..987c2b4e4 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h +++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h @@ -30,6 +30,7 @@ public: bool IsNetworkAvailable() override; NetworkType GetNetworkType(bool retrieve = false) override; void RegOnNetworkChange() override; + void BindExecutor(std::shared_ptr executors) override; friend class NetConnCallbackObserver; private: NetworkDelegateNormalImpl(); @@ -43,11 +44,15 @@ private: std::chrono::steady_clock::now().time_since_epoch()) .count(); } + ExecutorPool::Task GetTask(uint32_t retry); static constexpr int32_t EFFECTIVE_DURATION = 30 * 1000; // ms static constexpr int32_t NET_LOST_DURATION = 10 * 1000; // ms + static constexpr int MAX_RETRY_TIME = 3; + static constexpr int RETRY_WAIT_TIME_S = 1; NetworkType defaultNetwork_ = NONE; uint64_t expireTime_ = 0; uint64_t netLostTime_ = 0; + std::shared_ptr executors_; }; } // namespace OHOS::DistributedData #endif // OHOS_DISTRIBUTED_DATA_NETWORK_NORMAL_DELEGATE_IMPL_H \ No newline at end of file diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index aa42b9246..2c26686d8 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -299,6 +299,7 @@ void KvStoreDataService::OnStart() AccountDelegate::GetInstance()->RegisterHashFunc(Crypto::Sha256); DmAdapter::GetInstance().Init(executors_); AutoCache::GetInstance().Bind(executors_); + NetworkDelegate::GetInstance()->BindExecutor(executors_); static constexpr int32_t RETRY_TIMES = 50; static constexpr int32_t RETRY_INTERVAL = 500 * 1000; // unit is ms for (BlockInteger retry(RETRY_INTERVAL); retry < RETRY_TIMES; ++retry) { diff --git a/services/distributeddataservice/framework/include/network/network_delegate.h b/services/distributeddataservice/framework/include/network/network_delegate.h index ae7e9f94a..505902a4f 100644 --- a/services/distributeddataservice/framework/include/network/network_delegate.h +++ b/services/distributeddataservice/framework/include/network/network_delegate.h @@ -19,6 +19,7 @@ #include #include +#include "executor_pool.h" #include "types.h" namespace OHOS { @@ -37,6 +38,7 @@ public: API_EXPORT static bool RegisterNetworkInstance(NetworkDelegate *instance); virtual bool IsNetworkAvailable() = 0; virtual void RegOnNetworkChange() = 0; + virtual void BindExecutor(std::shared_ptr executors) = 0; virtual NetworkType GetNetworkType(bool retrieve = false) = 0; private: diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index a286b810c..c1e772133 100644 --- a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -668,7 +668,6 @@ std::pair CloudServiceImpl::QueryLastSyncInfo(const s int32_t CloudServiceImpl::OnInitialize() { XCollie xcollie(__FUNCTION__, XCollie::XCOLLIE_LOG | XCollie::XCOLLIE_RECOVERY); - NetworkDelegate::GetInstance()->RegOnNetworkChange(); DistributedDB::RuntimeConfig::SetCloudTranslate(std::make_shared()); Execute(GenTask(0, 0, CloudSyncScene::SERVICE_INIT, { WORK_CLOUD_INFO_UPDATE, WORK_SCHEMA_UPDATE, WORK_DO_CLOUD_SYNC, WORK_SUB })); -- Gitee From f8994e1f48f0c8200cdd7963e80e28594af65480 Mon Sep 17 00:00:00 2001 From: zhangdi Date: Tue, 1 Apr 2025 20:33:17 +0800 Subject: [PATCH 124/225] =?UTF-8?q?=E5=BA=94=E7=94=A8=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=9B=B4=E6=96=B0sync=E5=85=83=E6=95=B0?= =?UTF-8?q?=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangdi --- .../service/rdb/rdb_service_impl.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index c4123e299..482f3a958 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -1231,8 +1231,20 @@ int32_t RdbServiceImpl::RdbStatic::OnAppUpdate(const std::string &bundleName, in std::string prefix = Database::GetPrefix({std::to_string(user), "default", bundleName}); std::vector dataBase; if (MetaDataManager::GetInstance().LoadMeta(prefix, dataBase, true)) { - for (const auto &dataBase : dataBase) { - MetaDataManager::GetInstance().DelMeta(dataBase.GetKey(), true); + for (const auto &database : dataBase) { + ZLOGD("Delete matedata store is :%{public}s", database.name.c_str()); + MetaDataManager::GetInstance().DelMeta(database.GetKey(), true); + StoreMetaData meta; + meta.user = database.user; + meta.deviceId = database.deviceId; + meta.storeId = database.name; + meta.bundleName = bundleName; + Database base; + if (RdbSchemaConfig::GetDistributedSchema(meta, base) && !base.name.empty() && + !base.bundleName.empty()) { + ZLOGD("save metadata store is :%{public}s", base.name.c_str()); + MetaDataManager::GetInstance().SaveMeta(base.GetKey(), base, true); + } } } return CloseStore(bundleName, user, index); -- Gitee From 4d7bbc75127143535abb055474b57484ff016035 Mon Sep 17 00:00:00 2001 From: Jeam_wang Date: Thu, 27 Mar 2025 19:48:09 +0800 Subject: [PATCH 125/225] =?UTF-8?q?=E5=9C=A8=E7=BD=91=E7=BB=9C=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E4=B9=8B=E5=90=8E=E5=86=8D=E6=AC=A1=E8=A7=A6=E5=8F=91?= =?UTF-8?q?=E7=BD=91=E7=BB=9C=E7=9B=91=E5=90=AC=E6=B3=A8=E5=86=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jeam_wang --- .../adapter/network/src/network_delegate_normal_impl.cpp | 3 +-- .../adapter/network/src/network_delegate_normal_impl.h | 4 ++-- .../service/test/mock/network_delegate_mock.cpp | 5 +++++ .../service/test/mock/network_delegate_mock.h | 1 + 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp index 8e1b4a4ca..a97cd40fb 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp +++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp @@ -139,13 +139,12 @@ ExecutorPool::Task NetworkDelegateNormalImpl::GetTask(uint32_t retry) return; } auto nRet = NetConnClient::GetInstance().RegisterNetConnCallback(observer); - break; + if (nRet == NETMANAGER_SUCCESS) { return; } ZLOGE("RegisterNetConnCallback failed, ret = %{public}d", nRet); flag.store(false); if (retry + 1 > MAX_RETRY_TIME) { - flag.store(false); ZLOGE("fail to register subscriber!"); return; } diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h index 987c2b4e4..f4c62051d 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h +++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h @@ -47,8 +47,8 @@ private: ExecutorPool::Task GetTask(uint32_t retry); static constexpr int32_t EFFECTIVE_DURATION = 30 * 1000; // ms static constexpr int32_t NET_LOST_DURATION = 10 * 1000; // ms - static constexpr int MAX_RETRY_TIME = 3; - static constexpr int RETRY_WAIT_TIME_S = 1; + static constexpr int32_t MAX_RETRY_TIME = 3; + static constexpr int32_t RETRY_WAIT_TIME_S = 1; NetworkType defaultNetwork_ = NONE; uint64_t expireTime_ = 0; uint64_t netLostTime_ = 0; diff --git a/services/distributeddataservice/service/test/mock/network_delegate_mock.cpp b/services/distributeddataservice/service/test/mock/network_delegate_mock.cpp index ce26d253b..cfab2309b 100644 --- a/services/distributeddataservice/service/test/mock/network_delegate_mock.cpp +++ b/services/distributeddataservice/service/test/mock/network_delegate_mock.cpp @@ -30,5 +30,10 @@ void NetworkDelegateMock::RegOnNetworkChange() { return; } + +void NetworkDelegateMock::BindExecutor(std::shared_ptr executors) +{ + return; +} } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/network_delegate_mock.h b/services/distributeddataservice/service/test/mock/network_delegate_mock.h index 474e57c32..5e199efbe 100644 --- a/services/distributeddataservice/service/test/mock/network_delegate_mock.h +++ b/services/distributeddataservice/service/test/mock/network_delegate_mock.h @@ -24,6 +24,7 @@ public: bool IsNetworkAvailable() override; NetworkType GetNetworkType(bool retrieve = false) override; void RegOnNetworkChange() override; + void BindExecutor(std::shared_ptr executors) override; bool isNetworkAvailable_ = true; virtual ~NetworkDelegateMock() = default; }; -- Gitee From 20e1c853d9a0f44de3bc13cd7d522b8b8e556d7f Mon Sep 17 00:00:00 2001 From: Jeam_wang Date: Thu, 3 Apr 2025 17:02:39 +0800 Subject: [PATCH 126/225] =?UTF-8?q?=E5=9C=A8=E7=BD=91=E7=BB=9C=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E4=B9=8B=E5=90=8E=E5=86=8D=E6=AC=A1=E8=A7=A6=E5=8F=91?= =?UTF-8?q?=E7=BD=91=E7=BB=9C=E7=9B=91=E5=90=AC=E6=B3=A8=E5=86=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jeam_wang --- .../adapter/network/src/network_delegate_normal_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp index a97cd40fb..1edda0333 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp +++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp @@ -144,7 +144,7 @@ ExecutorPool::Task NetworkDelegateNormalImpl::GetTask(uint32_t retry) } ZLOGE("RegisterNetConnCallback failed, ret = %{public}d", nRet); flag.store(false); - if (retry + 1 > MAX_RETRY_TIME) { + if (retry + 1 >= MAX_RETRY_TIME) { ZLOGE("fail to register subscriber!"); return; } -- Gitee From 2aa71492fdb5f805b880450a4d81335f7e04f5ce Mon Sep 17 00:00:00 2001 From: louzhihao Date: Sat, 5 Apr 2025 17:00:48 +0800 Subject: [PATCH 127/225] user Signed-off-by: louzhihao Change-Id: I0f361edc8cde113bdc7dd7336e3e32c581714d25 --- .../service/data_share/common/context.h | 1 + .../data_share/data_share_service_impl.cpp | 35 ++++++++++--------- .../data_share/data_share_service_impl.h | 2 +- ...d_config_from_data_proxy_node_strategy.cpp | 2 +- ...g_from_data_share_bundle_info_strategy.cpp | 2 +- .../general/load_config_common_strategy.cpp | 3 +- .../load_config_data_info_strategy.cpp | 4 +-- .../strategies/get_data_strategy.cpp | 2 +- .../strategies/publish_strategy.cpp | 4 +-- .../published_data_subscriber_manager.cpp | 22 +++++++----- .../published_data_subscriber_manager.h | 12 ++++--- .../rdb_subscriber_manager.cpp | 30 +++++++++------- .../rdb_subscriber_manager.h | 3 +- .../test/data_share_service_impl_test.cpp | 4 +-- .../data_share_subscriber_managers_test.cpp | 6 ++-- 15 files changed, 76 insertions(+), 56 deletions(-) diff --git a/services/distributeddataservice/service/data_share/common/context.h b/services/distributeddataservice/service/data_share/common/context.h index 62da611a2..d19ebf6d1 100644 --- a/services/distributeddataservice/service/data_share/common/context.h +++ b/services/distributeddataservice/service/data_share/common/context.h @@ -37,6 +37,7 @@ public: virtual ~Context() = default; std::string uri; int32_t currentUserId = -1; + int32_t visitedUserId = -1; int32_t appIndex = 0; int32_t haMode = 0; std::string permission; diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp index 02b2ce855..d8ba1344f 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp @@ -118,7 +118,8 @@ std::pair DataShareServiceImpl::InsertEx(const std::string &ur callingTokenId}, true); auto [errCode, ret] = dbDelegate->InsertEx(providerInfo.tableName, valuesBucket); if (errCode == E_OK && ret > 0) { - NotifyChange(uri); + // only notify specific userId + NotifyChange(uri, providerInfo.visitedUserId); RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData); } else { ReportExcuteFault(callingTokenId, providerInfo, errCode, func); @@ -129,7 +130,7 @@ std::pair DataShareServiceImpl::InsertEx(const std::string &ur return ExecuteEx(uri, extUri, IPCSkeleton::GetCallingTokenID(), false, callBack); } -bool DataShareServiceImpl::NotifyChange(const std::string &uri) +bool DataShareServiceImpl::NotifyChange(const std::string &uri, int32_t userId) { RadarReporter::RadarReport report(RadarReporter::NOTIFY_OBSERVER_DATA_CHANGE, RadarReporter::NOTIFY_DATA_CHANGE, __FUNCTION__); @@ -139,8 +140,7 @@ bool DataShareServiceImpl::NotifyChange(const std::string &uri) report.SetError(RadarReporter::DATA_OBS_EMPTY_ERROR); return false; } - - ErrCode ret = obsMgrClient->NotifyChange(Uri(uri)); + ErrCode ret = obsMgrClient->NotifyChange(Uri(uri), userId); if (ret != ERR_OK) { ZLOGE("obsMgrClient->NotifyChange error return %{public}d", ret); report.SetError(RadarReporter::NOTIFY_ERROR); @@ -166,7 +166,7 @@ std::pair DataShareServiceImpl::UpdateEx(const std::string &ur callingTokenId}, true); auto [errCode, ret] = dbDelegate->UpdateEx(providerInfo.tableName, predicate, valuesBucket); if (errCode == E_OK && ret > 0) { - NotifyChange(uri); + NotifyChange(uri, providerInfo.visitedUserId); RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData); } else { ReportExcuteFault(callingTokenId, providerInfo, errCode, func); @@ -194,7 +194,7 @@ std::pair DataShareServiceImpl::DeleteEx(const std::string &ur callingTokenId}, true); auto [errCode, ret] = dbDelegate->DeleteEx(providerInfo.tableName, predicate); if (errCode == E_OK && ret > 0) { - NotifyChange(uri); + NotifyChange(uri, providerInfo.visitedUserId); RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData); } else { ReportExcuteFault(callingTokenId, providerInfo, errCode, func); @@ -251,7 +251,7 @@ int32_t DataShareServiceImpl::AddTemplate(const std::string &uri, const int64_t uri.c_str(), subscriberId, tpltId.bundleName_.c_str(), tplt.predicates_.size()); return templateStrategy_.Execute(context, [&uri, &tpltId, &tplt, &context]() -> int32_t { auto result = TemplateManager::GetInstance().Add( - Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->currentUserId, tplt); + Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->visitedUserId, tplt); RdbSubscriberManager::GetInstance().Emit(context->uri, tpltId.subscriberId_, tpltId.bundleName_, context); return result; }); @@ -270,7 +270,7 @@ int32_t DataShareServiceImpl::DelTemplate(const std::string &uri, const int64_t DistributedData::Anonymous::Change(uri).c_str(), subscriberId, tpltId.bundleName_.c_str()); return templateStrategy_.Execute(context, [&uri, &tpltId, &context]() -> int32_t { return TemplateManager::GetInstance().Delete( - Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->currentUserId); + Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->visitedUserId); }); } @@ -339,7 +339,7 @@ std::vector DataShareServiceImpl::Publish(const Data &data, con continue; } publishedData.emplace_back(context->uri, context->calledBundleName, item.subscriberId_); - userId = context->currentUserId; + userId = context->visitedUserId; } if (!publishedData.empty()) { PublishedDataSubscriberManager::GetInstance().Emit(publishedData, userId, callerBundleName); @@ -369,7 +369,8 @@ std::vector DataShareServiceImpl::SubscribeRdbData( auto context = std::make_shared(uri); results.emplace_back(uri, subscribeStrategy_.Execute(context, [&id, &observer, &context, this]() { return RdbSubscriberManager::GetInstance().Add( - Key(context->uri, id.subscriberId_, id.bundleName_), observer, context, binderInfo_.executors); + Key(context->uri, id.subscriberId_, id.bundleName_), + observer, context, binderInfo_.executors); })); } return results; @@ -437,7 +438,7 @@ std::vector DataShareServiceImpl::SubscribePublishedData(const result = subscribeStrategy_.Execute(context, [&subscriberId, &observer, &context]() { return PublishedDataSubscriberManager::GetInstance().Add( PublishedDataKey(context->uri, context->callerBundleName, subscriberId), observer, - context->callerTokenId); + context->callerTokenId, context->visitedUserId); }); results.emplace_back(uri, result); if (result == E_OK) { @@ -445,10 +446,10 @@ std::vector DataShareServiceImpl::SubscribePublishedData(const if (binderInfo_.executors != nullptr) { binderInfo_.executors->Execute([context, subscriberId]() { PublishedData::UpdateTimestamp( - context->uri, context->calledBundleName, subscriberId, context->currentUserId); + context->uri, context->calledBundleName, subscriberId, context->visitedUserId); }); } - userId = context->currentUserId; + userId = context->visitedUserId; } } if (!publishedKeys.empty()) { @@ -477,7 +478,7 @@ std::vector DataShareServiceImpl::UnsubscribePublishedData(cons if (result == E_OK && binderInfo_.executors != nullptr) { binderInfo_.executors->Execute([context, subscriberId]() { PublishedData::UpdateTimestamp( - context->uri, context->calledBundleName, subscriberId, context->currentUserId); + context->uri, context->calledBundleName, subscriberId, context->visitedUserId); }); } return result; @@ -510,7 +511,7 @@ std::vector DataShareServiceImpl::EnablePubSubs(const std::vect if (result == E_OK && binderInfo_.executors != nullptr) { binderInfo_.executors->Execute([context, subscriberId]() { PublishedData::UpdateTimestamp( - context->uri, context->calledBundleName, subscriberId, context->currentUserId); + context->uri, context->calledBundleName, subscriberId, context->visitedUserId); }); } results.emplace_back(uri, result); @@ -519,7 +520,7 @@ std::vector DataShareServiceImpl::EnablePubSubs(const std::vect if (PublishedDataSubscriberManager::GetInstance().IsNotifyOnEnabled(pKey, context->callerTokenId)) { publishedKeys.emplace_back(pKey); } - userId = context->currentUserId; + userId = context->visitedUserId; } } if (!publishedKeys.empty()) { @@ -548,7 +549,7 @@ std::vector DataShareServiceImpl::DisablePubSubs(const std::vec if (result == E_OK && binderInfo_.executors != nullptr) { binderInfo_.executors->Execute([context, subscriberId]() { PublishedData::UpdateTimestamp( - context->uri, context->calledBundleName, subscriberId, context->currentUserId); + context->uri, context->calledBundleName, subscriberId, context->visitedUserId); }); } return result; diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.h b/services/distributeddataservice/service/data_share/data_share_service_impl.h index e4d0a7d9d..49f285efe 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_impl.h +++ b/services/distributeddataservice/service/data_share/data_share_service_impl.h @@ -118,7 +118,7 @@ private: void RegisterDataShareServiceInfo(); void RegisterHandler(); bool SubscribeTimeChanged(); - bool NotifyChange(const std::string &uri); + bool NotifyChange(const std::string &uri, int32_t userId); bool GetCallerBundleName(std::string &bundleName); std::pair ExecuteEx(const std::string &uri, const std::string &extUri, const int32_t tokenId, bool isRead, ExecuteCallbackEx callback); diff --git a/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp index c796152ca..e3e01974b 100644 --- a/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp @@ -31,7 +31,7 @@ bool LoadConfigFromDataProxyNodeStrategy::operator()(std::shared_ptr co } context->type = PUBLISHED_DATA_TYPE; if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS( - context->calledBundleName, context->currentUserId, context->bundleInfo) != E_OK) { + context->calledBundleName, context->visitedUserId, context->bundleInfo) != E_OK) { ZLOGE("GetBundleInfoFromBMS failed! bundleName: %{public}s", context->calledBundleName.c_str()); context->errCode = E_BUNDLE_NAME_NOT_EXIST; return false; diff --git a/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp index 16fe91511..cc8f284c4 100644 --- a/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp @@ -81,7 +81,7 @@ bool LoadConfigFromDataShareBundleInfoStrategy::operator()(std::shared_ptrGetBundleInfoFromBMS( - context->calledBundleName, context->currentUserId, context->bundleInfo) != E_OK) { + context->calledBundleName, context->visitedUserId, context->bundleInfo) != E_OK) { ZLOGE("GetBundleInfoFromBMS failed! bundleName: %{public}s", context->calledBundleName.c_str()); return false; } diff --git a/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp index b8dece0fd..9a64d37c7 100644 --- a/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp @@ -33,13 +33,14 @@ bool LoadConfigCommonStrategy::operator()(std::shared_ptr context) context->callerTokenId = IPCSkeleton::GetCallingTokenID(); } context->currentUserId = AccountDelegate::GetInstance()->GetUserByToken(context->callerTokenId); + context->visitedUserId = context->currentUserId; if (!URIUtils::GetAppIndexFromProxyURI(context->uri, context->appIndex)) { return false; } // sa, userId is in uri, caller token id is from first caller tokenId if (context->currentUserId == 0) { GetInfoFromProxyURI( - context->uri, context->currentUserId, context->callerTokenId, context->calledBundleName); + context->uri, context->visitedUserId, context->callerTokenId, context->calledBundleName); URIUtils::FormatUri(context->uri); } if (context->needAutoLoadCallerBundleName && context->callerBundleName.empty()) { diff --git a/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp index d5283e4d3..095a04bdb 100644 --- a/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp @@ -53,12 +53,12 @@ bool LoadConfigNormalDataInfoStrategy::operator()(std::shared_ptr conte } DistributedData::StoreMetaData metaData; if (!QueryMetaData( - context->calledBundleName, context->calledStoreName, metaData, context->currentUserId, context->appIndex)) { + context->calledBundleName, context->calledStoreName, metaData, context->visitedUserId, context->appIndex)) { // connect extension and retry AAFwk::WantParams wantParams; ExtensionConnectAdaptor::TryAndWait(context->uri, context->calledBundleName, wantParams); if (!QueryMetaData( - context->calledBundleName, context->calledStoreName, metaData, context->currentUserId, context->appIndex)) { + context->calledBundleName, context->calledStoreName, metaData, context->visitedUserId, context->appIndex)) { ZLOGE("QueryMetaData fail, %{public}s", DistributedData::Anonymous::Change(context->uri).c_str()); context->errCode = NativeRdb::E_DB_NOT_EXIST; return false; diff --git a/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp index c32d5daff..b02436915 100644 --- a/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp @@ -36,7 +36,7 @@ Data GetDataStrategy::Execute(std::shared_ptr context, int &errorCode) errorCode = context->errCode; return Data(); } - auto result = PublishedData::Query(context->calledBundleName, context->currentUserId); + auto result = PublishedData::Query(context->calledBundleName, context->visitedUserId); Data data; for (auto &item : result) { if (!CheckPermission(context, item.value.key)) { diff --git a/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp index b0b7ca77a..a23d516b0 100644 --- a/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp @@ -42,10 +42,10 @@ int32_t PublishStrategy::Execute(std::shared_ptr context, const Publish return -1; } PublishedDataItem::DataType value = item.GetData(); - PublishedDataNode node(context->uri, context->calledBundleName, item.subscriberId_, context->currentUserId, + PublishedDataNode node(context->uri, context->calledBundleName, item.subscriberId_, context->visitedUserId, PublishedDataNode::MoveTo(value)); PublishedData data(node, context->version); - auto [status, count] = delegate->Upsert(KvDBDelegate::DATA_TABLE, data); + auto [status, count] = delegate->Upsert(KvDBDelegate::DATA_TABLE, data); if (status != E_OK) { ZLOGE("db Upsert failed, %{public}s %{public}s %{public}d", context->calledBundleName.c_str(), DistributedData::Anonymous::Change(context->uri).c_str(), status); diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.cpp b/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.cpp index 09dd531f9..b9bfc3c91 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.cpp +++ b/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.cpp @@ -32,15 +32,16 @@ PublishedDataSubscriberManager &PublishedDataSubscriberManager::GetInstance() return manager; } -int PublishedDataSubscriberManager::Add( - const PublishedDataKey &key, const sptr observer, uint32_t firstCallerTokenId) +int PublishedDataSubscriberManager::Add(const PublishedDataKey &key, + const sptr observer, uint32_t firstCallerTokenId, int32_t userId) { publishedDataCache_.Compute( - key, [&observer, &firstCallerTokenId, this](const PublishedDataKey &key, std::vector &value) { + key, [&observer, &firstCallerTokenId, userId, this](const PublishedDataKey &key, + std::vector &value) { ZLOGI("add publish subscriber, uri %{public}s tokenId 0x%{public}x", DistributedData::Anonymous::Change(key.key).c_str(), firstCallerTokenId); value.emplace_back(observer, firstCallerTokenId, IPCSkeleton::GetCallingTokenID(), - IPCSkeleton::GetCallingPid()); + IPCSkeleton::GetCallingPid(), userId); return true; }); return E_OK; @@ -112,6 +113,7 @@ int PublishedDataSubscriberManager::Enable(const PublishedDataKey &key, uint32_t return result ? E_OK : E_SUBSCRIBER_NOT_EXIST; } +// if arg observer is not null, notify that observer only; otherwise notify all observers void PublishedDataSubscriberManager::Emit(const std::vector &keys, int32_t userId, const std::string &ownerBundleName, const sptr observer) { @@ -133,7 +135,7 @@ void PublishedDataSubscriberManager::Emit(const std::vector &k publishedResult.erase(key); continue; } - PutInto(callbacks, val, key, observer); + PutInto(callbacks, val, key, observer, userId); break; } return false; @@ -157,7 +159,7 @@ void PublishedDataSubscriberManager::Emit(const std::vector &k void PublishedDataSubscriberManager::PutInto( std::map, std::vector> &callbacks, const std::vector &val, const PublishedDataKey &key, - const sptr observer) + const sptr observer, int32_t userId) { for (auto const &callback : val) { if (callback.enabled && callback.observer != nullptr) { @@ -165,6 +167,10 @@ void PublishedDataSubscriberManager::PutInto( if (observer != nullptr && callback.observer != observer) { continue; } + if (callback.userId != 0 && callback.userId != userId && userId != 0) { + ZLOGE("Not across user publish, from %{public}d to %{public}d", userId, callback.userId); + continue; + } callbacks[callback.observer].emplace_back(key); } } @@ -267,8 +273,8 @@ bool PublishedDataKey::operator!=(const PublishedDataKey &rhs) const } PublishedDataSubscriberManager::ObserverNode::ObserverNode(const sptr &observer, - uint32_t firstCallerTokenId, uint32_t callerTokenId, uint32_t callerPid) - : observer(observer), firstCallerTokenId(firstCallerTokenId), callerTokenId(callerTokenId), callerPid(callerPid) + uint32_t firstCallerTokenId, uint32_t callerTokenId, uint32_t callerPid, int32_t userId): observer(observer), + firstCallerTokenId(firstCallerTokenId), callerTokenId(callerTokenId), callerPid(callerPid), userId(userId) { } } // namespace OHOS::DataShare diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h b/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h index 37356d7e4..27e002d96 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h +++ b/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h @@ -26,7 +26,8 @@ #include "executor_pool.h" namespace OHOS::DataShare { struct PublishedDataKey { - PublishedDataKey(const std::string &key, const std::string &bundleName, int64_t subscriberId); + PublishedDataKey(const std::string &key, const std::string &bundleName, + int64_t subscriberId); bool operator<(const PublishedDataKey &rhs) const; bool operator>(const PublishedDataKey &rhs) const; bool operator<=(const PublishedDataKey &rhs) const; @@ -36,13 +37,14 @@ struct PublishedDataKey { std::string key; std::string bundleName; int64_t subscriberId; + int32_t userId; }; class PublishedDataSubscriberManager { public: static PublishedDataSubscriberManager &GetInstance(); int Add(const PublishedDataKey &key, const sptr observer, - uint32_t firstCallerTokenId); + uint32_t firstCallerTokenId, int32_t userId); int Delete(const PublishedDataKey &key, uint32_t firstCallerTokenId); void Delete(uint32_t callerTokenId, uint32_t callerPid); int Disable(const PublishedDataKey &key, uint32_t firstCallerTokenId); @@ -58,18 +60,20 @@ public: private: struct ObserverNode { ObserverNode(const sptr &observer, uint32_t firstCallerTokenId, - uint32_t callerTokenId = 0, uint32_t callerPid = 0); + uint32_t callerTokenId = 0, uint32_t callerPid = 0, int32_t userId = 0); sptr observer; uint32_t firstCallerTokenId; uint32_t callerTokenId; uint32_t callerPid; bool enabled = true; bool isNotifyOnEnabled = false; + int32_t userId = 0; }; PublishedDataSubscriberManager() = default; void PutInto(std::map, std::vector> &, - const std::vector &, const PublishedDataKey &, const sptr); + const std::vector &, const PublishedDataKey &, const sptr, + int32_t userId); ConcurrentMap> publishedDataCache_; }; } // namespace OHOS::DataShare diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp index b03fc242d..e8d34c239 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp +++ b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp @@ -119,9 +119,9 @@ int RdbSubscriberManager::Add(const Key &key, const sptr ZLOGI("add subscriber, uri %{private}s tokenId 0x%{public}x", key.uri.c_str(), context->callerTokenId); auto callerTokenId = IPCSkeleton::GetCallingTokenID(); auto callerPid = IPCSkeleton::GetCallingPid(); - value.emplace_back(observer, context->callerTokenId, callerTokenId, callerPid); + value.emplace_back(observer, context->callerTokenId, callerTokenId, callerPid, context->visitedUserId); std::vector node; - node.emplace_back(observer, context->callerTokenId, callerTokenId, callerPid); + node.emplace_back(observer, context->callerTokenId, callerTokenId, callerPid, context->visitedUserId); ExecutorPool::Task task = [key, node, context, this]() { LoadConfigDataInfoStrategy loadDataInfo; if (!loadDataInfo(context)) { @@ -130,9 +130,9 @@ int RdbSubscriberManager::Add(const Key &key, const sptr return; } DistributedData::StoreMetaData metaData = RdbSubscriberManager::GenMetaDataFromContext(context); - Notify(key, context->currentUserId, node, metaData); + Notify(key, context->visitedUserId, node, metaData); if (GetEnableObserverCount(key) == 1) { - SchedulerManager::GetInstance().Start(key, context->currentUserId, metaData); + SchedulerManager::GetInstance().Start(key, context->visitedUserId, metaData); } }; executorPool->Execute(task); @@ -227,13 +227,13 @@ int RdbSubscriberManager::Enable(const Key &key, std::shared_ptr contex if (it->isNotifyOnEnabled) { std::vector node; node.emplace_back(it->observer, context->callerTokenId); - Notify(key, context->currentUserId, node, metaData); + Notify(key, context->visitedUserId, node, metaData); } } return true; }); if (isChanged) { - SchedulerManager::GetInstance().Enable(key, context->currentUserId, metaData); + SchedulerManager::GetInstance().Enable(key, context->visitedUserId, metaData); } return result ? E_OK : E_SUBSCRIBER_NOT_EXIST; } @@ -252,12 +252,12 @@ void RdbSubscriberManager::Emit(const std::string &uri, std::shared_ptr if (key.uri != uri) { return false; } - Notify(key, context->currentUserId, val, metaData); + Notify(key, context->visitedUserId, val, metaData); SetObserverNotifyOnEnabled(val); return false; }); SchedulerManager::GetInstance().Execute( - uri, context->currentUserId, metaData); + uri, context->visitedUserId, metaData); } void RdbSubscriberManager::Emit(const std::string &uri, int32_t userId, @@ -372,6 +372,12 @@ int RdbSubscriberManager::Notify(const Key &key, int32_t userId, const std::vect ZLOGI("emit, valSize: %{public}zu, dataSize:%{public}zu, uri:%{public}s,", val.size(), changeNode.data_.size(), DistributedData::Anonymous::Change(changeNode.uri_).c_str()); for (const auto &callback : val) { + // not notify across user + if (callback.userId != userId && userId != 0 && callback.userId != 0) { + ZLOGI("Not allow across notify, uri:%{public}s, from %{public}d to %{public}d.", + DistributedData::Anonymous::Change(changeNode.uri_).c_str(), userId, callback.userId); + continue; + } if (callback.enabled && callback.observer != nullptr) { callback.observer->OnChangeFromRdb(changeNode); } @@ -399,12 +405,12 @@ void RdbSubscriberManager::Emit(const std::string &uri, int64_t subscriberId, if (key.uri != uri || key.subscriberId != subscriberId) { return false; } - Notify(key, context->currentUserId, val, metaData); + Notify(key, context->visitedUserId, val, metaData); SetObserverNotifyOnEnabled(val); return false; }); Key executeKey(uri, subscriberId, bundleName); - SchedulerManager::GetInstance().Start(executeKey, context->currentUserId, metaData); + SchedulerManager::GetInstance().Start(executeKey, context->visitedUserId, metaData); } DistributedData::StoreMetaData RdbSubscriberManager::GenMetaDataFromContext(const std::shared_ptr context) @@ -418,8 +424,8 @@ DistributedData::StoreMetaData RdbSubscriberManager::GenMetaDataFromContext(cons } RdbSubscriberManager::ObserverNode::ObserverNode(const sptr &observer, - uint32_t firstCallerTokenId, uint32_t callerTokenId, uint32_t callerPid) - : observer(observer), firstCallerTokenId(firstCallerTokenId), callerTokenId(callerTokenId), callerPid(callerPid) + uint32_t firstCallerTokenId, uint32_t callerTokenId, uint32_t callerPid, int32_t userId): observer(observer), + firstCallerTokenId(firstCallerTokenId), callerTokenId(callerTokenId), callerPid(callerPid), userId(userId) { } } // namespace OHOS::DataShare \ No newline at end of file diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h index 5bb2e82d8..8624397f8 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h +++ b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h @@ -73,13 +73,14 @@ public: private: struct ObserverNode { ObserverNode(const sptr &observer, uint32_t firstCallerTokenId, - uint32_t callerTokenId = 0, uint32_t callerPid = 0); + uint32_t callerTokenId = 0, uint32_t callerPid = 0, int32_t userId = 0); sptr observer; uint32_t firstCallerTokenId; uint32_t callerTokenId; uint32_t callerPid; bool enabled = true; bool isNotifyOnEnabled = false; + int32_t userId = 0; }; RdbSubscriberManager() = default; diff --git a/services/distributeddataservice/service/test/data_share_service_impl_test.cpp b/services/distributeddataservice/service/test/data_share_service_impl_test.cpp index 58efb56e4..65f79e4d5 100644 --- a/services/distributeddataservice/service/test/data_share_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/data_share_service_impl_test.cpp @@ -146,10 +146,10 @@ HWTEST_F(DataShareServiceImplTest, NotifyChange001, TestSize.Level1) { DataShareServiceImpl dataShareServiceImpl; std::string uri = SLIENT_ACCESS_URI; - auto result = dataShareServiceImpl.NotifyChange(uri); + auto result = dataShareServiceImpl.NotifyChange(uri, USER_TEST); EXPECT_EQ(result, true); - result = dataShareServiceImpl.NotifyChange(""); + result = dataShareServiceImpl.NotifyChange("", USER_TEST); EXPECT_EQ(result, false); } diff --git a/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp b/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp index 9b637f18a..467432cac 100644 --- a/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp +++ b/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp @@ -110,9 +110,9 @@ HWTEST_F(DataShareSubscriberManagersTest, Add, TestSize.Level1) nodes.emplace_back(node2); Template tpl(nodes, "select name1 as name from TBL00"); DataShare::Key key(DATA_SHARE_URI_TEST, tpltId.subscriberId_, tpltId.bundleName_); - auto result = TemplateManager::GetInstance().Add(key, context->currentUserId, tpl); + auto result = TemplateManager::GetInstance().Add(key, context->visitedUserId, tpl); EXPECT_EQ(result, DataShare::E_ERROR); - result = TemplateManager::GetInstance().Delete(key, context->currentUserId); + result = TemplateManager::GetInstance().Delete(key, context->visitedUserId); EXPECT_EQ(result, DataShare::E_ERROR); } @@ -210,7 +210,7 @@ HWTEST_F(DataShareSubscriberManagersTest, IsNotifyOnEnabled, TestSize.Level1) sptr observer; std::vector val; std::map, std::vector> callbacks; - PublishedDataSubscriberManager::GetInstance().PutInto(callbacks, val, key, observer); + PublishedDataSubscriberManager::GetInstance().PutInto(callbacks, val, key, observer, context->visitedUserId); std::vector publishedKeys; PublishedDataSubscriberManager::GetInstance().SetObserversNotifiedOnEnabled(publishedKeys); uint32_t tokenId = AccessTokenKit::GetHapTokenID(USER_TEST, BUNDLE_NAME_TEST, USER_TEST); -- Gitee From 7d78023d1b7b2605066257a10d1122b76a5535a2 Mon Sep 17 00:00:00 2001 From: zhangdi Date: Sun, 6 Apr 2025 03:42:07 +0000 Subject: [PATCH 128/225] update services/distributeddataservice/service/rdb/rdb_service_impl.cpp. Signed-off-by: zhangdi --- .../service/rdb/rdb_service_impl.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 482f3a958..baaff4ef0 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -1232,18 +1232,19 @@ int32_t RdbServiceImpl::RdbStatic::OnAppUpdate(const std::string &bundleName, in std::vector dataBase; if (MetaDataManager::GetInstance().LoadMeta(prefix, dataBase, true)) { for (const auto &database : dataBase) { - ZLOGD("Delete matedata store is :%{public}s", database.name.c_str()); MetaDataManager::GetInstance().DelMeta(database.GetKey(), true); + ZLOGD("del metadata store is: %{public}s; user is: %{public}s; bundleName is: %{public}s", + Anonymous::Change(database.name).c_str(), database.user.c_str(), database.bundleName.c_str()); StoreMetaData meta; meta.user = database.user; meta.deviceId = database.deviceId; meta.storeId = database.name; meta.bundleName = bundleName; Database base; - if (RdbSchemaConfig::GetDistributedSchema(meta, base) && !base.name.empty() && - !base.bundleName.empty()) { - ZLOGD("save metadata store is :%{public}s", base.name.c_str()); + if (RdbSchemaConfig::GetDistributedSchema(meta, base) && !base.name.empty() && !base.bundleName.empty()) { MetaDataManager::GetInstance().SaveMeta(base.GetKey(), base, true); + ZLOGD("save metadata store is: %{public}s; user is: %{public}s; bundleName is: %{public}s", + Anonymous::Change(base.name).c_str(), base.user.c_str(), base.bundleName.c_str()); } } } -- Gitee From fc73a75cfd3ac260f2abb3552487714021a8b63d Mon Sep 17 00:00:00 2001 From: linyifei Date: Thu, 27 Mar 2025 19:48:23 +0800 Subject: [PATCH 129/225] add subappId Signed-off-by: wanghuajian-6 --- .../src/session_manager/session_manager.cpp | 10 ++--- .../service/object/include/object_manager.h | 4 +- .../object/include/object_service_impl.h | 5 ++- .../service/object/src/object_manager.cpp | 38 +++++++++++++--- .../object/src/object_service_impl.cpp | 43 +++++++++++-------- .../service/udmf/store/runtime_store.cpp | 5 ++- .../service/udmf/udmf_service_impl.cpp | 10 ++++- 7 files changed, 78 insertions(+), 37 deletions(-) diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.cpp b/services/distributeddataservice/app/src/session_manager/session_manager.cpp index e13e43579..d1d8f05e3 100644 --- a/services/distributeddataservice/app/src/session_manager/session_manager.cpp +++ b/services/distributeddataservice/app/src/session_manager/session_manager.cpp @@ -48,11 +48,7 @@ Session SessionManager::GetSession(const SessionPoint &local, const std::string session.sourceDeviceId = local.deviceId; session.targetDeviceId = targetDeviceId; auto users = UserDelegate::GetInstance().GetRemoteUserStatus(targetDeviceId); - // system service - if (local.userId == UserDelegate::SYSTEM_USER) { - session.targetUserIds.push_back(UserDelegate::SYSTEM_USER); - } - + AclParams aclParams; if (!GetSendAuthParams(local, targetDeviceId, aclParams)) { ZLOGE("get send auth params failed:%{public}s", Anonymous::Change(targetDeviceId).c_str()); @@ -64,6 +60,8 @@ Session SessionManager::GetSession(const SessionPoint &local, const std::string aclParams.accCallee.userId = user.id; auto [isPermitted, isSameAccount] = AuthDelegate::GetInstance()->CheckAccess(local.userId, user.id, targetDeviceId, aclParams); + ZLOGD("targetDeviceId:%{public}s, user.id:%{public}d, isPermitted:%{public}d, isSameAccount: %{public}d", + Anonymous::Change(targetDeviceId).c_str(), user.id, isPermitted, isSameAccount); if (isPermitted) { auto it = std::find(session.targetUserIds.begin(), session.targetUserIds.end(), user.id); if (it == session.targetUserIds.end() && isSameAccount) { @@ -145,6 +143,8 @@ bool SessionManager::CheckSession(const SessionPoint &local, const SessionPoint } auto [isPermitted, isSameAccount] = AuthDelegate::GetInstance()->CheckAccess(local.userId, peer.userId, peer.deviceId, aclParams); + ZLOGD("peer.deviceId:%{public}s, peer.userId:%{public}d, isPermitted:%{public}d, isSameAccount: %{public}d", + Anonymous::Change(peer.deviceId).c_str(), peer.userId, isPermitted, isSameAccount); if (isPermitted && local.userId != UserDelegate::SYSTEM_USER) { isPermitted = Account::GetInstance()->IsUserForeground(local.userId); } diff --git a/services/distributeddataservice/service/object/include/object_manager.h b/services/distributeddataservice/service/object/include/object_manager.h index 2f4f6302c..a2f903436 100644 --- a/services/distributeddataservice/service/object/include/object_manager.h +++ b/services/distributeddataservice/service/object/include/object_manager.h @@ -202,8 +202,7 @@ private: + DmAdaper::GetInstance().GetLocalDevice().udid; }; std::recursive_mutex kvStoreMutex_; - std::mutex mutex_; - DistributedDB::KvStoreDelegateManager *kvStoreDelegateManager_ = nullptr; + std::shared_ptr kvStoreDelegateManager_ = nullptr; DistributedDB::KvStoreNbDelegate *delegate_ = nullptr; ObjectDataListener *objectDataListener_ = nullptr; sptr objectAssetsRecvListener_ = nullptr; @@ -214,7 +213,6 @@ private: ConcurrentMap callbacks_; std::shared_ptr executors_; DistributedData::AssetBindInfo ConvertBindInfo(ObjectStore::AssetBindInfo& bindInfo); - VBucket ConvertVBucket(ObjectStore::ValuesBucket &vBucket); ConcurrentMap> snapshots_; // key:bundleName_sessionId ConcurrentMap bindSnapshots_; // key:bundleName_storeName ConcurrentMap restoreStatus_; // key:bundleName+sessionId diff --git a/services/distributeddataservice/service/object/include/object_service_impl.h b/services/distributeddataservice/service/object/include/object_service_impl.h index 437d49e9e..e398edfac 100644 --- a/services/distributeddataservice/service/object/include/object_service_impl.h +++ b/services/distributeddataservice/service/object/include/object_service_impl.h @@ -17,6 +17,7 @@ #define DISTRIBUTEDDATASERVICE_OBJECT_SERVICE_H #include "feature/static_acts.h" +#include "metadata/store_meta_data.h" #include "object_manager.h" #include "object_service_stub.h" #include "visibility.h" @@ -40,7 +41,6 @@ public: int32_t DeleteSnapshot(const std::string &bundleName, const std::string &sessionId) override; int32_t IsBundleNameEqualTokenId( const std::string &bundleName, const std::string &sessionId, const uint32_t &tokenId); - void Clear(); int32_t ResolveAutoLaunch(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) override; int32_t OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &appId) override; int32_t OnInitialize() override; @@ -68,6 +68,9 @@ private: }; void RegisterObjectServiceInfo(); void RegisterHandler(); + int32_t SaveMetaData(StoreMetaData& saveMeta, const std::string &user, const std::string &account); + void UpdateMetaData(); + static Factory factory_; std::shared_ptr executors_; }; diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 3e3c554ff..588775802 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -313,7 +313,7 @@ int32_t ObjectStoreManager::Clear() return OBJECT_SUCCESS; } } - ZLOGD("user is change, need to change"); + ZLOGI("user changed, need to clear, userId:%{public}s", userId.c_str()); int32_t result = Open(); if (result != OBJECT_SUCCESS) { ZLOGE("Open failed, errCode = %{public}d", result); @@ -405,6 +405,22 @@ void ObjectStoreManager::NotifyChange(ObjectRecord &changedData) } } auto data = GetObjectData(changedData, saveInfo, hasAsset); + auto isSameAccount = DeviceManagerAdapter::GetInstance().IsSameAccount(saveInfo.sourceDeviceId); + if (!isSameAccount) { + ZLOGE("IsSameAccount failed. bundleName:%{public}s, source device:%{public}s", saveInfo.bundleName.c_str(), + Anonymous::Change(saveInfo.sourceDeviceId).c_str()); + std::vector> keys; + std::vector entries; + std::for_each(entries.begin(), entries.end(), [&keys](const DistributedDB::Entry &entry) { + keys.emplace_back(entry.key); + }); + auto status = delegate_->DeleteBatch(keys); + if (status != DistributedDB::DBStatus::OK) { + ZLOGE("Delete entries failed, bundleName:%{public}s, source device::%{public}s, status: %{public}d", + saveInfo.bundleName.c_str(), Anonymous::Change(saveInfo.sourceDeviceId).c_str(), status); + } + return; + } if (!hasAsset) { ObjectStore::RadarReporter::ReportStateStart(std::string(__FUNCTION__), ObjectStore::DATA_RESTORE, ObjectStore::DATA_RECV, ObjectStore::RADAR_SUCCESS, ObjectStore::START, saveInfo.bundleName); @@ -697,11 +713,15 @@ void ObjectStoreManager::DoNotifyWaitAssetTimeout(const std::string &objectKey) void ObjectStoreManager::SetData(const std::string &dataDir, const std::string &userId) { - ZLOGI("enter %{public}s", dataDir.c_str()); - kvStoreDelegateManager_ = - new DistributedDB::KvStoreDelegateManager(DistributedData::Bootstrap::GetInstance().GetProcessLabel(), userId); + ZLOGI("enter, user: %{public}s", userId.c_str()); + kvStoreDelegateManager_ = std::make_shared + (DistributedData::Bootstrap::GetInstance().GetProcessLabel(), userId); DistributedDB::KvStoreConfig kvStoreConfig { dataDir }; - kvStoreDelegateManager_->SetKvStoreConfig(kvStoreConfig); + auto status = kvStoreDelegateManager_->SetKvStoreConfig(kvStoreConfig); + if (status != DistributedDB::OK) { + ZLOGE("Set kvstore config failed, status: %{public}d", status); + return; + } userId_ = userId; } @@ -793,7 +813,7 @@ void ObjectStoreManager::ProcessOldEntry(const std::string &appId) { std::vector entries; auto status = delegate_->GetEntries(std::vector(appId.begin(), appId.end()), entries); - if (status != DistributedDB::DBStatus::NOT_FOUND) { + if (status == DistributedDB::DBStatus::NOT_FOUND) { ZLOGI("Get old entries empty, bundleName: %{public}s", appId.c_str()); return; } @@ -869,12 +889,16 @@ int32_t ObjectStoreManager::SyncOnStore( const std::string &prefix, const std::vector &deviceList, SyncCallBack &callback) { std::vector syncDevices; - for (auto &device : deviceList) { + for (auto const &device : deviceList) { if (device == LOCAL_DEVICE) { ZLOGI("Save to local, do not need sync, prefix: %{public}s", prefix.c_str()); callback({{LOCAL_DEVICE, OBJECT_SUCCESS}}); return OBJECT_SUCCESS; } + if (!DeviceManagerAdapter::GetInstance().IsSameAccount(device)) { + ZLOGE("IsSameAccount failed. device:%{public}s", Anonymous::Change(device).c_str()); + continue; + } syncDevices.emplace_back(DmAdaper::GetInstance().GetUuidByNetworkId(device)); } if (syncDevices.empty()) { diff --git a/services/distributeddataservice/service/object/src/object_service_impl.cpp b/services/distributeddataservice/service/object/src/object_service_impl.cpp index fdb08505e..c09b58286 100644 --- a/services/distributeddataservice/service/object/src/object_service_impl.cpp +++ b/services/distributeddataservice/service/object/src/object_service_impl.cpp @@ -137,6 +137,21 @@ int32_t ObjectServiceImpl::OnInitialize() const std::string accountId = DistributedData::AccountDelegate::GetInstance()->GetCurrentAccountId(); const auto userId = DistributedData::AccountDelegate::GetInstance()->GetUserByToken(token); StoreMetaData saveMeta; + SaveMetaData(saveMeta, std::to_string(userId), accountId); + ObjectStoreManager::GetInstance()->SetData(saveMeta.dataDir, std::to_string(userId)); + RegisterObjectServiceInfo(); + RegisterHandler(); + ObjectDmsHandler::GetInstance().RegisterDmsEvent(); + return OBJECT_SUCCESS; +} + +int32_t ObjectServiceImpl::SaveMetaData(StoreMetaData &saveMeta, const std::string &user, const std::string &account) +{ + auto localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + if (localDeviceId.empty()) { + ZLOGE("failed to get local device id"); + return OBJECT_INNER_ERROR; + } saveMeta.appType = "default"; saveMeta.deviceId = localDeviceId; saveMeta.storeId = DistributedObject::ObjectCommon::OBJECTSTORE_DB_STOREID; @@ -145,16 +160,15 @@ int32_t ObjectServiceImpl::OnInitialize() saveMeta.isEncrypt = false; saveMeta.bundleName = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); saveMeta.appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); - saveMeta.user = std::to_string(userId); - saveMeta.account = accountId; - saveMeta.tokenId = token; + saveMeta.user = user; + saveMeta.account = account; + saveMeta.tokenId = IPCSkeleton::GetCallingTokenID(); saveMeta.securityLevel = DistributedKv::SecurityLevel::S1; saveMeta.area = DistributedKv::Area::EL1; saveMeta.uid = IPCSkeleton::GetCallingUid(); saveMeta.storeType = ObjectDistributedType::OBJECT_SINGLE_VERSION; saveMeta.dataType = DistributedKv::DataType::TYPE_DYNAMICAL; saveMeta.dataDir = DistributedData::DirectoryManager::GetInstance().GetStorePath(saveMeta); - ObjectStoreManager::GetInstance()->SetData(saveMeta.dataDir, std::to_string(userId)); bool isSaved = DistributedData::MetaDataManager::GetInstance().SaveMeta(saveMeta.GetKey(), saveMeta) && DistributedData::MetaDataManager::GetInstance().SaveMeta(saveMeta.GetKey(), saveMeta, true); if (!isSaved) { @@ -168,18 +182,18 @@ int32_t ObjectServiceImpl::OnInitialize() if (!isSaved) { ZLOGE("Save appIdMeta failed"); } - ZLOGI("SaveMeta success appId %{public}s, storeId %{public}s", - saveMeta.appId.c_str(), saveMeta.GetStoreAlias().c_str()); - RegisterObjectServiceInfo(); - RegisterHandler(); - ObjectDmsHandler::GetInstance().RegisterDmsEvent(); + ZLOGI("SaveMeta success appId %{public}s, storeId %{public}s", saveMeta.appId.c_str(), + saveMeta.GetStoreAlias().c_str()); return OBJECT_SUCCESS; } int32_t ObjectServiceImpl::OnUserChange(uint32_t code, const std::string &user, const std::string &account) { if (code == static_cast(AccountStatus::DEVICE_ACCOUNT_SWITCHED)) { - Clear(); + int32_t status = ObjectStoreManager::GetInstance()->Clear(); + if (status != OBJECT_SUCCESS) { + ZLOGE("Clear fail user:%{public}s, status: %{public}d", user.c_str(), status); + } } return Feature::OnUserChange(code, user, account); } @@ -273,15 +287,6 @@ int32_t ObjectServiceImpl::IsBundleNameEqualTokenId( return OBJECT_SUCCESS; } -void ObjectServiceImpl::Clear() -{ - ZLOGI("begin."); - int32_t status = ObjectStoreManager::GetInstance()->Clear(); - if (status != OBJECT_SUCCESS) { - ZLOGE("save fail %{public}d", status); - } -} - int32_t ObjectServiceImpl::ObjectStatic::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) { int32_t result = ObjectStoreManager::GetInstance()->DeleteByAppId(bundleName, user); diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index 942cfcb92..764c43230 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -518,7 +518,10 @@ void RuntimeStore::SetDelegateManager(const std::string &dataDir, const std::str { delegateManager_ = std::make_shared(appId, userId, subUser); DistributedDB::KvStoreConfig kvStoreConfig { dataDir }; - delegateManager_->SetKvStoreConfig(kvStoreConfig); + auto status = delegateManager_->SetKvStoreConfig(kvStoreConfig); + if (status != DBStatus::OK) { + ZLOGE("SetKvStoreConfig failed, status: %{public}d.", status); + } } Status RuntimeStore::GetEntries(const std::string &dataPrefix, std::vector &entries) diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 28bdac177..02414efdf 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -535,6 +535,14 @@ int32_t UdmfServiceImpl::Sync(const QueryOption &query, const std::vector syncDevices; + for (auto const &device : devices) { + if (!DistributedData::DeviceManagerAdapter::GetInstance().IsSameAccount(device)) { + ZLOGW("is diff account. device:%{public}s", DistributedData::Anonymous::Change(device).c_str()); + continue; + } + syncDevices.emplace_back(device); + } RegisterAsyncProcessInfo(query.key); auto store = StoreCache::GetInstance().GetStore(key.intention); if (store == nullptr) { @@ -556,7 +564,7 @@ int32_t UdmfServiceImpl::Sync(const QueryOption &query, const std::vectorSync(devices, callback) != E_OK) { + if (store->Sync(syncDevices, callback) != E_OK) { ZLOGE("Store sync failed:%{public}s", key.intention.c_str()); RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, E_DB_ERROR, BizState::DFX_END); -- Gitee From 8aac6a9a2bc4d048bbe862a29ec9fd59368eaf02 Mon Sep 17 00:00:00 2001 From: gecheng Date: Mon, 7 Apr 2025 14:58:31 +0800 Subject: [PATCH 130/225] =?UTF-8?q?=E5=A2=9E=E5=8A=A0UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gecheng --- .../framework/test/store_test.cpp | 64 +++++++++++++++++++ .../service/cloud/sync_manager.h | 7 +- 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/framework/test/store_test.cpp b/services/distributeddataservice/framework/test/store_test.cpp index 7bc31f25e..f84c0aa0d 100644 --- a/services/distributeddataservice/framework/test/store_test.cpp +++ b/services/distributeddataservice/framework/test/store_test.cpp @@ -30,6 +30,8 @@ using namespace testing::ext; using namespace OHOS::DistributedData; namespace OHOS::Test { +static constexpr const char *TEST_CLOUD_STORE = "test_cloud_store"; + class GeneralValueTest : public testing::Test { public: static void SetUpTestCase(void){}; @@ -260,4 +262,66 @@ HWTEST_F(AutoCacheTest, GetDBStore, TestSize.Level2) meta.area = GeneralStore::EL5; EXPECT_NE(AutoCache::GetInstance().GetDBStore(meta, watchers).first, GeneralError::E_SCREEN_LOCKED); } + +/** +* @tc.name: CloseStore001 +* @tc.desc: AutoCache CloseStore001 +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(AutoCacheTest, CloseStore001, TestSize.Level2) +{ + GeneralStoreMock* store = new (std::nothrow) GeneralStoreMock(); + ASSERT_NE(store, nullptr); + AutoCache::Watchers watchers; + mock_->isLocked_ = true; + StoreMetaData meta; + meta.area = GeneralStore::EL1; + meta.dataDir = 'abc'; + uint32_t tokenId = 123; + std::string storeId = TEST_CLOUD_STORE; + std::string userId = ""; + AutoCache autoCache; + autoCache.stores_.Computer(tokenId, + [this, &meta, &watchers, &store](auto &, std::map &stores) -> bool { + std::string storeKey = "key"; + stores.emplace(std::piecewise_construct, std::forward_as_tuple(storeKey), + std::forward_as_tuple(store, watchers, 0, meta)); + return !stores.empty(); + }); + autoCache.CloseStore(tokenId, storeId, userId); + EXPECT_TRUE(autoCache.stores_.empty()); + } + + /** +* @tc.name: CloseStore002 +* @tc.desc: AutoCache CloseStore002 +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(AutoCacheTest, CloseStore002, TestSize.Level2) +{ + GeneralStoreMock* store = new (std::nothrow) GeneralStoreMock(); + ASSERT_NE(store, nullptr); + AutoCache::Watchers watchers; + mock_->isLocked_ = true; + StoreMetaData meta; + meta.area = GeneralStore::EL4; + meta.dataDir = 'abc'; + uint32_t tokenId = 123; + std::string storeId = TEST_CLOUD_STORE; + std::string userId = ""; + AutoCache autoCache; + autoCache.stores_.Computer(tokenId, + [this, &meta, &watchers, &store](auto &, std::map &stores) -> bool { + std::string storeKey = "key"; + stores.emplace(std::piecewise_construct, std::forward_as_tuple(storeKey), + std::forward_as_tuple(store, watchers, 0, meta)); + return !stores.empty(); + }); + autoCache.CloseStore(tokenId, storeId, userId); + EXPECT_FALSE(autoCache.stores_.empty()); + } } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/cloud/sync_manager.h b/services/distributeddataservice/service/cloud/sync_manager.h index f986bd04b..bc19b107b 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.h +++ b/services/distributeddataservice/service/cloud/sync_manager.h @@ -144,6 +144,10 @@ private: static std::pair GetLastResults(std::map &infos); static std::pair GetLastSyncInfoFromMeta(const QueryKey &queryKey); static void SaveLastSyncInfo(const QueryKey &queryKey, CloudLastSyncInfo &&info); + static void BatchReport(int32_t userId, const TraceIds &traceIds, SyncStage syncStage, int32_t errCode, + const std::string &message = ""); + static void ReportSyncEvent(const DistributedData::SyncEvent &evt, DistributedDataDfx::BizState bizState, + int32_t code); Task GetSyncTask(int32_t times, bool retry, RefCount ref, SyncInfo &&syncInfo); void UpdateSchema(const SyncInfo &syncInfo); std::function GetSyncHandler(Retryer retryer); @@ -164,13 +168,10 @@ private: Retryer retryer, int32_t triggerMode, const std::string &prepareTraceId, int32_t user); void BatchUpdateFinishState(const std::vector> &cloudSyncInfos, int32_t code); bool NeedSaveSyncInfo(const QueryKey &queryKey); - void BatchReport(int32_t userId, const TraceIds &traceIds, SyncStage syncStage, int32_t errCode, - const std::string &message = ""); void StartCloudSync(const DistributedData::SyncEvent &evt, const StoreMetaData &meta, const AutoCache::Store &store, Retryer retryer, DistributedData::GenDetails &details); std::pair GetMetaData(const StoreInfo &storeInfo); void AddCompensateSync(const StoreMetaData &meta); - void ReportSyncEvent(const DistributedData::SyncEvent &evt, DistributedDataDfx::BizState bizState, int32_t code); static std::atomic genId_; std::shared_ptr executor_; ConcurrentMap actives_; -- Gitee From 5e6da5776901411c23e245c289e3401f6aea51dd Mon Sep 17 00:00:00 2001 From: gecheng Date: Mon, 7 Apr 2025 15:06:55 +0800 Subject: [PATCH 131/225] =?UTF-8?q?=E5=A2=9E=E5=8A=A0UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gecheng --- .../framework/test/store_test.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/services/distributeddataservice/framework/test/store_test.cpp b/services/distributeddataservice/framework/test/store_test.cpp index f84c0aa0d..24e8f5218 100644 --- a/services/distributeddataservice/framework/test/store_test.cpp +++ b/services/distributeddataservice/framework/test/store_test.cpp @@ -278,12 +278,12 @@ HWTEST_F(AutoCacheTest, CloseStore001, TestSize.Level2) mock_->isLocked_ = true; StoreMetaData meta; meta.area = GeneralStore::EL1; - meta.dataDir = 'abc'; + meta.dataDir = "abc"; uint32_t tokenId = 123; std::string storeId = TEST_CLOUD_STORE; std::string userId = ""; AutoCache autoCache; - autoCache.stores_.Computer(tokenId, + autoCache.stores_.Compute(tokenId, [this, &meta, &watchers, &store](auto &, std::map &stores) -> bool { std::string storeKey = "key"; stores.emplace(std::piecewise_construct, std::forward_as_tuple(storeKey), @@ -291,10 +291,10 @@ HWTEST_F(AutoCacheTest, CloseStore001, TestSize.Level2) return !stores.empty(); }); autoCache.CloseStore(tokenId, storeId, userId); - EXPECT_TRUE(autoCache.stores_.empty()); - } + EXPECT_TRUE(autoCache.stores_.Empty()); +} - /** +/** * @tc.name: CloseStore002 * @tc.desc: AutoCache CloseStore002 * @tc.type: FUNC @@ -309,12 +309,12 @@ HWTEST_F(AutoCacheTest, CloseStore002, TestSize.Level2) mock_->isLocked_ = true; StoreMetaData meta; meta.area = GeneralStore::EL4; - meta.dataDir = 'abc'; + meta.dataDir = "abc"; uint32_t tokenId = 123; std::string storeId = TEST_CLOUD_STORE; std::string userId = ""; AutoCache autoCache; - autoCache.stores_.Computer(tokenId, + autoCache.stores_.Compute(tokenId, [this, &meta, &watchers, &store](auto &, std::map &stores) -> bool { std::string storeKey = "key"; stores.emplace(std::piecewise_construct, std::forward_as_tuple(storeKey), @@ -322,6 +322,6 @@ HWTEST_F(AutoCacheTest, CloseStore002, TestSize.Level2) return !stores.empty(); }); autoCache.CloseStore(tokenId, storeId, userId); - EXPECT_FALSE(autoCache.stores_.empty()); - } + EXPECT_FALSE(autoCache.stores_.Empty()); +} } // namespace OHOS::Test \ No newline at end of file -- Gitee From 0f6f0afa628dc066f3b8a96c5b713504212a5801 Mon Sep 17 00:00:00 2001 From: gecheng Date: Mon, 7 Apr 2025 17:40:11 +0800 Subject: [PATCH 132/225] =?UTF-8?q?=E5=86=85=E5=AD=98=E6=B3=84=E9=9C=B2?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gecheng --- .../rust/extension/cloud_server_impl.cpp | 12 ++++++++++-- .../rust/extension/cloud_server_impl.h | 1 + 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/rust/extension/cloud_server_impl.cpp b/services/distributeddataservice/rust/extension/cloud_server_impl.cpp index f47a26209..0d6c8e8a5 100644 --- a/services/distributeddataservice/rust/extension/cloud_server_impl.cpp +++ b/services/distributeddataservice/rust/extension/cloud_server_impl.cpp @@ -28,11 +28,19 @@ #include "utils/anonymous.h" namespace OHOS::CloudData { -__attribute__((used)) static bool g_isInit = - DistributedData::CloudServer::RegisterCloudInstance(new (std::nothrow) CloudServerImpl()); +__attribute__((used)) static bool g_isInit = CloudServerImpl::Init(); using namespace Security::AccessToken; using DBMetaMgr = DistributedData::MetaDataManager; using Anonymous = DistributedData::Anonymous; + +bool CloudServerImpl::Init() +{ + static CloudServerImpl cloudServerInstance; + static std::once_flag onceFlag; + std::call_once(onceFlag, [&]() { DistributedData::CloudServer::RegisterCloudInstance(&cloudServerInstance); }); + return true; +} + std::pair CloudServerImpl::GetServerInfo(int32_t userId, bool needSpaceInfo) { DBCloudInfo result; diff --git a/services/distributeddataservice/rust/extension/cloud_server_impl.h b/services/distributeddataservice/rust/extension/cloud_server_impl.h index bd7c185e7..debb7aadf 100644 --- a/services/distributeddataservice/rust/extension/cloud_server_impl.h +++ b/services/distributeddataservice/rust/extension/cloud_server_impl.h @@ -36,6 +36,7 @@ using DBRelation = DBSub::Relation; using DBErr = DistributedData::GeneralError; class CloudServerImpl : public DistributedData::CloudServer { public: + static bool Init(); std::pair GetServerInfo(int32_t userId, bool needSpaceInfo) override; std::pair GetAppSchema(int32_t userId, const std::string &bundleName) override; int32_t Subscribe(int32_t userId, const std::map> &dbs) override; -- Gitee From 367820f7f0f3bc1342da683dea9f105ecb16453e Mon Sep 17 00:00:00 2001 From: gecheng Date: Mon, 7 Apr 2025 17:51:34 +0800 Subject: [PATCH 133/225] =?UTF-8?q?=E5=86=85=E5=AD=98=E6=B3=84=E9=9C=B2?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gecheng --- .../distributeddataservice/rust/extension/cloud_server_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/rust/extension/cloud_server_impl.cpp b/services/distributeddataservice/rust/extension/cloud_server_impl.cpp index 0d6c8e8a5..6e9a020f4 100644 --- a/services/distributeddataservice/rust/extension/cloud_server_impl.cpp +++ b/services/distributeddataservice/rust/extension/cloud_server_impl.cpp @@ -28,7 +28,7 @@ #include "utils/anonymous.h" namespace OHOS::CloudData { -__attribute__((used)) static bool g_isInit = CloudServerImpl::Init(); +__attribute__((used)) static bool g_isInit = CloudServerImpl::Init(); using namespace Security::AccessToken; using DBMetaMgr = DistributedData::MetaDataManager; using Anonymous = DistributedData::Anonymous; -- Gitee From dffc51bd20d4df7ac64dd96b83460b05bb929a52 Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Mon, 7 Apr 2025 20:17:47 +0800 Subject: [PATCH 134/225] fix ut Signed-off-by: wanghuajian-6 --- .../src/session_manager/session_manager.cpp | 6 +++++- .../service/object/src/object_manager.cpp | 15 ++++++++----- .../service/test/BUILD.gn | 4 ++++ .../test/mock/device_manager_adapter_mock.cpp | 8 +++++++ .../test/mock/device_manager_adapter_mock.h | 2 ++ .../service/test/object_manager_test.cpp | 21 +++++++++++++++++++ 6 files changed, 50 insertions(+), 6 deletions(-) diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.cpp b/services/distributeddataservice/app/src/session_manager/session_manager.cpp index d1d8f05e3..4b5d6eaae 100644 --- a/services/distributeddataservice/app/src/session_manager/session_manager.cpp +++ b/services/distributeddataservice/app/src/session_manager/session_manager.cpp @@ -48,7 +48,11 @@ Session SessionManager::GetSession(const SessionPoint &local, const std::string session.sourceDeviceId = local.deviceId; session.targetDeviceId = targetDeviceId; auto users = UserDelegate::GetInstance().GetRemoteUserStatus(targetDeviceId); - + // system service + if (local.userId == UserDelegate::SYSTEM_USER) { + session.targetUserIds.push_back(UserDelegate::SYSTEM_USER); + } + AclParams aclParams; if (!GetSendAuthParams(local, targetDeviceId, aclParams)) { ZLOGE("get send auth params failed:%{public}s", Anonymous::Change(targetDeviceId).c_str()); diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 588775802..31534759a 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -409,12 +409,17 @@ void ObjectStoreManager::NotifyChange(ObjectRecord &changedData) if (!isSameAccount) { ZLOGE("IsSameAccount failed. bundleName:%{public}s, source device:%{public}s", saveInfo.bundleName.c_str(), Anonymous::Change(saveInfo.sourceDeviceId).c_str()); + auto status = Open(); + if (status != OBJECT_SUCCESS) { + ZLOGE("Open failed, bundleName:%{public}s, source device::%{public}s, status: %{public}d", + saveInfo.bundleName.c_str(), Anonymous::Change(saveInfo.sourceDeviceId).c_str(), status); + return; + } std::vector> keys; - std::vector entries; - std::for_each(entries.begin(), entries.end(), [&keys](const DistributedDB::Entry &entry) { - keys.emplace_back(entry.key); - }); - auto status = delegate_->DeleteBatch(keys); + for (const auto &[key, value] : changedData) { + keys.emplace_back(key.begin(), key.end()); + } + status = delegate_->DeleteBatch(keys); if (status != DistributedDB::DBStatus::OK) { ZLOGE("Delete entries failed, bundleName:%{public}s, source device::%{public}s, status: %{public}d", saveInfo.bundleName.c_str(), Anonymous::Change(saveInfo.sourceDeviceId).c_str(), status); diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 1a0d4a4d9..78ba03d29 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -774,6 +774,7 @@ ohos_unittest("ObjectManagerTest") { "../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_test.cpp", "object_service_impl_test.cpp", @@ -786,6 +787,7 @@ ohos_unittest("ObjectManagerTest") { "${dataobject_path}/frameworks/innerkitsimpl/include/common", "${dataobject_path}/interfaces/innerkits", "${data_service_path}/adapter/include/utils", + "${data_service_path}/service/test/mock", ] configs = [ ":module_private_config" ] @@ -799,6 +801,8 @@ ohos_unittest("ObjectManagerTest") { "dfs_service:cloudsync_asset_kit_inner", "dfs_service:distributed_file_daemon_kit_inner", "dmsfwk:distributed_sdk", + "googletest:gmock_main", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", diff --git a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp index fae2fb0f5..7bc2b7e82 100644 --- a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp +++ b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp @@ -50,6 +50,14 @@ bool DeviceManagerAdapter::IsSameAccount(const AccessCaller &accCaller, const Ac return BDeviceManagerAdapter::deviceManagerAdapter->IsSameAccount(accCaller, accCallee); } +bool DeviceManagerAdapter::IsSameAccount(const std::string &devicdId) +{ + if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { + return false; + } + return BDeviceManagerAdapter::deviceManagerAdapter->IsSameAccount(devicdId); +} + bool DeviceManagerAdapter::CheckAccessControl(const AccessCaller &accCaller, const AccessCallee &accCallee) { if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { diff --git a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h index 9c1114633..2a47a5510 100644 --- a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h +++ b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h @@ -33,6 +33,7 @@ public: virtual Status StartWatchDeviceChange(const AppDeviceChangeListener *, const PipeInfo &) = 0; virtual Status StopWatchDeviceChange(const AppDeviceChangeListener *, const PipeInfo &) = 0; virtual bool IsSameAccount(const AccessCaller &, const AccessCallee &) = 0; + virtual bool IsSameAccount(const std::string &) = 0; virtual std::string GetUuidByNetworkId(const std::string &); virtual DeviceInfo GetDeviceInfo(const std::string &); virtual std::string ToNetworkID(const std::string &); @@ -51,6 +52,7 @@ public: MOCK_METHOD(Status, StartWatchDeviceChange, (const AppDeviceChangeListener *, const PipeInfo &)); MOCK_METHOD(Status, StopWatchDeviceChange, (const AppDeviceChangeListener *, const PipeInfo &)); MOCK_METHOD(bool, IsSameAccount, (const AccessCaller &, const AccessCallee &)); + MOCK_METHOD(bool, IsSameAccount, (const std::string &)); MOCK_METHOD(std::string, GetUuidByNetworkId, (const std::string &)); MOCK_METHOD(DeviceInfo, GetDeviceInfo, (const std::string &)); MOCK_METHOD(std::string, ToNetworkID, (const std::string &)); diff --git a/services/distributeddataservice/service/test/object_manager_test.cpp b/services/distributeddataservice/service/test/object_manager_test.cpp index 835dca5b6..dfc4bf24a 100644 --- a/services/distributeddataservice/service/test/object_manager_test.cpp +++ b/services/distributeddataservice/service/test/object_manager_test.cpp @@ -20,6 +20,7 @@ #include #include +#include "device_manager_adapter_mock.h" #include "executor_pool.h" #include "kv_store_nb_delegate_mock.h" #include "object_types.h" @@ -27,6 +28,8 @@ using namespace testing::ext; using namespace OHOS::DistributedObject; +using namespace std; +using namespace testing; using AssetValue = OHOS::CommonType::AssetValue; using RestoreStatus = OHOS::DistributedObject::ObjectStoreManager::RestoreStatus; namespace OHOS::Test { @@ -35,6 +38,8 @@ class ObjectManagerTest : public testing::Test { public: void SetUp(); void TearDown(); + static void SetUpTestCase(void); + static void TearDownTestCase(void); protected: Asset asset_; @@ -52,6 +57,7 @@ protected: pid_t pid_ = 10; uint32_t tokenId_ = 100; AssetValue assetValue_; + static inline std::shared_ptr devMgrAdapterMock = nullptr; }; void ObjectManagerTest::SetUp() @@ -91,6 +97,18 @@ void ObjectManagerTest::SetUp() assetBindInfo_ = AssetBindInfo; } +void ObjectManagerTest::SetUpTestCase(void) +{ + devMgrAdapterMock = make_shared(); + BDeviceManagerAdapter::deviceManagerAdapter = devMgrAdapterMock; +} + +void ObjectManagerTest::TearDownTestCase(void) +{ + BDeviceManagerAdapter::deviceManagerAdapter = nullptr; + devMgrAdapterMock = nullptr; +} + void ObjectManagerTest::TearDown() {} /** @@ -349,6 +367,7 @@ HWTEST_F(ObjectManagerTest, NotifyChange002, TestSize.Level0) data.insert_or_assign(assetPrefix + ObjectStore::MODIFY_TIME_SUFFIX, value); data.insert_or_assign(assetPrefix + ObjectStore::SIZE_SUFFIX, value); data.insert_or_assign("testkey", value); + EXPECT_CALL(*devMgrAdapterMock, IsSameAccount(_)).WillOnce(Return(true)); manager->NotifyChange(data); EXPECT_TRUE(manager->restoreStatus_.Contains(bundleName+sessionId)); auto [has, taskId] = manager->objectTimer_.Find(bundleName+sessionId); @@ -533,10 +552,12 @@ HWTEST_F(ObjectManagerTest, SyncOnStore001, TestSize.Level0) 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); } -- Gitee From c693d7d41d1a3b3bd478553a9b0124a904641c9d Mon Sep 17 00:00:00 2001 From: gecheng Date: Mon, 7 Apr 2025 21:35:39 +0800 Subject: [PATCH 135/225] =?UTF-8?q?=E9=9D=99=E6=80=81=E5=91=8A=E8=AD=A6?= =?UTF-8?q?=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gecheng --- .../distributeddataservice/rust/extension/cloud_server_impl.cpp | 2 +- services/distributeddataservice/service/cloud/sync_manager.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/rust/extension/cloud_server_impl.cpp b/services/distributeddataservice/rust/extension/cloud_server_impl.cpp index 6e9a020f4..e5413cff2 100644 --- a/services/distributeddataservice/rust/extension/cloud_server_impl.cpp +++ b/services/distributeddataservice/rust/extension/cloud_server_impl.cpp @@ -552,7 +552,7 @@ int32_t CloudServerImpl::Unsubscribe(int32_t userId, const std::mapsecond); + uint32_t subId = static_cast(std::atoi(it->second.c_str())); if (OhCloudExtVectorPush(relation, &subId, sizeof(uint32_t)) != ERRNO_SUCCESS) { return DBErr::E_ERROR; } diff --git a/services/distributeddataservice/service/cloud/sync_manager.cpp b/services/distributeddataservice/service/cloud/sync_manager.cpp index 933cd92cb..adb7e9e53 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.cpp +++ b/services/distributeddataservice/service/cloud/sync_manager.cpp @@ -1006,7 +1006,7 @@ void SyncManager::CleanCompensateSync(int32_t userId) void SyncManager::AddCompensateSync(const StoreMetaData &meta) { - compensateSyncInfos_.Compute(std::stoi(meta.user), + compensateSyncInfos_.Compute(std::atoi(meta.user.c_str()), [&meta](auto &, std::map> &apps) { apps[meta.bundleName].insert(meta.storeId); return true; -- Gitee From aea219e3a486364d435605cb22004959da656042 Mon Sep 17 00:00:00 2001 From: gecheng Date: Tue, 8 Apr 2025 11:28:51 +0800 Subject: [PATCH 136/225] =?UTF-8?q?=E9=9D=99=E6=80=81=E5=91=8A=E8=AD=A6?= =?UTF-8?q?=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gecheng --- .../service/crypto/src/crypto_manager.cpp | 4 ++-- .../service/object/src/object_manager.cpp | 2 +- .../distributeddataservice/service/rdb/rdb_general_store.cpp | 2 +- .../service/test/rdb_general_store_test.cpp | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/services/distributeddataservice/service/crypto/src/crypto_manager.cpp b/services/distributeddataservice/service/crypto/src/crypto_manager.cpp index 16a775464..e278c678f 100644 --- a/services/distributeddataservice/service/crypto/src/crypto_manager.cpp +++ b/services/distributeddataservice/service/crypto/src/crypto_manager.cpp @@ -64,7 +64,7 @@ bool AddHksParams(HksParamSet *params, const CryptoManager::ParamConfig ¶mCo }; if (paramConfig.storageLevel > HKS_AUTH_STORAGE_LEVEL_DE) { hksParam.emplace_back( - HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::stoi(paramConfig.userId) }); + HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::atoi(paramConfig.userId.c_str()) }); } auto ret = HksAddParams(params, aes256Param, sizeof(aes256Param) / sizeof(aes256Param[0])); @@ -100,7 +100,7 @@ int32_t GetRootKeyParams(HksParamSet *¶ms, uint32_t storageLevel, const std: { .tag = HKS_TAG_AUTH_STORAGE_LEVEL, .uint32Param = storageLevel }, }; if (storageLevel > HKS_AUTH_STORAGE_LEVEL_DE) { - hksParam.emplace_back(HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::stoi(userId) }); + hksParam.emplace_back(HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::atoi(userId.c_str()) }); } ret = HksAddParams(params, hksParam.data(), hksParam.size()); diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 369c3eef8..0c2229e9d 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -536,7 +536,7 @@ void ObjectStoreManager::PullAssets(const std::map& d for (const auto& [objectId, assets] : changedAssets) { std::string networkId = DmAdaper::GetInstance().ToNetworkID(saveInfo.sourceDeviceId); auto block = std::make_shared>>(WAIT_TIME, std::tuple{ true, true }); - ObjectAssetLoader::GetInstance()->TransferAssetsAsync(std::stoi(GetCurrentUser()), + ObjectAssetLoader::GetInstance()->TransferAssetsAsync(std::atoi(GetCurrentUser().c_str()), saveInfo.bundleName, networkId, assets, [this, block](bool success) { block->SetValue({ false, success }); }); diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.cpp b/services/distributeddataservice/service/rdb/rdb_general_store.cpp index b8dc6345e..55beb04f8 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.cpp +++ b/services/distributeddataservice/service/rdb/rdb_general_store.cpp @@ -141,7 +141,7 @@ void RdbGeneralStore::InitStoreInfo(const StoreMetaData &meta) storeInfo_.bundleName = meta.bundleName; storeInfo_.storeName = meta.storeId; storeInfo_.instanceId = meta.instanceId; - storeInfo_.user = std::stoi(meta.user); + storeInfo_.user = std::atoi(meta.user.c_str()); storeInfo_.deviceId = DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid; } diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index de1ef193c..6f36ac141 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -393,7 +393,7 @@ HWTEST_F(RdbGeneralStoreTest, Close, TestSize.Level1) { auto store = new (std::nothrow) RdbGeneralStore(metaData_); ASSERT_NE(store, nullptr); - auto result = store->IsBound(std::stoi(metaData_.user)); + auto result = store->IsBound(std::atoi(metaData_.user.c_str())); EXPECT_EQ(result, false); EXPECT_EQ(store->delegate_, nullptr); auto ret = store->Close(); -- Gitee From 2167999b17939a86b7ca37d14ce5e3c2b5fbee30 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Tue, 8 Apr 2025 06:35:03 +0000 Subject: [PATCH 137/225] =?UTF-8?q?=E6=9B=BF=E6=8D=A2std:stoi=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E6=9B=BF=E6=8D=A2-0408?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .../service/kvdb/kvdb_general_store.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp index 957320389..cb14bf433 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp @@ -78,6 +78,7 @@ const std::map KVDBGeneralStore::dbStatusMap }; constexpr uint32_t LOCK_TIMEOUT = 3600; // second +static constexpr int DECIMAL_BASE = 10; // decimal base static DBSchema GetDBSchema(const Database &database) { DBSchema schema; @@ -201,7 +202,18 @@ KVDBGeneralStore::KVDBGeneralStore(const StoreMetaData &meta) storeInfo_.bundleName = meta.bundleName; storeInfo_.storeName = meta.storeId; storeInfo_.instanceId = meta.instanceId; - storeInfo_.user = std::stoi(meta.user); + char *endptr = nullptr; + errno = 0; + long userLong = strtol(meta.user, &endptr, DECIMAL_BASE); + if (endptr == nullptr || endptr == meta.user || *endptr != '\0') { + ZLOGE("User:%{public}s is invalid", meta.user); + return; + } + if (errno == ERANGE || userLong >= INT32_MAX || userLong <= INT32_MIN) { + ZLOGE("User:%{public}s is out of range", meta.user); + return; + } + storeInfo_.user = static_cast(userLong); enableCloud_ = meta.enableCloud; } -- Gitee From b9c1327922db8ba614d516dcad39cc28e2d6f28a Mon Sep 17 00:00:00 2001 From: suoqilong Date: Tue, 8 Apr 2025 06:59:52 +0000 Subject: [PATCH 138/225] =?UTF-8?q?=E6=9B=BF=E6=8D=A2std:stoi=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E6=9B=BF=E6=8D=A2-0408?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .../service/kvdb/kvdb_general_store.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp index cb14bf433..b11b56fa4 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp @@ -204,13 +204,13 @@ KVDBGeneralStore::KVDBGeneralStore(const StoreMetaData &meta) storeInfo_.instanceId = meta.instanceId; char *endptr = nullptr; errno = 0; - long userLong = strtol(meta.user, &endptr, DECIMAL_BASE); - if (endptr == nullptr || endptr == meta.user || *endptr != '\0') { - ZLOGE("User:%{public}s is invalid", meta.user); + long userLong = strtol(meta.user.c_str(), &endptr, DECIMAL_BASE); + if (endptr == nullptr || endptr == meta.user.c_str() || *endptr != '\0') { + ZLOGE("User:%{public}s is invalid", meta.user.c_str()); return; } if (errno == ERANGE || userLong >= INT32_MAX || userLong <= INT32_MIN) { - ZLOGE("User:%{public}s is out of range", meta.user); + ZLOGE("User:%{public}s is out of range", meta.user.c_str()); return; } storeInfo_.user = static_cast(userLong); -- Gitee From 4ad5569f961335ce0bf5685327f94f3bcd94d71e Mon Sep 17 00:00:00 2001 From: suoqilong Date: Tue, 8 Apr 2025 07:08:27 +0000 Subject: [PATCH 139/225] =?UTF-8?q?=E5=AE=89=E5=85=A8=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=97=AE=E9=A2=98=E6=95=B4=E6=94=B9-0408?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .../distributeddataservice/adapter/account/BUILD.gn | 5 +---- .../adapter/communicator/BUILD.gn | 5 +---- services/distributeddataservice/adapter/dfx/BUILD.gn | 5 +---- .../distributeddataservice/adapter/network/BUILD.gn | 2 -- .../adapter/schema_helper/BUILD.gn | 5 +---- .../distributeddataservice/adapter/screenlock/BUILD.gn | 5 +---- services/distributeddataservice/adapter/utils/BUILD.gn | 5 +---- services/distributeddataservice/app/BUILD.gn | 2 -- .../distributeddataservice/app/src/checker/BUILD.gn | 6 +----- .../distributeddataservice/app/src/installer/BUILD.gn | 6 +----- services/distributeddataservice/framework/BUILD.gn | 6 +----- .../rust/connect_adapter/BUILD.gn | 10 ++-------- .../distributeddataservice/rust/extension/BUILD.gn | 6 +----- services/distributeddataservice/service/BUILD.gn | 7 +------ .../distributeddataservice/service/backup/BUILD.gn | 2 -- .../distributeddataservice/service/bootstrap/BUILD.gn | 2 -- services/distributeddataservice/service/cloud/BUILD.gn | 2 -- .../distributeddataservice/service/common/BUILD.gn | 2 -- .../distributeddataservice/service/config/BUILD.gn | 2 -- .../distributeddataservice/service/crypto/BUILD.gn | 2 -- .../distributeddataservice/service/data_share/BUILD.gn | 2 -- .../distributeddataservice/service/dumper/BUILD.gn | 2 -- services/distributeddataservice/service/kvdb/BUILD.gn | 2 -- .../distributeddataservice/service/matrix/BUILD.gn | 2 -- .../distributeddataservice/service/object/BUILD.gn | 2 -- .../distributeddataservice/service/permission/BUILD.gn | 2 -- services/distributeddataservice/service/rdb/BUILD.gn | 2 -- services/distributeddataservice/service/udmf/BUILD.gn | 2 -- 28 files changed, 13 insertions(+), 90 deletions(-) diff --git a/services/distributeddataservice/adapter/account/BUILD.gn b/services/distributeddataservice/adapter/account/BUILD.gn index fc643f996..85697b11b 100755 --- a/services/distributeddataservice/adapter/account/BUILD.gn +++ b/services/distributeddataservice/adapter/account/BUILD.gn @@ -35,10 +35,7 @@ ohos_source_set("distributeddata_account") { "${data_service_path}/framework/include/account", ] - cflags_cc = [ - "-fvisibility=hidden", - "-fstack-protector-strong", - ] + cflags_cc = [ "-fvisibility=hidden" ] remove_configs = [ "//build/config/compiler:no_exceptions" ] diff --git a/services/distributeddataservice/adapter/communicator/BUILD.gn b/services/distributeddataservice/adapter/communicator/BUILD.gn index 522a20c21..ff2d7cf86 100755 --- a/services/distributeddataservice/adapter/communicator/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/BUILD.gn @@ -49,10 +49,7 @@ ohos_source_set("distributeddata_communicator") { "${data_service_path}/framework/include/utils", ] - cflags_cc = [ - "-fvisibility=hidden", - "-fstack-protector-strong", - ] + cflags_cc = [ "-fvisibility=hidden" ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", diff --git a/services/distributeddataservice/adapter/dfx/BUILD.gn b/services/distributeddataservice/adapter/dfx/BUILD.gn index 483c45449..dc2a52cb3 100644 --- a/services/distributeddataservice/adapter/dfx/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/BUILD.gn @@ -50,10 +50,7 @@ ohos_source_set("distributeddata_dfx") { "${data_service_path}/framework/include/utils", ] - cflags_cc = [ - "-fvisibility=hidden", - "-fstack-protector-strong", - ] + cflags_cc = [ "-fvisibility=hidden" ] external_deps = [ "c_utils:utils", diff --git a/services/distributeddataservice/adapter/network/BUILD.gn b/services/distributeddataservice/adapter/network/BUILD.gn index f120004b8..fb25666a3 100644 --- a/services/distributeddataservice/adapter/network/BUILD.gn +++ b/services/distributeddataservice/adapter/network/BUILD.gn @@ -37,7 +37,6 @@ ohos_source_set("distributeddata_network") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] configs = [ ":network_public_config" ] @@ -49,7 +48,6 @@ ohos_source_set("distributeddata_network") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] external_deps = [ "kv_store:datamgr_common" ] diff --git a/services/distributeddataservice/adapter/schema_helper/BUILD.gn b/services/distributeddataservice/adapter/schema_helper/BUILD.gn index 4bfbe3be2..26095037d 100644 --- a/services/distributeddataservice/adapter/schema_helper/BUILD.gn +++ b/services/distributeddataservice/adapter/schema_helper/BUILD.gn @@ -29,10 +29,7 @@ ohos_source_set("distributeddata_schema_helper") { } sources = [ "src/get_schema_helper.cpp" ] - cflags_cc = [ - "-fvisibility=hidden", - "-fstack-protector-strong", - ] + cflags_cc = [ "-fvisibility=hidden" ] include_dirs = [ "../include/schema_helper" ] diff --git a/services/distributeddataservice/adapter/screenlock/BUILD.gn b/services/distributeddataservice/adapter/screenlock/BUILD.gn index 28f3b0b78..ed1fd3913 100644 --- a/services/distributeddataservice/adapter/screenlock/BUILD.gn +++ b/services/distributeddataservice/adapter/screenlock/BUILD.gn @@ -24,10 +24,7 @@ ohos_source_set("distributeddata_screenlock") { } sources = [ "src/screen_lock.cpp" ] - cflags_cc = [ - "-fvisibility=hidden", - "-fstack-protector-strong", - ] + cflags_cc = [ "-fvisibility=hidden" ] include_dirs = [ "../include/screenlock", diff --git a/services/distributeddataservice/adapter/utils/BUILD.gn b/services/distributeddataservice/adapter/utils/BUILD.gn index 8325bf050..f96b7fe3e 100755 --- a/services/distributeddataservice/adapter/utils/BUILD.gn +++ b/services/distributeddataservice/adapter/utils/BUILD.gn @@ -24,10 +24,7 @@ ohos_source_set("distributeddata_utils") { } sources = [ "src/kvstore_utils.cpp" ] - cflags_cc = [ - "-fvisibility=hidden", - "-fstack-protector-strong", - ] + cflags_cc = [ "-fvisibility=hidden" ] if (build_public_version) { cflags_cc += [ "-DCONFIG_PUBLIC_VERSION" ] diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index b66d01341..7748c2fda 100644 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -76,13 +76,11 @@ config("module_private_config") { "-Oz", "-fdata-sections", "-ffunction-sections", - "-fstack-protector-strong", ] cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] diff --git a/services/distributeddataservice/app/src/checker/BUILD.gn b/services/distributeddataservice/app/src/checker/BUILD.gn index 6695b0d65..575e9fad2 100644 --- a/services/distributeddataservice/app/src/checker/BUILD.gn +++ b/services/distributeddataservice/app/src/checker/BUILD.gn @@ -30,7 +30,6 @@ ohos_source_set("distributeddata_checker") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] include_dirs = [ "${data_service_path}/framework/include" ] @@ -40,10 +39,7 @@ ohos_source_set("distributeddata_checker") { } ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils" ] - cflags = [ - "-Oz", - "-fstack-protector-strong", - ] + cflags = [ "-Oz" ] external_deps = [ "ability_base:base", "ability_base:want", diff --git a/services/distributeddataservice/app/src/installer/BUILD.gn b/services/distributeddataservice/app/src/installer/BUILD.gn index 49eb62d2f..0ccfc73e8 100644 --- a/services/distributeddataservice/app/src/installer/BUILD.gn +++ b/services/distributeddataservice/app/src/installer/BUILD.gn @@ -40,13 +40,9 @@ ohos_source_set("distributeddata_installer") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] - cflags = [ - "-Oz", - "-fstack-protector-strong", - ] + cflags = [ "-Oz" ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk", diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index 969705735..9270da8f4 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -124,15 +124,11 @@ ohos_shared_library("distributeddatasvcfwk") { "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-fdata-sections", "-ffunction-sections", - "-fstack-protector-strong", ] ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] - cflags_cc = [ - "-fvisibility=hidden", - "-fstack-protector-strong", - ] + cflags_cc = [ "-fvisibility=hidden" ] configs = [ ":module_config" ] diff --git a/services/distributeddataservice/rust/connect_adapter/BUILD.gn b/services/distributeddataservice/rust/connect_adapter/BUILD.gn index 292dc2003..49162568b 100644 --- a/services/distributeddataservice/rust/connect_adapter/BUILD.gn +++ b/services/distributeddataservice/rust/connect_adapter/BUILD.gn @@ -34,14 +34,8 @@ ohos_shared_library("conn_adapter") { "src/connect_wrapper.cpp", ] configs = [ ":export_connect" ] - cflags = [ - "-Werror", - "-fstack-protector-strong", - ] - cflags_cc = [ - "-fvisibility=hidden", - "-fstack-protector-strong", - ] + cflags = [ "-Werror" ] + cflags_cc = [ "-fvisibility=hidden" ] external_deps = [ "ability_base:want", diff --git a/services/distributeddataservice/rust/extension/BUILD.gn b/services/distributeddataservice/rust/extension/BUILD.gn index 6730b9901..d1c0fdc1d 100644 --- a/services/distributeddataservice/rust/extension/BUILD.gn +++ b/services/distributeddataservice/rust/extension/BUILD.gn @@ -47,13 +47,9 @@ ohos_shared_library("opencloudextension") { cflags = [ "-Werror", "-Wno-multichar", - "-fstack-protector-strong", ] - cflags_cc = [ - "-fvisibility=hidden", - "-fstack-protector-strong", - ] + cflags_cc = [ "-fvisibility=hidden" ] configs = [ ":module_public_config" ] diff --git a/services/distributeddataservice/service/BUILD.gn b/services/distributeddataservice/service/BUILD.gn index b07724a03..6274b1d1c 100644 --- a/services/distributeddataservice/service/BUILD.gn +++ b/services/distributeddataservice/service/BUILD.gn @@ -42,10 +42,7 @@ config("module_public_config") { "${kv_store_distributeddb_path}/interfaces/include/", "${kv_store_distributeddb_path}/interfaces/include/relational", ] - cflags = [ - "-Wno-c99-designator", - "-fstack-protector-strong", - ] + cflags = [ "-Wno-c99-designator" ] } ohos_shared_library("distributeddatasvc") { @@ -66,7 +63,6 @@ ohos_shared_library("distributeddatasvc") { "-Oz", "-fdata-sections", "-ffunction-sections", - "-fstack-protector-strong", ] ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] @@ -74,7 +70,6 @@ ohos_shared_library("distributeddatasvc") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] configs = [ ":module_public_config" ] diff --git a/services/distributeddataservice/service/backup/BUILD.gn b/services/distributeddataservice/service/backup/BUILD.gn index 6a492ef4b..6b90fa32f 100755 --- a/services/distributeddataservice/service/backup/BUILD.gn +++ b/services/distributeddataservice/service/backup/BUILD.gn @@ -32,7 +32,6 @@ ohos_source_set("distributeddata_backup") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] include_dirs = [ @@ -47,7 +46,6 @@ ohos_source_set("distributeddata_backup") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/bootstrap/BUILD.gn b/services/distributeddataservice/service/bootstrap/BUILD.gn index 70b1c24c0..ff48eaece 100644 --- a/services/distributeddataservice/service/bootstrap/BUILD.gn +++ b/services/distributeddataservice/service/bootstrap/BUILD.gn @@ -32,7 +32,6 @@ ohos_source_set("distributeddata_bootstrap") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] include_dirs = [ "${data_service_path}/service/config/include" ] @@ -44,7 +43,6 @@ ohos_source_set("distributeddata_bootstrap") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/cloud/BUILD.gn b/services/distributeddataservice/service/cloud/BUILD.gn index 3c592276d..b36909c07 100755 --- a/services/distributeddataservice/service/cloud/BUILD.gn +++ b/services/distributeddataservice/service/cloud/BUILD.gn @@ -39,7 +39,6 @@ ohos_source_set("distributeddata_cloud") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] include_dirs = [ @@ -60,7 +59,6 @@ ohos_source_set("distributeddata_cloud") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/common/BUILD.gn b/services/distributeddataservice/service/common/BUILD.gn index 7a493bd1b..3a8e1990d 100644 --- a/services/distributeddataservice/service/common/BUILD.gn +++ b/services/distributeddataservice/service/common/BUILD.gn @@ -31,7 +31,6 @@ ohos_source_set("distributeddata_common") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] include_dirs = [ "include" ] @@ -41,7 +40,6 @@ ohos_source_set("distributeddata_common") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] diff --git a/services/distributeddataservice/service/config/BUILD.gn b/services/distributeddataservice/service/config/BUILD.gn index 9349f8113..a2ea71cf4 100644 --- a/services/distributeddataservice/service/config/BUILD.gn +++ b/services/distributeddataservice/service/config/BUILD.gn @@ -39,7 +39,6 @@ ohos_source_set("distributeddata_config") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] include_dirs = [ @@ -53,7 +52,6 @@ ohos_source_set("distributeddata_config") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] diff --git a/services/distributeddataservice/service/crypto/BUILD.gn b/services/distributeddataservice/service/crypto/BUILD.gn index 18b166a96..2b8003be8 100644 --- a/services/distributeddataservice/service/crypto/BUILD.gn +++ b/services/distributeddataservice/service/crypto/BUILD.gn @@ -32,7 +32,6 @@ ohos_source_set("distributeddata_crypto") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] include_dirs = [ "include" ] @@ -43,7 +42,6 @@ ohos_source_set("distributeddata_crypto") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] configs = [ ":crypto_public_config" ] public_configs = [ ":crypto_public_config" ] diff --git a/services/distributeddataservice/service/data_share/BUILD.gn b/services/distributeddataservice/service/data_share/BUILD.gn index 3633536ec..8a6a2bfcb 100644 --- a/services/distributeddataservice/service/data_share/BUILD.gn +++ b/services/distributeddataservice/service/data_share/BUILD.gn @@ -95,13 +95,11 @@ ohos_source_set("data_share_service") { "-Wno-multichar", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] configs = [ ":module_public_config" ] diff --git a/services/distributeddataservice/service/dumper/BUILD.gn b/services/distributeddataservice/service/dumper/BUILD.gn index 9ba04db73..72b194d79 100644 --- a/services/distributeddataservice/service/dumper/BUILD.gn +++ b/services/distributeddataservice/service/dumper/BUILD.gn @@ -27,7 +27,6 @@ ohos_source_set("distributeddata_dumper") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] include_dirs = [ "include" ] @@ -38,7 +37,6 @@ ohos_source_set("distributeddata_dumper") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] diff --git a/services/distributeddataservice/service/kvdb/BUILD.gn b/services/distributeddataservice/service/kvdb/BUILD.gn index 9f1d96dae..874dc361c 100644 --- a/services/distributeddataservice/service/kvdb/BUILD.gn +++ b/services/distributeddataservice/service/kvdb/BUILD.gn @@ -55,7 +55,6 @@ ohos_source_set("distributeddata_kvdb") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] cflags = [ @@ -64,7 +63,6 @@ ohos_source_set("distributeddata_kvdb") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/matrix/BUILD.gn b/services/distributeddataservice/service/matrix/BUILD.gn index 3499cbe6c..e7f2d0a63 100755 --- a/services/distributeddataservice/service/matrix/BUILD.gn +++ b/services/distributeddataservice/service/matrix/BUILD.gn @@ -35,7 +35,6 @@ ohos_source_set("distributeddata_matrix") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] include_dirs = [ @@ -50,7 +49,6 @@ ohos_source_set("distributeddata_matrix") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/object/BUILD.gn b/services/distributeddataservice/service/object/BUILD.gn index 29056fe07..e76a7510e 100644 --- a/services/distributeddataservice/service/object/BUILD.gn +++ b/services/distributeddataservice/service/object/BUILD.gn @@ -49,7 +49,6 @@ ohos_source_set("distributeddata_object") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] include_dirs = [ "include" ] @@ -62,7 +61,6 @@ ohos_source_set("distributeddata_object") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/permission/BUILD.gn b/services/distributeddataservice/service/permission/BUILD.gn index 0f28d2778..2795bda98 100644 --- a/services/distributeddataservice/service/permission/BUILD.gn +++ b/services/distributeddataservice/service/permission/BUILD.gn @@ -36,7 +36,6 @@ ohos_source_set("distributeddata_permit") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] include_dirs = [ @@ -52,7 +51,6 @@ ohos_source_set("distributeddata_permit") { "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Oz", - "-fstack-protector-strong", ] deps = [ diff --git a/services/distributeddataservice/service/rdb/BUILD.gn b/services/distributeddataservice/service/rdb/BUILD.gn index ad693d92d..9c126c795 100644 --- a/services/distributeddataservice/service/rdb/BUILD.gn +++ b/services/distributeddataservice/service/rdb/BUILD.gn @@ -63,7 +63,6 @@ ohos_source_set("distributeddata_rdb") { "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Werror", "-Oz", - "-fstack-protector-strong", ] deps = [ @@ -97,7 +96,6 @@ ohos_source_set("distributeddata_rdb") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] subsystem_name = "distributeddatamgr" diff --git a/services/distributeddataservice/service/udmf/BUILD.gn b/services/distributeddataservice/service/udmf/BUILD.gn index 971ab2721..8176548a1 100644 --- a/services/distributeddataservice/service/udmf/BUILD.gn +++ b/services/distributeddataservice/service/udmf/BUILD.gn @@ -70,7 +70,6 @@ ohos_source_set("udmf_server") { "-D_LIBCPP_HAS_COND_CLOCKWAIT", "-Werror", "-Oz", - "-fstack-protector-strong", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] @@ -95,7 +94,6 @@ ohos_source_set("udmf_server") { cflags_cc = [ "-fvisibility=hidden", "-Oz", - "-fstack-protector-strong", ] subsystem_name = "distributeddatamgr" -- Gitee From 32f4e147c692ec9464c2f7ffc401f7a0d1bb2a03 Mon Sep 17 00:00:00 2001 From: yanhui Date: Tue, 8 Apr 2025 16:19:05 +0800 Subject: [PATCH 140/225] =?UTF-8?q?SoftBusClient=E5=A2=9E=E5=8A=A0networkI?= =?UTF-8?q?d=E5=B1=9E=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yanhui Change-Id: I494cc62ff95f1cb22a67337acfa7559235060aba --- .../communicator/src/softbus_adapter_standard.cpp | 13 ++++++++----- .../adapter/communicator/src/softbus_client.cpp | 9 +++++++-- .../adapter/communicator/src/softbus_client.h | 1 + .../adapter/include/communicator/commu_types.h | 1 + 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp index 81b9f74e4..363699e6a 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp @@ -207,7 +207,8 @@ std::shared_ptr SoftBusAdapter::GetConnect(const PipeInfo &pipeIn uint32_t qosType) { std::shared_ptr conn; - connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType](const auto &key, + auto networkId = DmAdapter::GetInstance().GetDeviceInfo(deviceId.deviceId).networkId; + connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType, &networkId](const auto &key, std::vector> &connects) -> bool { for (auto &connect : connects) { if (connect == nullptr) { @@ -218,7 +219,8 @@ std::shared_ptr SoftBusAdapter::GetConnect(const PipeInfo &pipeIn return true; } } - auto connect = std::make_shared(pipeInfo, deviceId, qosType); + DeviceId device = { .deviceId = deviceId.deviceId, .networkId = std::move(networkId) }; + auto connect = std::make_shared(pipeInfo, device, qosType); connects.emplace_back(connect); conn = connect; return true; @@ -354,23 +356,24 @@ std::string SoftBusAdapter::DelConnect(int32_t socket, bool isForce) if (!isForce && DmAdapter::GetInstance().IsOHOSType(deviceId)) { return false; } + std::string networkId; for (auto iter = connects.begin(); iter != connects.end();) { if (*iter != nullptr && **iter == socket) { name += deviceId; name += " "; + networkId = (*iter)->GetNetworkId(); iter = connects.erase(iter); } else { iter++; } } if (connects.empty()) { - closedConnect.insert(deviceId); + closedConnect.insert(networkId); return true; } return false; }); - for (const auto &deviceId : closedConnect) { - auto networkId = DmAdapter::GetInstance().GetDeviceInfo(deviceId).networkId; + for (const auto &networkId : closedConnect) { ConnectManager::GetInstance()->OnSessionClose(networkId); } return name; diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp index f4451869f..84df847a0 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp @@ -125,7 +125,7 @@ int32_t SoftBusClient::CreateSocket() const SocketInfo socketInfo; std::string peerName = pipe_.pipeId; socketInfo.peerName = const_cast(peerName.c_str()); - std::string networkId = DmAdapter::GetInstance().ToNetworkID(device_.deviceId); + std::string networkId = device_.networkId; socketInfo.peerNetworkId = const_cast(networkId.c_str()); std::string clientName = pipe_.pipeId; socketInfo.name = const_cast(clientName.c_str()); @@ -177,7 +177,7 @@ int32_t SoftBusClient::Open(int32_t socket, uint32_t type, const ISocketListener UpdateBindInfo(socket, mtu, status, async); ZLOGI("open %{public}s, session:%{public}s success, socket:%{public}d", KvStoreUtils::ToBeAnonymous(device_.deviceId).c_str(), pipe_.pipeId.c_str(), socket_); - ConnectManager::GetInstance()->OnSessionOpen(DmAdapter::GetInstance().GetDeviceInfo(device_.deviceId).networkId); + ConnectManager::GetInstance()->OnSessionOpen(device_.networkId); return status; } @@ -256,4 +256,9 @@ Status SoftBusClient::ReuseConnect(const ISocketListener *listener) int32_t status = Open(socket, QOS_REUSE, listener, false); return status == SOFTBUS_OK ? Status::SUCCESS : Status::NETWORK_ERROR; } + +std::string SoftBusClient::GetNetworkId() +{ + return device_.networkId; +} } // namespace OHOS::AppDistributedKv \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.h b/services/distributeddataservice/adapter/communicator/src/softbus_client.h index 67709bf90..d4df243c2 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.h +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.h @@ -51,6 +51,7 @@ public: void UpdateExpireTime(bool async = true); int32_t GetSoftBusError(); Status ReuseConnect(const ISocketListener *listener); + std::string GetNetworkId(); private: int32_t Open(int32_t socket, uint32_t type, const ISocketListener *listener, bool async = true); diff --git a/services/distributeddataservice/adapter/include/communicator/commu_types.h b/services/distributeddataservice/adapter/include/communicator/commu_types.h index 6b1f1af69..6cca6af2f 100644 --- a/services/distributeddataservice/adapter/include/communicator/commu_types.h +++ b/services/distributeddataservice/adapter/include/communicator/commu_types.h @@ -71,6 +71,7 @@ struct API_EXPORT PipeInfo { struct API_EXPORT DeviceId { std::string deviceId; + std::string networkId; }; enum class API_EXPORT MessageType { -- Gitee From 92b74374ca29463cb37ce1aaa44d2999135c23ff Mon Sep 17 00:00:00 2001 From: suoqilong Date: Wed, 9 Apr 2025 02:07:05 +0000 Subject: [PATCH 141/225] =?UTF-8?q?=E6=9B=BF=E6=8D=A2std:stoi=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E6=9B=BF=E6=8D=A2-0408?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .../service/kvdb/kvdb_general_store.cpp | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp index b11b56fa4..358468d15 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp @@ -78,7 +78,6 @@ const std::map KVDBGeneralStore::dbStatusMap }; constexpr uint32_t LOCK_TIMEOUT = 3600; // second -static constexpr int DECIMAL_BASE = 10; // decimal base static DBSchema GetDBSchema(const Database &database) { DBSchema schema; @@ -202,18 +201,7 @@ KVDBGeneralStore::KVDBGeneralStore(const StoreMetaData &meta) storeInfo_.bundleName = meta.bundleName; storeInfo_.storeName = meta.storeId; storeInfo_.instanceId = meta.instanceId; - char *endptr = nullptr; - errno = 0; - long userLong = strtol(meta.user.c_str(), &endptr, DECIMAL_BASE); - if (endptr == nullptr || endptr == meta.user.c_str() || *endptr != '\0') { - ZLOGE("User:%{public}s is invalid", meta.user.c_str()); - return; - } - if (errno == ERANGE || userLong >= INT32_MAX || userLong <= INT32_MIN) { - ZLOGE("User:%{public}s is out of range", meta.user.c_str()); - return; - } - storeInfo_.user = static_cast(userLong); + storeInfo_.user = std::atoi(meta.user.c_str()); enableCloud_ = meta.enableCloud; } -- Gitee From 69e246053cf4a2c27eb4ea5924c0b2fb911dcf70 Mon Sep 17 00:00:00 2001 From: l30005037 Date: Wed, 9 Apr 2025 10:52:31 +0800 Subject: [PATCH 142/225] The security link option is modified Signed-off-by: l30005037 --- services/distributeddataservice/adapter/utils/BUILD.gn | 2 +- services/distributeddataservice/app/BUILD.gn | 2 +- services/distributeddataservice/app/src/checker/BUILD.gn | 2 +- services/distributeddataservice/framework/BUILD.gn | 2 +- services/distributeddataservice/service/BUILD.gn | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/services/distributeddataservice/adapter/utils/BUILD.gn b/services/distributeddataservice/adapter/utils/BUILD.gn index f96b7fe3e..bf5b815f0 100755 --- a/services/distributeddataservice/adapter/utils/BUILD.gn +++ b/services/distributeddataservice/adapter/utils/BUILD.gn @@ -31,7 +31,7 @@ ohos_source_set("distributeddata_utils") { } include_dirs = [ "../include/utils" ] - ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] + ldflags = [ "-Wl,--exclude-libs,ALL" ] external_deps = [ "c_utils:utils", diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index 7748c2fda..084cbb75e 100644 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -83,7 +83,7 @@ config("module_private_config") { "-Oz", ] - ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] + ldflags = [ "-Wl,--gc-sections" ] } ohos_shared_library("distributeddataservice") { diff --git a/services/distributeddataservice/app/src/checker/BUILD.gn b/services/distributeddataservice/app/src/checker/BUILD.gn index 575e9fad2..f0fa8dd25 100644 --- a/services/distributeddataservice/app/src/checker/BUILD.gn +++ b/services/distributeddataservice/app/src/checker/BUILD.gn @@ -37,7 +37,7 @@ ohos_source_set("distributeddata_checker") { if (build_public_version) { cflags_cc += [ "-DCONFIG_PUBLIC_VERSION" ] } - ldflags = [ "-Wl,-z,relro,-z,now,--exclude-libs,ALL" ] + ldflags = [ "-Wl,--exclude-libs,ALL" ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils" ] cflags = [ "-Oz" ] external_deps = [ diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index 9270da8f4..344f08426 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -126,7 +126,7 @@ ohos_shared_library("distributeddatasvcfwk") { "-ffunction-sections", ] - ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] + ldflags = [ "-Wl,--gc-sections" ] cflags_cc = [ "-fvisibility=hidden" ] diff --git a/services/distributeddataservice/service/BUILD.gn b/services/distributeddataservice/service/BUILD.gn index 6274b1d1c..952c92895 100644 --- a/services/distributeddataservice/service/BUILD.gn +++ b/services/distributeddataservice/service/BUILD.gn @@ -65,7 +65,7 @@ ohos_shared_library("distributeddatasvc") { "-ffunction-sections", ] - ldflags = [ "-Wl,-z,relro,-z,now,--gc-sections" ] + ldflags = [ "-Wl,--gc-sections" ] cflags_cc = [ "-fvisibility=hidden", -- Gitee From 382b19d2e86449cbb2f60f0d037a5276e6d307ce Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Wed, 9 Apr 2025 11:43:31 +0800 Subject: [PATCH 143/225] fix ut Signed-off-by: wanghuajian-6 --- .../service/object/include/object_manager.h | 2 +- .../service/object/src/object_manager.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/service/object/include/object_manager.h b/services/distributeddataservice/service/object/include/object_manager.h index a2f903436..8fdaea708 100644 --- a/services/distributeddataservice/service/object/include/object_manager.h +++ b/services/distributeddataservice/service/object/include/object_manager.h @@ -95,7 +95,7 @@ public: sptr callback); void UnregisterRemoteCallback(const std::string &bundleName, pid_t pid, uint32_t tokenId, const std::string &sessionId = ""); - void NotifyChange(ObjectRecord &changedData); + void NotifyChange(const ObjectRecord &changedData); void NotifyAssetsReady(const std::string& objectKey, const std::string& bundleName, const std::string& srcNetworkId = ""); void NotifyAssetsStart(const std::string& objectKey, const std::string& srcNetworkId = ""); diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 31534759a..97ea8fe0c 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -393,7 +393,7 @@ void ObjectStoreManager::UnregisterRemoteCallback(const std::string &bundleName, })); } -void ObjectStoreManager::NotifyChange(ObjectRecord &changedData) +void ObjectStoreManager::NotifyChange(const ObjectRecord &changedData) { ZLOGI("OnChange start, size:%{public}zu", changedData.size()); bool hasAsset = false; @@ -424,7 +424,7 @@ void ObjectStoreManager::NotifyChange(ObjectRecord &changedData) ZLOGE("Delete entries failed, bundleName:%{public}s, source device::%{public}s, status: %{public}d", saveInfo.bundleName.c_str(), Anonymous::Change(saveInfo.sourceDeviceId).c_str(), status); } - return; + return Close(); } if (!hasAsset) { ObjectStore::RadarReporter::ReportStateStart(std::string(__FUNCTION__), ObjectStore::DATA_RESTORE, -- Gitee From 355d06174d7bff8ae6253e1d7ddf960bbc8a88fd Mon Sep 17 00:00:00 2001 From: wanxiaoqing Date: Mon, 7 Apr 2025 09:12:40 +0800 Subject: [PATCH 144/225] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wanxiaoqing --- .../service/udmf/udmf_service_impl.cpp | 27 ++++++++++++++----- .../service/udmf/udmf_service_impl.h | 1 + 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 408c19a00..45252d051 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -190,11 +190,23 @@ int32_t UdmfServiceImpl::GetData(const QueryOption &query, UnifiedData &unifiedD return res; } -int32_t UdmfServiceImpl::RetrieveData(const QueryOption &query, UnifiedData &unifiedData) +bool UdmfServiceImpl::CheckDragParams(UnifiedKey &key, const QueryOption &query) { - UnifiedKey key(query.key); if (!key.IsValid()) { ZLOGE("Unified key: %{public}s is invalid.", query.key.c_str()); + return false; + } + if (key.intention != UD_INTENTION_MAP.at(UD_INTENTION_DRAG)) { + ZLOGE("Invalid intention:%{public}s", key.intention.c_str()); + return false; + } + return true; +} + +int32_t UdmfServiceImpl::RetrieveData(const QueryOption &query, UnifiedData &unifiedData) +{ + UnifiedKey key(query.key); + if (!CheckDragParams(key, query)) { return E_INVALID_PARAMETERS; } auto store = StoreCache::GetInstance().GetStore(key.intention); @@ -701,14 +713,15 @@ int32_t UdmfServiceImpl::QueryDataCommon( { auto find = UD_INTENTION_MAP.find(query.intention); std::string intention = find == UD_INTENTION_MAP.end() ? intention : find->second; - if (!UnifiedDataUtils::IsValidOptions(query.key, intention)) { + UnifiedKey key(query.key); + if (!UnifiedDataUtils::IsValidOptions(key, intention, UD_INTENTION_MAP.at(UD_INTENTION_DATA_HUB))) { ZLOGE("Unified key: %{public}s and intention: %{public}s is invalid.", query.key.c_str(), intention.c_str()); return E_INVALID_PARAMETERS; } - std::string dataPrefix = DATA_PREFIX + intention; - UnifiedKey key(query.key); - key.IsValid(); - if (intention.empty()) { + std::string dataPrefix; + if (key.key.empty()) { + dataPrefix = DATA_PREFIX + intention; + } else { dataPrefix = UnifiedKey(key.key).GetPropertyKey(); intention = key.intention; } diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.h b/services/distributeddataservice/service/udmf/udmf_service_impl.h index 48a80b442..da95d6eb4 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.h +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.h @@ -60,6 +60,7 @@ private: void RegisterAsyncProcessInfo(const std::string &businessUdKey); void TransferToEntriesIfNeed(const QueryOption &query, UnifiedData &unifiedData); bool IsNeedTransferDeviceType(const QueryOption &query); + bool CheckDragParams(UnifiedKey &key, const QueryOption &query); class Factory { public: -- Gitee From 5c77d545b895ff0dd6b77040c4c77169777cbdbb Mon Sep 17 00:00:00 2001 From: ZhaoJinghui Date: Thu, 3 Apr 2025 18:31:10 +0800 Subject: [PATCH 145/225] add testcase Signed-off-by: ZhaoJinghui Change-Id: I5830effe5eb22e0af01122b683bcf46b4cde6ec8 --- .../service/rdb/cache_cursor.cpp | 4 +- .../service/test/BUILD.gn | 2 + .../service/test/rdb_service_impl_test.cpp | 656 ++++++++++++++++++ 3 files changed, 660 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/rdb/cache_cursor.cpp b/services/distributeddataservice/service/rdb/cache_cursor.cpp index 4c3b04d3c..e9ce03d3c 100644 --- a/services/distributeddataservice/service/rdb/cache_cursor.cpp +++ b/services/distributeddataservice/service/rdb/cache_cursor.cpp @@ -23,13 +23,13 @@ using namespace OHOS::DistributedData; CacheCursor::CacheCursor(std::vector &&records) : row_(0), maxCol_(0), records_(std::move(records)) { - maxRow_ = records_.size(); + maxRow_ = static_cast(records_.size()); if (maxRow_ > 0) { for (auto it = records_[0].begin(); it != records_[0].end(); it++) { colNames_.push_back(it->first); colTypes_.push_back(it->second.index()); } - maxCol_ = colNames_.size(); + maxCol_ = static_cast(colNames_.size()); } } diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 4fbaca571..9c0b1d91a 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -659,11 +659,13 @@ ohos_unittest("RdbServiceImplTest") { sources = [ "mock/db_change_data_mock.cpp", "mock/db_store_mock.cpp", + "mock/checker_mock.cpp", "rdb_service_impl_test.cpp", ] include_dirs = [ "${data_service_path}/adapter/include/communicator", + "${data_service_path}/framework/include/eventcenter", "${data_service_path}/service/test/mock", ] diff --git a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp index a60ab06c9..acce4946d 100644 --- a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp @@ -14,11 +14,19 @@ */ #include "account/account_delegate.h" +#include "bootstrap.h" +#include "checker_mock.h" +#include "cloud/change_event.h" +#include "cloud/schema_meta.h" +#include "crypto_manager.h" #include "device_manager_adapter.h" #include "device_matrix.h" +#include "event_center.h" #include "ipc_skeleton.h" +#include "metadata/capability_meta_data.h" #include "metadata/meta_data_manager.h" #include "metadata/store_meta_data.h" +#include "metadata/store_meta_data_local.h" #include "mock/db_store_mock.h" #include "rdb_service_impl.h" #include "relational_store_manager.h" @@ -49,11 +57,13 @@ public: protected: static std::shared_ptr dbStoreMock_; static StoreMetaData metaData_; + static CheckerMock checkerMock_; static void InitMetaDataManager(); }; std::shared_ptr RdbServiceImplTest::dbStoreMock_ = std::make_shared(); StoreMetaData RdbServiceImplTest::metaData_; +CheckerMock RdbServiceImplTest::checkerMock_; void RdbServiceImplTest::InitMetaData() { @@ -85,6 +95,7 @@ void RdbServiceImplTest::SetUpTestCase() auto dmExecutor = std::make_shared(max, min); DeviceManagerAdapter::GetInstance().Init(dmExecutor); InitMetaData(); + Bootstrap::GetInstance().LoadCheckers(); } void RdbServiceImplTest::TearDownTestCase() @@ -277,5 +288,650 @@ HWTEST_F(RdbServiceImplTest, GetCallbacks001, TestSize.Level0) EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); } +/** + * @tc.name: DoSync001 + * @tc.desc: Test DoSync when the store is null. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, DoSync001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + RdbService::Option option; + PredicatesMemo predicates; + AsyncDetail async; + + auto result = service.DoSync(param, option, predicates, async); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: DoSync002 + * @tc.desc: Test DoSync when meta sync is needed and succeeds. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, DoSync002, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.type_ = metaData_.storeType; + param.level_ = metaData_.securityLevel; + param.area_ = metaData_.area; + param.hapName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + param.isEncrypt_ = metaData_.isEncrypt; + param.isSearchable_ = metaData_.isSearchable; + param.haMode_ = metaData_.haMode; + param.asyncDownloadAsset_ = metaData_.asyncDownloadAsset; + + RdbService::Option option; + option.mode = DistributedData::GeneralStore::AUTO_SYNC_MODE; + option.seqNum = 1; + + PredicatesMemo predicates; + AsyncDetail async; + + auto result = service.DoSync(param, option, predicates, async); + EXPECT_EQ(result, RDB_ERROR); + + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** + * @tc.name: IsNeedMetaSync001 + * @tc.desc: Test IsNeedMetaSync when LoadMeta fails for CapMetaData. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, IsNeedMetaSync001, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + std::vector devices = {DmAdapter::GetInstance().ToUUID(metaData_.deviceId)}; + RdbServiceImpl service; + bool result = service.IsNeedMetaSync(metaData_, devices); + + EXPECT_EQ(result, true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** + * @tc.name: IsNeedMetaSync002 + * @tc.desc: Test IsNeedMetaSync when LoadMeta fails for StoreMetaData. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, IsNeedMetaSync002, TestSize.Level0) +{ + CapMetaData capMetaData; + auto capKey = CapMetaRow::GetKeyFor(metaData_.deviceId); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(std::string(capKey.begin(), capKey.end()), capMetaData), true); + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + std::vector devices = {DmAdapter::GetInstance().ToUUID(metaData_.deviceId)}; + RdbServiceImpl service; + bool result = service.IsNeedMetaSync(metaData_, devices); + + EXPECT_EQ(result, false); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** + * @tc.name: ProcessResult001 + * @tc.desc: Test ProcessResult when all results have DBStatus::OK. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, ProcessResult001, TestSize.Level0) +{ + RdbServiceImpl service; + std::map results = {{"device1", static_cast(DBStatus::OK)}, + {"device2", static_cast(DBStatus::OK)}}; + + auto result = service.ProcessResult(results); + + EXPECT_EQ(result.second.at("device1"), DBStatus::OK); + EXPECT_EQ(result.second.at("device2"), DBStatus::OK); +} + +/** + * @tc.name: ProcessResult002 + * @tc.desc: Test ProcessResult when some results have DBStatus::OK and others do not. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, ProcessResult002, TestSize.Level0) +{ + RdbServiceImpl service; + std::map results = {{"device1", static_cast(DBStatus::OK)}, + {"device2", static_cast(DBStatus::DB_ERROR)}, + {"device3", static_cast(DBStatus::OK)}}; + + auto result = service.ProcessResult(results); + + EXPECT_EQ(result.second.at("device1"), DBStatus::OK); + EXPECT_EQ(result.second.at("device2"), DBStatus::DB_ERROR); + EXPECT_EQ(result.second.at("device3"), DBStatus::OK); +} + +/** + * @tc.name: ProcessResult004 + * @tc.desc: Test ProcessResult with an empty results map. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, ProcessResult004, TestSize.Level0) +{ + RdbServiceImpl service; + std::map results; + + auto result = service.ProcessResult(results); + + EXPECT_EQ(result.first.size(), 0); + EXPECT_EQ(result.second.size(), 0); +} + +/** + * @tc.name: DoCompensateSync001 + * @tc.desc: Test DoCompensateSync when the event has valid bindInfo and COMPENSATE_SYNC event ID. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, DoCompensateSync001, TestSize.Level0) +{ + RdbServiceImpl service; + + int32_t eventId = 1; + DistributedData::BindEvent::BindEventInfo bindInfo; + bindInfo.bundleName = TEST_BUNDLE; + bindInfo.tokenId = metaData_.tokenId; + bindInfo.user = metaData_.uid; + bindInfo.storeName = TEST_STORE; + bindInfo.tableName = "test_table"; + bindInfo.primaryKey = {{"key1", "value1"}, {"key2", "value2"}}; + + BindEvent event(eventId, std::move(bindInfo)); + EventCenter::GetInstance().Subscribe(CloudEvent::LOCAL_CHANGE, [this] (const Event &event) { + auto &evt = static_cast(event); + auto mode = evt.GetMode(); + EXPECT_EQ(GeneralStore::GetPriorityLevel(GeneralStore::GetHighMode(static_cast(mode))), 1); + }); + service.DoCompensateSync(event); +} + +/** + * @tc.name: ReportStatistic001 + * @tc.desc: Test ReportStatistic when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, ReportStatistic001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + RdbStatEvent statEvent; + + int32_t result = service.ReportStatistic(param, statEvent); + + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: ReportStatistic002 + * @tc.desc: Test ReportStatistic when CheckAccess success. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, ReportStatistic002, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = TEST_BUNDLE; + param.storeName_ = TEST_STORE; + RdbStatEvent statEvent; + + int32_t result = service.ReportStatistic(param, statEvent); + + EXPECT_EQ(result, OK); +} + +/** + * @tc.name: GetReuseDevice001 + * @tc.desc: Test GetReuseDevice when all devices are reusable. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetReuseDevice001, TestSize.Level0) +{ + RdbServiceImpl service; + std::vector devices = {"device1"}; + + auto result = service.GetReuseDevice(devices); + EXPECT_EQ(result.size(), 0); +} + +/** + * @tc.name: DoAutoSync001 + * @tc.desc: Test DoAutoSync when the store is null. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, DoAutoSync001, TestSize.Level0) +{ + RdbServiceImpl service; + std::vector devices = {"device1"}; + DistributedData::Database dataBase; + std::vector tables = {"table1"}; + + auto result = service.DoAutoSync(devices, dataBase, tables); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: DoOnlineSync001 + * @tc.desc: Test DoOnlineSync when all tables have deviceSyncFields. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, DoOnlineSync001, TestSize.Level0) +{ + RdbServiceImpl service; + std::vector devices = {"device1"}; + DistributedData::Database dataBase; + dataBase.name = TEST_STORE; + + DistributedData::Table table1; + table1.name = "table1"; + table1.deviceSyncFields = {"field1", "field2"}; + DistributedData::Table table2; + table2.name = "table2"; + table2.deviceSyncFields = {}; + + dataBase.tables = {table1, table2}; + + auto result = service.DoOnlineSync(devices, dataBase); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: OnReady001 + * @tc.desc: Test OnReady when LoadMeta fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, OnReady001, TestSize.Level0) +{ + RdbServiceImpl service; + std::string device = "test_device"; + + int32_t result = service.OnReady(device); + EXPECT_EQ(result, 0); +} + +/** + * @tc.name: OnReady002 + * @tc.desc: Test OnReady when no databases have autoSyncType SYNC_ON_READY or SYNC_ON_CHANGE_READY. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, OnReady002, TestSize.Level0) +{ + RdbServiceImpl service; + std::string device = metaData_.deviceId; + + DistributedData::Database dataBase1; + dataBase1.name = "test_rdb_service_impl_sync_store2"; + dataBase1.bundleName = TEST_BUNDLE; + dataBase1.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(metaData_.tokenId)); + dataBase1.autoSyncType = AutoSyncType::SYNC_ON_READY; + + DistributedData::Database dataBase2; + dataBase2.name = "test_rdb_service_impl_sync_store2"; + dataBase2.bundleName = TEST_BUNDLE; + dataBase2.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(metaData_.tokenId)); + dataBase2.autoSyncType = AutoSyncType::SYNC_ON_CHANGE_READY; + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase1.GetKey(), metaData_, true), true); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase2.GetKey(), metaData_, true), true); + int32_t result = service.OnReady(device); + + EXPECT_EQ(result, 0); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase1.GetKey(), metaData_, true), true); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase2.GetKey(), metaData_, true), true); +} + +/** + * @tc.name: SetSearchable001 + * @tc.desc: Test SetSearchable when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, SetSearchable001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + + bool isSearchable = true; + int32_t result = service.SetSearchable(param, isSearchable); + + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: SetSearchable002 + * @tc.desc: Test SetSearchable when CheckAccess succeeds and PostSearchEvent is called. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, SetSearchable002, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + + bool isSearchable = true; + int32_t result = service.SetSearchable(param, isSearchable); + + EXPECT_EQ(result, RDB_OK); +} + +/** + * @tc.name: GetPassword001 + * @tc.desc: Test GetPassword when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetPassword001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + std::vector> password; + + int32_t result = service.GetPassword(param, password); + + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: GetPassword002 + * @tc.desc: Test GetPassword when no meta data is found. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetPassword002, TestSize.Level0) +{ + auto meta = metaData_; + meta.isEncrypt = true; + std::vector sKey{2, 249, 221, 119, 177, 216, 217, 134, 185, 139, 114, 38, 140, 64, 165, 35, + 77, 169, 0, 226, 226, 166, 37, 73, 181, 229, 42, 88, 108, 111, 131, 104, + 141, 43, 96, 119, 214, 34, 177, 129, 233, 96, 98, 164, 87, 115, 187, 170}; + SecretKeyMetaData secretKey; + secretKey.sKey = CryptoManager::GetInstance().Encrypt(sKey); + secretKey.area = 0; + secretKey.storeType = meta.storeType; + secretKey.time = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true), true); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetSecretKey(), secretKey, true), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = meta.bundleName; + param.storeName_ = meta.storeId; + std::vector> password; + int32_t result = service.GetPassword(param, password); + + EXPECT_EQ(result, RDB_ERROR); + + MetaDataManager::GetInstance().DelMeta(meta.GetKey(), true); + MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true); +} + +/** + * @tc.name: GetPassword003 + * @tc.desc: Test GetPassword when decryption fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetPassword003, TestSize.Level0) +{ + SecretKeyMetaData secretKey; + secretKey.sKey = {0x01, 0x02, 0x03}; // Invalid key for decryption + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetSecretKey(), secretKey, true), true); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, true), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + std::vector> password; + + int32_t result = service.GetPassword(param, password); + + EXPECT_EQ(result, RDB_ERROR); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetSecretKey(), true), true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), true), true); +} + +/** + * @tc.name: GetPassword004 + * @tc.desc: Test GetPassword when no meta data is found. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetPassword004, TestSize.Level0) +{ + auto meta = metaData_; + meta.isEncrypt = true; + std::vector sKey{2, 249, 221, 119, 177, 216, 217, 134, 185, 139, 114, 38, 140, 64, 165, 35, + 77, 169, 0, 226, 226, 166, 37, 73, 181, 229, 42, 88, 108, 111, 131, 104, + 141, 43, 96, 119, 214, 34, 177, 129, 233, 96, 98, 164, 87, 115, 187, 170}; + SecretKeyMetaData secretKey; + secretKey.sKey = CryptoManager::GetInstance().Encrypt(sKey); + secretKey.area = 0; + secretKey.storeType = meta.storeType; + secretKey.time = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true), true); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetCloneSecretKey(), secretKey, true), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = meta.bundleName; + param.storeName_ = meta.storeId; + param.type_ = meta.storeType; + std::vector> password; + + int32_t result = service.GetPassword(param, password); + + EXPECT_EQ(result, RDB_ERROR); + MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), true); + MetaDataManager::GetInstance().DelMeta(metaData_.GetCloneSecretKey(), true); +} + +/** + * @tc.name: LockCloudContainer001 + * @tc.desc: Test LockCloudContainer when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, LockCloudContainer001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + + auto result = service.LockCloudContainer(param); + + EXPECT_EQ(result.first, RDB_ERROR); + EXPECT_EQ(result.second, 0); +} + +/** + * @tc.name: LockCloudContainer002 + * @tc.desc: Test LockCloudContainer when CheckAccess succeeds and callback updates the result. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, LockCloudContainer002, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + + auto result = service.LockCloudContainer(param); + + // Simulate callback execution + EXPECT_EQ(result.first, RDB_ERROR); + EXPECT_EQ(result.second, 0); + + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** + * @tc.name: UnlockCloudContainer001 + * @tc.desc: Test UnlockCloudContainer when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, UnlockCloudContainer001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + + int32_t result = service.UnlockCloudContainer(param); + + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: UnlockCloudContainer002 + * @tc.desc: Test UnlockCloudContainer when CheckAccess succeeds and callback updates the result. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, UnlockCloudContainer002, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + + int32_t result = service.UnlockCloudContainer(param); + + // Simulate callback execution + EXPECT_EQ(result, RDB_ERROR); // Assuming the callback sets status to RDB_OK + + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** + * @tc.name: GetDebugInfo001 + * @tc.desc: Test GetDebugInfo when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetDebugInfo001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + std::map debugInfo; + + int32_t result = service.GetDebugInfo(param, debugInfo); + + EXPECT_EQ(result, RDB_ERROR); + EXPECT_TRUE(debugInfo.empty()); +} + +/** + * @tc.name: VerifyPromiseInfo001 + * @tc.desc: Test VerifyPromiseInfo when LoadMeta fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, VerifyPromiseInfo001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + + int32_t result = service.VerifyPromiseInfo(param); + + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: VerifyPromiseInfo002 + * @tc.desc: Test VerifyPromiseInfo when tokenId and uid are not in promiseInfo. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, VerifyPromiseInfo002, TestSize.Level0) +{ + StoreMetaDataLocal localMeta; + auto tokenId = IPCSkeleton::GetCallingTokenID(); + localMeta.isAutoSync = true; + localMeta.promiseInfo.tokenIds = {tokenId}; + localMeta.promiseInfo.uids = {}; + localMeta.promiseInfo.permissionNames = {}; + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKeyLocal(), localMeta, true), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.type_ = metaData_.storeType; + param.level_ = metaData_.securityLevel; + param.area_ = metaData_.area; + param.hapName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + param.isEncrypt_ = metaData_.isEncrypt; + param.isSearchable_ = metaData_.isSearchable; + param.haMode_ = metaData_.haMode; + param.asyncDownloadAsset_ = metaData_.asyncDownloadAsset; + param.user_ = metaData_.user; + + int32_t result = service.VerifyPromiseInfo(param); + + EXPECT_EQ(result, RDB_OK); + + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKeyLocal(), true), true); +} } // namespace DistributedRDBTest } // namespace OHOS::Test -- Gitee From 8bf3b6195226b72e6ccfef624d0e07b239baadce Mon Sep 17 00:00:00 2001 From: guochao Date: Wed, 12 Mar 2025 21:52:33 +0800 Subject: [PATCH 146/225] =?UTF-8?q?add=20=E4=BB=A3=E7=A0=81=E8=A6=86?= =?UTF-8?q?=E7=9B=96=E7=8E=87=20Signed-off-by:=20guochao=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test/mock/general_watcher_mock.cpp | 20 +- .../service/test/mock/general_watcher_mock.h | 10 +- .../service/test/rdb_general_store_test.cpp | 217 +++++++++++++++++- 3 files changed, 241 insertions(+), 6 deletions(-) diff --git a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp index f955a89cd..2bea20914 100644 --- a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp +++ b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp @@ -25,6 +25,24 @@ std::vector MockQuery::GetTables() return tables_; } +const std::string GetStatement() +{ + return "AS distributed_log"; +} + +void MockQuery::MakeRemoteQuery(const std::string &devices, const std::string &sql, Values &&args) +{ + isRemote_ = true; + devices_ = { devices }; + sql_ = sql; + args_ = std::move(args); +} + +void MockQuery::MakeQuery(const DistributedRdb::PredicatesMemo &predicates) +{ + devices_ = predicates.devices_; + tables_ = predicates.tables_; +} int32_t MockGeneralWatcher::OnChange(const Origin &origin, const PRIFields &primaryFields, ChangeInfo &&values) { return GeneralError::E_OK; @@ -34,4 +52,4 @@ int32_t MockGeneralWatcher::OnChange(const Origin &origin, const Fields &fields, { return GeneralError::E_OK; } -} // OHOS::DistributedData +} // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/service/test/mock/general_watcher_mock.h b/services/distributeddataservice/service/test/mock/general_watcher_mock.h index 41c635ff7..0142def54 100644 --- a/services/distributeddataservice/service/test/mock/general_watcher_mock.h +++ b/services/distributeddataservice/service/test/mock/general_watcher_mock.h @@ -14,12 +14,11 @@ */ #ifndef OHOS_DISTRIBUTEDDATA_SERVICE_TEST_GENERAL_WATCH_MOCK_H #define OHOS_DISTRIBUTEDDATA_SERVICE_TEST_GENERAL_WATCH_MOCK_H - -#include "store/general_value.h" +#include "rdb_query.h" #include "store/general_watcher.h" namespace OHOS::DistributedData { -class MockQuery : public GenQuery { +class MockQuery : public DistributedRdb::RdbQuery { public: ~MockQuery() = default; static constexpr uint64_t TYPE_ID = 0x20000001; @@ -28,6 +27,9 @@ public: bool IsEqual(uint64_t tid) override; std::vector GetTables() override; + const std::string GetStatement(); + void MakeRemoteQuery(const std::string &devices, const std::string &sql, DistributedData::Values &&args); + void MakeQuery(const DistributedRdb::PredicatesMemo &predicates); }; class MockGeneralWatcher : public DistributedData::GeneralWatcher { @@ -36,5 +38,5 @@ public: int32_t OnChange(const Origin &origin, const Fields &fields, ChangeData &&datas) override; }; -} // OHOS::DistributedData +} // namespace OHOS::DistributedData #endif \ No newline at end of file diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index de1ef193c..adb46f111 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -21,6 +21,9 @@ #include "bootstrap.h" #include "cloud/schema_meta.h" +#include "error/general_error.h" +#include "errors.h" +#include "eventcenter/event_center.h" #include "gtest/gtest.h" #include "log_print.h" #include "metadata/meta_data_manager.h" @@ -30,6 +33,9 @@ #include "mock/general_watcher_mock.h" #include "rdb_query.h" #include "store/general_store.h" +#include "store/general_value.h" +#include "store_observer.h" +#include "store_types.h" #include "types.h" using namespace testing::ext; @@ -79,6 +85,7 @@ void RdbGeneralStoreTest::InitMetaData() metaData_.storeId = STORE_NAME; metaData_.dataDir = "/data/service/el1/public/database/" + std::string(BUNDLE_NAME) + "/rdb"; metaData_.securityLevel = DistributedKv::SecurityLevel::S2; + metaData_.isSearchable = true; } class MockRelationalStoreDelegate : public DistributedDB::RelationalStoreDelegate { @@ -244,6 +251,7 @@ public: } }; + /** * @tc.name: BindSnapshots001 * @tc.desc: RdbGeneralStore BindSnapshots test @@ -688,6 +696,57 @@ HWTEST_F(RdbGeneralStoreTest, Query002, TestSize.Level1) EXPECT_EQ(result2, nullptr); } +/** + * @tc.name: Query003 + * @tc.desc: Test remote query with invalid device count + * @tc.type: FUNC + */ +HWTEST_F(RdbGeneralStoreTest, Query003, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + + MockQuery query; + const std::string devices = "device1"; + const std::string sql; + Values args; + query.MakeRemoteQuery(devices, sql, std::move(args)); + query.lastResult = true; + std::string table = "test_table"; + MockRelationalStoreDelegate mockDelegate; + store->delegate_ = &mockDelegate; + auto [err, cursor] = store->Query(table, query); + + EXPECT_EQ(err, GeneralError::E_OK); +} + +/** + * @tc.name: Query004 + * @tc.desc: Test successful remote query + * @tc.type: FUNC + */ +HWTEST_F(RdbGeneralStoreTest, Query004, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + + MockQuery query; + const std::string devices = "device1"; + const std::string sql; + Values args; + query.MakeRemoteQuery(devices, sql, std::move(args)); + query.lastResult = true; + + MockRelationalStoreDelegate mockDelegate; + store->delegate_ = &mockDelegate; + + std::string table = "test_table"; + auto [err, cursor] = store->Query(table, query); + + EXPECT_EQ(err, GeneralError::E_OK); + EXPECT_NE(cursor, nullptr); +} + /** * @tc.name: MergeMigratedData * @tc.desc: RdbGeneralStore MergeMigratedData function test @@ -734,6 +793,59 @@ HWTEST_F(RdbGeneralStoreTest, Sync, TestSize.Level1) EXPECT_EQ(result.first, GeneralError::E_OK); } +/** +* @tc.name: Sync +* @tc.desc: RdbGeneralStore Sync CLOUD_TIME_FIRST test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, Sync001, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + GeneralStore::Devices devices; + MockQuery query; + GeneralStore::DetailAsync async; + SyncParam syncParam; + syncParam.mode = GeneralStore::CLOUD_TIME_FIRST; + + MockRelationalStoreDelegate mockDelegate; + store->delegate_ = &mockDelegate; + auto [result1, result2] = store->Sync(devices, query, async, syncParam); + EXPECT_EQ(result1, GeneralError::E_OK); + syncParam.mode = GeneralStore::NEARBY_END; + std::tie(result1, result2) = store->Sync(devices, query, async, syncParam); + EXPECT_EQ(result1, GeneralError::E_ERROR); + syncParam.mode = GeneralStore::NEARBY_PULL_PUSH; + std::tie(result1, result2) = store->Sync(devices, query, async, syncParam); + EXPECT_EQ(result1, GeneralError::E_OK); +} + +/** +* @tc.name: Sync +* @tc.desc: RdbGeneralStore Sync DistributedTable test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, Sync002, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + GeneralStore::Devices devices; + RdbQuery query; + GeneralStore::DetailAsync async; + SyncParam syncParam; + + MockRelationalStoreDelegate mockDelegate; + mockDelegate.CreateDistributedTable("naturalbase_rdb_test"); + mockDelegate.CreateDistributedTable("naturalbase_rdb_name"); + store->delegate_ = &mockDelegate; + auto [result1, result2] = store->Sync(devices, query, async, syncParam); + EXPECT_EQ(result1, GeneralError::E_OK); +} + /** * @tc.name: PreSharing * @tc.desc: RdbGeneralStore PreSharing function test @@ -751,6 +863,46 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing, TestSize.Level1) EXPECT_EQ(result, nullptr); } +/** +* @tc.name: PreSharing +* @tc.desc: RdbGeneralStore PreSharing function test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, PreSharing001, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + MockQuery query; + query.lastResult = true; + auto [errCode, result] = store->PreSharing(query); + EXPECT_EQ(errCode, GeneralError::E_INVALID_ARGS); + EXPECT_EQ(result, nullptr); +} + +/** +* @tc.name: PreSharing +* @tc.desc: RdbGeneralStore PreSharing function test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, PreSharing002, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + MockQuery query; + DistributedRdb::PredicatesMemo predicates; + predicates.devices_ = { "device1" }; + predicates.tables_ = { "tables1" }; + query.lastResult = true; + query.MakeQuery(predicates); + auto [errCode, result] = store->PreSharing(query); + EXPECT_EQ(errCode, GeneralError::E_INVALID_ARGS); + EXPECT_EQ(result, nullptr); +} + /** * @tc.name: ExtractExtend * @tc.desc: RdbGeneralStore ExtractExtend function test @@ -763,7 +915,8 @@ HWTEST_F(RdbGeneralStoreTest, ExtractExtend, TestSize.Level1) auto store = new (std::nothrow) RdbGeneralStore(metaData_); ASSERT_NE(store, nullptr); RdbGeneralStore::VBucket extend = { { "#gid", { "0000000" } }, { "#flag", { true } }, - { "#value", { int64_t(100) } }, { "#float", { double(100) } }, { "#cloud_gid", { "cloud_gid" } } }; + { "#value", { int64_t(100) } }, { "#float", { double(100) } }, { "#cloud_gid", { "cloud_gid" } }, + { "cloud_gid", { "" } } }; DistributedData::VBuckets extends = { { extend } }; auto result = store->ExtractExtend(extends); EXPECT_EQ(result.size(), extends.size()); @@ -865,6 +1018,49 @@ HWTEST_F(RdbGeneralStoreTest, OnChange, TestSize.Level1) EXPECT_EQ(result, GeneralError::E_OK); } +/** +* @tc.name: OnChange001 +* @tc.desc: RdbGeneralStore OnChange function test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, OnChange001, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + MockGeneralWatcher watcher; + MockStoreChangedData data; + DistributedDB::ChangedData changedData; + changedData.primaryData[0] = { { std::monostate{}, 42, 3.14, "hello", true }, + { Bytes{ 1, 2, 3, 4 }, + DistributedDB::Asset{ 1, "zhangsan", "123", "/data/test", "file://xxx", "123", "100", "100", "999", + static_cast(AssetOpType::NO_CHANGE), static_cast(AssetStatus::NORMAL), 0 }, + Bytes{ 5, 6, 7, 8 } }, + { int64_t(-123), 2.718, 100, 0.001 } }; + changedData.primaryData[1] = { { std::monostate{}, 42, 3.14, "hello", true }, + { Bytes{ 1, 2, 3, 4 }, + DistributedDB::Asset{ 1, "zhangsan", "123", "/data/test", "file://xxx", "123", "100", "100", "999", + static_cast(AssetOpType::NO_CHANGE), static_cast(AssetStatus::NORMAL), 0 }, + Bytes{ 5, 6, 7, 8 } }, + { int64_t(-123), 2.718, 100, 0.001 } }; + changedData.primaryData[2] = { { "DELETE#ALL_CLOUDDATA", std::monostate{}, 42, 3.14, "hello", true }, + { Bytes{ 1, 2, 3, 4 }, + DistributedDB::Asset{ 1, "zhangsan", "123", "/data/test", "file://xxx", "123", "100", "100", "999", + static_cast(AssetOpType::NO_CHANGE), static_cast(AssetStatus::NORMAL), 0 }, + Bytes{ 5, 6, 7, 8 } }, + { int64_t(-123), 2.718, 100, 0.001 } }; + changedData.field = { "name", "age" }; + changedData.tableName = "test"; + auto result = store->Watch(GeneralWatcher::Origin::ORIGIN_ALL, watcher); + EXPECT_EQ(result, GeneralError::E_OK); + store->observer_.OnChange(data); + store->observer_.OnChange(DistributedDB::Origin::ORIGIN_CLOUD, "originalId", std::move(changedData)); + store->observer_.OnChange(DistributedDB::Origin::ORIGIN_LOCAL, "originalId", std::move(changedData)); + result = store->Unwatch(GeneralWatcher::Origin::ORIGIN_ALL, watcher); + EXPECT_EQ(result, GeneralError::E_OK); +} + /** * @tc.name: Release * @tc.desc: RdbGeneralStore Release and AddRef function test @@ -1163,5 +1359,24 @@ HWTEST_F(RdbGeneralStoreTest, GetCBTest, TestSize.Level1) auto result = store->GetCB(syncId); ASSERT_NE(result, nullptr); } + +/** +* @tc.name: UpdateDBStatus +* @tc.desc: UpdateDBStatus test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, UpdateDBStatus, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + auto result = store->UpdateDBStatus(); + EXPECT_EQ(result, E_ALREADY_CLOSED); + MockRelationalStoreDelegate mockDelegate; + store->delegate_ = &mockDelegate; + result = store->UpdateDBStatus(); + EXPECT_EQ(result, E_OK); +} } // namespace DistributedRDBTest } // namespace OHOS::Test \ No newline at end of file -- Gitee From e851276399ee56df736fe761235f1996dba70b7b Mon Sep 17 00:00:00 2001 From: yanhui Date: Wed, 9 Apr 2025 21:13:46 +0800 Subject: [PATCH 147/225] =?UTF-8?q?=E5=A2=9E=E5=8A=A0networkId=5F=E5=B1=9E?= =?UTF-8?q?=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yanhui Change-Id: I570bbefc71e2243de319a616cf3b6cbb1e8e24da --- .../communicator/src/softbus_adapter_standard.cpp | 9 ++++----- .../adapter/communicator/src/softbus_client.cpp | 13 ++++++------- .../adapter/communicator/src/softbus_client.h | 6 ++++-- .../test/unittest/softbus_adapter_standard_test.cpp | 6 ++++-- .../test/unittest/softbus_client_test.cpp | 2 +- .../adapter/include/communicator/commu_types.h | 1 - 6 files changed, 19 insertions(+), 18 deletions(-) diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp index 363699e6a..f4df6deec 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp @@ -207,7 +207,7 @@ std::shared_ptr SoftBusAdapter::GetConnect(const PipeInfo &pipeIn uint32_t qosType) { std::shared_ptr conn; - auto networkId = DmAdapter::GetInstance().GetDeviceInfo(deviceId.deviceId).networkId; + std::string networkId = DmAdapter::GetInstance().ToNetworkID(deviceId.deviceId); connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType, &networkId](const auto &key, std::vector> &connects) -> bool { for (auto &connect : connects) { @@ -219,8 +219,7 @@ std::shared_ptr SoftBusAdapter::GetConnect(const PipeInfo &pipeIn return true; } } - DeviceId device = { .deviceId = deviceId.deviceId, .networkId = std::move(networkId) }; - auto connect = std::make_shared(pipeInfo, device, qosType); + auto connect = std::make_shared(pipeInfo, deviceId, networkId, qosType); connects.emplace_back(connect); conn = connect; return true; @@ -367,8 +366,8 @@ std::string SoftBusAdapter::DelConnect(int32_t socket, bool isForce) iter++; } } - if (connects.empty()) { - closedConnect.insert(networkId); + if (connects.empty() && !networkId.empty()) { + closedConnect.insert(std::move(networkId)); return true; } return false; diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp index 84df847a0..23c8c7916 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp @@ -28,8 +28,8 @@ namespace OHOS::AppDistributedKv { using namespace OHOS::DistributedKv; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; using Context = DistributedData::CommunicatorContext; -SoftBusClient::SoftBusClient(const PipeInfo& pipeInfo, const DeviceId& deviceId, uint32_t type) - : type_(type), pipe_(pipeInfo), device_(deviceId) +SoftBusClient::SoftBusClient(const PipeInfo& pipeInfo, const DeviceId& deviceId, const std::string& networkId, + uint32_t type) : type_(type), pipe_(pipeInfo), device_(deviceId), networkId_(networkId) { mtu_ = DEFAULT_MTU_SIZE; } @@ -125,8 +125,7 @@ int32_t SoftBusClient::CreateSocket() const SocketInfo socketInfo; std::string peerName = pipe_.pipeId; socketInfo.peerName = const_cast(peerName.c_str()); - std::string networkId = device_.networkId; - socketInfo.peerNetworkId = const_cast(networkId.c_str()); + socketInfo.peerNetworkId = const_cast(networkId_.c_str()); std::string clientName = pipe_.pipeId; socketInfo.name = const_cast(clientName.c_str()); std::string pkgName = "ohos.distributeddata"; @@ -177,7 +176,7 @@ int32_t SoftBusClient::Open(int32_t socket, uint32_t type, const ISocketListener UpdateBindInfo(socket, mtu, status, async); ZLOGI("open %{public}s, session:%{public}s success, socket:%{public}d", KvStoreUtils::ToBeAnonymous(device_.deviceId).c_str(), pipe_.pipeId.c_str(), socket_); - ConnectManager::GetInstance()->OnSessionOpen(device_.networkId); + ConnectManager::GetInstance()->OnSessionOpen(networkId_); return status; } @@ -257,8 +256,8 @@ Status SoftBusClient::ReuseConnect(const ISocketListener *listener) return status == SOFTBUS_OK ? Status::SUCCESS : Status::NETWORK_ERROR; } -std::string SoftBusClient::GetNetworkId() +const std::string& SoftBusClient::GetNetworkId() const { - return device_.networkId; + return networkId_; } } // namespace OHOS::AppDistributedKv \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.h b/services/distributeddataservice/adapter/communicator/src/softbus_client.h index d4df243c2..a0196c94f 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.h +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.h @@ -33,7 +33,8 @@ public: QOS_REUSE, QOS_BUTT }; - SoftBusClient(const PipeInfo &pipeInfo, const DeviceId &deviceId, uint32_t type = QOS_HML); + SoftBusClient(const PipeInfo &pipeInfo, const DeviceId &deviceId, const std::string& networkId, + uint32_t type = QOS_HML); ~SoftBusClient(); using Time = std::chrono::steady_clock::time_point; @@ -51,7 +52,7 @@ public: void UpdateExpireTime(bool async = true); int32_t GetSoftBusError(); Status ReuseConnect(const ISocketListener *listener); - std::string GetNetworkId(); + const std::string& GetNetworkId() const; private: int32_t Open(int32_t socket, uint32_t type, const ISocketListener *listener, bool async = true); @@ -96,6 +97,7 @@ private: int32_t socket_ = INVALID_SOCKET_ID; int32_t bindState_ = -1; int32_t softBusError_ = 0; + const std::string networkId_; }; } // namespace OHOS::AppDistributedKv diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp index 641166b94..842b47777 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp @@ -181,7 +181,8 @@ HWTEST_F(SoftbusAdapterStandardTest, GetExpireTime, TestSize.Level0) appId.pipeId = "appId"; appId.userId = "groupId"; DeviceId id = {"DeviceId"}; - std::shared_ptr conn = std::make_shared(appId, id, SoftBusClient::QoSType::QOS_HML); + std::shared_ptr conn = std::make_shared( + appId, id, "", SoftBusClient::QoSType::QOS_HML); EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->GetExpireTime(conn)); } @@ -268,7 +269,8 @@ HWTEST_F(SoftbusAdapterStandardTest, OnClientShutdown, TestSize.Level1) appId.pipeId = "appId"; appId.userId = "groupId"; DeviceId id = {"DeviceId"}; - std::shared_ptr conn1 = std::make_shared(appId, id, SoftBusClient::QoSType::QOS_HML); + std::shared_ptr conn1 = std::make_shared( + appId, id, "", SoftBusClient::QoSType::QOS_HML); std::shared_ptr conn2 = nullptr; std::vector> clients; clients.emplace_back(conn1); diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp index 3ba198442..3f1d713de 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp @@ -46,7 +46,7 @@ void SoftbusClientTest::SetUpTestCase(void) pipeInfo.pipeId = "pipeId"; pipeInfo.userId = "userId"; DeviceId id = {"DeviceId"}; - client = std::make_shared(pipeInfo, id); + client = std::make_shared(pipeInfo, id, ""); } void SoftbusClientTest::TearDownTestCase(void) diff --git a/services/distributeddataservice/adapter/include/communicator/commu_types.h b/services/distributeddataservice/adapter/include/communicator/commu_types.h index 6cca6af2f..6b1f1af69 100644 --- a/services/distributeddataservice/adapter/include/communicator/commu_types.h +++ b/services/distributeddataservice/adapter/include/communicator/commu_types.h @@ -71,7 +71,6 @@ struct API_EXPORT PipeInfo { struct API_EXPORT DeviceId { std::string deviceId; - std::string networkId; }; enum class API_EXPORT MessageType { -- Gitee From 004c03403dd712e3d9c28a93f612ca8eddc9ff9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E5=AD=90=E6=9D=8E?= Date: Tue, 8 Apr 2025 18:14:55 +0800 Subject: [PATCH 148/225] fix bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 木子李 --- .../service/udmf/lifecycle/lifecycle_policy.cpp | 4 ++-- .../service/udmf/preprocess/data_handler.cpp | 4 ++-- .../service/udmf/store/runtime_store.cpp | 8 ++++---- .../service/udmf/udmf_service_impl.cpp | 15 ++++++++------- 4 files changed, 16 insertions(+), 15 deletions(-) diff --git a/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.cpp b/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.cpp index cc3d88659..095a95f65 100644 --- a/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.cpp +++ b/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.cpp @@ -30,7 +30,7 @@ Status LifeCyclePolicy::OnGot(const UnifiedKey &key) ZLOGE("Get store failed:%{public}s", key.intention.c_str()); return E_DB_ERROR; } - if (store->Delete(key.key) != E_OK) { + if (store->Delete(UnifiedKey(key.key).GetKeyCommonPrefix()) != E_OK) { ZLOGE("Remove data failed:%{public}s", key.intention.c_str()); return E_DB_ERROR; } @@ -92,7 +92,7 @@ Status LifeCyclePolicy::GetTimeoutKeys( } if (curTime > data.GetRuntime()->createTime + duration_cast(interval).count() || curTime < data.GetRuntime()->createTime) { - timeoutKeys.push_back(data.GetRuntime()->key.key); + timeoutKeys.push_back(UnifiedKey(data.GetRuntime()->key.key).GetKeyCommonPrefix()); } } return E_OK; diff --git a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp index d772d9998..74c7d856a 100644 --- a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp @@ -35,7 +35,7 @@ Status DataHandler::MarshalToEntries(const UnifiedData &unifiedData, std::vector std::vector udKeyBytes = { unifiedKey.begin(), unifiedKey.end() }; Entry entry = { udKeyBytes, runtimeBytes }; entries.emplace_back(entry); - std::string propsKey = unifiedData.GetRuntime()->key.GetPropertyKey() + UD_KEY_PROPERTIES_SEPARATOR; + std::string propsKey = unifiedData.GetRuntime()->key.GetKeyCommonPrefix() + UD_KEY_PROPERTIES_SEPARATOR; std::vector propsBytes; auto propsTlv = TLVObject(propsBytes); if (!TLVUtil::Writing(*unifiedData.GetProperties(), propsTlv, TAG::TAG_PROPERTIES)) { @@ -86,7 +86,7 @@ Status DataHandler::UnmarshalEntryItem(UnifiedData &unifiedData, const std::vect continue; } auto isStartWithKey = keyStr.find(key) == 0; - std::string propsKey = UnifiedKey(key).GetPropertyKey() + UD_KEY_PROPERTIES_SEPARATOR; + std::string propsKey = UnifiedKey(key).GetKeyCommonPrefix() + UD_KEY_PROPERTIES_SEPARATOR; if (!isStartWithKey && (keyStr == propsKey)) { std::shared_ptr properties; if (!TLVUtil::ReadTlv(properties, data, TAG::TAG_PROPERTIES)) { diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index 764c43230..da14366c4 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -113,7 +113,7 @@ Status RuntimeStore::Get(const std::string &key, UnifiedData &unifiedData) { UpdateTime(); std::vector entries; - if (GetEntries(UnifiedKey(key).GetPropertyKey(), entries) != E_OK) { + if (GetEntries(UnifiedKey(key).GetKeyCommonPrefix(), entries) != E_OK) { ZLOGE("GetEntries failed, dataPrefix: %{public}s.", key.c_str()); return E_DB_ERROR; } @@ -135,7 +135,7 @@ Status RuntimeStore::PutSummary(const UnifiedData &data, std::vector &ent UnifiedDataHelper::GetSummary(data, summary); } - auto propertyKey = data.GetRuntime()->key.GetPropertyKey(); + auto propertyKey = data.GetRuntime()->key.GetKeyCommonPrefix(); Value value; auto status = DataHandler::MarshalToEntries(summary, value, TAG::TAG_SUMMARY); if (status != E_OK) { @@ -151,7 +151,7 @@ Status RuntimeStore::GetSummary(UnifiedKey &key, Summary &summary) { UpdateTime(); Value value; - auto summaryKey = key.GetPropertyKey() + SUMMARY_SUFIX; + auto summaryKey = key.GetKeyCommonPrefix() + SUMMARY_SUFIX; auto res = kvStore_->Get({summaryKey.begin(), summaryKey.end()}, value); if (res != OK || value.empty()) { ZLOGW("Get stored summary failed, key: %{public}s, status:%{public}d", summaryKey.c_str(), res); @@ -213,7 +213,7 @@ Status RuntimeStore::GetRuntime(const std::string &key, Runtime &runtime) Status RuntimeStore::Update(const UnifiedData &unifiedData) { std::string key = unifiedData.GetRuntime()->key.key; - if (Delete(key) != E_OK) { + if (Delete(UnifiedKey(key).GetKeyCommonPrefix()) != E_OK) { UpdateTime(); ZLOGE("Delete unified data failed, dataPrefix: %{public}s.", key.c_str()); return E_DB_ERROR; diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 966cda233..6e89f011b 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -437,7 +437,7 @@ int32_t UdmfServiceImpl::DeleteData(const QueryOption &query, std::vectortokenId == query.tokenId) { unifiedDataSet.push_back(data); - deleteKeys.push_back(runtime->key.key); + deleteKeys.push_back(UnifiedKey(runtime->key.key).GetKeyCommonPrefix()); } } if (deleteKeys.empty()) { @@ -705,15 +705,16 @@ int32_t UdmfServiceImpl::QueryDataCommon( { auto find = UD_INTENTION_MAP.find(query.intention); std::string intention = find == UD_INTENTION_MAP.end() ? intention : find->second; - if (!UnifiedDataUtils::IsValidOptions(query.key, intention)) { + UnifiedKey key(query.key); + if (!UnifiedDataUtils::IsValidOptions(key, intention, UD_INTENTION_MAP.at(UD_INTENTION_DATA_HUB))) { ZLOGE("Unified key: %{public}s and intention: %{public}s is invalid.", query.key.c_str(), intention.c_str()); return E_INVALID_PARAMETERS; } - std::string dataPrefix = DATA_PREFIX + intention; - UnifiedKey key(query.key); - key.IsValid(); - if (intention.empty()) { - dataPrefix = UnifiedKey(key.key).GetPropertyKey(); + std::string dataPrefix; + if (key.key.empty()) { + dataPrefix = DATA_PREFIX + intention; + } else { + dataPrefix = UnifiedKey(key.key).GetKeyCommonPrefix(); intention = key.intention; } ZLOGD("dataPrefix = %{public}s, intention: %{public}s.", dataPrefix.c_str(), intention.c_str()); -- Gitee From cff7be68412d06b149c606e862e96566ba6a661e Mon Sep 17 00:00:00 2001 From: wTong6 Date: Fri, 11 Apr 2025 14:43:22 +0800 Subject: [PATCH 149/225] fix Signed-off-by: wTong6 --- .../service/cloud/cloud_service_impl.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index c1e772133..cf3f5d1d7 100644 --- a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -791,7 +791,8 @@ std::pair CloudServiceImpl::GetCloudInfoFromServer(int32_t u ZLOGD("cloud server is nullptr, user:%{public}d", userId); return { SERVER_UNAVAILABLE, cloudInfo }; } - return instance->GetServerInfo(cloudInfo.user, false); + auto [code, info] = instance->GetServerInfo(cloudInfo.user, false); + return { code != E_OK ? code : info.IsValid() ? E_OK : E_ERROR, info }; } int32_t CloudServiceImpl::UpdateCloudInfoFromServer(int32_t user) -- Gitee From 0295e61e3ab8fabd9347b168d091ab4ea9cb1ce3 Mon Sep 17 00:00:00 2001 From: Axi_Beft Date: Thu, 10 Apr 2025 16:46:54 +0800 Subject: [PATCH 150/225] datashare add uri log Signed-off-by: Axi_Beft --- .../service/data_share/data_share_service_stub.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp index d0b000ee9..e7cddaba8 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp @@ -53,6 +53,8 @@ int32_t DataShareServiceStub::OnInsertEx(MessageParcel &data, MessageParcel &rep return IPC_STUB_INVALID_DATA_ERR; } auto [errCode, status] = InsertEx(uri, extUri, bucket); + ZLOGI("Insert uri:%{public}s, errCode:%{public}x, status:%{public}x", + DistributedData::Anonymous::Change(uri).c_str(), errCode, status); if (!ITypesUtil::Marshal(reply, errCode, status)) { ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status); return IPC_STUB_WRITE_PARCEL_ERR; @@ -72,6 +74,8 @@ int32_t DataShareServiceStub::OnUpdateEx(MessageParcel &data, MessageParcel &rep return IPC_STUB_INVALID_DATA_ERR; } auto [errCode, status] = UpdateEx(uri, extUri, predicate, bucket); + ZLOGI("Update uri:%{public}s, errCode:%{public}x, status:%{public}x", + DistributedData::Anonymous::Change(uri).c_str(), errCode, status); if (!ITypesUtil::Marshal(reply, errCode, status)) { ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status); return IPC_STUB_WRITE_PARCEL_ERR; @@ -89,6 +93,8 @@ int32_t DataShareServiceStub::OnDeleteEx(MessageParcel &data, MessageParcel &rep return IPC_STUB_INVALID_DATA_ERR; } auto [errCode, status] = DeleteEx(uri, extUri, predicate); + ZLOGI("Delete uri:%{public}s, errCode:%{public}x, status:%{public}x", + DistributedData::Anonymous::Change(uri).c_str(), errCode, status); if (!ITypesUtil::Marshal(reply, errCode, status)) { ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status); return IPC_STUB_WRITE_PARCEL_ERR; -- Gitee From 603cb3e07c094f30e91f84d550fc595cb4346fd7 Mon Sep 17 00:00:00 2001 From: zqz Date: Tue, 1 Apr 2025 22:32:03 +0800 Subject: [PATCH 151/225] Signed-off-by: zqz Change-Id: I08c9b9b1ae636f24cd1610cd35daeebc66bb23d2 Signed-off-by: zqz Change-Id: Id62faa59a5a4f17f7a1cec4d61e7f13399a3a5af Signed-off-by: zqz --- .../service/rdb/rdb_service_impl.cpp | 21 +++++++++++++------ .../service/rdb/rdb_service_impl.h | 2 ++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index c4123e299..cbbf4c1f2 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -812,6 +812,20 @@ void RdbServiceImpl::SetReturnParam(StoreMetaData &metadata, RdbSyncerParam &par param.haMode_ = metadata.haMode; } +void RdbServiceImpl::SaveLaunchInfo(StoreMetaData &meta) +{ + RemoteChangeEvent::DataInfo info; + info.bundleName = meta.bundleName; + info.deviceId = meta.deviceId; + info.userId = meta.user; + if (executors_ != nullptr) { + executors_->Schedule(ExecutorPool::INVALID_DELAY, [dataInfo = std::move(info)]() mutable { + auto evt = std::make_unique(RemoteChangeEvent::RDB_META_SAVE, std::move(dataInfo)); + EventCenter::GetInstance().PostEvent(std::move(evt)); + }); + } +} + int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) { XCollie xcollie(__FUNCTION__, XCollie::XCOLLIE_LOG | XCollie::XCOLLIE_RECOVERY); @@ -833,12 +847,7 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); AutoLaunchMetaData launchData; if (!MetaDataManager::GetInstance().LoadMeta(meta.GetAutoLaunchKey(), launchData, true)) { - RemoteChangeEvent::DataInfo info; - info.bundleName = meta.bundleName; - info.deviceId = meta.deviceId; - info.userId = meta.user; - auto evt = std::make_unique(RemoteChangeEvent::RDB_META_SAVE, std::move(info)); - EventCenter::GetInstance().PostEvent(std::move(evt)); + SaveLaunchInfo(meta); } } diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.h b/services/distributeddataservice/service/rdb/rdb_service_impl.h index da3d154cf..e58c6618f 100755 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -245,6 +245,8 @@ private: bool TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, StoreMetaData &meta); + void SaveLaunchInfo(StoreMetaData &meta); + static Factory factory_; ConcurrentMap syncAgents_; std::shared_ptr executors_; -- Gitee From beff14b6981e06bba4066dd168735606e5b26c34 Mon Sep 17 00:00:00 2001 From: Jeam_wang Date: Thu, 3 Apr 2025 21:22:05 +0800 Subject: [PATCH 152/225] =?UTF-8?q?=E8=B4=A6=E6=88=B7=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E8=83=BD=E5=8A=9B=E7=9B=91=E5=90=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jeam_wang --- .../adapter/network/src/network_delegate_normal_impl.cpp | 2 +- services/distributeddataservice/app/BUILD.gn | 1 + .../app/src/kvstore_data_service.cpp | 8 ++++++-- .../framework/include/network/network_delegate.h | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp index 1edda0333..5f6d25db0 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp +++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp @@ -121,7 +121,7 @@ void NetworkDelegateNormalImpl::RegOnNetworkChange() void NetworkDelegateNormalImpl::BindExecutor(std::shared_ptr executors) { - executors_ = executors; + executors_ = std::move(executors); } ExecutorPool::Task NetworkDelegateNormalImpl::GetTask(uint32_t retry) diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index 084cbb75e..4c0087d06 100644 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -125,6 +125,7 @@ ohos_shared_library("distributeddataservice") { configs = [ ":module_private_config" ] deps = [ + "${data_service_path}/adapter/network:distributeddata_network", "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/app/src/checker:distributeddata_checker", "${data_service_path}/app/src/installer:distributeddata_installer", diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index 2c26686d8..b64886f8d 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -322,6 +322,7 @@ void KvStoreDataService::OnStart() AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); AddSystemAbilityListener(MEMORY_MANAGER_SA_ID); AddSystemAbilityListener(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID); + AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN); RegisterStoreInfo(); Handler handlerStoreInfo = std::bind(&KvStoreDataService::DumpStoreInfo, this, std::placeholders::_1, std::placeholders::_2); @@ -356,9 +357,10 @@ void KvStoreDataService::OnAddSystemAbility(int32_t systemAbilityId, const std:: ZLOGI("add system abilityid:%{public}d", systemAbilityId); (void)deviceId; if (systemAbilityId == COMMON_EVENT_SERVICE_ID) { - AccountDelegate::GetInstance()->SubscribeAccountEvent(); Installer::GetInstance().Init(this, executors_); ScreenManager::GetInstance()->SubscribeScreenEvent(); + } else if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { + AccountDelegate::GetInstance()->SubscribeAccountEvent(); } else if (systemAbilityId == MEMORY_MANAGER_SA_ID) { Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), 1, 1, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); @@ -372,10 +374,12 @@ void KvStoreDataService::OnRemoveSystemAbility(int32_t systemAbilityId, const st { ZLOGI("remove system abilityid:%{public}d", systemAbilityId); (void)deviceId; + if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { + AccountDelegate::GetInstance()->UnsubscribeAccountEvent(); + } if (systemAbilityId != COMMON_EVENT_SERVICE_ID) { return; } - AccountDelegate::GetInstance()->UnsubscribeAccountEvent(); ScreenManager::GetInstance()->UnsubscribeScreenEvent(); Installer::GetInstance().UnsubscribeEvent(); } diff --git a/services/distributeddataservice/framework/include/network/network_delegate.h b/services/distributeddataservice/framework/include/network/network_delegate.h index 505902a4f..38763f58d 100644 --- a/services/distributeddataservice/framework/include/network/network_delegate.h +++ b/services/distributeddataservice/framework/include/network/network_delegate.h @@ -20,7 +20,7 @@ #include #include "executor_pool.h" -#include "types.h" +#include "visibility.h" namespace OHOS { namespace DistributedData { -- Gitee From c78ae1c18376fe660f9e91fc8c5517f1b165d852 Mon Sep 17 00:00:00 2001 From: gecheng Date: Tue, 15 Apr 2025 09:50:32 +0800 Subject: [PATCH 153/225] =?UTF-8?q?=E7=94=A8=E4=BE=8B=E7=AD=89=E7=BA=A7?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gecheng --- .../service/test/cloud_data_test.cpp | 82 +++++++++---------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/services/distributeddataservice/service/test/cloud_data_test.cpp b/services/distributeddataservice/service/test/cloud_data_test.cpp index 8b5655a44..c73a92d27 100644 --- a/services/distributeddataservice/service/test/cloud_data_test.cpp +++ b/services/distributeddataservice/service/test/cloud_data_test.cpp @@ -321,7 +321,7 @@ void CloudDataTest::TearDown() * @tc.require: * @tc.author: ht */ -HWTEST_F(CloudDataTest, GetSchema, TestSize.Level0) +HWTEST_F(CloudDataTest, GetSchema, TestSize.Level1) { auto cloudServerMock = std::make_shared(); auto user = AccountDelegate::GetInstance()->GetUserByToken(OHOS::IPCSkeleton::GetCallingTokenID()); @@ -384,7 +384,7 @@ HWTEST_F(CloudDataTest, QueryStatistics002, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryStatistics003, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryStatistics003, TestSize.Level1) { // Construct the statisticInfo data auto creator = [](const StoreMetaData &metaData) -> GeneralStore* { @@ -420,7 +420,7 @@ HWTEST_F(CloudDataTest, QueryStatistics003, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryStatistics004, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryStatistics004, TestSize.Level1) { // Construct the statisticInfo data auto creator = [](const StoreMetaData &metaData) -> GeneralStore* { @@ -494,7 +494,7 @@ HWTEST_F(CloudDataTest, QueryLastSyncInfo003, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryLastSyncInfo004, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryLastSyncInfo004, TestSize.Level1) { auto ret = cloudServiceImpl_->DisableCloud(TEST_CLOUD_ID); EXPECT_EQ(ret, CloudData::CloudService::SUCCESS); @@ -518,7 +518,7 @@ HWTEST_F(CloudDataTest, QueryLastSyncInfo004, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryLastSyncInfo005, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryLastSyncInfo005, TestSize.Level1) { std::map switches; switches.emplace(TEST_CLOUD_ID, true); @@ -739,7 +739,7 @@ HWTEST_F(CloudDataTest, QueryLastSyncInfo010, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryLastSyncInfo011, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryLastSyncInfo011, TestSize.Level1) { schemaMeta_.databases[1].name = TEST_CLOUD_STORE_1; MetaDataManager::GetInstance().SaveMeta(cloudInfo_.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta_, true); @@ -868,7 +868,7 @@ HWTEST_F(CloudDataTest, UpdateFinishSyncInfo, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, Share001, TestSize.Level0) +HWTEST_F(CloudDataTest, Share001, TestSize.Level1) { std::string sharingRes = ""; CloudData::Participants participants{}; @@ -883,7 +883,7 @@ HWTEST_F(CloudDataTest, Share001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, Unshare001, TestSize.Level0) +HWTEST_F(CloudDataTest, Unshare001, TestSize.Level1) { std::string sharingRes = ""; CloudData::Participants participants{}; @@ -898,7 +898,7 @@ HWTEST_F(CloudDataTest, Unshare001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, ChangePrivilege001, TestSize.Level0) +HWTEST_F(CloudDataTest, ChangePrivilege001, TestSize.Level1) { std::string sharingRes = ""; CloudData::Participants participants{}; @@ -913,7 +913,7 @@ HWTEST_F(CloudDataTest, ChangePrivilege001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, ChangeConfirmation001, TestSize.Level0) +HWTEST_F(CloudDataTest, ChangeConfirmation001, TestSize.Level1) { std::string sharingRes = ""; int32_t confirmation = 0; @@ -928,7 +928,7 @@ HWTEST_F(CloudDataTest, ChangeConfirmation001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, ConfirmInvitation001, TestSize.Level0) +HWTEST_F(CloudDataTest, ConfirmInvitation001, TestSize.Level1) { std::string sharingRes = ""; int32_t confirmation = 0; @@ -943,7 +943,7 @@ HWTEST_F(CloudDataTest, ConfirmInvitation001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, Exit001, TestSize.Level0) +HWTEST_F(CloudDataTest, Exit001, TestSize.Level1) { std::string sharingRes = ""; std::pair result; @@ -957,7 +957,7 @@ HWTEST_F(CloudDataTest, Exit001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, Query001, TestSize.Level0) +HWTEST_F(CloudDataTest, Query001, TestSize.Level1) { std::string sharingRes = ""; CloudData::QueryResults result; @@ -971,7 +971,7 @@ HWTEST_F(CloudDataTest, Query001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryByInvitation001, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryByInvitation001, TestSize.Level1) { std::string invitation = ""; CloudData::QueryResults result; @@ -1015,7 +1015,7 @@ HWTEST_F(CloudDataTest, AllocResourceAndShare001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, SetGlobalCloudStrategy001, TestSize.Level0) +HWTEST_F(CloudDataTest, SetGlobalCloudStrategy001, TestSize.Level1) { std::vector values; values.push_back(CloudData::NetWorkStrategy::WIFI); @@ -1033,7 +1033,7 @@ HWTEST_F(CloudDataTest, SetGlobalCloudStrategy001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, SetCloudStrategy001, TestSize.Level0) +HWTEST_F(CloudDataTest, SetCloudStrategy001, TestSize.Level1) { std::vector values; values.push_back(CloudData::NetWorkStrategy::WIFI); @@ -1148,7 +1148,7 @@ HWTEST_F(CloudDataTest, NotifyDataChange002, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, NotifyDataChange003, TestSize.Level0) +HWTEST_F(CloudDataTest, NotifyDataChange003, TestSize.Level1) { constexpr const int32_t userId = 100; constexpr const int32_t defaultUserId = 0; @@ -1300,7 +1300,7 @@ HWTEST_F(CloudDataTest, EnableCloud, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnEnableCloud, TestSize.Level0) +HWTEST_F(CloudDataTest, OnEnableCloud, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1321,7 +1321,7 @@ HWTEST_F(CloudDataTest, OnEnableCloud, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnDisableCloud, TestSize.Level0) +HWTEST_F(CloudDataTest, OnDisableCloud, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1340,7 +1340,7 @@ HWTEST_F(CloudDataTest, OnDisableCloud, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnChangeAppSwitch, TestSize.Level0) +HWTEST_F(CloudDataTest, OnChangeAppSwitch, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1361,7 +1361,7 @@ HWTEST_F(CloudDataTest, OnChangeAppSwitch, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnClean, TestSize.Level0) +HWTEST_F(CloudDataTest, OnClean, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1382,7 +1382,7 @@ HWTEST_F(CloudDataTest, OnClean, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnNotifyDataChange, TestSize.Level0) +HWTEST_F(CloudDataTest, OnNotifyDataChange, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1402,7 +1402,7 @@ HWTEST_F(CloudDataTest, OnNotifyDataChange, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnNotifyChange, TestSize.Level0) +HWTEST_F(CloudDataTest, OnNotifyChange, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1424,7 +1424,7 @@ HWTEST_F(CloudDataTest, OnNotifyChange, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnQueryStatistics, TestSize.Level0) +HWTEST_F(CloudDataTest, OnQueryStatistics, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1445,7 +1445,7 @@ HWTEST_F(CloudDataTest, OnQueryStatistics, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnQueryLastSyncInfo, TestSize.Level0) +HWTEST_F(CloudDataTest, OnQueryLastSyncInfo, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1466,7 +1466,7 @@ HWTEST_F(CloudDataTest, OnQueryLastSyncInfo, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnSetGlobalCloudStrategy, TestSize.Level0) +HWTEST_F(CloudDataTest, OnSetGlobalCloudStrategy, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1488,7 +1488,7 @@ HWTEST_F(CloudDataTest, OnSetGlobalCloudStrategy, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnAllocResourceAndShare, TestSize.Level0) +HWTEST_F(CloudDataTest, OnAllocResourceAndShare, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1512,7 +1512,7 @@ HWTEST_F(CloudDataTest, OnAllocResourceAndShare, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnShare, TestSize.Level0) +HWTEST_F(CloudDataTest, OnShare, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1534,7 +1534,7 @@ HWTEST_F(CloudDataTest, OnShare, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnUnshare, TestSize.Level0) +HWTEST_F(CloudDataTest, OnUnshare, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1556,7 +1556,7 @@ HWTEST_F(CloudDataTest, OnUnshare, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnExit, TestSize.Level0) +HWTEST_F(CloudDataTest, OnExit, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1577,7 +1577,7 @@ HWTEST_F(CloudDataTest, OnExit, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnChangePrivilege, TestSize.Level0) +HWTEST_F(CloudDataTest, OnChangePrivilege, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1599,7 +1599,7 @@ HWTEST_F(CloudDataTest, OnChangePrivilege, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnQuery, TestSize.Level0) +HWTEST_F(CloudDataTest, OnQuery, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1620,7 +1620,7 @@ HWTEST_F(CloudDataTest, OnQuery, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnQueryByInvitation, TestSize.Level0) +HWTEST_F(CloudDataTest, OnQueryByInvitation, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1641,7 +1641,7 @@ HWTEST_F(CloudDataTest, OnQueryByInvitation, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnConfirmInvitation, TestSize.Level0) +HWTEST_F(CloudDataTest, OnConfirmInvitation, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1663,7 +1663,7 @@ HWTEST_F(CloudDataTest, OnConfirmInvitation, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnChangeConfirmation, TestSize.Level0) +HWTEST_F(CloudDataTest, OnChangeConfirmation, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1982,7 +1982,7 @@ HWTEST_F(CloudDataTest, UpdateCloudInfoFromServer, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, GetCloudInfo, TestSize.Level0) +HWTEST_F(CloudDataTest, GetCloudInfo, TestSize.Level1) { MetaDataManager::GetInstance().DelMeta(cloudInfo_.GetKey(), true); auto ret = cloudServiceImpl_->GetCloudInfo(cloudInfo_.user); @@ -2202,7 +2202,7 @@ HWTEST_F(CloudDataTest, OnAppUninstall, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, GetCloudInfo001, TestSize.Level0) +HWTEST_F(CloudDataTest, GetCloudInfo001, TestSize.Level1) { int32_t userId = 1000; auto [status, cloudInfo] = cloudServiceImpl_->GetCloudInfo(userId); @@ -2504,7 +2504,7 @@ HWTEST_F(CloudDataTest, GetPriorityLevel004, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, UpdateSchemaFromHap001, TestSize.Level0) +HWTEST_F(CloudDataTest, UpdateSchemaFromHap001, TestSize.Level1) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudData::CloudServiceImpl::HapInfo info = { .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE, .user = -1 }; @@ -2518,7 +2518,7 @@ HWTEST_F(CloudDataTest, UpdateSchemaFromHap001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, UpdateSchemaFromHap002, TestSize.Level0) +HWTEST_F(CloudDataTest, UpdateSchemaFromHap002, TestSize.Level1) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudData::CloudServiceImpl::HapInfo info = { .instIndex = 0, .bundleName = "", .user = cloudInfo_.user }; @@ -2532,7 +2532,7 @@ HWTEST_F(CloudDataTest, UpdateSchemaFromHap002, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, UpdateSchemaFromHap003, TestSize.Level0) +HWTEST_F(CloudDataTest, UpdateSchemaFromHap003, TestSize.Level1) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudData::CloudServiceImpl::HapInfo info = { @@ -2552,7 +2552,7 @@ HWTEST_F(CloudDataTest, UpdateSchemaFromHap003, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, UpdateSchemaFromHap004, TestSize.Level0) +HWTEST_F(CloudDataTest, UpdateSchemaFromHap004, TestSize.Level1) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudInfo::AppInfo exampleAppInfo; -- Gitee From 32b7cb46c944d2c9520ccb6ff483e9f996b6f2f0 Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Tue, 15 Apr 2025 14:51:49 +0800 Subject: [PATCH 154/225] fix clear bug Signed-off-by: wanghuajian-6 --- .../service/object/include/object_manager.h | 5 ++--- .../service/object/src/object_manager.cpp | 9 ++++----- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/services/distributeddataservice/service/object/include/object_manager.h b/services/distributeddataservice/service/object/include/object_manager.h index 8fdaea708..b1e69d0c1 100644 --- a/services/distributeddataservice/service/object/include/object_manager.h +++ b/services/distributeddataservice/service/object/include/object_manager.h @@ -196,10 +196,9 @@ private: { return appId + SEPERATOR + sessionId + SEPERATOR; }; - inline std::string GetMetaUserIdKey(const std::string &userId, const std::string &appId) + inline std::string GetMetaUserIdKey(const std::string &appId) { - return std::string(USERID) + SEPERATOR + userId + SEPERATOR + appId + SEPERATOR - + DmAdaper::GetInstance().GetLocalDevice().udid; + return std::string(USERID) + SEPERATOR + appId + SEPERATOR + DmAdaper::GetInstance().GetLocalDevice().udid; }; std::recursive_mutex kvStoreMutex_; std::shared_ptr kvStoreDelegateManager_ = nullptr; diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index c86d28e1b..00bf53435 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -297,7 +297,7 @@ int32_t ObjectStoreManager::Clear() } std::vector metaData; std::string appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); - std::string metaKey = GetMetaUserIdKey(userId, appId); + std::string metaKey = GetMetaUserIdKey(appId); if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(metaKey, metaData, true)) { ZLOGE("no store of %{public}s", appId.c_str()); return OBJECT_STORE_NOT_FOUND; @@ -338,11 +338,10 @@ int32_t ObjectStoreManager::DeleteByAppId(const std::string &appId, int32_t user appId.c_str(), user); } Close(); - std::string userId = std::to_string(user); - std::string metaKey = GetMetaUserIdKey(userId, appId); + std::string metaKey = GetMetaUserIdKey(appId); auto status = DistributedData::MetaDataManager::GetInstance().DelMeta(metaKey, true); if (!status) { - ZLOGE("Delete meta failed, userId: %{public}s, appId: %{public}s", userId.c_str(), appId.c_str()); + ZLOGE("Delete meta failed, userId: %{public}d, appId: %{public}s", user, appId.c_str()); } return result; } @@ -1104,7 +1103,7 @@ void ObjectStoreManager::SaveUserToMeta() userMeta.storeId = DistributedObject::ObjectCommon::OBJECTSTORE_DB_STOREID; userMeta.user = userId; userMeta.storeType = ObjectDistributedType::OBJECT_SINGLE_VERSION; - std::string userMetaKey = GetMetaUserIdKey(userId, appId); + std::string userMetaKey = GetMetaUserIdKey(appId); auto saved = DistributedData::MetaDataManager::GetInstance().SaveMeta(userMetaKey, userMeta, true); if (!saved) { ZLOGE("userMeta save failed"); -- Gitee From 7547c780df77efadc8ff34dbc70e269ee030ac70 Mon Sep 17 00:00:00 2001 From: zph Date: Tue, 15 Apr 2025 16:50:40 +0800 Subject: [PATCH 155/225] update Signed-off-by: zph --- .../service/test/udmf_run_time_store_test.cpp | 49 +++++++++++++++++++ .../service/udmf/store/runtime_store.cpp | 4 ++ 2 files changed, 53 insertions(+) diff --git a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp index 99f347cf5..962adbcbf 100644 --- a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp +++ b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp @@ -670,5 +670,54 @@ HWTEST_F(UdmfRunTimeStoreTest, GetSummary, TestSize.Level1) auto status = store->GetSummary(key, summary); ASSERT_EQ(status, E_DB_ERROR); } + +/** +* @tc.name: GetRuntime001 +* @tc.desc: Normal testcase of GetRuntime +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, GetRuntime001, TestSize.Level1) +{ + UnifiedData inputData; + CustomOption option = {.intention = Intention::UD_INTENTION_DRAG}; + auto status = PreProcessUtils::RuntimeDataImputation(inputData, option); + EXPECT_EQ(status, E_OK); + auto key = inputData.GetRuntime()->key.GetUnifiedKey(); + + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + status = store->PutRuntime(key, *inputData.GetRuntime()); + EXPECT_EQ(status, E_OK); + + Runtime outRuntime; + status = store->GetRuntime(key, outRuntime); + EXPECT_EQ(status, E_OK); + EXPECT_EQ(inputData.GetRuntime()->createTime, outRuntime.createTime); +} + +/** +* @tc.name: GetRuntime002 +* @tc.desc: Abnormal testcase of GetRuntime +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, GetRuntime002, TestSize.Level1) +{ + UnifiedData inputData; + CustomOption option = {.intention = Intention::UD_INTENTION_DRAG}; + auto status = PreProcessUtils::RuntimeDataImputation(inputData, option); + EXPECT_EQ(status, E_OK); + auto key = inputData.GetRuntime()->key.GetUnifiedKey(); + + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + + Runtime outRuntime; + status = store->GetRuntime(key, outRuntime); + EXPECT_EQ(status, E_NOT_FOUND); +} }; // namespace DistributedDataTest }; // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index da14366c4..fa6f511e9 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -198,6 +198,10 @@ Status RuntimeStore::GetRuntime(const std::string &key, Runtime &runtime) UpdateTime(); Value value; auto res = kvStore_->Get({key.begin(), key.end()}, value); + if (res == NOT_FOUND) { + ZLOGW("Runtime not found, key: %{public}s", key.c_str()); + return E_NOT_FOUND; + } if (res != OK || value.empty()) { ZLOGE("Get failed, key: %{public}s, status:%{public}d", key.c_str(), res); return E_DB_ERROR; -- Gitee From c22d8ee255f8c498a93b6825233e07b9bf8cdaa2 Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Tue, 15 Apr 2025 20:16:01 +0800 Subject: [PATCH 156/225] fix clear bug Signed-off-by: wanghuajian-6 --- .../distributeddataservice/framework/BUILD.gn | 1 + .../include/metadata/object_user_meta_data.h | 37 ++++++++++++ .../metadata/object_user_meta_data.cpp | 38 ++++++++++++ .../service/object/include/object_manager.h | 6 +- .../service/object/src/object_manager.cpp | 60 +++++++++++-------- .../object/src/object_service_impl.cpp | 1 + 6 files changed, 116 insertions(+), 27 deletions(-) create mode 100644 services/distributeddataservice/framework/include/metadata/object_user_meta_data.h create mode 100644 services/distributeddataservice/framework/metadata/object_user_meta_data.cpp diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index 344f08426..a1ba24c67 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -92,6 +92,7 @@ ohos_shared_library("distributeddatasvcfwk") { "metadata/matrix_meta_data.cpp", "metadata/meta_data.cpp", "metadata/meta_data_manager.cpp", + "metadata/object_user_meta_data.cpp", "metadata/secret_key_meta_data.cpp", "metadata/store_debug_info.cpp", "metadata/store_meta_data.cpp", diff --git a/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h b/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h new file mode 100644 index 000000000..91e81b868 --- /dev/null +++ b/services/distributeddataservice/framework/include/metadata/object_user_meta_data.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 DISTRIBUTEDDATAMGR_OBJECT_USER_META_DATA_H +#define DISTRIBUTEDDATAMGR_OBJECT_USER_META_DATA_H +#include +#include + +#include "serializable/serializable.h" +namespace OHOS::DistributedData { +class API_EXPORT ObjectUserMetaData final : public Serializable { +public: + std::string userId; + + API_EXPORT bool Marshal(json &node) const override; + API_EXPORT bool Unmarshal(const json &node) override; + API_EXPORT ObjectUserMetaData(); + + API_EXPORT static std::string GetKey(); + +private: + static constexpr const char *KEY_PREFIX = "ObjectUserMetaData"; +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_OBJECT_USER_META_DATA_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp b/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp new file mode 100644 index 000000000..9324ebc28 --- /dev/null +++ b/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp @@ -0,0 +1,38 @@ +/* + * 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 "metadata/object_user_meta_data.h" + +#include "utils/constant.h" + +namespace OHOS::DistributedData { + +ObjectUserMetaData::ObjectUserMetaData() +{ +} +bool ObjectUserMetaData::Marshal(json &node) const +{ + return SetValue(node[GET_NAME(userId)], userId); +} + +bool ObjectUserMetaData::Unmarshal(const json &node) +{ + return GetValue(node, GET_NAME(userId), userId); +} + +std::string ObjectUserMetaData::GetKey() +{ + return KEY_PREFIX; +} +} \ No newline at end of file diff --git a/services/distributeddataservice/service/object/include/object_manager.h b/services/distributeddataservice/service/object/include/object_manager.h index b1e69d0c1..f1e38aa20 100644 --- a/services/distributeddataservice/service/object/include/object_manager.h +++ b/services/distributeddataservice/service/object/include/object_manager.h @@ -89,6 +89,7 @@ public: sptr callback, uint32_t tokenId); void SetData(const std::string &dataDir, const std::string &userId); int32_t Clear(); + int32_t ClearOldUserMeta(); int32_t DeleteByAppId(const std::string &appId, int32_t user); void RegisterRemoteCallback(const std::string &bundleName, const std::string &sessionId, pid_t pid, uint32_t tokenId, @@ -196,9 +197,10 @@ private: { return appId + SEPERATOR + sessionId + SEPERATOR; }; - inline std::string GetMetaUserIdKey(const std::string &appId) + inline std::string GetMetaUserIdKey(const std::string &userId, const std::string &appId) { - return std::string(USERID) + SEPERATOR + appId + SEPERATOR + DmAdaper::GetInstance().GetLocalDevice().udid; + return std::string(USERID) + SEPERATOR + userId + SEPERATOR + appId + SEPERATOR + + DmAdaper::GetInstance().GetLocalDevice().udid; }; std::recursive_mutex kvStoreMutex_; std::shared_ptr kvStoreDelegateManager_ = nullptr; diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 00bf53435..6c4987a8c 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -29,6 +29,7 @@ #include "kvstore_utils.h" #include "log_print.h" #include "metadata/meta_data_manager.h" +#include "metadata/object_user_meta_data.h" #include "metadata/store_meta_data.h" #include "object_dms_handler.h" #include "object_radar_reporter.h" @@ -295,23 +296,15 @@ int32_t ObjectStoreManager::Clear() if (userId.empty()) { return OBJECT_INNER_ERROR; } - std::vector metaData; - std::string appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); - std::string metaKey = GetMetaUserIdKey(appId); - if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(metaKey, metaData, true)) { - ZLOGE("no store of %{public}s", appId.c_str()); + DistributedData::ObjectUserMetaData userMeta; + std::string userMetaKey = DistributedData::ObjectUserMetaData::GetKey(); + if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(userMetaKey, userMeta, true)) { + ZLOGE("no meta of userId:%{public}s", userId.c_str()); return OBJECT_STORE_NOT_FOUND; } - for (const auto &storeMeta : metaData) { - if (storeMeta.storeType < StoreMetaData::StoreType::STORE_OBJECT_BEGIN - || storeMeta.storeType > StoreMetaData::StoreType::STORE_OBJECT_END) { - continue; - } - if (storeMeta.user == userId) { - ZLOGI("user is same, not need to change, mate user:%{public}s::user:%{public}s.", - storeMeta.user.c_str(), userId.c_str()); - return OBJECT_SUCCESS; - } + if (userMeta.userId == userId) { + ZLOGI("user is same, not need to change, user:%{public}s.", userId.c_str()); + return OBJECT_SUCCESS; } ZLOGI("user changed, need to clear, userId:%{public}s", userId.c_str()); int32_t result = Open(); @@ -324,6 +317,30 @@ int32_t ObjectStoreManager::Clear() return result; } +int32_t ObjectStoreManager::ClearOldUserMeta() +{ + std::string userId = GetCurrentUser(); + if (userId.empty()) { + ZLOGI("get userId error, one minute again"); + executors_->Schedule(std::chrono::minutes(INTERVAL), std::bind(&ObjectStoreManager::ClearOldUserMeta, this)); + return OBJECT_INNER_ERROR; + } + ObjectUserMetaData userMetaData; + userMetaData.userId = userId; + if (!DistributedData::MetaDataManager::GetInstance().SaveMeta(DistributedData::ObjectUserMetaData::GetKey(), + userMetaData, true)) { + ZLOGE("save meta error, userId:%{public}s", userId.c_str()); + return OBJECT_INNER_ERROR; + } + std::string appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); + std::string metaKey = GetMetaUserIdKey(userId, appId); + if (!DistributedData::MetaDataManager::GetInstance().DelMeta(metaKey, true)) { + ZLOGE("delete old meta error, userId:%{public}s", userId.c_str()); + return OBJECT_INNER_ERROR; + } + return OBJECT_SUCCESS; +} + int32_t ObjectStoreManager::DeleteByAppId(const std::string &appId, int32_t user) { int32_t result = Open(); @@ -338,11 +355,6 @@ int32_t ObjectStoreManager::DeleteByAppId(const std::string &appId, int32_t user appId.c_str(), user); } Close(); - std::string metaKey = GetMetaUserIdKey(appId); - auto status = DistributedData::MetaDataManager::GetInstance().DelMeta(metaKey, true); - if (!status) { - ZLOGE("Delete meta failed, userId: %{public}d, appId: %{public}s", user, appId.c_str()); - } return result; } @@ -1099,11 +1111,9 @@ void ObjectStoreManager::SaveUserToMeta() return; } std::string appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); - StoreMetaData userMeta; - userMeta.storeId = DistributedObject::ObjectCommon::OBJECTSTORE_DB_STOREID; - userMeta.user = userId; - userMeta.storeType = ObjectDistributedType::OBJECT_SINGLE_VERSION; - std::string userMetaKey = GetMetaUserIdKey(appId); + DistributedData::ObjectUserMetaData userMeta; + userMeta.userId = userId; + auto userMetaKey = DistributedData::ObjectUserMetaData::GetKey(); auto saved = DistributedData::MetaDataManager::GetInstance().SaveMeta(userMetaKey, userMeta, true); if (!saved) { ZLOGE("userMeta save failed"); diff --git a/services/distributeddataservice/service/object/src/object_service_impl.cpp b/services/distributeddataservice/service/object/src/object_service_impl.cpp index c09b58286..553d1ace8 100644 --- a/services/distributeddataservice/service/object/src/object_service_impl.cpp +++ b/services/distributeddataservice/service/object/src/object_service_impl.cpp @@ -139,6 +139,7 @@ int32_t ObjectServiceImpl::OnInitialize() StoreMetaData saveMeta; SaveMetaData(saveMeta, std::to_string(userId), accountId); ObjectStoreManager::GetInstance()->SetData(saveMeta.dataDir, std::to_string(userId)); + ObjectStoreManager::GetInstance()->ClearOldUserMeta(); RegisterObjectServiceInfo(); RegisterHandler(); ObjectDmsHandler::GetInstance().RegisterDmsEvent(); -- Gitee From f706ae0e4bf0e97862b1e570fdb5da3ba15a3d10 Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Tue, 15 Apr 2025 21:20:24 +0800 Subject: [PATCH 157/225] fix clear bug Signed-off-by: wanghuajian-6 --- .../framework/test/meta_data_test.cpp | 14 ++++++++++++++ .../service/object/src/object_manager.cpp | 3 +-- .../service/test/object_manager_test.cpp | 12 ++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 952990503..58359051e 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -25,6 +25,7 @@ #include "metadata/matrix_meta_data.h" #include "metadata/meta_data.h" #include "metadata/meta_data_manager.h" +#include "metadata/object_user_meta_data.h" #include "metadata/secret_key_meta_data.h" #include "metadata/store_meta_data.h" #include "metadata/store_meta_data_local.h" @@ -994,4 +995,17 @@ HWTEST_F(ServiceMetaDataTest, GetKey, TestSize.Level1) std::string prefix = metaData.GetKey(); EXPECT_EQ(prefix, expectedPrefix); } + +/** +* @tc.name: ObjectUserMetaDataGetKey +* @tc.desc: ObjectUserMetaDataGetKey +* @tc.type: FUNC +*/ +HWTEST_F(ServiceMetaDataTest, ObjectUserMetaDataGetKey, TestSize.Level1) +{ + ObjectUserMetaData metaData; + std::string expectedPrefix = "ObjectUserMetaData"; + std::string prefix = metaData.GetKey(); + EXPECT_EQ(prefix, expectedPrefix); +} } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 6c4987a8c..049be5d40 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -297,8 +297,7 @@ int32_t ObjectStoreManager::Clear() return OBJECT_INNER_ERROR; } DistributedData::ObjectUserMetaData userMeta; - std::string userMetaKey = DistributedData::ObjectUserMetaData::GetKey(); - if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(userMetaKey, userMeta, true)) { + if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(userMeta.GetKey(), userMeta, true)) { ZLOGE("no meta of userId:%{public}s", userId.c_str()); return OBJECT_STORE_NOT_FOUND; } diff --git a/services/distributeddataservice/service/test/object_manager_test.cpp b/services/distributeddataservice/service/test/object_manager_test.cpp index dfc4bf24a..cfed2eacf 100644 --- a/services/distributeddataservice/service/test/object_manager_test.cpp +++ b/services/distributeddataservice/service/test/object_manager_test.cpp @@ -1086,4 +1086,16 @@ HWTEST_F(ObjectManagerTest, GetObjectData002, TestSize.Level1) EXPECT_NE(saveInfo.bundleName, bundleName); EXPECT_FALSE(hasAsset); } + +/** +* @tc.name: ClearOldUserMeta001 +* @tc.desc: test clear old user meta. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, ClearOldUserMeta001, TestSize.Level1) +{ + auto manager = ObjectStoreManager::GetInstance(); + auto status = manager->ClearOldUserMeta(); + ASSERT_EQ(status, DistributedObject::OBJECT_SUCCESS); +} } // namespace OHOS::Test -- Gitee From a24ebe2674e767e59cf2d9f82eb2a006014e56a8 Mon Sep 17 00:00:00 2001 From: guochao Date: Wed, 16 Apr 2025 15:51:37 +0800 Subject: [PATCH 158/225] =?UTF-8?q?add=20=E4=BB=A3=E7=A0=81=E8=A6=86?= =?UTF-8?q?=E7=9B=96=E7=8E=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: guochao --- .../service/test/BUILD.gn | 6 +- .../test/mock/general_watcher_mock.cpp | 4 + .../mock/relational_store_delegate_mock.h | 167 +++++++ .../mock/relational_store_manager_mock.cpp | 36 ++ .../service/test/rdb_general_store_test.cpp | 427 +++++------------- 5 files changed, 313 insertions(+), 327 deletions(-) create mode 100644 services/distributeddataservice/service/test/mock/relational_store_delegate_mock.h create mode 100644 services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index fd6760832..a19051a87 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -596,6 +596,7 @@ ohos_unittest("RdbServiceTest") { "${data_service_path}/service/rdb/rdb_watcher.cpp", "cache_cursor_test.cpp", "mock/general_watcher_mock.cpp", + "mock/relational_store_manager_mock.cpp", "rdb_asset_loader_test.cpp", "rdb_cloud_test.cpp", "rdb_cursor_test.cpp", @@ -613,8 +614,6 @@ ohos_unittest("RdbServiceTest") { configs = [ ":module_private_config" ] cflags = [ - "-Dprivate=public", - "-Dprotected=public", "-Wno-multichar", "-Wno-c99-designator", "-fno-access-control", # Ignore Private Member Access Control @@ -626,17 +625,16 @@ ohos_unittest("RdbServiceTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gmock", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", - "kv_store:distributeddb", ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "${kv_store_distributeddb_path}:distributeddb", "${relational_store_inner_api_path}:native_rdb_static", "//third_party/googletest:gtest_main", ] diff --git a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp index 2bea20914..9a4a88a5e 100644 --- a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp +++ b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp @@ -40,6 +40,10 @@ void MockQuery::MakeRemoteQuery(const std::string &devices, const std::string &s void MockQuery::MakeQuery(const DistributedRdb::PredicatesMemo &predicates) { + if (!predicates.tables_.empty()) { + predicates_ = std::make_shared(*predicates.tables_.begin()); + predicates_->SetWhereClause("id = 1"); + } devices_ = predicates.devices_; tables_ = predicates.tables_; } diff --git a/services/distributeddataservice/service/test/mock/relational_store_delegate_mock.h b/services/distributeddataservice/service/test/mock/relational_store_delegate_mock.h new file mode 100644 index 000000000..9b6829f83 --- /dev/null +++ b/services/distributeddataservice/service/test/mock/relational_store_delegate_mock.h @@ -0,0 +1,167 @@ +/* + * 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 "rdb_general_store.h" +namespace DistributedDB { +class MockRelationalStoreDelegate : public DistributedDB::RelationalStoreDelegate { +public: + ~MockRelationalStoreDelegate() = default; + + DBStatus Sync(const std::vector &devices, DistributedDB::SyncMode mode, const Query &query, + const SyncStatusCallback &onComplete, bool wait) override + { + return DBStatus::OK; + } + + int32_t GetCloudSyncTaskCount() override + { + static int32_t count = 0; + count = (count + 1) % 2; // The result of count + 1 is the remainder of 2. + return count; + } + + DBStatus RemoveDeviceData(const std::string &device, const std::string &tableName) override + { + return DBStatus::OK; + } + + DBStatus RemoteQuery(const std::string &device, const RemoteCondition &condition, uint64_t timeout, + std::shared_ptr &result) override + { + if (device == "test") { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } + + DBStatus RemoveDeviceData() override + { + return DBStatus::OK; + } + + DBStatus Sync(const std::vector &devices, DistributedDB::SyncMode mode, const Query &query, + const SyncProcessCallback &onProcess, int64_t waitTime) override + { + return DBStatus::OK; + } + + DBStatus SetCloudDB(const std::shared_ptr &cloudDb) override + { + return DBStatus::OK; + } + + DBStatus SetCloudDbSchema(const DataBaseSchema &schema) override + { + return DBStatus::OK; + } + + DBStatus RegisterObserver(StoreObserver *observer) override + { + return DBStatus::OK; + } + + DBStatus UnRegisterObserver() override + { + return DBStatus::OK; + } + + DBStatus UnRegisterObserver(StoreObserver *observer) override + { + return DBStatus::OK; + } + + DBStatus SetIAssetLoader(const std::shared_ptr &loader) override + { + return DBStatus::OK; + } + + DBStatus Sync(const CloudSyncOption &option, const SyncProcessCallback &onProcess) override + { + return DBStatus::OK; + } + + DBStatus SetTrackerTable(const TrackerSchema &schema) override + { + if (schema.tableName == "WITH_INVENTORY_DATA") { + return DBStatus::WITH_INVENTORY_DATA; + } + if (schema.tableName == "test") { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } + + DBStatus ExecuteSql(const SqlCondition &condition, std::vector &records) override + { + if (condition.sql == "") { + return DBStatus::DB_ERROR; + } + + std::string sqls = "INSERT INTO test ( #flag, #float, #gid, #value) VALUES ( ?, ?, ?, ?)"; + std::string sqlIn = " UPDATE test SET setSql WHERE whereSql"; + std::string sql = "REPLACE INTO test ( #flag, #float, #gid, #value) VALUES ( ?, ?, ?, ?)"; + if (condition.sql == sqls || condition.sql == sqlIn || condition.sql == sql) { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } + + DBStatus SetReference(const std::vector &tableReferenceProperty) override + { + if (g_testResult) { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } + + DBStatus CleanTrackerData(const std::string &tableName, int64_t cursor) override + { + return DBStatus::OK; + } + + DBStatus Pragma(PragmaCmd cmd, PragmaData &pragmaData) override + { + return DBStatus::OK; + } + + DBStatus UpsertData(const std::string &tableName, const std::vector &records, + RecordStatus status = RecordStatus::WAIT_COMPENSATED_SYNC) override + { + return DBStatus::OK; + } + + DBStatus SetCloudSyncConfig(const CloudSyncConfig &config) override + { + return DBStatus::OK; + } + static bool g_testResult; + +protected: + DBStatus RemoveDeviceDataInner(const std::string &device, ClearMode mode) override + { + if (g_testResult) { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } + + DBStatus CreateDistributedTableInner(const std::string &tableName, TableSyncType type) override + { + if (tableName == "test") { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } +}; +} // namespace DistributedDB \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp new file mode 100644 index 000000000..21474d1a5 --- /dev/null +++ b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp @@ -0,0 +1,36 @@ +/* + * 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 "MockRelationalStoreManager" +#include + +#include "relational_store_delegate_mock.h" +#include "relational_store_manager.h" +namespace DistributedDB { +DB_API DBStatus RelationalStoreManager::OpenStore(const std::string &path, const std::string &storeId, + const RelationalStoreDelegate::Option &option, RelationalStoreDelegate *&delegate) +{ + delegate = std::make_shared().get(); + if (storeId == "mock") { + return OK; + } + return DB_ERROR; +} + +DB_API DBStatus RelationalStoreManager::CloseStore(RelationalStoreDelegate *store) +{ + store = nullptr; + return OK; +} +} // namespace DistributedDB \ No newline at end of file diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index adb46f111..be88fcbae 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -32,6 +32,7 @@ #include "metadata/store_meta_data_local.h" #include "mock/general_watcher_mock.h" #include "rdb_query.h" +#include "relational_store_delegate_mock.h" #include "store/general_store.h" #include "store/general_value.h" #include "store_observer.h" @@ -43,14 +44,15 @@ using namespace DistributedDB; using namespace OHOS::DistributedData; using namespace OHOS::DistributedRdb; using DBStatus = DistributedDB::DBStatus; -using StoreMetaData = OHOS::DistributedData::StoreMetaData; RdbGeneralStore::Values g_RdbValues = { { "0000000" }, { true }, { int64_t(100) }, { double(100) }, { int64_t(1) }, { Bytes({ 1, 2, 3, 4 }) } }; RdbGeneralStore::VBucket g_RdbVBucket = { { "#gid", { "0000000" } }, { "#flag", { true } }, { "#value", { int64_t(100) } }, { "#float", { double(100) } } }; -bool g_testResult = false; +bool MockRelationalStoreDelegate::g_testResult = false; namespace OHOS::Test { namespace DistributedRDBTest { +using StoreMetaData = OHOS::DistributedData::StoreMetaData; +using namespace OHOS::DistributedRdb; static constexpr uint32_t PRINT_ERROR_CNT = 150; static constexpr const char *BUNDLE_NAME = "test_rdb_general_store"; static constexpr const char *STORE_NAME = "test_service_rdb"; @@ -65,7 +67,7 @@ public: }; void TearDown() { - g_testResult = false; + MockRelationalStoreDelegate::g_testResult = false; }; protected: @@ -88,156 +90,6 @@ void RdbGeneralStoreTest::InitMetaData() metaData_.isSearchable = true; } -class MockRelationalStoreDelegate : public DistributedDB::RelationalStoreDelegate { -public: - ~MockRelationalStoreDelegate() = default; - - DBStatus Sync(const std::vector &devices, DistributedDB::SyncMode mode, const Query &query, - const SyncStatusCallback &onComplete, bool wait) override - { - return DBStatus::OK; - } - - int32_t GetCloudSyncTaskCount() override - { - static int32_t count = 0; - count = (count + 1) % 2; // The result of count + 1 is the remainder of 2. - return count; - } - - DBStatus RemoveDeviceData(const std::string &device, const std::string &tableName) override - { - return DBStatus::OK; - } - - DBStatus RemoteQuery(const std::string &device, const RemoteCondition &condition, uint64_t timeout, - std::shared_ptr &result) override - { - if (device == "test") { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } - - DBStatus RemoveDeviceData() override - { - return DBStatus::OK; - } - - DBStatus Sync(const std::vector &devices, DistributedDB::SyncMode mode, const Query &query, - const SyncProcessCallback &onProcess, int64_t waitTime) override - { - return DBStatus::OK; - } - - DBStatus SetCloudDB(const std::shared_ptr &cloudDb) override - { - return DBStatus::OK; - } - - DBStatus SetCloudDbSchema(const DataBaseSchema &schema) override - { - return DBStatus::OK; - } - - DBStatus RegisterObserver(StoreObserver *observer) override - { - return DBStatus::OK; - } - - DBStatus UnRegisterObserver() override - { - return DBStatus::OK; - } - - DBStatus UnRegisterObserver(StoreObserver *observer) override - { - return DBStatus::OK; - } - - DBStatus SetIAssetLoader(const std::shared_ptr &loader) override - { - return DBStatus::OK; - } - - DBStatus Sync(const CloudSyncOption &option, const SyncProcessCallback &onProcess) override - { - return DBStatus::OK; - } - - DBStatus SetTrackerTable(const TrackerSchema &schema) override - { - if (schema.tableName == "WITH_INVENTORY_DATA") { - return DBStatus::WITH_INVENTORY_DATA; - } - if (schema.tableName == "test") { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } - - DBStatus ExecuteSql(const SqlCondition &condition, std::vector &records) override - { - if (condition.sql == "") { - return DBStatus::DB_ERROR; - } - - std::string sqls = "INSERT INTO test ( #flag, #float, #gid, #value) VALUES ( ?, ?, ?, ?)"; - std::string sqlIn = " UPDATE test SET setSql WHERE whereSql"; - std::string sql = "REPLACE INTO test ( #flag, #float, #gid, #value) VALUES ( ?, ?, ?, ?)"; - if (condition.sql == sqls || condition.sql == sqlIn || condition.sql == sql) { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } - - DBStatus SetReference(const std::vector &tableReferenceProperty) override - { - if (g_testResult) { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } - - DBStatus CleanTrackerData(const std::string &tableName, int64_t cursor) override - { - return DBStatus::OK; - } - - DBStatus Pragma(PragmaCmd cmd, PragmaData &pragmaData) override - { - return DBStatus::OK; - } - - DBStatus UpsertData(const std::string &tableName, const std::vector &records, - RecordStatus status = RecordStatus::WAIT_COMPENSATED_SYNC) override - { - return DBStatus::OK; - } - - DBStatus SetCloudSyncConfig(const CloudSyncConfig &config) override - { - return DBStatus::OK; - } - -protected: - DBStatus RemoveDeviceDataInner(const std::string &device, ClearMode mode) override - { - if (g_testResult) { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } - - DBStatus CreateDistributedTableInner(const std::string &tableName, TableSyncType type) override - { - if (tableName == "test") { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } -}; - class MockStoreChangedData : public DistributedDB::StoreChangedData { public: std::string GetDataChangeDevice() const override @@ -256,12 +108,10 @@ public: * @tc.name: BindSnapshots001 * @tc.desc: RdbGeneralStore BindSnapshots test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, BindSnapshots001, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); BindAssets bindAssets; auto result = store->BindSnapshots(bindAssets.bindAssets); @@ -272,15 +122,13 @@ HWTEST_F(RdbGeneralStoreTest, BindSnapshots001, TestSize.Level1) * @tc.name: BindSnapshots002 * @tc.desc: RdbGeneralStore BindSnapshots nullptr test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, BindSnapshots002, TestSize.Level1) { DistributedData::StoreMetaData meta; meta = metaData_; meta.isEncrypt = true; - auto store = new (std::nothrow) RdbGeneralStore(meta); + auto store = std::make_shared(meta); ASSERT_NE(store, nullptr); store->snapshots_.bindAssets = nullptr; BindAssets bindAssets; @@ -292,12 +140,10 @@ HWTEST_F(RdbGeneralStoreTest, BindSnapshots002, TestSize.Level1) * @tc.name: Bind001 * @tc.desc: RdbGeneralStore Bind bindInfo test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Bind001, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedData::Database database; GeneralStore::CloudConfig config; @@ -338,16 +184,13 @@ HWTEST_F(RdbGeneralStoreTest, Bind001, TestSize.Level1) * @tc.name: Bind002 * @tc.desc: RdbGeneralStore Bind delegate_ is nullptr test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Bind002, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedData::Database database; std::map bindInfos; - std::shared_ptr db = std::make_shared(); std::shared_ptr loader = std::make_shared(); GeneralStore::BindInfo bindInfo(db, loader); @@ -367,12 +210,10 @@ HWTEST_F(RdbGeneralStoreTest, Bind002, TestSize.Level1) * @tc.name: Bind003 * @tc.desc: RdbGeneralStore Bind delegate_ test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Bind003, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedData::Database database; std::map bindInfos; @@ -382,8 +223,8 @@ HWTEST_F(RdbGeneralStoreTest, Bind003, TestSize.Level1) GeneralStore::BindInfo bindInfo(db, loader); uint32_t key = 1; bindInfos[key] = bindInfo; - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); GeneralStore::CloudConfig config; auto result = store->Bind(database, bindInfos, config); EXPECT_NE(store->delegate_, nullptr); @@ -394,21 +235,18 @@ HWTEST_F(RdbGeneralStoreTest, Bind003, TestSize.Level1) * @tc.name: Close * @tc.desc: RdbGeneralStore Close and IsBound function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Close, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); auto result = store->IsBound(std::stoi(metaData_.user)); EXPECT_EQ(result, false); EXPECT_EQ(store->delegate_, nullptr); auto ret = store->Close(); EXPECT_EQ(ret, GeneralError::E_OK); - - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); ret = store->Close(); EXPECT_EQ(ret, GeneralError::E_BUSY); } @@ -417,7 +255,6 @@ HWTEST_F(RdbGeneralStoreTest, Close, TestSize.Level1) * @tc.name: Close * @tc.desc: RdbGeneralStore Close test * @tc.type: FUNC -* @tc.require: * @tc.author: shaoyuanzhao */ HWTEST_F(RdbGeneralStoreTest, BusyClose, TestSize.Level1) @@ -440,21 +277,18 @@ HWTEST_F(RdbGeneralStoreTest, BusyClose, TestSize.Level1) * @tc.name: Execute * @tc.desc: RdbGeneralStore Execute function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Execute, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; EXPECT_EQ(store->delegate_, nullptr); auto result = store->Execute(table, sql); EXPECT_EQ(result, GeneralError::E_ERROR); - - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->Execute(table, sql); EXPECT_EQ(result, GeneralError::E_OK); @@ -467,12 +301,10 @@ HWTEST_F(RdbGeneralStoreTest, Execute, TestSize.Level1) * @tc.name: SqlConcatenate * @tc.desc: RdbGeneralStore SqlConcatenate function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, SqlConcatenate, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedData::VBucket value; std::string strColumnSql = "strColumnSql"; @@ -493,12 +325,10 @@ HWTEST_F(RdbGeneralStoreTest, SqlConcatenate, TestSize.Level1) * @tc.name: Insert001 * @tc.desc: RdbGeneralStore Insert error test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Insert001, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedData::VBuckets values; EXPECT_EQ(values.size(), 0); @@ -527,23 +357,16 @@ HWTEST_F(RdbGeneralStoreTest, Insert001, TestSize.Level1) * @tc.name: Insert002 * @tc.desc: RdbGeneralStore Insert function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Insert002, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string table = "table"; DistributedData::VBuckets extends = { { g_RdbVBucket } }; auto result = store->Insert(table, std::move(extends)); EXPECT_EQ(result, GeneralError::E_ERROR); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; - result = store->Insert(table, std::move(extends)); - EXPECT_EQ(result, GeneralError::E_OK); - std::string test = "test"; result = store->Insert(test, std::move(extends)); EXPECT_EQ(result, GeneralError::E_ERROR); @@ -555,18 +378,20 @@ HWTEST_F(RdbGeneralStoreTest, Insert002, TestSize.Level1) result = store->Insert(test, std::move(extends)); EXPECT_EQ(result, GeneralError::E_ERROR); } + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); + result = store->Insert(table, std::move(extends)); + EXPECT_EQ(result, GeneralError::E_OK); } /** * @tc.name: Update * @tc.desc: RdbGeneralStore Update function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Update, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string table = "table"; std::string setSql = "setSql"; @@ -590,9 +415,8 @@ HWTEST_F(RdbGeneralStoreTest, Update, TestSize.Level1) result = store->Update(table, setSql, std::move(g_RdbValues), whereSql, std::move(g_RdbValues)); EXPECT_EQ(result, GeneralError::E_ERROR); - - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->Update(table, setSql, std::move(g_RdbValues), whereSql, std::move(g_RdbValues)); EXPECT_EQ(result, GeneralError::E_OK); @@ -604,12 +428,10 @@ HWTEST_F(RdbGeneralStoreTest, Update, TestSize.Level1) * @tc.name: Replace * @tc.desc: RdbGeneralStore Replace function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Replace, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string table = "table"; RdbGeneralStore::VBucket values; @@ -621,9 +443,8 @@ HWTEST_F(RdbGeneralStoreTest, Replace, TestSize.Level1) result = store->Replace(table, std::move(g_RdbVBucket)); EXPECT_EQ(result, GeneralError::E_ERROR); - - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->Replace(table, std::move(g_RdbVBucket)); EXPECT_EQ(result, GeneralError::E_OK); @@ -635,12 +456,10 @@ HWTEST_F(RdbGeneralStoreTest, Replace, TestSize.Level1) * @tc.name: Delete * @tc.desc: RdbGeneralStore Delete function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Delete, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; @@ -652,21 +471,18 @@ HWTEST_F(RdbGeneralStoreTest, Delete, TestSize.Level1) * @tc.name: Query001 * @tc.desc: RdbGeneralStore Query function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Query001, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; auto [err1, result1] = store->Query(table, sql, std::move(g_RdbValues)); EXPECT_EQ(err1, GeneralError::E_ALREADY_CLOSED); EXPECT_EQ(result1, nullptr); - - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); auto [err2, result2] = store->Query(table, sql, std::move(g_RdbValues)); EXPECT_EQ(err2, GeneralError::E_OK); EXPECT_NE(result2, nullptr); @@ -676,12 +492,10 @@ HWTEST_F(RdbGeneralStoreTest, Query001, TestSize.Level1) * @tc.name: Query002 * @tc.desc: RdbGeneralStore Query function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Query002, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; @@ -703,7 +517,8 @@ HWTEST_F(RdbGeneralStoreTest, Query002, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Query003, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + metaData_.storeId = "mock"; + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockQuery query; @@ -713,10 +528,7 @@ HWTEST_F(RdbGeneralStoreTest, Query003, TestSize.Level1) query.MakeRemoteQuery(devices, sql, std::move(args)); query.lastResult = true; std::string table = "test_table"; - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; auto [err, cursor] = store->Query(table, query); - EXPECT_EQ(err, GeneralError::E_OK); } @@ -727,7 +539,7 @@ HWTEST_F(RdbGeneralStoreTest, Query003, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Query004, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockQuery query; @@ -737,8 +549,8 @@ HWTEST_F(RdbGeneralStoreTest, Query004, TestSize.Level1) query.MakeRemoteQuery(devices, sql, std::move(args)); query.lastResult = true; - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); std::string table = "test_table"; auto [err, cursor] = store->Query(table, query); @@ -751,20 +563,18 @@ HWTEST_F(RdbGeneralStoreTest, Query004, TestSize.Level1) * @tc.name: MergeMigratedData * @tc.desc: RdbGeneralStore MergeMigratedData function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, MergeMigratedData, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string tableName = "tableName"; DistributedData::VBuckets extends = { { g_RdbVBucket } }; auto result = store->MergeMigratedData(tableName, std::move(extends)); EXPECT_EQ(result, GeneralError::E_ERROR); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->MergeMigratedData(tableName, std::move(extends)); EXPECT_EQ(result, GeneralError::E_OK); } @@ -773,12 +583,10 @@ HWTEST_F(RdbGeneralStoreTest, MergeMigratedData, TestSize.Level1) * @tc.name: Sync * @tc.desc: RdbGeneralStore Sync function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Sync, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); GeneralStore::Devices devices; MockQuery query; @@ -787,8 +595,8 @@ HWTEST_F(RdbGeneralStoreTest, Sync, TestSize.Level1) auto result = store->Sync(devices, query, async, syncParam); EXPECT_EQ(result.first, GeneralError::E_ALREADY_CLOSED); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->Sync(devices, query, async, syncParam); EXPECT_EQ(result.first, GeneralError::E_OK); } @@ -797,12 +605,10 @@ HWTEST_F(RdbGeneralStoreTest, Sync, TestSize.Level1) * @tc.name: Sync * @tc.desc: RdbGeneralStore Sync CLOUD_TIME_FIRST test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Sync001, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); GeneralStore::Devices devices; MockQuery query; @@ -810,8 +616,8 @@ HWTEST_F(RdbGeneralStoreTest, Sync001, TestSize.Level1) SyncParam syncParam; syncParam.mode = GeneralStore::CLOUD_TIME_FIRST; - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); auto [result1, result2] = store->Sync(devices, query, async, syncParam); EXPECT_EQ(result1, GeneralError::E_OK); syncParam.mode = GeneralStore::NEARBY_END; @@ -826,18 +632,16 @@ HWTEST_F(RdbGeneralStoreTest, Sync001, TestSize.Level1) * @tc.name: Sync * @tc.desc: RdbGeneralStore Sync DistributedTable test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Sync002, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + metaData_.storeId = "mock"; + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); GeneralStore::Devices devices; RdbQuery query; GeneralStore::DetailAsync async; SyncParam syncParam; - MockRelationalStoreDelegate mockDelegate; mockDelegate.CreateDistributedTable("naturalbase_rdb_test"); mockDelegate.CreateDistributedTable("naturalbase_rdb_name"); @@ -850,12 +654,10 @@ HWTEST_F(RdbGeneralStoreTest, Sync002, TestSize.Level1) * @tc.name: PreSharing * @tc.desc: RdbGeneralStore PreSharing function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, PreSharing, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockQuery query; auto [errCode, result] = store->PreSharing(query); @@ -867,12 +669,10 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing, TestSize.Level1) * @tc.name: PreSharing * @tc.desc: RdbGeneralStore PreSharing function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, PreSharing001, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockQuery query; query.lastResult = true; @@ -885,12 +685,10 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing001, TestSize.Level1) * @tc.name: PreSharing * @tc.desc: RdbGeneralStore PreSharing function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, PreSharing002, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockQuery query; DistributedRdb::PredicatesMemo predicates; @@ -899,20 +697,40 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing002, TestSize.Level1) query.lastResult = true; query.MakeQuery(predicates); auto [errCode, result] = store->PreSharing(query); - EXPECT_EQ(errCode, GeneralError::E_INVALID_ARGS); + EXPECT_EQ(errCode, GeneralError::E_ALREADY_CLOSED); EXPECT_EQ(result, nullptr); } +/** +* @tc.name: PreSharing +* @tc.desc: RdbGeneralStore PreSharing function test +* @tc.type: FUNC +*/ +HWTEST_F(RdbGeneralStoreTest, PreSharing003, TestSize.Level1) +{ + ZLOGE("PreSharing003 start"); + metaData_.storeId = "mock"; + auto store = std::make_shared(metaData_); + ASSERT_NE(store, nullptr); + MockQuery query; + DistributedRdb::PredicatesMemo predicates; + predicates.devices_ = { "device1" }; + predicates.tables_ = { "tables1" }; + query.lastResult = true; + query.MakeQuery(predicates); + auto [errCode, result] = store->PreSharing(query); + EXPECT_EQ(errCode, GeneralError::E_CLOUD_DISABLED); + ASSERT_EQ(result, nullptr); +} + /** * @tc.name: ExtractExtend * @tc.desc: RdbGeneralStore ExtractExtend function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, ExtractExtend, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); RdbGeneralStore::VBucket extend = { { "#gid", { "0000000" } }, { "#flag", { true } }, { "#value", { int64_t(100) } }, { "#float", { double(100) } }, { "#cloud_gid", { "cloud_gid" } }, @@ -929,12 +747,10 @@ HWTEST_F(RdbGeneralStoreTest, ExtractExtend, TestSize.Level1) * @tc.name: Clean * @tc.desc: RdbGeneralStore Clean function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string tableName = "tableName"; std::vector devices = { "device1", "device2" }; @@ -945,8 +761,8 @@ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) result = store->Clean(devices, GeneralStore::CLOUD_INFO, tableName); EXPECT_EQ(result, GeneralError::E_ALREADY_CLOSED); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->Clean(devices, GeneralStore::CLOUD_INFO, tableName); EXPECT_EQ(result, GeneralError::E_OK); result = store->Clean(devices, GeneralStore::CLOUD_DATA, tableName); @@ -955,7 +771,7 @@ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) result = store->Clean(devices1, GeneralStore::NEARBY_DATA, tableName); EXPECT_EQ(result, GeneralError::E_OK); - g_testResult = true; + MockRelationalStoreDelegate::g_testResult = true; result = store->Clean(devices, GeneralStore::CLOUD_INFO, tableName); EXPECT_EQ(result, GeneralError::E_ERROR); result = store->Clean(devices, GeneralStore::CLOUD_DATA, tableName); @@ -970,12 +786,10 @@ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) * @tc.name: Watch * @tc.desc: RdbGeneralStore Watch and Unwatch function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Watch, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockGeneralWatcher watcher; auto result = store->Watch(GeneralWatcher::Origin::ORIGIN_CLOUD, watcher); @@ -998,12 +812,10 @@ HWTEST_F(RdbGeneralStoreTest, Watch, TestSize.Level1) * @tc.name: OnChange * @tc.desc: RdbGeneralStore OnChange function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, OnChange, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockGeneralWatcher watcher; MockStoreChangedData data; @@ -1027,7 +839,7 @@ HWTEST_F(RdbGeneralStoreTest, OnChange, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, OnChange001, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockGeneralWatcher watcher; MockStoreChangedData data; @@ -1065,8 +877,6 @@ HWTEST_F(RdbGeneralStoreTest, OnChange001, TestSize.Level1) * @tc.name: Release * @tc.desc: RdbGeneralStore Release and AddRef function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Release, TestSize.Level1) { @@ -1093,8 +903,6 @@ HWTEST_F(RdbGeneralStoreTest, Release, TestSize.Level1) * @tc.name: SetDistributedTables * @tc.desc: RdbGeneralStore SetDistributedTables function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) { @@ -1114,7 +922,7 @@ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) std::vector test = { "test" }; result = store->SetDistributedTables(test, type, references); EXPECT_EQ(result, GeneralError::E_ERROR); - g_testResult = true; + MockRelationalStoreDelegate::g_testResult = true; result = store->SetDistributedTables(tables, type, references); EXPECT_EQ(result, GeneralError::E_ERROR); } @@ -1123,8 +931,6 @@ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) * @tc.name: SetTrackerTable * @tc.desc: RdbGeneralStore SetTrackerTable function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, SetTrackerTable, TestSize.Level1) { @@ -1150,17 +956,15 @@ HWTEST_F(RdbGeneralStoreTest, SetTrackerTable, TestSize.Level1) * @tc.name: RemoteQuery * @tc.desc: RdbGeneralStore RemoteQuery function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, RemoteQuery, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string device = "device"; DistributedDB::RemoteCondition remoteCondition; - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); auto result = store->RemoteQuery("test", remoteCondition); EXPECT_EQ(result, nullptr); result = store->RemoteQuery(device, remoteCondition); @@ -1171,12 +975,10 @@ HWTEST_F(RdbGeneralStoreTest, RemoteQuery, TestSize.Level1) * @tc.name: ConvertStatus * @tc.desc: RdbGeneralStore ConvertStatus function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, ConvertStatus, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); auto result = store->ConvertStatus(DBStatus::OK); EXPECT_EQ(result, GeneralError::E_OK); @@ -1202,15 +1004,12 @@ HWTEST_F(RdbGeneralStoreTest, ConvertStatus, TestSize.Level1) * @tc.name: QuerySql * @tc.desc: RdbGeneralStore QuerySql function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, QuerySql, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + metaData_.storeId = "mock"; + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; auto [err1, result1] = store->QuerySql("", std::move(g_RdbValues)); EXPECT_EQ(err1, GeneralError::E_ERROR); EXPECT_TRUE(result1.empty()); @@ -1224,12 +1023,10 @@ HWTEST_F(RdbGeneralStoreTest, QuerySql, TestSize.Level1) * @tc.name: BuildSqlWhenCloumnEmpty * @tc.desc: test buildsql method when cloumn empty * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenCloumnEmpty, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string table = "mock_table"; std::string statement = "mock_statement"; @@ -1244,12 +1041,10 @@ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenCloumnEmpty, TestSize.Level1) * @tc.name: BuildSqlWhenParamValid * @tc.desc: test buildsql method when param valid * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenParamValid, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string table = "mock_table"; std::string statement = "mock_statement"; @@ -1267,12 +1062,10 @@ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenParamValid, TestSize.Level1) * @tc.name: LockAndUnLockCloudDBTest * @tc.desc: lock and unlock cloudDB test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, LockAndUnLockCloudDBTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); auto result = store->LockCloudDB(); EXPECT_EQ(result.first, 1); @@ -1285,12 +1078,10 @@ HWTEST_F(RdbGeneralStoreTest, LockAndUnLockCloudDBTest, TestSize.Level1) * @tc.name: InFinishedTest * @tc.desc: isFinished test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, InFinishedTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; bool isFinished = store->IsFinished(syncId); @@ -1301,12 +1092,10 @@ HWTEST_F(RdbGeneralStoreTest, InFinishedTest, TestSize.Level1) * @tc.name: GetRdbCloudTest * @tc.desc: getRdbCloud test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, GetRdbCloudTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); auto rdbCloud = store->GetRdbCloud(); EXPECT_EQ(rdbCloud, nullptr); @@ -1316,12 +1105,10 @@ HWTEST_F(RdbGeneralStoreTest, GetRdbCloudTest, TestSize.Level1) * @tc.name: RegisterDetailProgressObserverTest * @tc.desc: RegisterDetailProgressObserver test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, RegisterDetailProgressObserverTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedData::GeneralStore::DetailAsync async; auto result = store->RegisterDetailProgressObserver(async); @@ -1332,12 +1119,10 @@ HWTEST_F(RdbGeneralStoreTest, RegisterDetailProgressObserverTest, TestSize.Level * @tc.name: GetFinishTaskTest * @tc.desc: GetFinishTask test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, GetFinishTaskTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; auto result = store->GetFinishTask(syncId); @@ -1348,12 +1133,10 @@ HWTEST_F(RdbGeneralStoreTest, GetFinishTaskTest, TestSize.Level1) * @tc.name: GetCBTest * @tc.desc: GetCB test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, GetCBTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; auto result = store->GetCB(syncId); @@ -1364,17 +1147,15 @@ HWTEST_F(RdbGeneralStoreTest, GetCBTest, TestSize.Level1) * @tc.name: UpdateDBStatus * @tc.desc: UpdateDBStatus test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, UpdateDBStatus, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); auto result = store->UpdateDBStatus(); EXPECT_EQ(result, E_ALREADY_CLOSED); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->UpdateDBStatus(); EXPECT_EQ(result, E_OK); } -- Gitee From d359551a16f4d961b01eb15dc126e44d5f64c9de Mon Sep 17 00:00:00 2001 From: ZhaoJinghui Date: Wed, 16 Apr 2025 01:13:58 +0800 Subject: [PATCH 159/225] fix GetPassword testcase Signed-off-by: ZhaoJinghui Change-Id: Ib59dd88eef879f43710c162902fbe555ad09e2da --- .../service/test/rdb_service_impl_test.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp index acce4946d..85453a359 100644 --- a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp @@ -96,6 +96,7 @@ void RdbServiceImplTest::SetUpTestCase() DeviceManagerAdapter::GetInstance().Init(dmExecutor); InitMetaData(); Bootstrap::GetInstance().LoadCheckers(); + CryptoManager::GetInstance().GenerateRootKey(); } void RdbServiceImplTest::TearDownTestCase() @@ -705,8 +706,10 @@ HWTEST_F(RdbServiceImplTest, GetPassword002, TestSize.Level0) std::vector> password; int32_t result = service.GetPassword(param, password); - EXPECT_EQ(result, RDB_ERROR); - + EXPECT_EQ(result, RDB_OK); + size_t KEY_COUNT = 2; + ASSERT_EQ(password.size(), KEY_COUNT); + EXPECT_EQ(password.at(0), sKey); MetaDataManager::GetInstance().DelMeta(meta.GetKey(), true); MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true); } @@ -770,7 +773,10 @@ HWTEST_F(RdbServiceImplTest, GetPassword004, TestSize.Level0) int32_t result = service.GetPassword(param, password); - EXPECT_EQ(result, RDB_ERROR); + EXPECT_EQ(result, RDB_OK); + size_t KEY_COUNT = 2; + ASSERT_EQ(password.size(), KEY_COUNT); + EXPECT_EQ(password.at(1), sKey); MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), true); MetaDataManager::GetInstance().DelMeta(metaData_.GetCloneSecretKey(), true); } -- Gitee From eab81626bfe1d9f053a7430a0bd93b815a33c21d Mon Sep 17 00:00:00 2001 From: guochao Date: Wed, 16 Apr 2025 17:09:24 +0800 Subject: [PATCH 160/225] add test Signed-off-by: guochao --- services/distributeddataservice/service/test/BUILD.gn | 1 - .../test/mock/relational_store_delegate_mock.h | 11 +++++++---- .../service/test/rdb_general_store_test.cpp | 8 ++++---- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index a19051a87..632d849bc 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -625,7 +625,6 @@ ohos_unittest("RdbServiceTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", - "googletest:gmock", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", diff --git a/services/distributeddataservice/service/test/mock/relational_store_delegate_mock.h b/services/distributeddataservice/service/test/mock/relational_store_delegate_mock.h index 9b6829f83..0f5308d45 100644 --- a/services/distributeddataservice/service/test/mock/relational_store_delegate_mock.h +++ b/services/distributeddataservice/service/test/mock/relational_store_delegate_mock.h @@ -12,6 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef RELATIONAL_STORE_DELEGATE_MOCK_H +#define RELATIONAL_STORE_DELEGATE_MOCK_H #include "rdb_general_store.h" namespace DistributedDB { class MockRelationalStoreDelegate : public DistributedDB::RelationalStoreDelegate { @@ -119,7 +121,7 @@ public: DBStatus SetReference(const std::vector &tableReferenceProperty) override { - if (g_testResult) { + if (gTestResult) { return DBStatus::DB_ERROR; } return DBStatus::OK; @@ -145,12 +147,12 @@ public: { return DBStatus::OK; } - static bool g_testResult; + static bool gTestResult; protected: DBStatus RemoveDeviceDataInner(const std::string &device, ClearMode mode) override { - if (g_testResult) { + if (gTestResult) { return DBStatus::DB_ERROR; } return DBStatus::OK; @@ -164,4 +166,5 @@ protected: return DBStatus::OK; } }; -} // namespace DistributedDB \ No newline at end of file +} // namespace DistributedDB +#endif \ No newline at end of file diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index be88fcbae..6e360fd1f 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -48,7 +48,7 @@ RdbGeneralStore::Values g_RdbValues = { { "0000000" }, { true }, { int64_t(100) { Bytes({ 1, 2, 3, 4 }) } }; RdbGeneralStore::VBucket g_RdbVBucket = { { "#gid", { "0000000" } }, { "#flag", { true } }, { "#value", { int64_t(100) } }, { "#float", { double(100) } } }; -bool MockRelationalStoreDelegate::g_testResult = false; +bool MockRelationalStoreDelegate::gTestResult = false; namespace OHOS::Test { namespace DistributedRDBTest { using StoreMetaData = OHOS::DistributedData::StoreMetaData; @@ -67,7 +67,7 @@ public: }; void TearDown() { - MockRelationalStoreDelegate::g_testResult = false; + MockRelationalStoreDelegate::gTestResult = false; }; protected: @@ -771,7 +771,7 @@ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) result = store->Clean(devices1, GeneralStore::NEARBY_DATA, tableName); EXPECT_EQ(result, GeneralError::E_OK); - MockRelationalStoreDelegate::g_testResult = true; + MockRelationalStoreDelegate::gTestResult = true; result = store->Clean(devices, GeneralStore::CLOUD_INFO, tableName); EXPECT_EQ(result, GeneralError::E_ERROR); result = store->Clean(devices, GeneralStore::CLOUD_DATA, tableName); @@ -922,7 +922,7 @@ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) std::vector test = { "test" }; result = store->SetDistributedTables(test, type, references); EXPECT_EQ(result, GeneralError::E_ERROR); - MockRelationalStoreDelegate::g_testResult = true; + MockRelationalStoreDelegate::gTestResult = true; result = store->SetDistributedTables(tables, type, references); EXPECT_EQ(result, GeneralError::E_ERROR); } -- Gitee From 568ca52556c675522f03df72540e217e0429db8d Mon Sep 17 00:00:00 2001 From: guochao Date: Wed, 16 Apr 2025 17:18:13 +0800 Subject: [PATCH 161/225] fix:fuzz Signed-off-by: guochao --- .../rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp | 4 +++- .../fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp index 9f10a09f5..c5871d302 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include "rdb_result_set_impl.h" @@ -34,7 +35,8 @@ constexpr uint32_t CODE_MAX = NativeRdb::RemoteResultSet::Code::CMD_MAX + 1; bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) { - uint32_t code = static_cast(*data) % (CODE_MAX - CODE_MIN + 1) + CODE_MIN; + FuzzedDataProvider provider(data, size); + uint32_t code = provider.ConsumeIntegral() % (CODE_MAX - CODE_MIN + 1) + CODE_MIN; MessageParcel request; request.WriteInterfaceToken(INTERFACE_TOKEN); request.WriteBuffer(data, size); diff --git a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp index a9ef6e03d..4b829bc26 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp @@ -17,6 +17,7 @@ #include #include +#include #include "ipc_skeleton.h" #include "rdb_service_impl.h" @@ -39,7 +40,8 @@ bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) rdbServiceImpl->OnBind( { "RdbServiceStubFuzz", static_cast(IPCSkeleton::GetSelfTokenID()), std::move(executor) }); - uint32_t code = static_cast(*data) % (CODE_MAX - CODE_MIN + 1) + CODE_MIN; + FuzzedDataProvider provider(data, size); + uint32_t code = provider.ConsumeIntegral() % (CODE_MAX - CODE_MIN + 1) + CODE_MIN; MessageParcel request; request.WriteInterfaceToken(INTERFACE_TOKEN); request.WriteBuffer(data, size); -- Gitee From ca8e3905b5c12a176c672fb1cb14d192deb2e8e5 Mon Sep 17 00:00:00 2001 From: wTong6 Date: Wed, 16 Apr 2025 10:00:59 +0800 Subject: [PATCH 162/225] fix Signed-off-by: wTong6 --- .../framework/include/cloud/schema_meta.h | 5 ++- .../framework/include/store/general_store.h | 1 + .../service/cloud/cloud_service_impl.cpp | 43 +++++++++++++++++-- .../service/cloud/cloud_service_impl.h | 1 + .../service/kvdb/kvdb_general_store.cpp | 5 +++ .../service/test/kvdb_general_store_test.cpp | 5 ++- .../test/mock/kv_store_nb_delegate_mock.cpp | 5 +++ .../test/mock/kv_store_nb_delegate_mock.h | 1 + 8 files changed, 60 insertions(+), 6 deletions(-) diff --git a/services/distributeddataservice/framework/include/cloud/schema_meta.h b/services/distributeddataservice/framework/include/cloud/schema_meta.h index bc74d210b..33dc0cb41 100644 --- a/services/distributeddataservice/framework/include/cloud/schema_meta.h +++ b/services/distributeddataservice/framework/include/cloud/schema_meta.h @@ -73,7 +73,8 @@ public: static constexpr const char *SHARING_RESOURCE = "#_sharing_resource"; static constexpr const char *HASH_KEY = "#_hash_key"; - static constexpr uint32_t CURRENT_VERSION = 0x10000; + static constexpr uint32_t CURRENT_VERSION = 0x10001; + static constexpr uint32_t CLEAN_WATER_VERSION = 0x10001; static inline uint32_t GetLowVersion(uint32_t metaVersion = CURRENT_VERSION) { return metaVersion & 0xFFFF; @@ -104,4 +105,4 @@ enum AutoSyncType { }; } // namespace OHOS::DistributedData -#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CLOUD_SCHEMA_META_H +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CLOUD_SCHEMA_META_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/store/general_store.h b/services/distributeddataservice/framework/include/store/general_store.h index dd4e27e7d..dc109463a 100644 --- a/services/distributeddataservice/framework/include/store/general_store.h +++ b/services/distributeddataservice/framework/include/store/general_store.h @@ -61,6 +61,7 @@ public: CLOUD_DATA, CLOUD_INFO, LOCAL_DATA, + CLEAN_WATER, CLEAN_MODE_BUTT }; diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index cf3f5d1d7..fe9aa097b 100644 --- a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -275,7 +275,9 @@ void CloudServiceImpl::DoClean(int32_t user, const SchemaMeta &schemaMeta, int32 storeInfo.bundleName = meta.bundleName; storeInfo.user = atoi(meta.user.c_str()); storeInfo.storeName = meta.storeId; - EventCenter::GetInstance().PostEvent(std::make_unique(CloudEvent::CLEAN_DATA, storeInfo)); + if (action != GeneralStore::CLEAN_WATER) { + EventCenter::GetInstance().PostEvent(std::make_unique(CloudEvent::CLEAN_DATA, storeInfo)); + } auto status = store->Clean({}, action, ""); if (status != E_OK) { ZLOGW("remove device data status:%{public}d, user:%{public}d, bundleName:%{public}s, " @@ -669,10 +671,16 @@ int32_t CloudServiceImpl::OnInitialize() { XCollie xcollie(__FUNCTION__, XCollie::XCOLLIE_LOG | XCollie::XCOLLIE_RECOVERY); DistributedDB::RuntimeConfig::SetCloudTranslate(std::make_shared()); - Execute(GenTask(0, 0, CloudSyncScene::SERVICE_INIT, - { WORK_CLOUD_INFO_UPDATE, WORK_SCHEMA_UPDATE, WORK_DO_CLOUD_SYNC, WORK_SUB })); std::vector users; Account::GetInstance()->QueryUsers(users); + for (auto user : users) { + if (user == DEFAULT_USER) { + continue; + } + CleanWaterVersion(user); + } + Execute(GenTask(0, 0, CloudSyncScene::SERVICE_INIT, + { WORK_CLOUD_INFO_UPDATE, WORK_SCHEMA_UPDATE, WORK_DO_CLOUD_SYNC, WORK_SUB })); for (auto user : users) { if (user == DEFAULT_USER) { continue; @@ -687,6 +695,35 @@ int32_t CloudServiceImpl::OnInitialize() return E_OK; } +bool CloudServiceImpl::CleanWaterVersion(int32_t user) +{ + auto [status, cloudInfo] = GetCloudInfoFromMeta(user); + if (status != SUCCESS) { + return false; + } + auto stores = CheckerManager::GetInstance().GetDynamicStores(); + auto staticStores = CheckerManager::GetInstance().GetStaticStores(); + stores.insert(stores.end(), staticStores.begin(), staticStores.end()); + auto keys = cloudInfo.GetSchemaKey(); + for (const auto &[bundle, key] : keys) { + SchemaMeta schemaMeta; + if (MetaDataManager::GetInstance().LoadMeta(key, schemaMeta, true) && + schemaMeta.metaVersion < SchemaMeta::CLEAN_WATER_VERSION) { + bool found = std::any_of(stores.begin(), stores.end(), + [&schemaMeta](const CheckerManager::StoreInfo &storeInfo) { + return storeInfo.bundleName == schemaMeta.bundleName; + }); + if (!found) { + continue; + } + DoClean(user, schemaMeta, GeneralStore::CleanMode::CLEAN_WATER); + schemaMeta.metaVersion = SchemaMeta::CLEAN_WATER_VERSION; + } + MetaDataManager::GetInstance().SaveMeta(key, schemaMeta, true); + } + return true; +} + int32_t CloudServiceImpl::OnBind(const BindInfo &info) { if (executor_ != nullptr || info.executors == nullptr) { diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.h b/services/distributeddataservice/service/cloud/cloud_service_impl.h index c1ec1dd09..21283817f 100644 --- a/services/distributeddataservice/service/cloud/cloud_service_impl.h +++ b/services/distributeddataservice/service/cloud/cloud_service_impl.h @@ -145,6 +145,7 @@ private: bool ReleaseUserInfo(int32_t user, CloudSyncScene scene); bool DoCloudSync(int32_t user, CloudSyncScene scene); bool StopCloudSync(int32_t user, CloudSyncScene scene); + bool CleanWaterVersion(int32_t user); static std::pair GetCloudInfo(int32_t userId); static std::pair GetCloudInfoFromMeta(int32_t userId); diff --git a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp index 358468d15..05a49cda2 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp @@ -521,6 +521,11 @@ int32_t KVDBGeneralStore::Clean(const std::vector &devices, int32_t case CLOUD_DATA: status = delegate_->RemoveDeviceData("", static_cast(CLOUD_DATA)); break; + case CLEAN_WATER: + ClearKvMetaDataOption option; + option.type = ClearKvMetaOpType::CLEAN_CLOUD_WATERMARK; + status = delegate_->ClearMetaData(option); + break; case NEARBY_DATA: if (devices.empty()) { status = delegate_->RemoveDeviceData(); diff --git a/services/distributeddataservice/service/test/kvdb_general_store_test.cpp b/services/distributeddataservice/service/test/kvdb_general_store_test.cpp index 6da7e1d41..57ca2a415 100644 --- a/services/distributeddataservice/service/test/kvdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_general_store_test.cpp @@ -567,7 +567,7 @@ HWTEST_F(KVDBGeneralStoreTest, Clean, TestSize.Level0) std::string tableName = "tableName"; auto ret = store->Clean(devices, -1, tableName); EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS); - ret = store->Clean(devices, 5, tableName); + ret = store->Clean(devices, 6, tableName); EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS); ret = store->Clean(devices, GeneralStore::CleanMode::NEARBY_DATA, tableName); EXPECT_EQ(ret, GeneralError::E_ALREADY_CLOSED); @@ -587,6 +587,9 @@ HWTEST_F(KVDBGeneralStoreTest, Clean, TestSize.Level0) ret = store->Clean(devices, GeneralStore::CleanMode::LOCAL_DATA, tableName); EXPECT_EQ(ret, GeneralError::E_ERROR); + + ret = store->Clean(devices, GeneralStore::CleanMode::CLEAN_WATER, tableName); + EXPECT_EQ(ret, GeneralError::E_OK); } /** diff --git a/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.cpp b/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.cpp index 09b0962e8..fd5dab19d 100644 --- a/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.cpp +++ b/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.cpp @@ -337,4 +337,9 @@ KvStoreNbDelegate::DatabaseStatus KvStoreNbDelegateMock::GetDatabaseStatus() con { return {}; } + +DBStatus KvStoreNbDelegateMock::ClearMetaData(ClearKvMetaDataOption option) +{ + return DBStatus::OK; +} } // namespace DistributedDB \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.h b/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.h index 7f3d77c8d..8a97092b8 100644 --- a/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.h +++ b/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.h @@ -107,6 +107,7 @@ public: DBStatus Sync(const DeviceSyncOption &option, const DeviceSyncProcessCallback &onProcess); DBStatus CancelSync(uint32_t syncId); DatabaseStatus GetDatabaseStatus() const; + DBStatus ClearMetaData(ClearKvMetaDataOption option); }; } // namespace DistributedDB #endif // KV_STORE_NB_DELEGATE_H_MOCK \ No newline at end of file -- Gitee From 7c9994f501df8a59752b9a968404161246aaa1e7 Mon Sep 17 00:00:00 2001 From: louzhihao Date: Tue, 15 Apr 2025 14:59:18 +0800 Subject: [PATCH 163/225] inner kit permission Signed-off-by: louzhihao Change-Id: I0aee3f3ca874a992970c2b2304b6726ada219263 --- conf/config.json | 3 +- .../service/config/BUILD.gn | 1 + .../service/config/include/config_factory.h | 2 +- .../config/include/model/datashare_config.h | 29 +++++++++ .../config/include/model/global_config.h | 3 +- .../service/config/src/config_factory.cpp | 4 +- .../config/src/model/datashare_config.cpp | 30 +++++++++ .../config/src/model/global_config.cpp | 4 +- .../service/data_share/BUILD.gn | 1 + .../data_share/common/bundle_mgr_proxy.cpp | 19 ++++++ .../data_share/common/bundle_mgr_proxy.h | 3 + .../data_share/common/common_utils.cpp | 64 +++++++++++++++++++ .../service/data_share/common/common_utils.h | 34 ++++++++++ .../data_share/data_provider_config.cpp | 10 ++- .../data_share/data_share_profile_config.cpp | 4 +- .../data_share/data_share_service_stub.cpp | 31 +++------ .../data_share/data_share_service_stub.h | 2 - ...d_config_from_data_proxy_node_strategy.cpp | 4 +- ...g_from_data_share_bundle_info_strategy.cpp | 4 +- .../service/test/BUILD.gn | 4 ++ .../fuzztest/cloudservicestub_fuzzer/BUILD.gn | 1 + .../datashareservicestub_fuzzer/BUILD.gn | 1 + .../fuzztest/kvdbservicestub_fuzzer/BUILD.gn | 1 + .../objectservicestub_fuzzer/BUILD.gn | 1 + .../fuzztest/rdbservicestub_fuzzer/BUILD.gn | 1 + 25 files changed, 219 insertions(+), 42 deletions(-) create mode 100644 services/distributeddataservice/service/config/include/model/datashare_config.h create mode 100644 services/distributeddataservice/service/config/src/model/datashare_config.cpp create mode 100644 services/distributeddataservice/service/data_share/common/common_utils.cpp create mode 100644 services/distributeddataservice/service/data_share/common/common_utils.h diff --git a/conf/config.json b/conf/config.json index d03630732..b1d053eb8 100644 --- a/conf/config.json +++ b/conf/config.json @@ -86,6 +86,5 @@ "schedularInternal" : 1800, "backupInternal" : 36000, "backupNumber" : 20 - }, - "dataShareExtNames": [] + } } \ No newline at end of file diff --git a/services/distributeddataservice/service/config/BUILD.gn b/services/distributeddataservice/service/config/BUILD.gn index a2ea71cf4..4a23f2cd1 100644 --- a/services/distributeddataservice/service/config/BUILD.gn +++ b/services/distributeddataservice/service/config/BUILD.gn @@ -29,6 +29,7 @@ ohos_source_set("distributeddata_config") { "src/model/checker_config.cpp", "src/model/cloud_config.cpp", "src/model/component_config.cpp", + "src/model/datashare_config.cpp", "src/model/directory_config.cpp", "src/model/global_config.cpp", "src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/config/include/config_factory.h b/services/distributeddataservice/service/config/include/config_factory.h index b9cbebe7d..268ca1513 100644 --- a/services/distributeddataservice/service/config/include/config_factory.h +++ b/services/distributeddataservice/service/config/include/config_factory.h @@ -33,7 +33,7 @@ public: API_EXPORT CloudConfig *GetCloudConfig(); API_EXPORT std::vector *GetAppIdMappingConfig(); API_EXPORT ThreadConfig *GetThreadConfig(); - API_EXPORT std::vector GetDataShareExtNames(); + API_EXPORT DataShareConfig *GetDataShareConfig(); private: static constexpr const char *CONF_PATH = "/system/etc/distributeddata/conf"; ConfigFactory(); diff --git a/services/distributeddataservice/service/config/include/model/datashare_config.h b/services/distributeddataservice/service/config/include/model/datashare_config.h new file mode 100644 index 000000000..4487c0d1b --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/datashare_config.h @@ -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. +*/ +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DATASHARE_CONFIG_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DATASHARE_CONFIG_H + +#include "serializable/serializable.h" +namespace OHOS { +namespace DistributedData { +class DataShareConfig final : public Serializable { +public: + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; + std::vector dataShareExtNames; +}; +} // namespace DistributedData +} // namespace OHOS +#endif //OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DATASHARE_CONFIG_H \ No newline at end of file diff --git a/services/distributeddataservice/service/config/include/model/global_config.h b/services/distributeddataservice/service/config/include/model/global_config.h index 1b048b46e..1ce17a445 100644 --- a/services/distributeddataservice/service/config/include/model/global_config.h +++ b/services/distributeddataservice/service/config/include/model/global_config.h @@ -20,6 +20,7 @@ #include "model/checker_config.h" #include "model/cloud_config.h" #include "model/component_config.h" +#include "model/datashare_config.h" #include "model/directory_config.h" #include "model/network_config.h" #include "model/thread_config.h" @@ -40,7 +41,7 @@ public: CloudConfig *cloud = nullptr; std::vector *appIdMapping = nullptr; ThreadConfig *thread = nullptr; - std::vector dataShareExtNames; + DataShareConfig *dataShare = nullptr; ~GlobalConfig(); bool Marshal(json &node) const override; bool Unmarshal(const json &node) override; diff --git a/services/distributeddataservice/service/config/src/config_factory.cpp b/services/distributeddataservice/service/config/src/config_factory.cpp index 5936484a9..52445b928 100644 --- a/services/distributeddataservice/service/config/src/config_factory.cpp +++ b/services/distributeddataservice/service/config/src/config_factory.cpp @@ -92,9 +92,9 @@ ThreadConfig *ConfigFactory::GetThreadConfig() return config_.thread; } -std::vector ConfigFactory::GetDataShareExtNames() +DataShareConfig *ConfigFactory::GetDataShareConfig() { - return config_.dataShareExtNames; + return config_.dataShare; } } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/datashare_config.cpp b/services/distributeddataservice/service/config/src/model/datashare_config.cpp new file mode 100644 index 000000000..0eae37a2b --- /dev/null +++ b/services/distributeddataservice/service/config/src/model/datashare_config.cpp @@ -0,0 +1,30 @@ +/* + * 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 "model/datashare_config.h" +namespace OHOS { +namespace DistributedData { +bool DataShareConfig::Marshal(json &node) const +{ + SetValue(node[GET_NAME(dataShareExtNames)], dataShareExtNames); + return true; +} + +bool DataShareConfig::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(dataShareExtNames), dataShareExtNames); + return true; +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/global_config.cpp b/services/distributeddataservice/service/config/src/model/global_config.cpp index e5c4d2f67..d00583f24 100644 --- a/services/distributeddataservice/service/config/src/model/global_config.cpp +++ b/services/distributeddataservice/service/config/src/model/global_config.cpp @@ -30,7 +30,7 @@ bool GlobalConfig::Marshal(json &node) const SetValue(node[GET_NAME(cloud)], cloud); SetValue(node[GET_NAME(appIdMapping)], appIdMapping); SetValue(node[GET_NAME(thread)], thread); - SetValue(node[GET_NAME(dataShareExtNames)], dataShareExtNames); + SetValue(node[GET_NAME(dataShare)], dataShare); return true; } @@ -48,7 +48,7 @@ bool GlobalConfig::Unmarshal(const json &node) GetValue(node, GET_NAME(cloud), cloud); GetValue(node, GET_NAME(appIdMapping), appIdMapping); GetValue(node, GET_NAME(thread), thread); - GetValue(node, GET_NAME(dataShareExtNames), dataShareExtNames); + GetValue(node, GET_NAME(dataShare), dataShare); return true; } diff --git a/services/distributeddataservice/service/data_share/BUILD.gn b/services/distributeddataservice/service/data_share/BUILD.gn index 8a6a2bfcb..86d79cd5e 100644 --- a/services/distributeddataservice/service/data_share/BUILD.gn +++ b/services/distributeddataservice/service/data_share/BUILD.gn @@ -49,6 +49,7 @@ ohos_source_set("data_share_service") { sources = [ "common/app_connect_manager.cpp", "common/bundle_mgr_proxy.cpp", + "common/common_utils.cpp", "common/db_delegate.cpp", "common/div_strategy.cpp", "common/extension_ability_manager.cpp", diff --git a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp index 410408beb..4e5e29b04 100644 --- a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp +++ b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp @@ -16,6 +16,7 @@ #include "bundle_mgr_proxy.h" #include "account/account_delegate.h" +#include "common_utils.h" #include "datashare_errno.h" #include "datashare_radar_reporter.h" #include "if_system_ability_manager.h" @@ -114,6 +115,23 @@ int BundleMgrProxy::GetBundleInfoFromBMS( return E_OK; } +int BundleMgrProxy::GetBundleInfoFromBMSWithCheck( + const std::string &bundleName, int32_t userId, BundleConfig &bundleConfig, int32_t appIndex) +{ + int res = GetBundleInfoFromBMS(bundleName, userId, bundleConfig, appIndex); + if (res != E_OK) { + return res; + } + // Not allow normal app visit normal app. + if (!DataShareThreadLocal::IsFromSystemApp() && !bundleConfig.isSystemApp) { + ZLOGE("Not allow normal app visit normal app, bundle:%{public}s, callingPid:%{public}d", + bundleName.c_str(), IPCSkeleton::GetCallingPid()); + return E_NOT_SYSTEM_APP; + } + + return E_OK; +} + std::pair BundleMgrProxy::GetCallerAppIdentifier( const std::string &bundleName, int32_t userId) { @@ -199,6 +217,7 @@ std::pair BundleMgrProxy::ConvertToDataShareBundle(AppExecFwk return std::make_pair(err, bundleConfig); } bundleConfig.extensionInfos = extensionInfos; + bundleConfig.isSystemApp = bundleInfo.applicationInfo.isSystemApp; return std::make_pair(E_OK, bundleConfig); } diff --git a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h index 71bcc496e..c0c3d774e 100644 --- a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h +++ b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h @@ -57,6 +57,7 @@ struct ExtensionAbilityInfo { struct BundleConfig { std::string name; bool singleton = false; + bool isSystemApp = false; std::vector hapModuleInfos; std::vector extensionInfos; }; @@ -67,6 +68,8 @@ public: static std::shared_ptr GetInstance(); int GetBundleInfoFromBMS(const std::string &bundleName, int32_t userId, BundleConfig &bundleConfig, int32_t appIndex = 0); + int GetBundleInfoFromBMSWithCheck(const std::string &bundleName, int32_t userId, + BundleConfig &bundleConfig, int32_t appIndex = 0); void Delete(const std::string &bundleName, int32_t userId, int32_t appIndex); sptr CheckBMS(); std::pair GetCallerAppIdentifier(const std::string &bundleName, int32_t userId); diff --git a/services/distributeddataservice/service/data_share/common/common_utils.cpp b/services/distributeddataservice/service/data_share/common/common_utils.cpp new file mode 100644 index 000000000..deeab89cb --- /dev/null +++ b/services/distributeddataservice/service/data_share/common/common_utils.cpp @@ -0,0 +1,64 @@ +/* + * 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 "CommonUtils" +#include "common_utils.h" + +#include "accesstoken_kit.h" +#include "config_factory.h" +#include "log_print.h" +#include "tokenid_kit.h" + +namespace OHOS::DataShare { + +bool& DataShareThreadLocal::GetFromSystemApp() +{ + static thread_local bool isFromSystemApp = true; + return isFromSystemApp; +} + +void DataShareThreadLocal::SetFromSystemApp(bool isFromSystemApp) +{ + GetFromSystemApp() = isFromSystemApp; +} + +bool DataShareThreadLocal::IsFromSystemApp() +{ + return GetFromSystemApp(); +} + +void DataShareThreadLocal::CleanFromSystemApp() +{ + SetFromSystemApp(true); +} + +bool CheckSystemAbility(uint32_t tokenId) +{ + Security::AccessToken::ATokenTypeEnum tokenType = + Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId); + return (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE || + tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL); +} + +// GetTokenType use tokenId, and IsSystemApp use fullTokenId, these are different +bool CheckSystemCallingPermission(uint32_t tokenId, uint64_t fullTokenId) +{ + if (CheckSystemAbility(tokenId)) { + return true; + } + // IsSystemAppByFullTokenID here is not IPC + return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); +} + +} // namespace OHOS::DataShare diff --git a/services/distributeddataservice/service/data_share/common/common_utils.h b/services/distributeddataservice/service/data_share/common/common_utils.h new file mode 100644 index 000000000..1b8379dc7 --- /dev/null +++ b/services/distributeddataservice/service/data_share/common/common_utils.h @@ -0,0 +1,34 @@ +/* + * 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 DATASHARESERVICE_COMMON_UTILS_H +#define DATASHARESERVICE_COMMON_UTILS_H + +#include +#include + +namespace OHOS::DataShare { +struct DataShareThreadLocal { + static bool& GetFromSystemApp(); + static void SetFromSystemApp(bool isFromSystemApp); + static bool IsFromSystemApp(); + static void CleanFromSystemApp(); +}; + +bool CheckSystemAbility(uint32_t tokenId); + +bool CheckSystemCallingPermission(uint32_t tokenId, uint64_t fullTokenId); + +} // namespace OHOS::DataShare +#endif // DATASHARESERVICE_COMMON_UTILS_H diff --git a/services/distributeddataservice/service/data_share/data_provider_config.cpp b/services/distributeddataservice/service/data_share/data_provider_config.cpp index 81eb0145f..74a7630fb 100644 --- a/services/distributeddataservice/service/data_share/data_provider_config.cpp +++ b/services/distributeddataservice/service/data_share/data_provider_config.cpp @@ -64,7 +64,7 @@ std::pair DataProviderConfig::GetBundleInfo() } providerInfo_.bundleName = uriConfig_.pathSegments[0]; } - auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS( + auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck( providerInfo_.bundleName, providerInfo_.visitedUserId, bundleInfo, providerInfo_.appIndex); return std::make_pair(ret, bundleInfo); } @@ -158,7 +158,7 @@ int DataProviderConfig::GetFromExtension() return E_URI_NOT_EXIST; } BundleConfig bundleInfo; - auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS( + auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck( providerInfo_.bundleName, providerInfo_.visitedUserId, bundleInfo, providerInfo_.appIndex); if (ret != E_OK) { ZLOGE("BundleInfo failed! bundleName: %{public}s", providerInfo_.bundleName.c_str()); @@ -249,7 +249,11 @@ std::pair DataProviderConfig::GetProvider bool DataProviderConfig::IsInExtList(const std::string &bundleName) { - auto extNames = ConfigFactory::GetInstance().GetDataShareExtNames(); + DataShareConfig *config = ConfigFactory::GetInstance().GetDataShareConfig(); + if (config == nullptr) { + return true; + } + std::vector& extNames = config->dataShareExtNames; return std::find(extNames.begin(), extNames.end(), bundleName) != extNames.end(); } } // namespace OHOS::DataShare diff --git a/services/distributeddataservice/service/data_share/data_share_profile_config.cpp b/services/distributeddataservice/service/data_share/data_share_profile_config.cpp index 9787d9df1..ecf2ab8cd 100644 --- a/services/distributeddataservice/service/data_share/data_share_profile_config.cpp +++ b/services/distributeddataservice/service/data_share/data_share_profile_config.cpp @@ -275,9 +275,9 @@ bool DataShareProfileConfig::GetProfileInfo(const std::string &calledBundleName, { BundleConfig bundleInfo; // profile is the same when app clone - if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS(calledBundleName, + if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck(calledBundleName, currentUserId, bundleInfo) != E_OK) { - ZLOGE("data share GetBundleInfoFromBMS failed! bundleName: %{public}s, currentUserId = %{public}d", + ZLOGE("data share GetBundleInfoFromBMSWithCheck failed! bundleName: %{public}s, currentUserId = %{public}d", calledBundleName.c_str(), currentUserId); return false; } diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp index d0b000ee9..ab765ec94 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp @@ -18,8 +18,7 @@ #include "data_share_service_stub.h" #include -#include "accesstoken_kit.h" -#include "tokenid_kit.h" +#include "common_utils.h" #include "data_share_obs_proxy.h" #include "hiview_adapter.h" #include "hiview_fault_adapter.h" @@ -327,24 +326,6 @@ int32_t DataShareServiceStub::OnNotifyConnectDone(MessageParcel &data, MessagePa return 0; } -bool DataShareServiceStub::CheckProxyCallingPermission(uint32_t tokenId) -{ - Security::AccessToken::ATokenTypeEnum tokenType = - Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId); - return (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE || - tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL); -} - -// GetTokenType use tokenId, and IsSystemApp use fullTokenId, these are different -bool DataShareServiceStub::CheckSystemUidCallingPermission(uint32_t tokenId, uint64_t fullTokenId) -{ - if (CheckProxyCallingPermission(tokenId)) { - return true; - } - // IsSystemAppByFullTokenID here is not IPC - return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); -} - int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply) { int tryTimes = TRY_TIMES; @@ -353,10 +334,12 @@ int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Me std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); } auto callingPid = IPCSkeleton::GetCallingPid(); + auto fullTokenId = IPCSkeleton::GetCallingFullTokenID(); + bool isSystemApp = CheckSystemCallingPermission(IPCSkeleton::GetCallingTokenID(), fullTokenId); + DataShareThreadLocal::SetFromSystemApp(isSystemApp); if (code >= DATA_SHARE_CMD_SYSTEM_CODE) { - auto fullTokenId = IPCSkeleton::GetCallingFullTokenID(); - if (!CheckSystemUidCallingPermission(IPCSkeleton::GetCallingTokenID(), fullTokenId)) { - ZLOGE("CheckSystemUidCallingPermission fail, token:%{public}" PRIx64 + if (!isSystemApp) { + ZLOGE("CheckSystemCallingPermission fail, token:%{public}" PRIx64 ", callingPid:%{public}d, code:%{public}u", fullTokenId, callingPid, code); return E_NOT_SYSTEM_APP; } @@ -366,6 +349,7 @@ int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Me ZLOGI("code:%{public}u, callingPid:%{public}d", code, callingPid); } if (!CheckInterfaceToken(data)) { + DataShareThreadLocal::CleanFromSystemApp(); return DATA_SHARE_ERROR; } int res = -1; @@ -384,6 +368,7 @@ int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Me } HiViewAdapter::GetInstance().ReportDataStatistic(callerInfo); } + DataShareThreadLocal::CleanFromSystemApp(); return res; } diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.h b/services/distributeddataservice/service/data_share/data_share_service_stub.h index b84c26967..d13b20993 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_stub.h +++ b/services/distributeddataservice/service/data_share/data_share_service_stub.h @@ -29,8 +29,6 @@ public: private: static constexpr std::chrono::milliseconds TIME_THRESHOLD = std::chrono::milliseconds(500); static bool CheckInterfaceToken(MessageParcel& data); - bool CheckProxyCallingPermission(uint32_t tokenId); - bool CheckSystemUidCallingPermission(uint32_t tokenId, uint64_t fullTokenId); int32_t OnQuery(MessageParcel& data, MessageParcel& reply); int32_t OnAddTemplate(MessageParcel& data, MessageParcel& reply); int32_t OnDelTemplate(MessageParcel& data, MessageParcel& reply); diff --git a/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp index e3e01974b..8bbaebcea 100644 --- a/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp @@ -30,9 +30,9 @@ bool LoadConfigFromDataProxyNodeStrategy::operator()(std::shared_ptr co return false; } context->type = PUBLISHED_DATA_TYPE; - if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS( + if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck( context->calledBundleName, context->visitedUserId, context->bundleInfo) != E_OK) { - ZLOGE("GetBundleInfoFromBMS failed! bundleName: %{public}s", context->calledBundleName.c_str()); + ZLOGE("GetBundleInfoFromBMSWithCheck failed! bundleName: %{public}s", context->calledBundleName.c_str()); context->errCode = E_BUNDLE_NAME_NOT_EXIST; return false; } diff --git a/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp index cc8f284c4..cb4b331ac 100644 --- a/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp @@ -80,9 +80,9 @@ bool LoadConfigFromDataShareBundleInfoStrategy::operator()(std::shared_ptrcalledBundleName.c_str()); return false; } - if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS( + if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck( context->calledBundleName, context->visitedUserId, context->bundleInfo) != E_OK) { - ZLOGE("GetBundleInfoFromBMS failed! bundleName: %{public}s", context->calledBundleName.c_str()); + ZLOGE("GetBundleInfoFromBMSWithCheck failed! bundleName: %{public}s", context->calledBundleName.c_str()); return false; } for (auto const &item : context->bundleInfo.extensionInfos) { diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 4cf45945b..3d08e69a5 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -85,6 +85,7 @@ ohos_unittest("CloudDataTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", @@ -181,6 +182,7 @@ ohos_unittest("CloudServiceImplTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", @@ -1046,6 +1048,7 @@ ohos_unittest("DataShareServiceImplTest") { "${data_service_path}/service/crypto/src/crypto_manager.cpp", "${data_service_path}/service/data_share/common/app_connect_manager.cpp", "${data_service_path}/service/data_share/common/bundle_mgr_proxy.cpp", + "${data_service_path}/service/data_share/common/common_utils.cpp", "${data_service_path}/service/data_share/common/db_delegate.cpp", "${data_service_path}/service/data_share/common/div_strategy.cpp", "${data_service_path}/service/data_share/common/extension_ability_manager.cpp", @@ -1672,6 +1675,7 @@ ohos_unittest("BootStrapMockTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn index 3cb8f10bd..94c5b63cb 100644 --- a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn @@ -82,6 +82,7 @@ ohos_fuzztest("CloudServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn index a980b47de..d8ab23c45 100644 --- a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn @@ -56,6 +56,7 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "${data_service_path}/service/crypto/src/crypto_manager.cpp", "${data_service_path}/service/data_share/common/app_connect_manager.cpp", "${data_service_path}/service/data_share/common/bundle_mgr_proxy.cpp", + "${data_service_path}/service/data_share/common/common_utils.cpp", "${data_service_path}/service/data_share/common/db_delegate.cpp", "${data_service_path}/service/data_share/common/div_strategy.cpp", "${data_service_path}/service/data_share/common/extension_ability_manager.cpp", diff --git a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn index 458b5897b..c4b2cd891 100644 --- a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn @@ -69,6 +69,7 @@ ohos_fuzztest("KvdbServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn index 336b0dbfc..5f3f05b54 100755 --- a/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn @@ -68,6 +68,7 @@ ohos_fuzztest("ObjectServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn index e51d78511..302d59f33 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn @@ -74,6 +74,7 @@ ohos_fuzztest("RdbServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", -- Gitee From 4cfeff40d9dab19a6fe7fac65ded1066edac1447 Mon Sep 17 00:00:00 2001 From: guochao Date: Thu, 17 Apr 2025 12:14:59 +0800 Subject: [PATCH 164/225] add test Signed-off-by: guochao --- .../service/test/mock/general_watcher_mock.cpp | 1 + .../service/test/mock/general_watcher_mock.h | 3 +++ .../test/mock/relational_store_manager_mock.cpp | 4 ++-- .../service/test/rdb_general_store_test.cpp | 15 ++++++--------- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp index 9a4a88a5e..fea50b964 100644 --- a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp +++ b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp @@ -49,6 +49,7 @@ void MockQuery::MakeQuery(const DistributedRdb::PredicatesMemo &predicates) } int32_t MockGeneralWatcher::OnChange(const Origin &origin, const PRIFields &primaryFields, ChangeInfo &&values) { + primaryFields_ = primaryFields; return GeneralError::E_OK; } diff --git a/services/distributeddataservice/service/test/mock/general_watcher_mock.h b/services/distributeddataservice/service/test/mock/general_watcher_mock.h index 0142def54..a2c8b767b 100644 --- a/services/distributeddataservice/service/test/mock/general_watcher_mock.h +++ b/services/distributeddataservice/service/test/mock/general_watcher_mock.h @@ -37,6 +37,9 @@ public: int32_t OnChange(const Origin &origin, const PRIFields &primaryFields, ChangeInfo &&values) override; int32_t OnChange(const Origin &origin, const Fields &fields, ChangeData &&datas) override; + +private: + PRIFields primaryFields_; }; } // namespace OHOS::DistributedData #endif \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp index 21474d1a5..be77dce7f 100644 --- a/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp +++ b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp @@ -18,7 +18,7 @@ #include "relational_store_delegate_mock.h" #include "relational_store_manager.h" namespace DistributedDB { -DB_API DBStatus RelationalStoreManager::OpenStore(const std::string &path, const std::string &storeId, +DBStatus RelationalStoreManager::OpenStore(const std::string &path, const std::string &storeId, const RelationalStoreDelegate::Option &option, RelationalStoreDelegate *&delegate) { delegate = std::make_shared().get(); @@ -28,7 +28,7 @@ DB_API DBStatus RelationalStoreManager::OpenStore(const std::string &path, const return DB_ERROR; } -DB_API DBStatus RelationalStoreManager::CloseStore(RelationalStoreDelegate *store) +DBStatus RelationalStoreManager::CloseStore(RelationalStoreDelegate *store) { store = nullptr; return OK; diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index 6e360fd1f..4cc0c4c25 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -512,7 +512,7 @@ HWTEST_F(RdbGeneralStoreTest, Query002, TestSize.Level1) /** * @tc.name: Query003 - * @tc.desc: Test remote query with invalid device count + * @tc.desc: it is not a remote query return E_ERROR. * @tc.type: FUNC */ HWTEST_F(RdbGeneralStoreTest, Query003, TestSize.Level1) @@ -525,11 +525,10 @@ HWTEST_F(RdbGeneralStoreTest, Query003, TestSize.Level1) const std::string devices = "device1"; const std::string sql; Values args; - query.MakeRemoteQuery(devices, sql, std::move(args)); query.lastResult = true; std::string table = "test_table"; auto [err, cursor] = store->Query(table, query); - EXPECT_EQ(err, GeneralError::E_OK); + EXPECT_EQ(err, GeneralError::E_ERROR); } /** @@ -667,7 +666,7 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing, TestSize.Level1) /** * @tc.name: PreSharing -* @tc.desc: RdbGeneralStore PreSharing function test +* @tc.desc: RdbGeneralStore PreSharing function test, return E_INVALID_ARGS. * @tc.type: FUNC */ HWTEST_F(RdbGeneralStoreTest, PreSharing001, TestSize.Level1) @@ -683,7 +682,7 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing001, TestSize.Level1) /** * @tc.name: PreSharing -* @tc.desc: RdbGeneralStore PreSharing function test +* @tc.desc: RdbGeneralStore PreSharing function delegate is nullptr test. * @tc.type: FUNC */ HWTEST_F(RdbGeneralStoreTest, PreSharing002, TestSize.Level1) @@ -703,12 +702,11 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing002, TestSize.Level1) /** * @tc.name: PreSharing -* @tc.desc: RdbGeneralStore PreSharing function test +* @tc.desc: RdbGeneralStore PreSharing function E_CLOUD_DISABLED test. * @tc.type: FUNC */ HWTEST_F(RdbGeneralStoreTest, PreSharing003, TestSize.Level1) { - ZLOGE("PreSharing003 start"); metaData_.storeId = "mock"; auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); @@ -834,8 +832,6 @@ HWTEST_F(RdbGeneralStoreTest, OnChange, TestSize.Level1) * @tc.name: OnChange001 * @tc.desc: RdbGeneralStore OnChange function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, OnChange001, TestSize.Level1) { @@ -868,6 +864,7 @@ HWTEST_F(RdbGeneralStoreTest, OnChange001, TestSize.Level1) EXPECT_EQ(result, GeneralError::E_OK); store->observer_.OnChange(data); store->observer_.OnChange(DistributedDB::Origin::ORIGIN_CLOUD, "originalId", std::move(changedData)); + EXPECT_EQ(watcher.primaryFields_[changedData.tableName], *(changedData.field.begin())); store->observer_.OnChange(DistributedDB::Origin::ORIGIN_LOCAL, "originalId", std::move(changedData)); result = store->Unwatch(GeneralWatcher::Origin::ORIGIN_ALL, watcher); EXPECT_EQ(result, GeneralError::E_OK); -- Gitee From 3c80856d05358f1c2a860ee576026dd915797644 Mon Sep 17 00:00:00 2001 From: guochao Date: Thu, 17 Apr 2025 15:37:04 +0800 Subject: [PATCH 165/225] add Signed-off-by: guochao --- .../service/test/mock/general_watcher_mock.cpp | 1 + .../service/test/mock/general_watcher_mock.h | 1 + .../service/test/rdb_general_store_test.cpp | 5 ++++- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp index fea50b964..e5d20802c 100644 --- a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp +++ b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp @@ -49,6 +49,7 @@ void MockQuery::MakeQuery(const DistributedRdb::PredicatesMemo &predicates) } int32_t MockGeneralWatcher::OnChange(const Origin &origin, const PRIFields &primaryFields, ChangeInfo &&values) { + origin_ = origin; primaryFields_ = primaryFields; return GeneralError::E_OK; } diff --git a/services/distributeddataservice/service/test/mock/general_watcher_mock.h b/services/distributeddataservice/service/test/mock/general_watcher_mock.h index a2c8b767b..f82741779 100644 --- a/services/distributeddataservice/service/test/mock/general_watcher_mock.h +++ b/services/distributeddataservice/service/test/mock/general_watcher_mock.h @@ -39,6 +39,7 @@ public: int32_t OnChange(const Origin &origin, const Fields &fields, ChangeData &&datas) override; private: + Origin origin_; PRIFields primaryFields_; }; } // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index 4cc0c4c25..084dacb27 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -860,12 +860,15 @@ HWTEST_F(RdbGeneralStoreTest, OnChange001, TestSize.Level1) { int64_t(-123), 2.718, 100, 0.001 } }; changedData.field = { "name", "age" }; changedData.tableName = "test"; + DistributedDB::ChangedData changedDataTmp; + changedDataTmp = changedData; auto result = store->Watch(GeneralWatcher::Origin::ORIGIN_ALL, watcher); EXPECT_EQ(result, GeneralError::E_OK); store->observer_.OnChange(data); store->observer_.OnChange(DistributedDB::Origin::ORIGIN_CLOUD, "originalId", std::move(changedData)); - EXPECT_EQ(watcher.primaryFields_[changedData.tableName], *(changedData.field.begin())); + EXPECT_EQ(watcher.primaryFields_[changedDataTmp.tableName], *(changedDataTmp.field.begin())); store->observer_.OnChange(DistributedDB::Origin::ORIGIN_LOCAL, "originalId", std::move(changedData)); + EXPECT_EQ(watcher.origin_.id[0], "originalId"); result = store->Unwatch(GeneralWatcher::Origin::ORIGIN_ALL, watcher); EXPECT_EQ(result, GeneralError::E_OK); } -- Gitee From 29626e0f8ac906602e4657cdc0220abc2aac852d Mon Sep 17 00:00:00 2001 From: guochao Date: Thu, 17 Apr 2025 16:21:23 +0800 Subject: [PATCH 166/225] add Signed-off-by: guochao --- .../service/test/rdb_general_store_test.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index 084dacb27..f1e56cbbd 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -867,7 +867,8 @@ HWTEST_F(RdbGeneralStoreTest, OnChange001, TestSize.Level1) store->observer_.OnChange(data); store->observer_.OnChange(DistributedDB::Origin::ORIGIN_CLOUD, "originalId", std::move(changedData)); EXPECT_EQ(watcher.primaryFields_[changedDataTmp.tableName], *(changedDataTmp.field.begin())); - store->observer_.OnChange(DistributedDB::Origin::ORIGIN_LOCAL, "originalId", std::move(changedData)); + store->observer_.OnChange(DistributedDB::Origin::ORIGIN_LOCAL, "originalId", std::move(changedDataTmp)); + EXPECT_NE(watcher.origin_.id.size(), 0); EXPECT_EQ(watcher.origin_.id[0], "originalId"); result = store->Unwatch(GeneralWatcher::Origin::ORIGIN_ALL, watcher); EXPECT_EQ(result, GeneralError::E_OK); -- Gitee From 92470f30136ecea4df7b549465338cf44a139f50 Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Thu, 17 Apr 2025 20:07:36 +0800 Subject: [PATCH 167/225] fix clear bug and std::bind check Signed-off-by: wanghuajian-6 --- .../include/metadata/object_user_meta_data.h | 2 -- .../metadata/object_user_meta_data.cpp | 2 -- .../service/object/src/object_manager.cpp | 23 +++++++++++-------- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h b/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h index 91e81b868..cd2dd38e4 100644 --- a/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h @@ -15,8 +15,6 @@ #ifndef DISTRIBUTEDDATAMGR_OBJECT_USER_META_DATA_H #define DISTRIBUTEDDATAMGR_OBJECT_USER_META_DATA_H -#include -#include #include "serializable/serializable.h" namespace OHOS::DistributedData { diff --git a/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp b/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp index 9324ebc28..e4471f745 100644 --- a/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp @@ -14,8 +14,6 @@ */ #include "metadata/object_user_meta_data.h" -#include "utils/constant.h" - namespace OHOS::DistributedData { ObjectUserMetaData::ObjectUserMetaData() diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 049be5d40..797a7cace 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -292,20 +292,21 @@ int32_t ObjectStoreManager::Retrieve( int32_t ObjectStoreManager::Clear() { ZLOGI("enter"); + DistributedData::ObjectUserMetaData userMeta; + if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(userMeta.GetKey(), userMeta, true)) { + ZLOGI("no object user meta. don't need clear"); + return OBJECT_SUCCESS; + } std::string userId = GetCurrentUser(); if (userId.empty()) { + ZLOGE("no user error"); return OBJECT_INNER_ERROR; } - DistributedData::ObjectUserMetaData userMeta; - if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(userMeta.GetKey(), userMeta, true)) { - ZLOGE("no meta of userId:%{public}s", userId.c_str()); - return OBJECT_STORE_NOT_FOUND; - } if (userMeta.userId == userId) { - ZLOGI("user is same, not need to change, user:%{public}s.", userId.c_str()); + ZLOGI("user is same, don't need clear, user:%{public}s.", userId.c_str()); return OBJECT_SUCCESS; } - ZLOGI("user changed, need to clear, userId:%{public}s", userId.c_str()); + ZLOGI("user changed, need clear, userId:%{public}s", userId.c_str()); int32_t result = Open(); if (result != OBJECT_SUCCESS) { ZLOGE("Open failed, errCode = %{public}d", result); @@ -321,7 +322,9 @@ int32_t ObjectStoreManager::ClearOldUserMeta() std::string userId = GetCurrentUser(); if (userId.empty()) { ZLOGI("get userId error, one minute again"); - executors_->Schedule(std::chrono::minutes(INTERVAL), std::bind(&ObjectStoreManager::ClearOldUserMeta, this)); + executors_->Schedule(std::chrono::minutes(INTERVAL), [this]() { + ClearOldUserMeta(); + }); return OBJECT_INNER_ERROR; } ObjectUserMetaData userMetaData; @@ -1121,7 +1124,9 @@ void ObjectStoreManager::SaveUserToMeta() void ObjectStoreManager::CloseAfterMinute() { - executors_->Schedule(std::chrono::minutes(INTERVAL), std::bind(&ObjectStoreManager::Close, this)); + executors_->Schedule(std::chrono::minutes(INTERVAL), [this]() { + Close(); + }); } void ObjectStoreManager::SetThreadPool(std::shared_ptr executors) -- Gitee From 9c80066d5a32ab6a6ff8527f5a902d6e1fe747af Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Thu, 17 Apr 2025 20:10:35 +0800 Subject: [PATCH 168/225] fix clear bug and std::bind check Signed-off-by: wanghuajian-6 --- .../service/object/src/object_manager.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 797a7cace..6dfceec2c 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -1115,10 +1115,10 @@ void ObjectStoreManager::SaveUserToMeta() std::string appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); DistributedData::ObjectUserMetaData userMeta; userMeta.userId = userId; - auto userMetaKey = DistributedData::ObjectUserMetaData::GetKey(); - auto saved = DistributedData::MetaDataManager::GetInstance().SaveMeta(userMetaKey, userMeta, true); + auto saved = DistributedData::MetaDataManager::GetInstance().SaveMeta( + DistributedData::ObjectUserMetaData::GetKey(), userMeta, true); if (!saved) { - ZLOGE("userMeta save failed"); + ZLOGE("userMeta save failed, userId:%{public}s", userId.c_str()); } } -- Gitee From e75128c5a233351e8f2e11e0ef6dd2c6a271232f Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Thu, 17 Apr 2025 20:49:50 +0800 Subject: [PATCH 169/225] fix clear bug and std::bind check Signed-off-by: wanghuajian-6 --- .../service/object/src/object_manager.cpp | 4 ++-- .../service/object/src/object_service_impl.cpp | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 6dfceec2c..de0d9fe6a 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -1098,8 +1098,8 @@ std::vector ObjectStoreManager::SplitEntryKey(const std::string &ke std::string ObjectStoreManager::GetCurrentUser() { std::vector users; - AccountDelegate::GetInstance()->QueryUsers(users); - if (users.empty()) { + if (!AccountDelegate::GetInstance()->QueryUsers(users)) { + ZLOGE("QueryUsers failed."); return ""; } return std::to_string(users[0]); diff --git a/services/distributeddataservice/service/object/src/object_service_impl.cpp b/services/distributeddataservice/service/object/src/object_service_impl.cpp index 553d1ace8..517f1458b 100644 --- a/services/distributeddataservice/service/object/src/object_service_impl.cpp +++ b/services/distributeddataservice/service/object/src/object_service_impl.cpp @@ -383,8 +383,9 @@ void ObjectServiceImpl::RegisterObjectServiceInfo() void ObjectServiceImpl::RegisterHandler() { - Handler handler = - std::bind(&ObjectServiceImpl::DumpObjectServiceInfo, this, std::placeholders::_1, std::placeholders::_2); + Handler handler = [this](int fd, std::map> ¶ms) { + DumpObjectServiceInfo(fd, params); + }; DumpManager::GetInstance().AddHandler("FEATURE_INFO", uintptr_t(this), handler); } -- Gitee From edb3cac325e4f5b436f897b3d968d9166932b95c Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Fri, 18 Apr 2025 10:56:00 +0800 Subject: [PATCH 170/225] fix clear bug and std::bind check Signed-off-by: wanghuajian-6 --- .../framework/metadata/object_user_meta_data.cpp | 1 - .../service/object/include/object_manager.h | 2 +- .../service/object/src/object_manager.cpp | 7 ++----- .../service/object/src/object_service_impl.cpp | 2 +- .../service/test/object_manager_test.cpp | 2 +- 5 files changed, 5 insertions(+), 9 deletions(-) diff --git a/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp b/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp index e4471f745..c5d5d9e07 100644 --- a/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp @@ -15,7 +15,6 @@ #include "metadata/object_user_meta_data.h" namespace OHOS::DistributedData { - ObjectUserMetaData::ObjectUserMetaData() { } diff --git a/services/distributeddataservice/service/object/include/object_manager.h b/services/distributeddataservice/service/object/include/object_manager.h index f1e38aa20..6ce04d901 100644 --- a/services/distributeddataservice/service/object/include/object_manager.h +++ b/services/distributeddataservice/service/object/include/object_manager.h @@ -89,7 +89,7 @@ public: sptr callback, uint32_t tokenId); void SetData(const std::string &dataDir, const std::string &userId); int32_t Clear(); - int32_t ClearOldUserMeta(); + int32_t CleanOldUserMeta(); int32_t DeleteByAppId(const std::string &appId, int32_t user); void RegisterRemoteCallback(const std::string &bundleName, const std::string &sessionId, pid_t pid, uint32_t tokenId, diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index de0d9fe6a..e121bb10e 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -317,14 +317,11 @@ int32_t ObjectStoreManager::Clear() return result; } -int32_t ObjectStoreManager::ClearOldUserMeta() +int32_t ObjectStoreManager::CleanOldUserMeta() { std::string userId = GetCurrentUser(); if (userId.empty()) { - ZLOGI("get userId error, one minute again"); - executors_->Schedule(std::chrono::minutes(INTERVAL), [this]() { - ClearOldUserMeta(); - }); + ZLOGI("get userId error"); return OBJECT_INNER_ERROR; } ObjectUserMetaData userMetaData; diff --git a/services/distributeddataservice/service/object/src/object_service_impl.cpp b/services/distributeddataservice/service/object/src/object_service_impl.cpp index 517f1458b..a207bf00f 100644 --- a/services/distributeddataservice/service/object/src/object_service_impl.cpp +++ b/services/distributeddataservice/service/object/src/object_service_impl.cpp @@ -139,7 +139,7 @@ int32_t ObjectServiceImpl::OnInitialize() StoreMetaData saveMeta; SaveMetaData(saveMeta, std::to_string(userId), accountId); ObjectStoreManager::GetInstance()->SetData(saveMeta.dataDir, std::to_string(userId)); - ObjectStoreManager::GetInstance()->ClearOldUserMeta(); + ObjectStoreManager::GetInstance()->CleanOldUserMeta(); RegisterObjectServiceInfo(); RegisterHandler(); ObjectDmsHandler::GetInstance().RegisterDmsEvent(); diff --git a/services/distributeddataservice/service/test/object_manager_test.cpp b/services/distributeddataservice/service/test/object_manager_test.cpp index cfed2eacf..b795e592a 100644 --- a/services/distributeddataservice/service/test/object_manager_test.cpp +++ b/services/distributeddataservice/service/test/object_manager_test.cpp @@ -1095,7 +1095,7 @@ HWTEST_F(ObjectManagerTest, GetObjectData002, TestSize.Level1) HWTEST_F(ObjectManagerTest, ClearOldUserMeta001, TestSize.Level1) { auto manager = ObjectStoreManager::GetInstance(); - auto status = manager->ClearOldUserMeta(); + auto status = manager->CleanOldUserMeta(); ASSERT_EQ(status, DistributedObject::OBJECT_SUCCESS); } } // namespace OHOS::Test -- Gitee From 5552733d0ae96f6829e8c585560f9484a8b548f8 Mon Sep 17 00:00:00 2001 From: guochao Date: Fri, 18 Apr 2025 17:43:48 +0800 Subject: [PATCH 171/225] =?UTF-8?q?fix:testcase=20=E7=A9=BA=E6=8C=87?= =?UTF-8?q?=E9=92=88=20Signed-off-by:=20guochao=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mock/relational_store_manager_mock.cpp | 4 +- .../service/test/rdb_general_store_test.cpp | 87 ++++--------------- 2 files changed, 20 insertions(+), 71 deletions(-) diff --git a/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp index be77dce7f..c17943733 100644 --- a/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp +++ b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp @@ -21,7 +21,9 @@ namespace DistributedDB { DBStatus RelationalStoreManager::OpenStore(const std::string &path, const std::string &storeId, const RelationalStoreDelegate::Option &option, RelationalStoreDelegate *&delegate) { - delegate = std::make_shared().get(); + delegate = new (std::nothrow) MockRelationalStoreDelegate(); + delegate->CreateDistributedTable("naturalbase_rdb_test"); + delegate->CreateDistributedTable("naturalbase_rdb_name"); if (storeId == "mock") { return OK; } diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index 2721fe24f..1f126533a 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -64,15 +64,22 @@ public: { Bootstrap::GetInstance().LoadDirectory(); InitMetaData(); + store = std::make_shared(metaData_); + ASSERT_NE(store, nullptr); }; void TearDown() { MockRelationalStoreDelegate::gTestResult = false; + if (store->delegate_ != nullptr) { + delete store->delegate_; + store->delegate_ = nullptr; + } }; protected: void InitMetaData(); StoreMetaData metaData_; + std::shared_ptr store; }; void RdbGeneralStoreTest::InitMetaData() @@ -103,7 +110,6 @@ public: } }; - /** * @tc.name: BindSnapshots001 * @tc.desc: RdbGeneralStore BindSnapshots test @@ -111,8 +117,6 @@ public: */ HWTEST_F(RdbGeneralStoreTest, BindSnapshots001, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); BindAssets bindAssets; auto result = store->BindSnapshots(bindAssets.bindAssets); EXPECT_EQ(result, GeneralError::E_OK); @@ -143,8 +147,6 @@ HWTEST_F(RdbGeneralStoreTest, BindSnapshots002, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Bind001, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); DistributedData::Database database; GeneralStore::CloudConfig config; std::map bindInfos; @@ -187,8 +189,6 @@ HWTEST_F(RdbGeneralStoreTest, Bind001, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Bind002, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); DistributedData::Database database; std::map bindInfos; std::shared_ptr db = std::make_shared(); @@ -213,8 +213,6 @@ HWTEST_F(RdbGeneralStoreTest, Bind002, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Bind003, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); DistributedData::Database database; std::map bindInfos; @@ -238,8 +236,6 @@ HWTEST_F(RdbGeneralStoreTest, Bind003, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Close, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); auto result = store->IsBound(std::atoi(metaData_.user.c_str())); EXPECT_EQ(result, false); EXPECT_EQ(store->delegate_, nullptr); @@ -280,8 +276,6 @@ HWTEST_F(RdbGeneralStoreTest, BusyClose, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Execute, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; EXPECT_EQ(store->delegate_, nullptr); @@ -304,8 +298,6 @@ HWTEST_F(RdbGeneralStoreTest, Execute, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, SqlConcatenate, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); DistributedData::VBucket value; std::string strColumnSql = "strColumnSql"; std::string strRowValueSql = "strRowValueSql"; @@ -328,8 +320,6 @@ HWTEST_F(RdbGeneralStoreTest, SqlConcatenate, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Insert001, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); DistributedData::VBuckets values; EXPECT_EQ(values.size(), 0); std::string table = "table"; @@ -360,8 +350,6 @@ HWTEST_F(RdbGeneralStoreTest, Insert001, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Insert002, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; DistributedData::VBuckets extends = { { g_RdbVBucket } }; auto result = store->Insert(table, std::move(extends)); @@ -391,8 +379,6 @@ HWTEST_F(RdbGeneralStoreTest, Insert002, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Update, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; std::string setSql = "setSql"; RdbGeneralStore::Values values; @@ -431,8 +417,6 @@ HWTEST_F(RdbGeneralStoreTest, Update, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Replace, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; RdbGeneralStore::VBucket values; auto result = store->Replace("", std::move(g_RdbVBucket)); @@ -459,8 +443,6 @@ HWTEST_F(RdbGeneralStoreTest, Replace, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Delete, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; auto result = store->Delete(table, sql, std::move(g_RdbValues)); @@ -474,8 +456,6 @@ HWTEST_F(RdbGeneralStoreTest, Delete, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Query001, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; auto [err1, result1] = store->Query(table, sql, std::move(g_RdbValues)); @@ -495,8 +475,6 @@ HWTEST_F(RdbGeneralStoreTest, Query001, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Query002, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; MockQuery query; @@ -518,7 +496,7 @@ HWTEST_F(RdbGeneralStoreTest, Query002, TestSize.Level1) HWTEST_F(RdbGeneralStoreTest, Query003, TestSize.Level1) { metaData_.storeId = "mock"; - auto store = std::make_shared(metaData_); + store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockQuery query; @@ -538,9 +516,6 @@ HWTEST_F(RdbGeneralStoreTest, Query003, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Query004, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); - MockQuery query; const std::string devices = "device1"; const std::string sql; @@ -565,8 +540,6 @@ HWTEST_F(RdbGeneralStoreTest, Query004, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, MergeMigratedData, TestSize.Level1) { - auto store = std::make_shared(metaData_); - ASSERT_NE(store, nullptr); std::string tableName = "tableName"; DistributedData::VBuckets extends = { { g_RdbVBucket } }; auto result = store->MergeMigratedData(tableName, std::move(extends)); @@ -585,7 +558,6 @@ HWTEST_F(RdbGeneralStoreTest, MergeMigratedData, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Sync, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); GeneralStore::Devices devices; MockQuery query; @@ -607,7 +579,6 @@ HWTEST_F(RdbGeneralStoreTest, Sync, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Sync001, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); GeneralStore::Devices devices; MockQuery query; @@ -635,16 +606,13 @@ HWTEST_F(RdbGeneralStoreTest, Sync001, TestSize.Level1) HWTEST_F(RdbGeneralStoreTest, Sync002, TestSize.Level1) { metaData_.storeId = "mock"; - auto store = std::make_shared(metaData_); + store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); + GeneralStore::Devices devices; RdbQuery query; GeneralStore::DetailAsync async; SyncParam syncParam; - MockRelationalStoreDelegate mockDelegate; - mockDelegate.CreateDistributedTable("naturalbase_rdb_test"); - mockDelegate.CreateDistributedTable("naturalbase_rdb_name"); - store->delegate_ = &mockDelegate; auto [result1, result2] = store->Sync(devices, query, async, syncParam); EXPECT_EQ(result1, GeneralError::E_OK); } @@ -656,7 +624,6 @@ HWTEST_F(RdbGeneralStoreTest, Sync002, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, PreSharing, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockQuery query; auto [errCode, result] = store->PreSharing(query); @@ -671,7 +638,6 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, PreSharing001, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockQuery query; query.lastResult = true; @@ -687,7 +653,6 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing001, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, PreSharing002, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockQuery query; DistributedRdb::PredicatesMemo predicates; @@ -708,7 +673,7 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing002, TestSize.Level1) HWTEST_F(RdbGeneralStoreTest, PreSharing003, TestSize.Level1) { metaData_.storeId = "mock"; - auto store = std::make_shared(metaData_); + store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockQuery query; DistributedRdb::PredicatesMemo predicates; @@ -728,7 +693,6 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing003, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, ExtractExtend, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); RdbGeneralStore::VBucket extend = { { "#gid", { "0000000" } }, { "#flag", { true } }, { "#value", { int64_t(100) } }, { "#float", { double(100) } }, { "#cloud_gid", { "cloud_gid" } }, @@ -748,7 +712,6 @@ HWTEST_F(RdbGeneralStoreTest, ExtractExtend, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string tableName = "tableName"; std::vector devices = { "device1", "device2" }; @@ -787,7 +750,6 @@ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Watch, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockGeneralWatcher watcher; auto result = store->Watch(GeneralWatcher::Origin::ORIGIN_CLOUD, watcher); @@ -813,7 +775,6 @@ HWTEST_F(RdbGeneralStoreTest, Watch, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, OnChange, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockGeneralWatcher watcher; MockStoreChangedData data; @@ -835,7 +796,6 @@ HWTEST_F(RdbGeneralStoreTest, OnChange, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, OnChange001, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); MockGeneralWatcher watcher; MockStoreChangedData data; @@ -868,7 +828,7 @@ HWTEST_F(RdbGeneralStoreTest, OnChange001, TestSize.Level1) store->observer_.OnChange(DistributedDB::Origin::ORIGIN_CLOUD, "originalId", std::move(changedData)); EXPECT_EQ(watcher.primaryFields_[changedDataTmp.tableName], *(changedDataTmp.field.begin())); store->observer_.OnChange(DistributedDB::Origin::ORIGIN_LOCAL, "originalId", std::move(changedDataTmp)); - EXPECT_NE(watcher.origin_.id.size(), 0); + ASSERT_NE(watcher.origin_.id.size(), 0); EXPECT_EQ(watcher.origin_.id[0], "originalId"); result = store->Unwatch(GeneralWatcher::Origin::ORIGIN_ALL, watcher); EXPECT_EQ(result, GeneralError::E_OK); @@ -907,7 +867,6 @@ HWTEST_F(RdbGeneralStoreTest, Release, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); ASSERT_NE(store, nullptr); std::vector tables = { "table1", "table2" }; int32_t type = 0; @@ -915,8 +874,8 @@ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) auto result = store->SetDistributedTables(tables, type, references); EXPECT_EQ(result, GeneralError::E_ALREADY_CLOSED); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->SetDistributedTables(tables, type, references); EXPECT_EQ(result, GeneralError::E_OK); @@ -935,7 +894,6 @@ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, SetTrackerTable, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); ASSERT_NE(store, nullptr); std::string tableName = "tableName"; std::set trackerColNames = { "col1", "col2" }; @@ -943,8 +901,8 @@ HWTEST_F(RdbGeneralStoreTest, SetTrackerTable, TestSize.Level1) auto result = store->SetTrackerTable(tableName, trackerColNames, extendColNames); EXPECT_EQ(result, GeneralError::E_ALREADY_CLOSED); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->SetTrackerTable(tableName, trackerColNames, extendColNames); EXPECT_EQ(result, GeneralError::E_OK); result = store->SetTrackerTable("WITH_INVENTORY_DATA", trackerColNames, extendColNames); @@ -960,7 +918,6 @@ HWTEST_F(RdbGeneralStoreTest, SetTrackerTable, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, RemoteQuery, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string device = "device"; DistributedDB::RemoteCondition remoteCondition; @@ -979,7 +936,6 @@ HWTEST_F(RdbGeneralStoreTest, RemoteQuery, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, ConvertStatus, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); auto result = store->ConvertStatus(DBStatus::OK); EXPECT_EQ(result, GeneralError::E_OK); @@ -1009,7 +965,7 @@ HWTEST_F(RdbGeneralStoreTest, ConvertStatus, TestSize.Level1) HWTEST_F(RdbGeneralStoreTest, QuerySql, TestSize.Level1) { metaData_.storeId = "mock"; - auto store = std::make_shared(metaData_); + store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); auto [err1, result1] = store->QuerySql("", std::move(g_RdbValues)); EXPECT_EQ(err1, GeneralError::E_ERROR); @@ -1027,7 +983,6 @@ HWTEST_F(RdbGeneralStoreTest, QuerySql, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenCloumnEmpty, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string table = "mock_table"; std::string statement = "mock_statement"; @@ -1045,7 +1000,6 @@ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenCloumnEmpty, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenParamValid, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); std::string table = "mock_table"; std::string statement = "mock_statement"; @@ -1066,7 +1020,6 @@ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenParamValid, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, LockAndUnLockCloudDBTest, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); auto result = store->LockCloudDB(); EXPECT_EQ(result.first, 1); @@ -1082,7 +1035,6 @@ HWTEST_F(RdbGeneralStoreTest, LockAndUnLockCloudDBTest, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, InFinishedTest, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; bool isFinished = store->IsFinished(syncId); @@ -1096,7 +1048,6 @@ HWTEST_F(RdbGeneralStoreTest, InFinishedTest, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, GetRdbCloudTest, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); auto rdbCloud = store->GetRdbCloud(); EXPECT_EQ(rdbCloud, nullptr); @@ -1109,7 +1060,6 @@ HWTEST_F(RdbGeneralStoreTest, GetRdbCloudTest, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, RegisterDetailProgressObserverTest, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedData::GeneralStore::DetailAsync async; auto result = store->RegisterDetailProgressObserver(async); @@ -1123,7 +1073,6 @@ HWTEST_F(RdbGeneralStoreTest, RegisterDetailProgressObserverTest, TestSize.Level */ HWTEST_F(RdbGeneralStoreTest, GetFinishTaskTest, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; auto result = store->GetFinishTask(syncId); @@ -1137,7 +1086,6 @@ HWTEST_F(RdbGeneralStoreTest, GetFinishTaskTest, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, GetCBTest, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; auto result = store->GetCB(syncId); @@ -1151,7 +1099,6 @@ HWTEST_F(RdbGeneralStoreTest, GetCBTest, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, UpdateDBStatus, TestSize.Level1) { - auto store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); auto result = store->UpdateDBStatus(); EXPECT_EQ(result, E_ALREADY_CLOSED); -- Gitee From 856d5f7197d42b4399d4197c1197fb0fd785fa80 Mon Sep 17 00:00:00 2001 From: guochao Date: Fri, 18 Apr 2025 18:54:52 +0800 Subject: [PATCH 172/225] fix Signed-off-by: guochao --- .../service/test/mock/relational_store_manager_mock.cpp | 4 ++++ .../service/test/rdb_general_store_test.cpp | 4 ---- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp index c17943733..fa61b0cc4 100644 --- a/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp +++ b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp @@ -22,6 +22,9 @@ DBStatus RelationalStoreManager::OpenStore(const std::string &path, const std::s const RelationalStoreDelegate::Option &option, RelationalStoreDelegate *&delegate) { delegate = new (std::nothrow) MockRelationalStoreDelegate(); + if (delegate == nullptr) { + return DB_ERROR; + } delegate->CreateDistributedTable("naturalbase_rdb_test"); delegate->CreateDistributedTable("naturalbase_rdb_name"); if (storeId == "mock") { @@ -32,6 +35,7 @@ DBStatus RelationalStoreManager::OpenStore(const std::string &path, const std::s DBStatus RelationalStoreManager::CloseStore(RelationalStoreDelegate *store) { + delete store; store = nullptr; return OK; } diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index 1f126533a..a350c7d36 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -70,10 +70,6 @@ public: void TearDown() { MockRelationalStoreDelegate::gTestResult = false; - if (store->delegate_ != nullptr) { - delete store->delegate_; - store->delegate_ = nullptr; - } }; protected: -- Gitee From 7fbc61a448575f8a684861ce2fb162950413eae1 Mon Sep 17 00:00:00 2001 From: guochao Date: Fri, 18 Apr 2025 19:38:25 +0800 Subject: [PATCH 173/225] fix Signed-off-by: guochao --- .../service/test/rdb_general_store_test.cpp | 23 ------------------- 1 file changed, 23 deletions(-) diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index a350c7d36..c6f60f81f 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -554,7 +554,6 @@ HWTEST_F(RdbGeneralStoreTest, MergeMigratedData, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Sync, TestSize.Level1) { - ASSERT_NE(store, nullptr); GeneralStore::Devices devices; MockQuery query; GeneralStore::DetailAsync async; @@ -575,7 +574,6 @@ HWTEST_F(RdbGeneralStoreTest, Sync, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Sync001, TestSize.Level1) { - ASSERT_NE(store, nullptr); GeneralStore::Devices devices; MockQuery query; GeneralStore::DetailAsync async; @@ -620,7 +618,6 @@ HWTEST_F(RdbGeneralStoreTest, Sync002, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, PreSharing, TestSize.Level1) { - ASSERT_NE(store, nullptr); MockQuery query; auto [errCode, result] = store->PreSharing(query); EXPECT_NE(errCode, GeneralError::E_OK); @@ -634,7 +631,6 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, PreSharing001, TestSize.Level1) { - ASSERT_NE(store, nullptr); MockQuery query; query.lastResult = true; auto [errCode, result] = store->PreSharing(query); @@ -649,7 +645,6 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing001, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, PreSharing002, TestSize.Level1) { - ASSERT_NE(store, nullptr); MockQuery query; DistributedRdb::PredicatesMemo predicates; predicates.devices_ = { "device1" }; @@ -689,7 +684,6 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing003, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, ExtractExtend, TestSize.Level1) { - ASSERT_NE(store, nullptr); RdbGeneralStore::VBucket extend = { { "#gid", { "0000000" } }, { "#flag", { true } }, { "#value", { int64_t(100) } }, { "#float", { double(100) } }, { "#cloud_gid", { "cloud_gid" } }, { "cloud_gid", { "" } } }; @@ -708,7 +702,6 @@ HWTEST_F(RdbGeneralStoreTest, ExtractExtend, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) { - ASSERT_NE(store, nullptr); std::string tableName = "tableName"; std::vector devices = { "device1", "device2" }; auto result = store->Clean(devices, -1, tableName); @@ -746,7 +739,6 @@ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Watch, TestSize.Level1) { - ASSERT_NE(store, nullptr); MockGeneralWatcher watcher; auto result = store->Watch(GeneralWatcher::Origin::ORIGIN_CLOUD, watcher); EXPECT_EQ(result, GeneralError::E_INVALID_ARGS); @@ -771,7 +763,6 @@ HWTEST_F(RdbGeneralStoreTest, Watch, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, OnChange, TestSize.Level1) { - ASSERT_NE(store, nullptr); MockGeneralWatcher watcher; MockStoreChangedData data; DistributedDB::ChangedData changedData; @@ -792,7 +783,6 @@ HWTEST_F(RdbGeneralStoreTest, OnChange, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, OnChange001, TestSize.Level1) { - ASSERT_NE(store, nullptr); MockGeneralWatcher watcher; MockStoreChangedData data; DistributedDB::ChangedData changedData; @@ -863,7 +853,6 @@ HWTEST_F(RdbGeneralStoreTest, Release, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) { - ASSERT_NE(store, nullptr); std::vector tables = { "table1", "table2" }; int32_t type = 0; std::vector references; @@ -890,7 +879,6 @@ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, SetTrackerTable, TestSize.Level1) { - ASSERT_NE(store, nullptr); std::string tableName = "tableName"; std::set trackerColNames = { "col1", "col2" }; std::set extendColNames = { "extendColName1", "extendColName2" }; @@ -914,7 +902,6 @@ HWTEST_F(RdbGeneralStoreTest, SetTrackerTable, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, RemoteQuery, TestSize.Level1) { - ASSERT_NE(store, nullptr); std::string device = "device"; DistributedDB::RemoteCondition remoteCondition; metaData_.storeId = "mock"; @@ -932,7 +919,6 @@ HWTEST_F(RdbGeneralStoreTest, RemoteQuery, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, ConvertStatus, TestSize.Level1) { - ASSERT_NE(store, nullptr); auto result = store->ConvertStatus(DBStatus::OK); EXPECT_EQ(result, GeneralError::E_OK); result = store->ConvertStatus(DBStatus::CLOUD_NETWORK_ERROR); @@ -979,7 +965,6 @@ HWTEST_F(RdbGeneralStoreTest, QuerySql, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenCloumnEmpty, TestSize.Level1) { - ASSERT_NE(store, nullptr); std::string table = "mock_table"; std::string statement = "mock_statement"; std::vector columns; @@ -996,7 +981,6 @@ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenCloumnEmpty, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenParamValid, TestSize.Level1) { - ASSERT_NE(store, nullptr); std::string table = "mock_table"; std::string statement = "mock_statement"; std::vector columns; @@ -1016,7 +1000,6 @@ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenParamValid, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, LockAndUnLockCloudDBTest, TestSize.Level1) { - ASSERT_NE(store, nullptr); auto result = store->LockCloudDB(); EXPECT_EQ(result.first, 1); EXPECT_EQ(result.second, 0); @@ -1031,7 +1014,6 @@ HWTEST_F(RdbGeneralStoreTest, LockAndUnLockCloudDBTest, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, InFinishedTest, TestSize.Level1) { - ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; bool isFinished = store->IsFinished(syncId); EXPECT_TRUE(isFinished); @@ -1044,7 +1026,6 @@ HWTEST_F(RdbGeneralStoreTest, InFinishedTest, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, GetRdbCloudTest, TestSize.Level1) { - ASSERT_NE(store, nullptr); auto rdbCloud = store->GetRdbCloud(); EXPECT_EQ(rdbCloud, nullptr); } @@ -1056,7 +1037,6 @@ HWTEST_F(RdbGeneralStoreTest, GetRdbCloudTest, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, RegisterDetailProgressObserverTest, TestSize.Level1) { - ASSERT_NE(store, nullptr); DistributedData::GeneralStore::DetailAsync async; auto result = store->RegisterDetailProgressObserver(async); EXPECT_EQ(result, GeneralError::E_OK); @@ -1069,7 +1049,6 @@ HWTEST_F(RdbGeneralStoreTest, RegisterDetailProgressObserverTest, TestSize.Level */ HWTEST_F(RdbGeneralStoreTest, GetFinishTaskTest, TestSize.Level1) { - ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; auto result = store->GetFinishTask(syncId); ASSERT_NE(result, nullptr); @@ -1082,7 +1061,6 @@ HWTEST_F(RdbGeneralStoreTest, GetFinishTaskTest, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, GetCBTest, TestSize.Level1) { - ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; auto result = store->GetCB(syncId); ASSERT_NE(result, nullptr); @@ -1095,7 +1073,6 @@ HWTEST_F(RdbGeneralStoreTest, GetCBTest, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, UpdateDBStatus, TestSize.Level1) { - ASSERT_NE(store, nullptr); auto result = store->UpdateDBStatus(); EXPECT_EQ(result, E_ALREADY_CLOSED); metaData_.storeId = "mock"; -- Gitee From 1de703e4b9f2c5a733bdb2ff0348444b7482fd0d Mon Sep 17 00:00:00 2001 From: Cuiziyuan Date: Tue, 15 Apr 2025 17:14:47 +0800 Subject: [PATCH 174/225] format uri Signed-off-by: Cuiziyuan --- .../data_proxy/load_config_from_data_proxy_node_strategy.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp index e3e01974b..5e39aa56b 100644 --- a/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp @@ -40,10 +40,12 @@ bool LoadConfigFromDataProxyNodeStrategy::operator()(std::shared_ptr co context->permission = "reject"; return true; } + std::string uri = context->uri; + URIUtils::FormatUri(uri); for (auto const &hapModuleInfo : context->bundleInfo.hapModuleInfos) { auto proxyDatas = hapModuleInfo.proxyDatas; for (auto const &proxyData : proxyDatas) { - if (proxyData.uri != context->uri) { + if (proxyData.uri != uri) { continue; } context->permission = context->isRead ? proxyData.requiredReadPermission -- Gitee From 6dde52e8391c8add7d14a7fba70a6173af91a103 Mon Sep 17 00:00:00 2001 From: Cuiziyuan Date: Thu, 17 Apr 2025 16:46:48 +0800 Subject: [PATCH 175/225] =?UTF-8?q?=E5=8D=A1=E7=89=87=E8=8B=A5=E6=97=A0?= =?UTF-8?q?=E5=AE=9A=E6=97=B6=E5=99=A8=EF=BC=8C=E9=87=8D=E6=96=B0=E5=8F=AF?= =?UTF-8?q?=E8=A7=81=E6=97=B6=E4=B8=8D=E5=88=A4=E6=96=AD=E5=AE=9A=E6=97=B6?= =?UTF-8?q?=E5=99=A8=E6=98=AF=E5=90=A6=E6=9B=BE=E8=A2=AB=E5=81=9C=E6=AD=A2?= =?UTF-8?q?=E8=BF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Cuiziyuan --- .../service/data_share/common/scheduler_manager.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp b/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp index 79ca80155..ba1015c36 100644 --- a/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp +++ b/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp @@ -87,6 +87,13 @@ void SchedulerManager::Stop(const Key &key) void SchedulerManager::Enable(const Key &key, int32_t userId, const DistributedData::StoreMetaData &metaData) { + Template tpl; + if (!TemplateManager::GetInstance().Get(key, userId, tpl) || + tpl.scheduler_.empty() || tpl.scheduler_.find(REMIND_TIMER_FUNC) == std::string::npos) { + ZLOGE("find template scheduler failed, %{public}s, %{public}" PRId64 ", %{public}s", + DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str()); + return; + } bool isTimerStopped = false; { std::lock_guard lock(mutex_); -- Gitee From 721fcefa6506acfbc2c496708bd0a80bbd21aa6d Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Sat, 19 Apr 2025 17:14:02 +0800 Subject: [PATCH 176/225] fix clear bug Signed-off-by: wanghuajian-6 --- services/distributeddataservice/service/test/BUILD.gn | 4 ++++ .../service/test/object_manager_test.cpp | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 9c0b1d91a..9b1b757b3 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -828,6 +828,7 @@ ohos_unittest("ObjectDmsHandlerTest") { ohos_unittest("ObjectManagerTest") { 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", @@ -849,6 +850,7 @@ ohos_unittest("ObjectManagerTest") { include_dirs = [ "${dataobject_path}/frameworks/innerkitsimpl/include", + "${data_service_path}/app/src", "${data_service_path}/service/common", "${dataobject_path}/frameworks/innerkitsimpl/include/common", "${dataobject_path}/interfaces/innerkits", @@ -864,6 +866,7 @@ ohos_unittest("ObjectManagerTest") { "access_token:libtokenid_sdk", "c_utils:utils", "data_object:distributeddataobject_impl", + "dataclassification:data_transit_mgr", "dfs_service:cloudsync_asset_kit_inner", "dfs_service:distributed_file_daemon_kit_inner", "dmsfwk:distributed_sdk", @@ -874,6 +877,7 @@ ohos_unittest("ObjectManagerTest") { "ipc:ipc_core", "json:nlohmann_json_static", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "kv_store:distributeddb", "relational_store:native_rdb", ] diff --git a/services/distributeddataservice/service/test/object_manager_test.cpp b/services/distributeddataservice/service/test/object_manager_test.cpp index b795e592a..9d5abb512 100644 --- a/services/distributeddataservice/service/test/object_manager_test.cpp +++ b/services/distributeddataservice/service/test/object_manager_test.cpp @@ -20,14 +20,17 @@ #include #include +#include "bootstrap.h" #include "device_manager_adapter_mock.h" #include "executor_pool.h" +#include "kvstore_meta_manager.h" #include "kv_store_nb_delegate_mock.h" #include "object_types.h" #include "snapshot/machine_status.h" using namespace testing::ext; using namespace OHOS::DistributedObject; +using namespace OHOS::DistributedData; using namespace std; using namespace testing; using AssetValue = OHOS::CommonType::AssetValue; @@ -1094,6 +1097,13 @@ HWTEST_F(ObjectManagerTest, GetObjectData002, TestSize.Level1) */ HWTEST_F(ObjectManagerTest, ClearOldUserMeta001, TestSize.Level1) { + std::shared_ptr executors = std::make_shared(1, 0); + Bootstrap::GetInstance().LoadDirectory(); + Bootstrap::GetInstance().LoadCheckers(); + DistributedKv::KvStoreMetaManager::GetInstance().BindExecutor(executors); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaParameter(); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaListener(); + auto manager = ObjectStoreManager::GetInstance(); auto status = manager->CleanOldUserMeta(); ASSERT_EQ(status, DistributedObject::OBJECT_SUCCESS); -- Gitee From c53266dd12f462415fc41eaa8f28261b38265038 Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Sat, 19 Apr 2025 19:27:03 +0800 Subject: [PATCH 177/225] fix clear bug Signed-off-by: wanghuajian-6 --- .../distributeddataservice/service/test/object_manager_test.cpp | 2 +- .../service/test/object_service_impl_test.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/test/object_manager_test.cpp b/services/distributeddataservice/service/test/object_manager_test.cpp index 9d5abb512..e9001c69e 100644 --- a/services/distributeddataservice/service/test/object_manager_test.cpp +++ b/services/distributeddataservice/service/test/object_manager_test.cpp @@ -187,7 +187,7 @@ HWTEST_F(ObjectManagerTest, Clear001, TestSize.Level0) { auto manager = ObjectStoreManager::GetInstance(); auto result = manager->Clear(); - ASSERT_EQ(result, OHOS::DistributedObject::OBJECT_STORE_NOT_FOUND); + ASSERT_EQ(result, OHOS::DistributedObject::OBJECT_SUCCESS); } /** diff --git a/services/distributeddataservice/service/test/object_service_impl_test.cpp b/services/distributeddataservice/service/test/object_service_impl_test.cpp index e67f493ab..4a0a0b2f3 100644 --- a/services/distributeddataservice/service/test/object_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/object_service_impl_test.cpp @@ -149,6 +149,6 @@ HWTEST_F(ObjectServiceImplTest, ResolveAutoLaunch001, TestSize.Level1) std::string identifier = "identifier"; std::shared_ptr objectServiceImpl = std::make_shared(); int32_t ret = objectServiceImpl->ResolveAutoLaunch(identifier, param); - EXPECT_EQ(ret, OBJECT_STORE_NOT_FOUND); + EXPECT_EQ(ret, OBJECT_SUCCESS); } } \ No newline at end of file -- Gitee From 926c0bf092d08e5de639a0cee931fb830887ce1b Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Sat, 19 Apr 2025 20:27:43 +0800 Subject: [PATCH 178/225] fix clear bug Signed-off-by: wanghuajian-6 --- .../service/object/include/object_manager.h | 2 +- .../service/object/src/object_manager.cpp | 22 ++++++++++++++----- .../object/src/object_service_impl.cpp | 2 +- .../service/test/object_manager_test.cpp | 19 ++++++++-------- 4 files changed, 28 insertions(+), 17 deletions(-) diff --git a/services/distributeddataservice/service/object/include/object_manager.h b/services/distributeddataservice/service/object/include/object_manager.h index 6ce04d901..158b5c50a 100644 --- a/services/distributeddataservice/service/object/include/object_manager.h +++ b/services/distributeddataservice/service/object/include/object_manager.h @@ -89,7 +89,7 @@ public: sptr callback, uint32_t tokenId); void SetData(const std::string &dataDir, const std::string &userId); int32_t Clear(); - int32_t CleanOldUserMeta(); + int32_t InitUserMeta(); int32_t DeleteByAppId(const std::string &appId, int32_t user); void RegisterRemoteCallback(const std::string &bundleName, const std::string &sessionId, pid_t pid, uint32_t tokenId, diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index e121bb10e..176ed3786 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -294,7 +294,11 @@ int32_t ObjectStoreManager::Clear() ZLOGI("enter"); DistributedData::ObjectUserMetaData userMeta; if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(userMeta.GetKey(), userMeta, true)) { - ZLOGI("no object user meta. don't need clear"); + ZLOGE("load meta error"); + return OBJECT_INNER_ERROR; + } + if (userMeta.userId.empty()) { + ZLOGI("no object user meta, don't need clean"); return OBJECT_SUCCESS; } std::string userId = GetCurrentUser(); @@ -317,17 +321,25 @@ int32_t ObjectStoreManager::Clear() return result; } -int32_t ObjectStoreManager::CleanOldUserMeta() +int32_t ObjectStoreManager::InitUserMeta() { + ObjectUserMetaData userMeta; + if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(userMeta.GetKey(), userMeta, true)) { + ZLOGE("load meta error"); + return OBJECT_INNER_ERROR; + } + if (!userMeta.userId.empty()) { + ZLOGI("userId has been set, don't need clean"); + return OBJECT_SUCCESS; + } std::string userId = GetCurrentUser(); if (userId.empty()) { ZLOGI("get userId error"); return OBJECT_INNER_ERROR; } - ObjectUserMetaData userMetaData; - userMetaData.userId = userId; + userMeta.userId = userId; if (!DistributedData::MetaDataManager::GetInstance().SaveMeta(DistributedData::ObjectUserMetaData::GetKey(), - userMetaData, true)) { + userMeta, true)) { ZLOGE("save meta error, userId:%{public}s", userId.c_str()); return OBJECT_INNER_ERROR; } diff --git a/services/distributeddataservice/service/object/src/object_service_impl.cpp b/services/distributeddataservice/service/object/src/object_service_impl.cpp index a207bf00f..71f6195e7 100644 --- a/services/distributeddataservice/service/object/src/object_service_impl.cpp +++ b/services/distributeddataservice/service/object/src/object_service_impl.cpp @@ -139,7 +139,7 @@ int32_t ObjectServiceImpl::OnInitialize() StoreMetaData saveMeta; SaveMetaData(saveMeta, std::to_string(userId), accountId); ObjectStoreManager::GetInstance()->SetData(saveMeta.dataDir, std::to_string(userId)); - ObjectStoreManager::GetInstance()->CleanOldUserMeta(); + ObjectStoreManager::GetInstance()->InitUserMeta(); RegisterObjectServiceInfo(); RegisterHandler(); ObjectDmsHandler::GetInstance().RegisterDmsEvent(); diff --git a/services/distributeddataservice/service/test/object_manager_test.cpp b/services/distributeddataservice/service/test/object_manager_test.cpp index e9001c69e..4250b4c64 100644 --- a/services/distributeddataservice/service/test/object_manager_test.cpp +++ b/services/distributeddataservice/service/test/object_manager_test.cpp @@ -104,6 +104,12 @@ void ObjectManagerTest::SetUpTestCase(void) { devMgrAdapterMock = make_shared(); BDeviceManagerAdapter::deviceManagerAdapter = devMgrAdapterMock; + std::shared_ptr executors = std::make_shared(1, 0); + Bootstrap::GetInstance().LoadDirectory(); + Bootstrap::GetInstance().LoadCheckers(); + DistributedKv::KvStoreMetaManager::GetInstance().BindExecutor(executors); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaParameter(); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaListener(); } void ObjectManagerTest::TearDownTestCase(void) @@ -1091,21 +1097,14 @@ HWTEST_F(ObjectManagerTest, GetObjectData002, TestSize.Level1) } /** -* @tc.name: ClearOldUserMeta001 +* @tc.name: InitUserMeta001 * @tc.desc: test clear old user meta. * @tc.type: FUNC */ -HWTEST_F(ObjectManagerTest, ClearOldUserMeta001, TestSize.Level1) +HWTEST_F(ObjectManagerTest, InitUserMeta001, TestSize.Level1) { - std::shared_ptr executors = std::make_shared(1, 0); - Bootstrap::GetInstance().LoadDirectory(); - Bootstrap::GetInstance().LoadCheckers(); - DistributedKv::KvStoreMetaManager::GetInstance().BindExecutor(executors); - DistributedKv::KvStoreMetaManager::GetInstance().InitMetaParameter(); - DistributedKv::KvStoreMetaManager::GetInstance().InitMetaListener(); - auto manager = ObjectStoreManager::GetInstance(); - auto status = manager->CleanOldUserMeta(); + auto status = manager->InitUserMeta(); ASSERT_EQ(status, DistributedObject::OBJECT_SUCCESS); } } // namespace OHOS::Test -- Gitee From 592857f5dcefd2e923204994768e0f66ff707800 Mon Sep 17 00:00:00 2001 From: wanghuajian-6 Date: Mon, 21 Apr 2025 11:49:01 +0800 Subject: [PATCH 179/225] fix clear bug Signed-off-by: wanghuajian-6 --- .../service/object/src/object_manager.cpp | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 176ed3786..51635cf04 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -324,11 +324,7 @@ int32_t ObjectStoreManager::Clear() int32_t ObjectStoreManager::InitUserMeta() { ObjectUserMetaData userMeta; - if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(userMeta.GetKey(), userMeta, true)) { - ZLOGE("load meta error"); - return OBJECT_INNER_ERROR; - } - if (!userMeta.userId.empty()) { + if (DistributedData::MetaDataManager::GetInstance().LoadMeta(userMeta.GetKey(), userMeta, true)) { ZLOGI("userId has been set, don't need clean"); return OBJECT_SUCCESS; } @@ -338,17 +334,17 @@ int32_t ObjectStoreManager::InitUserMeta() return OBJECT_INNER_ERROR; } userMeta.userId = userId; - if (!DistributedData::MetaDataManager::GetInstance().SaveMeta(DistributedData::ObjectUserMetaData::GetKey(), - userMeta, true)) { - ZLOGE("save meta error, userId:%{public}s", userId.c_str()); - return OBJECT_INNER_ERROR; - } std::string appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); std::string metaKey = GetMetaUserIdKey(userId, appId); if (!DistributedData::MetaDataManager::GetInstance().DelMeta(metaKey, true)) { ZLOGE("delete old meta error, userId:%{public}s", userId.c_str()); return OBJECT_INNER_ERROR; } + if (!DistributedData::MetaDataManager::GetInstance().SaveMeta(DistributedData::ObjectUserMetaData::GetKey(), + userMeta, true)) { + ZLOGE("save meta error, userId:%{public}s", userId.c_str()); + return OBJECT_INNER_ERROR; + } return OBJECT_SUCCESS; } -- Gitee From e10097db6f54763012c0b134d32657c951b559d2 Mon Sep 17 00:00:00 2001 From: xuwenqi Date: Sat, 29 Mar 2025 18:17:00 +0800 Subject: [PATCH 180/225] add testcase Signed-off-by: xuwenqi Change-Id: I1a6f787f1b6a573d7d90fbe7a9e355011a2c8a4c --- .../service/test/data_share_common_test.cpp | 475 ++++++++++++++++++ .../service/test/kv_dalegate_test.cpp | 288 +++++++++++ 2 files changed, 763 insertions(+) diff --git a/services/distributeddataservice/service/test/data_share_common_test.cpp b/services/distributeddataservice/service/test/data_share_common_test.cpp index ad14f7d37..9f9f92555 100644 --- a/services/distributeddataservice/service/test/data_share_common_test.cpp +++ b/services/distributeddataservice/service/test/data_share_common_test.cpp @@ -16,9 +16,14 @@ #include #include +#include "extension_connect_adaptor.h" #include "data_share_profile_config.h" #include "div_strategy.h" #include "log_print.h" +#include "rdb_delegate.h" +#include "rdb_subscriber_manager.h" +#include "scheduler_manager.h" +#include "seq_strategy.h" #include "strategy.h" namespace OHOS::Test { @@ -89,4 +94,474 @@ HWTEST_F(DataShareCommonTest, DivStrategy003, TestSize.Level1) EXPECT_EQ(result, false); ZLOGI("DataShareCommonTest DivStrategy003 end"); } + +/** +* @tc.name: SeqStrategyInit001 +* @tc.desc: test SeqStrategyInit function when item is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a seqStrategy object and strategy2 = nullptr + 2.call Init function +* @tc.experct: Init failed and return false +*/ +HWTEST_F(DataShareCommonTest, SeqStrategyInit001, TestSize.Level1) +{ + ZLOGI("SeqStrategyInit001 start"); + Strategy* strategy1 = new Strategy(); + Strategy* strategy2 = nullptr; + SeqStrategy seqStrategy; + bool result = seqStrategy.Init({strategy1, strategy2}); + EXPECT_FALSE(result); + delete strategy1; + ZLOGI("SeqStrategyInit001 end"); +} + +/** +* @tc.name: DoConnect001 +* @tc.desc: test DoConnect function when callback_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a ExtensionConnectAdaptor object and callback = nullptr + 2.call DoConnect function +* @tc.experct: DoConnect failed and return false +*/ +HWTEST_F(DataShareCommonTest, DoConnect001, TestSize.Level1) +{ + ZLOGI("DoConnect001 start"); + std::string uri = "testUri"; + std::string bundleName = "testBundle"; + AAFwk::WantParams wantParams; + ExtensionConnectAdaptor extensionConnectAdaptor; + bool result = extensionConnectAdaptor.DoConnect(uri, bundleName, wantParams); + EXPECT_FALSE(result); + ZLOGI("DoConnect001 end"); +} + +/** +* @tc.name: InsertEx001 +* @tc.desc: test InsertEx function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a rdbDelegate object and store_ = nullptr + 2.call InsertEx function +* @tc.experct: InsertEx failed and return E_DB_ERROR +*/ +HWTEST_F(DataShareCommonTest, InsertEx001, TestSize.Level1) +{ + ZLOGI("InsertEx001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string tableName = ""; + DataShare::DataShareValuesBucket valuesBucket; + std::string name0 = ""; + valuesBucket.Put("", name0); + auto result = rdbDelegate.InsertEx(tableName, valuesBucket); + EXPECT_EQ(result.first, E_DB_ERROR); + ZLOGI("InsertEx001 end"); +} + +/** +* @tc.name: UpdateEx001 +* @tc.desc: test UpdateEx function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call UpdateEx function +* @tc.experct: UpdateEx failed and return E_DB_ERROR +*/ +HWTEST_F(DataShareCommonTest, UpdateEx001, TestSize.Level1) +{ + ZLOGI("UpdateEx001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string tableName = ""; + DataShare::DataShareValuesBucket valuesBucket; + std::string name0 = ""; + valuesBucket.Put("", name0); + DataSharePredicates predicate; + auto result = rdbDelegate.UpdateEx(tableName, predicate, valuesBucket); + EXPECT_EQ(result.first, E_DB_ERROR); + ZLOGI("UpdateEx001 end"); +} + +/** +* @tc.name: DeleteEx001 +* @tc.desc: test DeleteEx function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call DeleteEx function +* @tc.experct: DeleteEx failed and return E_DB_ERROR +*/ +HWTEST_F(DataShareCommonTest, DeleteEx001, TestSize.Level1) +{ + ZLOGI("DeleteEx001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string tableName = ""; + DataSharePredicates predicate; + auto result = rdbDelegate.DeleteEx(tableName, predicate); + EXPECT_EQ(result.first, E_DB_ERROR); + ZLOGI("DeleteEx001 end"); +} + +/** +* @tc.name: Query001 +* @tc.desc: test Query function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call Query function +* @tc.experct: Query failed and return errCode +*/ +HWTEST_F(DataShareCommonTest, Query001, TestSize.Level1) +{ + ZLOGI("Query001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string tableName = ""; + DataSharePredicates predicate; + std::vector columns; + int32_t callingPid = 1; + uint32_t callingTokenId = 1; + auto result = rdbDelegate.Query(tableName, predicate, columns, callingPid, callingTokenId); + EXPECT_EQ(result.first, rdbDelegate.errCode_); + ZLOGI("Query001 end"); +} + +/** +* @tc.name: Query002 +* @tc.desc: test Query function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call Query function +* @tc.experct: Query failed and return "" +*/ +HWTEST_F(DataShareCommonTest, Query002, TestSize.Level1) +{ + ZLOGI("Query002 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string sql = "testsql"; + std::vector selectionArgs; + auto result = rdbDelegate.Query(sql, selectionArgs); + EXPECT_EQ(result, ""); + ZLOGI("Query002 end"); +} + +/** +* @tc.name: QuerySql001 +* @tc.desc: test QuerySql function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call QuerySql function +* @tc.experct: QuerySql failed and return nullptr +*/ +HWTEST_F(DataShareCommonTest, QuerySql001, TestSize.Level1) +{ + ZLOGI("QuerySql001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string sql = "testsql"; + auto result = rdbDelegate.QuerySql(sql); + EXPECT_EQ(result, nullptr); + ZLOGI("QuerySql001 end"); +} + +/** +* @tc.name: UpdateSql001 +* @tc.desc: test UpdateSql function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call UpdateSql function +* @tc.experct: UpdateSql failed and return E_ERROR +*/ +HWTEST_F(DataShareCommonTest, UpdateSql001, TestSize.Level1) +{ + ZLOGI("UpdateSql001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string sql = "testsql"; + auto result = rdbDelegate.UpdateSql(sql); + EXPECT_EQ(result.first, OHOS::DataShare::E_ERROR); + ZLOGI("UpdateSql001 end"); +} + +/** +* @tc.name: EraseTimerTaskId001 +* @tc.desc: test EraseTimerTaskId function when not find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and timerCache_ is null + 2.call EraseTimerTaskId function +* @tc.experct: not find key, EraseTimerTaskId failed and return -1 +*/ +HWTEST_F(DataShareCommonTest, EraseTimerTaskId001, TestSize.Level1) +{ + ZLOGI("EraseTimerTaskId001 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + int64_t result = manager.EraseTimerTaskId(key); + EXPECT_EQ(result, -1); + ZLOGI("EraseTimerTaskId001 end"); +} + +/** +* @tc.name: EraseTimerTaskId002 +* @tc.desc: test EraseTimerTaskId function when find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and timerCache_[key] = timeid + 2.call EraseTimerTaskId function +* @tc.experct: find key, EraseTimerTaskId success and return timeid +*/ +HWTEST_F(DataShareCommonTest, EraseTimerTaskId002, TestSize.Level1) +{ + ZLOGI("EraseTimerTaskId002 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + int64_t timeid = 1; + manager.timerCache_[key] = timeid; + int64_t result = manager.EraseTimerTaskId(key); + EXPECT_EQ(result, timeid); + ZLOGI("EraseTimerTaskId002 end"); +} + +/** +* @tc.name: GetSchedulerStatus001 +* @tc.desc: test GetSchedulerStatus function when not find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and schedulerStatusCache_ is null + 2.call GetSchedulerStatus function +* @tc.experct: not find key, GetSchedulerStatus failed and return false +*/ +HWTEST_F(DataShareCommonTest, GetSchedulerStatus001, TestSize.Level1) +{ + ZLOGI("GetSchedulerStatus001 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + bool result = manager.GetSchedulerStatus(key); + EXPECT_FALSE(result); + ZLOGI("GetSchedulerStatus001 end"); +} + +/** +* @tc.name: GetSchedulerStatus002 +* @tc.desc: test GetSchedulerStatus function when find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and schedulerStatusCache_[key] = true; + 2.call GetSchedulerStatus function +* @tc.experct: find key, GetSchedulerStatus success and return true +*/ +HWTEST_F(DataShareCommonTest, GetSchedulerStatus002, TestSize.Level1) +{ + ZLOGI("GetSchedulerStatus002 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.schedulerStatusCache_[key] = true; + bool result = manager.GetSchedulerStatus(key); + EXPECT_TRUE(result); + ZLOGI("GetSchedulerStatus002 end"); +} + +/** +* @tc.name: RemoveTimer001 +* @tc.desc: test RemoveTimer function when executor_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object what timerCache_[key] = 1 and executor_ is nullptr + 2.call RemoveTimer function to remove timer +* @tc.experct: RemoveTimer failed and timerCache_ is not null +*/ +HWTEST_F(DataShareCommonTest, RemoveTimer001, TestSize.Level1) +{ + ZLOGI("RemoveTimer001 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.executor_ = nullptr; + manager.timerCache_[key] = 1; + manager.RemoveTimer(key); + EXPECT_NE(manager.timerCache_.find(key), manager.timerCache_.end()); + ZLOGI("RemoveTimer001 end"); +} + +/** +* @tc.name: RemoveTimer002 +* @tc.desc: test RemoveTimer function when executor_ is not nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and timerCache_[key] = 1 and executor_ is not nullptr + 2.call RemoveTimer function to remove timer +* @tc.experct: RemoveTimer success and timerCache_ is null +*/ +HWTEST_F(DataShareCommonTest, RemoveTimer002, TestSize.Level1) +{ + ZLOGI("RemoveTimer002 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.executor_ = std::make_shared(5, 3); + manager.timerCache_[key] = 1; + manager.RemoveTimer(key); + EXPECT_EQ(manager.timerCache_.find(key), manager.timerCache_.end()); + ZLOGI("RemoveTimer002 end"); +} + +/** +* @tc.name: ClearTimer001 +* @tc.desc: test ClearTimer function when executor_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object what timerCache_[key] = 1 and executor_ is nullptr + 2.call ClearTimer function to clear timer +* @tc.experct: ClearTimer failed and timerCache_ is not empty +*/ +HWTEST_F(DataShareCommonTest, ClearTimer001, TestSize.Level1) +{ + ZLOGI("ClearTimer001 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.executor_ = nullptr; + manager.timerCache_[key] = 1; + manager.ClearTimer(); + EXPECT_FALSE(manager.timerCache_.empty()); + ZLOGI("ClearTimer001 end"); +} + +/** +* @tc.name: ClearTimer002 +* @tc.desc: test ClearTimer function when executor_ is not nullptr and find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and timerCache_[key] = 1 and executor_ is not nullptr + 2.call ClearTimer function to clear timer +* @tc.experct: ClearTimer success and timerCache_ is empty +*/ +HWTEST_F(DataShareCommonTest, ClearTimer002, TestSize.Level1) +{ + ZLOGI("ClearTimer002 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.executor_ = std::make_shared(5, 3); + manager.timerCache_[key] = 1; + manager.ClearTimer(); + EXPECT_TRUE(manager.timerCache_.empty()); + ZLOGI("ClearTimer002 end"); +} + +/** +* @tc.name: ClearTimer003 +* @tc.desc: test ClearTimer function when executor_ is not nullptr and not find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and timerCache_ is null + 2.call ClearTimer function +* @tc.experct: ClearTimer failed and timerCache_ is empty +*/ +HWTEST_F(DataShareCommonTest, ClearTimer003, TestSize.Level1) +{ + ZLOGI("ClearTimer003 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.executor_ = std::make_shared(5, 3); + manager.ClearTimer(); + EXPECT_TRUE(manager.timerCache_.empty()); + ZLOGI("ClearTimer003 end"); +} } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/kv_dalegate_test.cpp b/services/distributeddataservice/service/test/kv_dalegate_test.cpp index 26bba5c02..4920e91b2 100644 --- a/services/distributeddataservice/service/test/kv_dalegate_test.cpp +++ b/services/distributeddataservice/service/test/kv_dalegate_test.cpp @@ -112,4 +112,292 @@ HWTEST_F(KvDelegateTest, GetVersion001, TestSize.Level1) EXPECT_EQ(result, false); ZLOGI("KvDelegateTest GetVersion001 end"); } + +/** +* @tc.name: Upsert001 +* @tc.desc: test Upsert function when GDR_DBOpen failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= false + 2.call Upsert function to upsert filter +* @tc.experct: Upsert failed and return E_ERROR +*/ +HWTEST_F(KvDelegateTest, Upsert001, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Upsert001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + std::string collectionName = "test"; + std::string filter = "filter"; + std::string value = "value"; + auto result = kvDelegate.Upsert(collectionName, filter, value); + EXPECT_EQ(result.first, E_ERROR); + ZLOGI("KvDelegateTest Upsert001 end"); +} + +/** +* @tc.name: Upsert002 +* @tc.desc: test Upsert function when GRD_UpsertDoc failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= true + 2.call Upsert function to upsert filter +* @tc.experct: Upsert failed and return GRD_INVALID_ARGS +*/ +HWTEST_F(KvDelegateTest, Upsert002, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Upsert001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.isInitDone_= true; + std::string collectionName = "test"; + std::string filter = "filter"; + std::string value = "value"; + auto result = kvDelegate.Upsert(collectionName, filter, value); + EXPECT_EQ(result.first, GRD_INVALID_ARGS); + ZLOGI("KvDelegateTest Upsert002 end"); +} + +/** +* @tc.name: Delete001 +* @tc.desc: test Delete function when GDR_DBOpen failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= false + 2.call Delete function to Delete filter +* @tc.experct: Delete failed and return E_ERROR +*/ +HWTEST_F(KvDelegateTest, Delete001, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Delete001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + std::string collectionName = "test"; + std::string filter = "filter"; + auto result = kvDelegate.Delete(collectionName, filter); + EXPECT_EQ(result.first, E_ERROR); + ZLOGI("KvDelegateTest Delete001 end"); +} + +/** +* @tc.name: Delete002 +* @tc.desc: test Delete function when GRD_DeleteDoc failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= true + 2.call Delete function to Delete filter +* @tc.experct: Delete failed and return GRD_INVALID_ARGS +*/ +HWTEST_F(KvDelegateTest, Delete002, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Delete002 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.isInitDone_= true; + std::string collectionName = "test"; + std::string filter = "filter"; + auto result = kvDelegate.Delete(collectionName, filter); + EXPECT_EQ(result.first, GRD_INVALID_ARGS); + ZLOGI("KvDelegateTest Delete002 end"); +} + +/** +* @tc.name: Init001 +* @tc.desc: test Init function when isInitDone_ = true +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= true + 2.call Init function +* @tc.experct: Init failed and return true +*/ +HWTEST_F(KvDelegateTest, Init001, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Init001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.isInitDone_ = true; + auto result = kvDelegate.Init(); + EXPECT_TRUE(result); + ZLOGI("KvDelegateTest Init001 end"); +} + +/** +* @tc.name: Init002 +* @tc.desc: test Init function when isInitDone_ = false +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= false + 2.call Init function +* @tc.experct: Init failed and return false +*/ +HWTEST_F(KvDelegateTest, Init002, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Init002 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + auto result = kvDelegate.Init(); + EXPECT_FALSE(result); + ZLOGI("KvDelegateTest Init002 end"); +} + +/** +* @tc.name: Get001 +* @tc.desc: test Get function when GDR_DBOpen failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= false + 2.call Get function +* @tc.experct: Get failed and return E_ERROR +*/ +HWTEST_F(KvDelegateTest, Get001, TestSize.Level1) +{ + ZLOGI("Get001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + std::string collectionName = "test"; + std::string filter = "filter"; + std::string projection = "projection"; + std::string value = "value"; + std::string result = "result"; + auto result1 = kvDelegate.Get(collectionName, filter, projection, result); + EXPECT_EQ(result1, E_ERROR); + ZLOGI("Get001 end"); +} + +/** +* @tc.name: Get002 +* @tc.desc: test Get function when GRD_FindDoc failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= true + 2.call Get function +* @tc.experct: Get failed and return GRD_INVALID_ARGS +*/ +HWTEST_F(KvDelegateTest, Get002, TestSize.Level1) +{ + ZLOGI("Get002 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.isInitDone_ = true; + std::string collectionName = "test"; + std::string filter = "filter"; + std::string projection = "projection"; + std::string value = "value"; + std::string result = "result"; + auto result1 = kvDelegate.Get(collectionName, filter, projection, result); + EXPECT_EQ(result1, GRD_INVALID_ARGS); + ZLOGI("Get002 end"); +} + +/** +* @tc.name: Backup001 +* @tc.desc: test Backup function when hasChange_ is true +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.hasChange_ = true + 2.call Backup function +* @tc.experct: need backup and change kvDelegate.hasChange_ to false +*/ +HWTEST_F(KvDelegateTest, Backup001, TestSize.Level1) +{ + ZLOGI("Backup001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.hasChange_ = true; + kvDelegate.Backup(); + EXPECT_FALSE(kvDelegate.hasChange_); + ZLOGI("Backup001 end"); +} + +/** +* @tc.name: Backup002 +* @tc.desc: test Backup function when hasChange_ is false +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.hasChange_ = false + 2.call Backup function +* @tc.experct: no need to backup and kvDelegate.hasChange_ not change +*/ +HWTEST_F(KvDelegateTest, Backup002, TestSize.Level1) +{ + ZLOGI("Backup002 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.Backup(); + EXPECT_FALSE(kvDelegate.hasChange_); + ZLOGI("Backup002 end"); +} + +/** +* @tc.name: GetBatch001 +* @tc.desc: test GetBatch function when GDR_DBOpen failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= false + 2.call GetBach function +* @tc.experct: GetBach failed and return E_ERROR +*/ +HWTEST_F(KvDelegateTest, GetBatch001, TestSize.Level1) +{ + ZLOGI("GetBatch001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + std::string collectionName = "test"; + std::string filter = "filter"; + std::string projection = "projection"; + std::string value = "value"; + std::vector result; + auto result1 = kvDelegate.GetBatch(collectionName, filter, projection, result); + EXPECT_EQ(result1, E_ERROR); + ZLOGI("GetBatch001 end"); +} + +/** +* @tc.name: GetBatch002 +* @tc.desc: test GetBatch function when GRD_FindDoc failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= true + 2.call GetBatch function +* @tc.experct: GetBatch failed and return GRD_INVALID_ARGS +*/ +HWTEST_F(KvDelegateTest, GetBatch002, TestSize.Level1) +{ + ZLOGI("GetBatch002 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.isInitDone_ = true; + std::string collectionName = "test"; + std::string filter = "filter"; + std::string projection = "projection"; + std::string value = "value"; + std::vector result; + auto result1 = kvDelegate.GetBatch(collectionName, filter, projection, result); + EXPECT_EQ(result1, GRD_INVALID_ARGS); + ZLOGI("GetBatch001 end"); +} } // namespace OHOS::Test \ No newline at end of file -- Gitee From acaffaa3d4bac633a91cb767bceca3c109e5d864 Mon Sep 17 00:00:00 2001 From: yangliu Date: Mon, 21 Apr 2025 18:07:04 +0800 Subject: [PATCH 181/225] update Signed-off-by: yangliu --- .../src/device_manager_adapter.cpp | 31 +++++++++++++++++++ .../communicator/device_manager_adapter.h | 2 ++ 2 files changed, 33 insertions(+) diff --git a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp index b9b0078f6..074bae762 100644 --- a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp +++ b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp @@ -176,6 +176,7 @@ void DeviceManagerAdapter::Online(const DmDeviceInfo &info) KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, static_cast(dvInfo.authForm), dvInfo.osType); SaveDeviceInfo(dvInfo, DeviceChangeType::DEVICE_ONLINE); + SaveHosDevInfo(dvInfo, DeviceChangeType::DEVICE_ONLINE); syncTask_.Insert(dvInfo.uuid, dvInfo.uuid); auto observers = GetObservers(); ResetLocalDeviceInfo(); @@ -245,6 +246,7 @@ void DeviceManagerAdapter::Offline(const DmDeviceInfo &info) KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, static_cast(dvInfo.authForm), dvInfo.osType); SaveDeviceInfo(dvInfo, DeviceChangeType::DEVICE_OFFLINE); + SaveHosDevInfo(dvInfo, DeviceChangeType::DEVICE_OFFLINE); auto task = [this, dvInfo]() { observers_.ForEachCopies([&dvInfo](const auto &key, auto &value) { if (value != nullptr) { @@ -409,6 +411,9 @@ bool DeviceManagerAdapter::IsOHOSType(const std::string &id) int32_t DeviceManagerAdapter::GetAuthType(const std::string &id) { DeviceInfo dvInfo; + if (hosDeviceInfos_.Get(id, dvInfo)) { + return static_cast(dvInfo.authForm); + } if (!deviceInfos_.Get(id, dvInfo)) { InitDeviceInfo(); deviceInfos_.Get(id, dvInfo); @@ -642,4 +647,30 @@ void DeviceManagerAdapter::ResetLocalDeviceInfo() deviceInfos_.Set(local.udid, local); deviceInfos_.Set(local.networkId, local); } + +void DeviceManagerAdapter::SaveHosDevInfo(const DeviceInfo &dvInfo, const DeviceChangeType &type) +{ + if (dvInfo.networkId == DeviceManagerAdapter::cloudDmInfo.networkId || + dvInfo.osType == OH_OS_TYPE) { + return; + } + switch (type) { + case DeviceChangeType::DEVICE_ONLINE: { + hosDeviceInfos_.Set(dvInfo.networkId, dvInfo); + hosDeviceInfos_.Set(dvInfo.uuid, dvInfo); + hosDeviceInfos_.Set(dvInfo.udid, dvInfo); + break; + } + case DeviceChangeType::DEVICE_OFFLINE: { + hosDeviceInfos_.Delete(dvInfo.networkId); + hosDeviceInfos_.Delete(dvInfo.uuid); + hosDeviceInfos_.Delete(dvInfo.udid); + break; + } + default: { + ZLOGW("unknown type."); + break; + } + } +} } // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h b/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h index a50783ae1..cacdeef59 100644 --- a/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h +++ b/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h @@ -91,6 +91,7 @@ private: void OnChanged(const DmDeviceInfo &info); std::vector GetObservers(); void ResetLocalDeviceInfo(); + void SaveHosDevInfo(const DeviceInfo &dvInfo, const DeviceChangeType &type); static inline uint64_t GetTimeStamp() { return std::chrono::duration_cast( @@ -103,6 +104,7 @@ private: const DmDeviceInfo cloudDmInfo; ConcurrentMap observers_ {}; LRUBucket deviceInfos_ {64}; + LRUBucket hosDeviceInfos_ {64}; static constexpr size_t TIME_TASK_CAPACITY = 50; static constexpr int32_t SYNC_TIMEOUT = 60 * 1000; // ms static constexpr int32_t OH_OS_TYPE = 10; -- Gitee From 60086f97a41f9c0b1a81208835d8fc59686306b3 Mon Sep 17 00:00:00 2001 From: yangliu Date: Mon, 21 Apr 2025 19:28:42 +0800 Subject: [PATCH 182/225] update Signed-off-by: yangliu --- .../adapter/include/communicator/device_manager_adapter.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h b/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h index cacdeef59..18b7b76cc 100644 --- a/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h +++ b/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h @@ -91,7 +91,7 @@ private: void OnChanged(const DmDeviceInfo &info); std::vector GetObservers(); void ResetLocalDeviceInfo(); - void SaveHosDevInfo(const DeviceInfo &dvInfo, const DeviceChangeType &type); + void SaveHosDevInfo(const DeviceInfo &dvInfo, const AppDistributedKv::DeviceChangeType &type); static inline uint64_t GetTimeStamp() { return std::chrono::duration_cast( -- Gitee From cc4e4f161e4a0252d203683efcf2085ec8b3cf51 Mon Sep 17 00:00:00 2001 From: yangliu Date: Mon, 21 Apr 2025 19:55:05 +0800 Subject: [PATCH 183/225] update Signed-off-by: yangliu --- .../adapter/communicator/src/device_manager_adapter.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp index 074bae762..2aba86879 100644 --- a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp +++ b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp @@ -265,8 +265,9 @@ void DeviceManagerAdapter::OnChanged(const DmDeviceInfo &info) ZLOGE("get device info fail"); return; } - ZLOGI("[OnChanged] uuid:%{public}s, name:%{public}s, type:%{public}d", - KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType); + ZLOGI("[OnChanged] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d", + KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, + static_cast(dvInfo.authForm)); } void DeviceManagerAdapter::OnReady(const DmDeviceInfo &info) -- Gitee From fd06323ac36f487952049ea103368e8166ec6477 Mon Sep 17 00:00:00 2001 From: guochao Date: Tue, 22 Apr 2025 10:30:21 +0800 Subject: [PATCH 184/225] add fix Signed-off-by: guochao --- .../service/rdb/rdb_result_set_impl.cpp | 1 + .../rdbresultsetstub_fuzzer.cpp | 19 +++++++------------ .../rdbservicestub_fuzzer.cpp | 17 ++++++----------- 3 files changed, 14 insertions(+), 23 deletions(-) diff --git a/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp b/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp index f6e7d4dd5..7efae1dd1 100644 --- a/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp @@ -36,6 +36,7 @@ RdbResultSetImpl::RdbResultSetImpl(std::shared_ptr resultSet) : resultSe count_ = resultSet_->GetCount(); resultSet_->GetColumnNames(colNames_); } + ZLOGE("test only"); } int RdbResultSetImpl::GetAllColumnNames(std::vector &columnNames) diff --git a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp index c5871d302..1b28c9a1b 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp @@ -15,31 +15,31 @@ #include "rdbresultsetstub_fuzzer.h" +#include + #include #include -#include #include +#include "message_parcel.h" #include "rdb_result_set_impl.h" #include "rdb_result_set_stub.h" -#include "message_parcel.h" -#include "store/cursor.h" #include "securec.h" +#include "store/cursor.h" using namespace OHOS::DistributedRdb; namespace OHOS { const std::u16string INTERFACE_TOKEN = u"OHOS::NativeRdb.IResultSet"; -constexpr uint32_t CODE_MIN = 0; -constexpr uint32_t CODE_MAX = NativeRdb::RemoteResultSet::Code::CMD_MAX + 1; bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) { FuzzedDataProvider provider(data, size); - uint32_t code = provider.ConsumeIntegral() % (CODE_MAX - CODE_MIN + 1) + CODE_MIN; + uint32_t code = provider.ConsumeIntegral(); + std::vector remaining_data = provider.ConsumeRemainingBytes(); MessageParcel request; request.WriteInterfaceToken(INTERFACE_TOKEN); - request.WriteBuffer(data, size); + request.WriteBuffer(static_cast(remaining_data.data()), remaining_data.size()); request.RewindRead(0); MessageParcel reply; MessageOption option; @@ -54,11 +54,6 @@ bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { - if (data == nullptr) { - return 0; - } - OHOS::OnRemoteRequestFuzz(data, size); - return 0; } \ No newline at end of file diff --git a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp index 4b829bc26..df6b5f1ae 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp @@ -15,21 +15,20 @@ #include "rdbservicestub_fuzzer.h" +#include + #include #include -#include #include "ipc_skeleton.h" -#include "rdb_service_impl.h" #include "message_parcel.h" +#include "rdb_service_impl.h" #include "securec.h" using namespace OHOS::DistributedRdb; namespace OHOS { const std::u16string INTERFACE_TOKEN = u"OHOS.DistributedRdb.IRdbService"; -constexpr uint32_t CODE_MIN = 0; -constexpr uint32_t CODE_MAX = static_cast(RdbServiceCode::RDB_SERVICE_CMD_MAX) + 1; constexpr size_t NUM_MIN = 5; constexpr size_t NUM_MAX = 12; @@ -41,10 +40,11 @@ bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) { "RdbServiceStubFuzz", static_cast(IPCSkeleton::GetSelfTokenID()), std::move(executor) }); FuzzedDataProvider provider(data, size); - uint32_t code = provider.ConsumeIntegral() % (CODE_MAX - CODE_MIN + 1) + CODE_MIN; + uint32_t code = provider.ConsumeIntegral(); + std::vector remaining_data = provider.ConsumeRemainingBytes(); MessageParcel request; request.WriteInterfaceToken(INTERFACE_TOKEN); - request.WriteBuffer(data, size); + request.WriteBuffer(static_cast(remaining_data.data()), remaining_data.size()); request.RewindRead(0); MessageParcel reply; std::shared_ptr rdbServiceStub = rdbServiceImpl; @@ -56,11 +56,6 @@ bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { - if (data == nullptr) { - return 0; - } - OHOS::OnRemoteRequestFuzz(data, size); - return 0; } \ No newline at end of file -- Gitee From e5b8a0028f0cc44539564db985e3f6d73f60332a Mon Sep 17 00:00:00 2001 From: guochao Date: Tue, 22 Apr 2025 11:21:50 +0800 Subject: [PATCH 185/225] delete log Signed-off-by: guochao --- .../distributeddataservice/service/rdb/rdb_result_set_impl.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp b/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp index 7efae1dd1..f6e7d4dd5 100644 --- a/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp @@ -36,7 +36,6 @@ RdbResultSetImpl::RdbResultSetImpl(std::shared_ptr resultSet) : resultSe count_ = resultSet_->GetCount(); resultSet_->GetColumnNames(colNames_); } - ZLOGE("test only"); } int RdbResultSetImpl::GetAllColumnNames(std::vector &columnNames) -- Gitee From a1a848a2c6d1a08f8c3b7a18483a81d06aa5f550 Mon Sep 17 00:00:00 2001 From: yangliu Date: Tue, 22 Apr 2025 15:29:08 +0800 Subject: [PATCH 186/225] update Signed-off-by: yangliu --- .../src/device_manager_adapter.cpp | 51 ++++++------------- .../communicator/device_manager_adapter.h | 3 +- 2 files changed, 17 insertions(+), 37 deletions(-) diff --git a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp index 2aba86879..81d9ce9fd 100644 --- a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp +++ b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp @@ -246,7 +246,6 @@ void DeviceManagerAdapter::Offline(const DmDeviceInfo &info) KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, static_cast(dvInfo.authForm), dvInfo.osType); SaveDeviceInfo(dvInfo, DeviceChangeType::DEVICE_OFFLINE); - SaveHosDevInfo(dvInfo, DeviceChangeType::DEVICE_OFFLINE); auto task = [this, dvInfo]() { observers_.ForEachCopies([&dvInfo](const auto &key, auto &value) { if (value != nullptr) { @@ -265,9 +264,9 @@ void DeviceManagerAdapter::OnChanged(const DmDeviceInfo &info) ZLOGE("get device info fail"); return; } - ZLOGI("[OnChanged] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d", + ZLOGI("[OnChanged] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d osType:%{public}d", KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, - static_cast(dvInfo.authForm)); + static_cast(dvInfo.authForm), dvInfo.osType); } void DeviceManagerAdapter::OnReady(const DmDeviceInfo &info) @@ -278,8 +277,9 @@ void DeviceManagerAdapter::OnReady(const DmDeviceInfo &info) return; } readyDevices_.InsertOrAssign(dvInfo.uuid, std::make_pair(DeviceState::DEVICE_ONREADY, dvInfo)); - ZLOGI("[OnReady] uuid:%{public}s, name:%{public}s, type:%{public}d", - KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType); + ZLOGI("[OnReady] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d, osType:%{public}d", + KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, + static_cast(dvInfo.authForm), dvInfo.osType); auto task = [this, dvInfo]() { observers_.ForEachCopies([&dvInfo](const auto &key, auto &value) { if (value != nullptr) { @@ -329,6 +329,11 @@ void DeviceManagerAdapter::SaveDeviceInfo(const DeviceInfo &dvInfo, const Device deviceInfos_.Set(dvInfo.uuid, dvInfo); deviceInfos_.Set(dvInfo.udid, dvInfo); readyDevices_.InsertOrAssign(dvInfo.uuid, std::make_pair(DeviceState::DEVICE_ONLINE, dvInfo)); + if (dvInfo.osType != OH_OS_TYPE) { + otherDeviceInfos_.Set(dvInfo.networkId, dvInfo); + otherDeviceInfos_.Set(dvInfo.uuid, dvInfo); + otherDeviceInfos_.Set(dvInfo.udid, dvInfo); + } break; } case DeviceChangeType::DEVICE_OFFLINE: { @@ -336,6 +341,11 @@ void DeviceManagerAdapter::SaveDeviceInfo(const DeviceInfo &dvInfo, const Device deviceInfos_.Delete(dvInfo.uuid); deviceInfos_.Delete(dvInfo.udid); readyDevices_.Erase(dvInfo.uuid); + if (dvInfo.osType != OH_OS_TYPE) { + otherDeviceInfos_.Delete(dvInfo.networkId, dvInfo); + otherDeviceInfos_.Delete(dvInfo.uuid, dvInfo); + otherDeviceInfos_.Delete(dvInfo.udid, dvInfo); + } break; } default: { @@ -412,10 +422,7 @@ bool DeviceManagerAdapter::IsOHOSType(const std::string &id) int32_t DeviceManagerAdapter::GetAuthType(const std::string &id) { DeviceInfo dvInfo; - if (hosDeviceInfos_.Get(id, dvInfo)) { - return static_cast(dvInfo.authForm); - } - if (!deviceInfos_.Get(id, dvInfo)) { + if (!otherDeviceInfos_.Get(id, dvInfo) && !deviceInfos_.Get(id, dvInfo)) { InitDeviceInfo(); deviceInfos_.Get(id, dvInfo); } @@ -648,30 +655,4 @@ void DeviceManagerAdapter::ResetLocalDeviceInfo() deviceInfos_.Set(local.udid, local); deviceInfos_.Set(local.networkId, local); } - -void DeviceManagerAdapter::SaveHosDevInfo(const DeviceInfo &dvInfo, const DeviceChangeType &type) -{ - if (dvInfo.networkId == DeviceManagerAdapter::cloudDmInfo.networkId || - dvInfo.osType == OH_OS_TYPE) { - return; - } - switch (type) { - case DeviceChangeType::DEVICE_ONLINE: { - hosDeviceInfos_.Set(dvInfo.networkId, dvInfo); - hosDeviceInfos_.Set(dvInfo.uuid, dvInfo); - hosDeviceInfos_.Set(dvInfo.udid, dvInfo); - break; - } - case DeviceChangeType::DEVICE_OFFLINE: { - hosDeviceInfos_.Delete(dvInfo.networkId); - hosDeviceInfos_.Delete(dvInfo.uuid); - hosDeviceInfos_.Delete(dvInfo.udid); - break; - } - default: { - ZLOGW("unknown type."); - break; - } - } -} } // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h b/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h index 18b7b76cc..53135966b 100644 --- a/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h +++ b/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h @@ -91,7 +91,6 @@ private: void OnChanged(const DmDeviceInfo &info); std::vector GetObservers(); void ResetLocalDeviceInfo(); - void SaveHosDevInfo(const DeviceInfo &dvInfo, const AppDistributedKv::DeviceChangeType &type); static inline uint64_t GetTimeStamp() { return std::chrono::duration_cast( @@ -104,7 +103,7 @@ private: const DmDeviceInfo cloudDmInfo; ConcurrentMap observers_ {}; LRUBucket deviceInfos_ {64}; - LRUBucket hosDeviceInfos_ {64}; + LRUBucket otherDeviceInfos_ {64}; static constexpr size_t TIME_TASK_CAPACITY = 50; static constexpr int32_t SYNC_TIMEOUT = 60 * 1000; // ms static constexpr int32_t OH_OS_TYPE = 10; -- Gitee From 717b8fe6bef08028e5fd2d466c2ff7d7d5add150 Mon Sep 17 00:00:00 2001 From: yangliu Date: Tue, 22 Apr 2025 15:29:42 +0800 Subject: [PATCH 187/225] update Signed-off-by: yangliu --- .../adapter/communicator/src/device_manager_adapter.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp index 81d9ce9fd..175685d82 100644 --- a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp +++ b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp @@ -176,7 +176,6 @@ void DeviceManagerAdapter::Online(const DmDeviceInfo &info) KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, static_cast(dvInfo.authForm), dvInfo.osType); SaveDeviceInfo(dvInfo, DeviceChangeType::DEVICE_ONLINE); - SaveHosDevInfo(dvInfo, DeviceChangeType::DEVICE_ONLINE); syncTask_.Insert(dvInfo.uuid, dvInfo.uuid); auto observers = GetObservers(); ResetLocalDeviceInfo(); -- Gitee From d08d7ee3b2473e7c1238dcfe589a81e0f0df2c5a Mon Sep 17 00:00:00 2001 From: yangliu Date: Tue, 22 Apr 2025 15:49:26 +0800 Subject: [PATCH 188/225] update Signed-off-by: yangliu --- .../adapter/communicator/src/device_manager_adapter.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp index 175685d82..817824732 100644 --- a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp +++ b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp @@ -341,9 +341,9 @@ void DeviceManagerAdapter::SaveDeviceInfo(const DeviceInfo &dvInfo, const Device deviceInfos_.Delete(dvInfo.udid); readyDevices_.Erase(dvInfo.uuid); if (dvInfo.osType != OH_OS_TYPE) { - otherDeviceInfos_.Delete(dvInfo.networkId, dvInfo); - otherDeviceInfos_.Delete(dvInfo.uuid, dvInfo); - otherDeviceInfos_.Delete(dvInfo.udid, dvInfo); + otherDeviceInfos_.Delete(dvInfo.networkId); + otherDeviceInfos_.Delete(dvInfo.uuid); + otherDeviceInfos_.Delete(dvInfo.udid); } break; } -- Gitee From ab13313dc6df495c98b22656914910ddc873473e Mon Sep 17 00:00:00 2001 From: guochao Date: Tue, 22 Apr 2025 15:57:58 +0800 Subject: [PATCH 189/225] =?UTF-8?q?=E9=99=90=E5=88=B6code=E7=A0=81?= =?UTF-8?q?=E8=8C=83=E5=9B=B4=20Signed-off-by:=20guochao=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp | 4 ++-- .../fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp index 1b28c9a1b..14d6d1c69 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp @@ -28,14 +28,14 @@ #include "store/cursor.h" using namespace OHOS::DistributedRdb; - namespace OHOS { +using Code = NativeRdb::RemoteResultSet::Code; const std::u16string INTERFACE_TOKEN = u"OHOS::NativeRdb.IResultSet"; bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) { FuzzedDataProvider provider(data, size); - uint32_t code = provider.ConsumeIntegral(); + uint32_t code = provider.ConsumeIntegralInRange(0, Code::CMD_MAX); std::vector remaining_data = provider.ConsumeRemainingBytes(); MessageParcel request; request.WriteInterfaceToken(INTERFACE_TOKEN); diff --git a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp index df6b5f1ae..60767879a 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp @@ -40,7 +40,8 @@ bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) { "RdbServiceStubFuzz", static_cast(IPCSkeleton::GetSelfTokenID()), std::move(executor) }); FuzzedDataProvider provider(data, size); - uint32_t code = provider.ConsumeIntegral(); + uint32_t code = + provider.ConsumeIntegralInRange(0, static_cast(RdbServiceCode::RDB_SERVICE_CMD_MAX)); std::vector remaining_data = provider.ConsumeRemainingBytes(); MessageParcel request; request.WriteInterfaceToken(INTERFACE_TOKEN); -- Gitee From 2b4bc25f16e16afa75b51a70ea38046a9c270c6f Mon Sep 17 00:00:00 2001 From: ZhaoJinghui Date: Tue, 22 Apr 2025 18:59:28 +0800 Subject: [PATCH 190/225] add testcase Signed-off-by: ZhaoJinghui Change-Id: Ibd2dc359d7a4ae75a38278e6be1a931d3021ddd8 --- .../service/test/rdb_service_impl_test.cpp | 161 ++++++++++++++++++ 1 file changed, 161 insertions(+) diff --git a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp index 85453a359..7d6416dcb 100644 --- a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp @@ -29,6 +29,7 @@ #include "metadata/store_meta_data_local.h" #include "mock/db_store_mock.h" #include "rdb_service_impl.h" +#include "rdb_types.h" #include "relational_store_manager.h" #include "gtest/gtest.h" @@ -781,6 +782,166 @@ HWTEST_F(RdbServiceImplTest, GetPassword004, TestSize.Level0) MetaDataManager::GetInstance().DelMeta(metaData_.GetCloneSecretKey(), true); } +/** + * @tc.name: GetPassword005 + * @tc.desc: Test GetPassword when no meta data. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetPassword005, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = TEST_BUNDLE; + param.storeName_ = TEST_STORE; + param.type_ = StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN; + std::vector> password; + + int32_t result = service.GetPassword(param, password); + + EXPECT_EQ(result, RDB_NO_META); +} + +/** + * @tc.name: SetDistributedTables001 + * @tc.desc: Test SetDistributedTables when CheckAccess not pass. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, SetDistributedTables001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + std::vector tables; + std::vector references; + + int32_t result = service.SetDistributedTables(param, tables, references, false); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: SetDistributedTables002 + * @tc.desc: Test SetDistributedTables when type is search. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, SetDistributedTables002, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = TEST_BUNDLE; + param.storeName_ = TEST_STORE; + param.type_ = StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN; + std::vector tables; + std::vector references; + + int32_t result = + service.SetDistributedTables(param, tables, references, false, + DistributedTableType::DISTRIBUTED_SEARCH); + EXPECT_EQ(result, RDB_OK); +} + +/** + * @tc.name: Sync001 + * @tc.desc: Test Sync when CheckAccess not pass. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, Sync001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + RdbService::Option option {}; + PredicatesMemo predicates; + + int32_t result = service.Sync(param, option, predicates, nullptr); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: Subscribe001 + * @tc.desc: Test Subscribe when option mode invalid. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, Subscribe001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + SubscribeOption option {}; + option.mode = SubscribeMode::SUBSCRIBE_MODE_MAX; + + int32_t result = service.Subscribe(param, option, nullptr); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: UnSubscribe001 + * @tc.desc: Test UnSubscribe when option mode invalid. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, UnSubscribe001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + SubscribeOption option {}; + option.mode = SubscribeMode::SUBSCRIBE_MODE_MAX; + + int32_t result = service.UnSubscribe(param, option, nullptr); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: UpgradeCloneSecretKey001 + * @tc.desc: Test UpgradeCloneSecretKey when meta invalid. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, UpgradeCloneSecretKey001, TestSize.Level0) +{ + auto meta = metaData_; + meta.isEncrypt = true; + std::vector sKey{2, 249, 221, 119, 177, 216, 217, 134, 185, 139, 114, 38, 140, 64, 165, 35, + 77, 169, 0, 226, 226, 166, 37, 73, 181, 229, 42, 88, 108, 111, 131, 104, + 141, 43, 96, 119, 214, 34, 177, 129, 233, 96, 98, 164, 87, 115, 187, 170}; + SecretKeyMetaData secretKey; + secretKey.sKey = CryptoManager::GetInstance().Encrypt(sKey); + secretKey.area = -1; + secretKey.storeType = meta.storeType; + secretKey.time = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetCloneSecretKey(), secretKey, true), true); + + RdbServiceImpl service; + + auto result = service.UpgradeCloneSecretKey(meta); + ASSERT_EQ(result, true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(meta.GetCloneSecretKey(), true), true); +} + +/** + * @tc.name: GetDfxInfo001 + * @tc.desc: Test GetDfxInfo when CheckAccess not pass. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetDfxInfo001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + DistributedRdb::RdbDfxInfo dfxInfo; + + int32_t result = service.GetDfxInfo(param, dfxInfo); + EXPECT_EQ(result, RDB_ERROR); +} /** * @tc.name: LockCloudContainer001 * @tc.desc: Test LockCloudContainer when CheckAccess fails. -- Gitee From 3c6b6351fbecf40abb9f8088f3706b1b03a0eaf1 Mon Sep 17 00:00:00 2001 From: guochao Date: Tue, 22 Apr 2025 21:42:42 +0800 Subject: [PATCH 191/225] =?UTF-8?q?add=20=E5=88=86=E6=94=AF=E8=A6=86?= =?UTF-8?q?=E7=9B=96=E7=8E=87=20Signed-off-by:=20guochao=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../distributeddataservice/app/test/BUILD.gn | 2 + .../test/unittest/session_manager_test.cpp | 362 +++++++++++++++++- 2 files changed, 356 insertions(+), 8 deletions(-) diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index f3f912893..384041b03 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -41,6 +41,7 @@ config("module_private_config") { "${data_service_path}/app/src", "${data_service_path}/app/src/session_manager", "${data_service_path}/service/kvdb", + "${data_service_path}/service/test/mock", "${device_manager_path}/interfaces/inner_kits/native_cpp/include", "//commonlibrary/c_utils/base/include", "//utils/system/safwk/native/include", @@ -166,6 +167,7 @@ ohos_unittest("SessionManagerTest") { "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", "file_api:securitylabel", + "googletest:gmock", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index 8031dc6c6..bc43d180c 100644 --- a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -16,7 +16,11 @@ #include "accesstoken_kit.h" #include "bootstrap.h" #include "device_manager_adapter.h" +#include "device_manager_adapter_mock.h" +#include "gtest/gtest.h" #include "kvstore_meta_manager.h" +#include "meta_data_manager_mock.h" +#include "account_delegate_mock.h" #include "metadata/meta_data_manager.h" #include "metadata/store_meta_data.h" #include "nativetoken_kit.h" @@ -24,18 +28,23 @@ #include "session_manager/upgrade_manager.h" #include "token_setproc.h" #include "user_delegate.h" -#include "gtest/gtest.h" +#include "user_delegate_mock.h" namespace { +using namespace testing; using namespace testing::ext; using namespace OHOS::DistributedKv; using namespace OHOS::DistributedData; +using namespace DistributedDB; using namespace OHOS; using namespace OHOS::Security::AccessToken; +using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo; +using UserInfo = DistributedDB::UserInfo; constexpr const char *PEER_DEVICE_ID = "PEER_DEVICE_ID"; constexpr int PEER_USER_ID1 = 101; constexpr int PEER_USER_ID2 = 100; constexpr int METADATA_UID = 2000000; +static constexpr int32_t OH_OS_TYPE = 10; void GrantPermissionNative() { @@ -55,7 +64,7 @@ void GrantPermissionNative() uint64_t tokenId = GetAccessTokenId(&infoInstance); SetSelfTokenID(tokenId); AccessTokenKit::ReloadNativeTokenInfo(); - delete []perms; + delete[] perms; } class SessionManagerTest : public testing::Test { @@ -102,6 +111,12 @@ public: metaData.storeType = 1; MetaDataManager::GetInstance().SaveMeta(metaData.GetKey(), metaData); GrantPermissionNative(); + deviceManagerAdapterMock = std::make_shared(); + BDeviceManagerAdapter::deviceManagerAdapter = deviceManagerAdapterMock; + metaDataManagerMock = std::make_shared(); + BMetaDataManager::metaDataManager = metaDataManagerMock; + userDelegateMock = std::make_shared(); + BUserDelegate::userDelegate = userDelegateMock; } static void TearDownTestCase() { @@ -119,22 +134,76 @@ public: metaData.uid = METADATA_UID; metaData.storeType = 1; MetaDataManager::GetInstance().DelMeta(metaData.GetKey()); + deviceManagerAdapterMock = nullptr; + BDeviceManagerAdapter::deviceManagerAdapter = nullptr; + metaDataManagerMock = nullptr; + BMetaDataManager::metaDataManager = nullptr; + userDelegateMock = nullptr; + BUserDelegate::userDelegate = nullptr; } void SetUp() { + ConstructValidData(); } void TearDown() { } + void ConstructValidData() + { + // 构建有效数据缓冲区 + RouteHead head; + head.magic = RouteHead::MAGIC_NUMBER; + head.version = RouteHead::VERSION; + head.dataLen = + sizeof(SessionDevicePair) + sizeof(SessionUserPair) + sizeof(uint32_t) * 1 + sizeof(SessionAppId) + 5; + head.checkSum = 0; // 假设校验和正确 + + // 序列化头部 + uint8_t *ptr = dataBuffer; + memcpy(ptr, &head, sizeof(RouteHead)); + ptr += sizeof(RouteHead); + + // 设备对 + SessionDevicePair devPair; + memset(devPair.sourceId, 'A', SessionDevicePair::MAX_DEVICE_ID); + memset(devPair.targetId, 'B', SessionDevicePair::MAX_DEVICE_ID); + memcpy(ptr, &devPair, sizeof(SessionDevicePair)); + ptr += sizeof(SessionDevicePair); + + // 用户对 + SessionUserPair userPair; + userPair.sourceUserId = 100; + userPair.targetUserCount = 1; + uint32_t targetUser = 200; + memcpy(ptr, &userPair, sizeof(SessionUserPair)); + ptr += sizeof(SessionUserPair); + memcpy(ptr, &targetUser, sizeof(uint32_t)); + ptr += sizeof(uint32_t); + + // 应用ID + SessionAppId appId; + appId.len = 5; + const char *appStr = "test"; + memcpy(ptr, &appId, sizeof(SessionAppId)); + ptr += sizeof(SessionAppId); + memcpy(ptr, appStr, 5); + } + + uint8_t dataBuffer[1024]; + const uint32_t validTotalLen = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair) + + sizeof(uint32_t) * 1 + sizeof(SessionAppId) + 5; + static inline std::shared_ptr deviceManagerAdapterMock = nullptr; + static inline std::shared_ptr metaDataManagerMock = nullptr; + static inline std::shared_ptr userDelegateMock = nullptr; }; /** -* @tc.name: PackAndUnPack01 -* @tc.desc: test get db dir -* @tc.type: FUNC -* @tc.require: -* @tc.author: illybyy -*/ + * @tc.name: PackAndUnPack01 + * @tc.desc: test get db dir + * @tc.type: FUNC + * @tc.require: + * @tc.author: illybyy + */ HWTEST_F(SessionManagerTest, PackAndUnPack01, TestSize.Level2) { const DistributedDB::ExtendInfo info = { @@ -152,9 +221,286 @@ HWTEST_F(SessionManagerTest, PackAndUnPack01, TestSize.Level2) auto recvHandler = RouteHeadHandlerImpl::Create({}); ASSERT_NE(recvHandler, nullptr); uint32_t parseSize = 1; + auto res = recvHandler->ParseHeadDataLen(nullptr, routeHeadSize, parseSize); + EXPECT_EQ(res, false); recvHandler->ParseHeadDataLen(data.get(), routeHeadSize, parseSize); EXPECT_EQ(routeHeadSize, parseSize); recvHandler->ParseHeadDataUser(data.get(), routeHeadSize, "", users); ASSERT_EQ(users.size(), 0); } +/** + * @tc.name: GetHeadDataSize_Test1 + * @tc.desc: test appId equal processLabel. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, GetHeadDataSize_Test1, TestSize.Level1) +{ + ExtendInfo info; + // 创建RouteHeadHandlerImpl实例 + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t headSize = 0; + // 设置appId_为Bootstrap::GetInstance().GetProcessLabel() + routeHeadHandlerImpl.appId_ = Bootstrap::GetInstance().GetProcessLabel(); + // 调用GetHeadDataSize方法 + auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize); + // 验证返回状态和headSize的值 + EXPECT_EQ(status, DistributedDB::OK); + EXPECT_EQ(headSize, 0); +} +/** + * @tc.name: GetHeadDataSize_Test2 + * @tc.desc: test appId not equal processLabel. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, GetHeadDataSize_Test2, TestSize.Level1) +{ + ExtendInfo info; + // 创建RouteHeadHandlerImpl实例 + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t headSize = 0; + // 设置appId_不等于Bootstrap::GetInstance().GetProcessLabel() + routeHeadHandlerImpl.appId_ = "otherAppId"; + // 调用GetHeadDataSize方法 + auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize); + // 验证返回状态和headSize的值 + EXPECT_EQ(status, DistributedDB::OK); + EXPECT_EQ(headSize, 0); +} +/** + * @tc.name: GetHeadDataSize_Test3 + * @tc.desc: test devInfo.osType equal OH_OS_TYPE, appId not equal processLabel. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, GetHeadDataSize_Test3, TestSize.Level1) +{ + // 设置devInfo.osType等于OH_OS_TYPE + DeviceInfo deviceInfo; + deviceInfo.osType = OH_OS_TYPE; + EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo)); + ExtendInfo info; + // 创建RouteHeadHandlerImpl实例 + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t headSize = 0; + // 设置appId_不等于Bootstrap::GetInstance().GetProcessLabel() + routeHeadHandlerImpl.appId_ = "otherAppId"; + // 调用GetHeadDataSize方法 + auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize); + // 验证返回状态和headSize的值 + EXPECT_EQ(status, DistributedDB::OK); + EXPECT_EQ(headSize, 0); +} +/** + * @tc.name: GetHeadDataSize_Test4 + * @tc.desc: test GetHeadDataSize + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, GetHeadDataSize_Test4, TestSize.Level1) +{ + const DistributedDB::ExtendInfo info = { + .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID + }; + auto sendHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(sendHandler, nullptr); + // 设置devInfo.osType等于OH_OS_TYPE + DeviceInfo deviceInfo; + deviceInfo.osType = OH_OS_TYPE; + EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo)); + CapMetaData capMetaData; + capMetaData.version = CapMetaData::CURRENT_VERSION; + EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) + .WillRepeatedly(DoAll(SetArgReferee<1>(capMetaData), Return(true))); + + std::vector userStatus; + UserStatus userStat1; + UserStatus userStat2; + UserStatus userStat3; + userStat1.id = 1; + userStat2.id = 2; + userStat3.id = 3; + userStatus.push_back(userStat1); + userStatus.push_back(userStat2); + userStatus.push_back(userStat3); + EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillRepeatedly(Return(userStatus)); + + uint32_t headSize = 0; + // 调用GetHeadDataSize方法 + auto status = sendHandler->GetHeadDataSize(headSize); + // 验证返回状态和headSize的值 + EXPECT_EQ(status, DistributedDB::OK); + EXPECT_EQ(headSize, 0); + + uint32_t routeHeadSize = 10; + std::unique_ptr data = std::make_unique(routeHeadSize); + status = sendHandler->FillHeadData(data.get(), routeHeadSize, routeHeadSize); + EXPECT_EQ(status, DistributedDB::DB_ERROR); +} +/** + * @tc.name: ParseHeadDataUserTest001 + * @tc.desc: test parse null data. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, ParseHeadDataUserTest001, TestSize.Level1) +{ + // 创建RouteHeadHandlerImpl实例 + const DistributedDB::ExtendInfo info = { + .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID + }; + auto sendHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(sendHandler, nullptr); + + // 创建测试数据 + uint32_t totalLen = 10; + std::string label = "testLabel"; + std::vector userInfos; + + // 调用待测试方法 + bool result = sendHandler->ParseHeadDataUser(nullptr, totalLen, label, userInfos); + + // 验证结果 + EXPECT_FALSE(result); + EXPECT_EQ(userInfos.size(), 0); +} +/** + * @tc.name: ParseHeadDataUserTest002 + * @tc.desc: test totalLen < sizeof(RouteHead). + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, ParseHeadDataUserTest002, TestSize.Level1) +{ + // 创建RouteHeadHandlerImpl实例 + const DistributedDB::ExtendInfo info = { + .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID + }; + auto sendHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(sendHandler, nullptr); + + // 创建测试数据 + uint8_t data[10] = { 0 }; + std::string label = "testLabel"; + std::vector userInfos; + + // 调用待测试方法 + bool result = sendHandler->ParseHeadDataUser(data, sizeof(RouteHead) - 1, label, userInfos); + + // 验证结果 + EXPECT_FALSE(result); + EXPECT_EQ(userInfos.size(), 0); +} + +/** + * @tc.name: ParseHeadDataUserTest003 + * @tc.desc: test totalLen < sizeof(RouteHead). + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, ParseHeadDataUserTest003, TestSize.Level1) +{ + // 创建RouteHeadHandlerImpl实例 + const DistributedDB::ExtendInfo info = { + .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID + }; + auto sendHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(sendHandler, nullptr); + + // 创建测试数据 + uint8_t data[10] = { 0 }; + std::string label = "testLabel"; + std::vector userInfos; + + RouteHead head = { 0 }; + head.version = RouteHead::VERSION; + head.dataLen = sizeof(data) - sizeof(RouteHead); + + // 调用待测试方法 + bool result = sendHandler->ParseHeadDataUser(data, sizeof(RouteHead), label, userInfos); + + // 验证结果 + EXPECT_FALSE(result); + EXPECT_EQ(userInfos.size(), 0); +} + +/** + * @tc.name: UnPackData_InvalidMagic + * @tc.desc: test invalid magic. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, UnPackData_InvalidMagic, TestSize.Level1) +{ + RouteHead *head = reinterpret_cast(dataBuffer); + head->magic = 0xFFFF; // Invalid magic + ExtendInfo info; + // 创建RouteHeadHandlerImpl实例 + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t unpackedSize; + EXPECT_FALSE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize)); +} + +/** + * @tc.name: UnPackData_VersionMismatch + * @tc.desc: test version mismatch. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, UnPackData_VersionMismatch, TestSize.Level1) +{ + RouteHead *head = reinterpret_cast(dataBuffer); + head->version = 0x00; // Invalid version + ExtendInfo info; + // 创建RouteHeadHandlerImpl实例 + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t unpackedSize; + EXPECT_FALSE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize)); +} + +/** + * @tc.name: UnPackData_ValidData + * @tc.desc: test valid data. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, UnPackData_ValidData, TestSize.Level1) +{ + ExtendInfo info; + // 创建RouteHeadHandlerImpl实例 + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t unpackedSize; + EXPECT_TRUE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize)); + EXPECT_EQ(unpackedSize, validTotalLen); +} + +/** + * @tc.name: ParseHeadDataUser_OHOS_LoadMetaFailed + * @tc.desc: test load meta failed. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, ParseHeadDataUser_OHOS_LoadMetaFailed, TestSize.Level1) +{ + // 创建RouteHeadHandlerImpl实例 + const DistributedDB::ExtendInfo info = { + .appId = "otherAppId", .storeId = "test_store", .userId = "0", .dstTarget = "device123" + }; + auto sendHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(sendHandler, nullptr); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillOnce(Return(true)); + + string label = "test_label"; + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)).WillOnce(Return(false)); + + int foregroundUser = 100; + EXPECT_CALL(AccountDelegateMock::Init(), QueryForegroundUserId(_)).WillRepeatedly(DoAll(SetArgReferee<0>(foregroundUser), Return(true))); + + vector userInfos; + EXPECT_TRUE(sendHandler->ParseHeadDataUser(dataBuffer, validTotalLen, label, userInfos)); + ASSERT_EQ(userInfos.size(), 1); + EXPECT_EQ(userInfos[0].receiveUser, "100"); +} } // namespace \ No newline at end of file -- Gitee From 49fe35c0b8c9b468d50470393b08b593e1ae8b9f Mon Sep 17 00:00:00 2001 From: guochao Date: Tue, 22 Apr 2025 23:06:10 +0800 Subject: [PATCH 192/225] =?UTF-8?q?fix=20=E4=B8=8D=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E5=87=BD=E6=95=B0=20Signed-off-by:=20guochao=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test/unittest/session_manager_test.cpp | 235 +++++++++--------- 1 file changed, 121 insertions(+), 114 deletions(-) diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index bc43d180c..9c0ca691d 100644 --- a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -14,13 +14,13 @@ */ #include "accesstoken_kit.h" +#include "account_delegate_mock.h" #include "bootstrap.h" #include "device_manager_adapter.h" #include "device_manager_adapter_mock.h" #include "gtest/gtest.h" #include "kvstore_meta_manager.h" #include "meta_data_manager_mock.h" -#include "account_delegate_mock.h" #include "metadata/meta_data_manager.h" #include "metadata/store_meta_data.h" #include "nativetoken_kit.h" @@ -29,6 +29,7 @@ #include "token_setproc.h" #include "user_delegate.h" #include "user_delegate_mock.h" +#include "utils/endian_converter.h" namespace { using namespace testing; @@ -150,60 +151,95 @@ public: } void ConstructValidData() { - // 构建有效数据缓冲区 - RouteHead head; + constexpr size_t BUFFER_SIZE = sizeof(dataBuffer); + memset_s(dataBuffer, BUFFER_SIZE, 0, BUFFER_SIZE); // 清空缓冲区 + + // 构建有效数据 + RouteHead head{}; head.magic = RouteHead::MAGIC_NUMBER; head.version = RouteHead::VERSION; - head.dataLen = - sizeof(SessionDevicePair) + sizeof(SessionUserPair) + sizeof(uint32_t) * 1 + sizeof(SessionAppId) + 5; - head.checkSum = 0; // 假设校验和正确 + head.dataLen = sizeof(SessionDevicePair) + sizeof(SessionUserPair) + sizeof(uint32_t) * 1 + + sizeof(SessionAppId) + APP_STR_LEN; // 应用ID长度+内容 + head.checkSum = 0; // 假设校验和正确 // 序列化头部 uint8_t *ptr = dataBuffer; - memcpy(ptr, &head, sizeof(RouteHead)); - ptr += sizeof(RouteHead); + size_t remaining = BUFFER_SIZE; - // 设备对 - SessionDevicePair devPair; - memset(devPair.sourceId, 'A', SessionDevicePair::MAX_DEVICE_ID); - memset(devPair.targetId, 'B', SessionDevicePair::MAX_DEVICE_ID); - memcpy(ptr, &devPair, sizeof(SessionDevicePair)); + // 1. 写入RouteHead + errno_t err = memcpy_s(ptr, remaining, &head, sizeof(RouteHead)); + ASSERT_EQ(err, 0) << "Failed to copy RouteHead"; + ptr += sizeof(RouteHead); + remaining -= sizeof(RouteHead); + + // 2. 写入SessionDevicePair + SessionDevicePair devPair{}; + // 安全初始化设备ID + constexpr size_t DEV_ID_SIZE = sizeof(devPair.sourceId); + err = memset_s(devPair.sourceId, DEV_ID_SIZE, 'A', DEV_ID_SIZE - 1); // 留1字节给终止符 + ASSERT_EQ(err, 0) << "Failed to init sourceId"; + devPair.sourceId[DEV_ID_SIZE - 1] = '\0'; + + err = memset_s(devPair.targetId, DEV_ID_SIZE, 'B', DEV_ID_SIZE - 1); + ASSERT_EQ(err, 0) << "Failed to init targetId"; + devPair.targetId[DEV_ID_SIZE - 1] = '\0'; + + err = memcpy_s(ptr, remaining, &devPair, sizeof(SessionDevicePair)); + ASSERT_EQ(err, 0) << "Failed to copy SessionDevicePair"; ptr += sizeof(SessionDevicePair); + remaining -= sizeof(SessionDevicePair); - // 用户对 - SessionUserPair userPair; - userPair.sourceUserId = 100; - userPair.targetUserCount = 1; - uint32_t targetUser = 200; - memcpy(ptr, &userPair, sizeof(SessionUserPair)); + // 3. 写入SessionUserPair + SessionUserPair userPair{}; + userPair.sourceUserId = HostToNet(100U); // 注意字节序转换 + userPair.targetUserCount = HostToNet(1U); + + err = memcpy_s(ptr, remaining, &userPair, sizeof(SessionUserPair)); + ASSERT_EQ(err, 0) << "Failed to copy SessionUserPair"; ptr += sizeof(SessionUserPair); - memcpy(ptr, &targetUser, sizeof(uint32_t)); + remaining -= sizeof(SessionUserPair); + + // 写入目标用户ID + uint32_t targetUser = HostToNet(200U); + err = memcpy_s(ptr, remaining, &targetUser, sizeof(uint32_t)); + ASSERT_EQ(err, 0) << "Failed to copy targetUser"; ptr += sizeof(uint32_t); + remaining -= sizeof(uint32_t); - // 应用ID - SessionAppId appId; - appId.len = 5; + // 4. 写入SessionAppId + SessionAppId appId{}; const char *appStr = "test"; - memcpy(ptr, &appId, sizeof(SessionAppId)); + + appId.len = HostToNet(static_cast(APP_STR_LEN)); + + err = memcpy_s(ptr, remaining, &appId, sizeof(SessionAppId)); + ASSERT_EQ(err, 0) << "Failed to copy SessionAppId"; ptr += sizeof(SessionAppId); - memcpy(ptr, appStr, 5); - } + remaining -= sizeof(SessionAppId); + // 写入应用ID内容 + err = memcpy_s(ptr, remaining, appStr, APP_STR_LEN); + ASSERT_EQ(err, 0) << "Failed to copy appId data"; + ptr += APP_STR_LEN; + remaining -= APP_STR_LEN; + } + // 验证总长度 + const size_t validTotalLen = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair) + + sizeof(uint32_t) * 1 + sizeof(SessionAppId) + APP_STR_LEN; uint8_t dataBuffer[1024]; - const uint32_t validTotalLen = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair) - + sizeof(uint32_t) * 1 + sizeof(SessionAppId) + 5; + static constexpr size_t APP_STR_LEN = 5; // 包括终止符 static inline std::shared_ptr deviceManagerAdapterMock = nullptr; static inline std::shared_ptr metaDataManagerMock = nullptr; static inline std::shared_ptr userDelegateMock = nullptr; }; /** - * @tc.name: PackAndUnPack01 - * @tc.desc: test get db dir - * @tc.type: FUNC - * @tc.require: - * @tc.author: illybyy - */ + * @tc.name: PackAndUnPack01 + * @tc.desc: test get db dir + * @tc.type: FUNC + * @tc.require: + * @tc.author: illybyy + */ HWTEST_F(SessionManagerTest, PackAndUnPack01, TestSize.Level2) { const DistributedDB::ExtendInfo info = { @@ -229,11 +265,11 @@ HWTEST_F(SessionManagerTest, PackAndUnPack01, TestSize.Level2) ASSERT_EQ(users.size(), 0); } /** - * @tc.name: GetHeadDataSize_Test1 - * @tc.desc: test appId equal processLabel. - * @tc.type: FUNC - * @tc.author: guochao - */ + * @tc.name: GetHeadDataSize_Test1 + * @tc.desc: test appId equal processLabel. + * @tc.type: FUNC + * @tc.author: guochao + */ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test1, TestSize.Level1) { ExtendInfo info; @@ -249,11 +285,11 @@ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test1, TestSize.Level1) EXPECT_EQ(headSize, 0); } /** - * @tc.name: GetHeadDataSize_Test2 - * @tc.desc: test appId not equal processLabel. - * @tc.type: FUNC - * @tc.author: guochao - */ + * @tc.name: GetHeadDataSize_Test2 + * @tc.desc: test appId not equal processLabel. + * @tc.type: FUNC + * @tc.author: guochao + */ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test2, TestSize.Level1) { ExtendInfo info; @@ -269,11 +305,11 @@ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test2, TestSize.Level1) EXPECT_EQ(headSize, 0); } /** - * @tc.name: GetHeadDataSize_Test3 - * @tc.desc: test devInfo.osType equal OH_OS_TYPE, appId not equal processLabel. - * @tc.type: FUNC - * @tc.author: guochao - */ + * @tc.name: GetHeadDataSize_Test3 + * @tc.desc: test devInfo.osType equal OH_OS_TYPE, appId not equal processLabel. + * @tc.type: FUNC + * @tc.author: guochao + */ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test3, TestSize.Level1) { // 设置devInfo.osType等于OH_OS_TYPE @@ -293,11 +329,11 @@ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test3, TestSize.Level1) EXPECT_EQ(headSize, 0); } /** - * @tc.name: GetHeadDataSize_Test4 - * @tc.desc: test GetHeadDataSize - * @tc.type: FUNC - * @tc.author: guochao - */ + * @tc.name: GetHeadDataSize_Test4 + * @tc.desc: test GetHeadDataSize + * @tc.type: FUNC + * @tc.author: guochao + */ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test4, TestSize.Level1) { const DistributedDB::ExtendInfo info = { @@ -339,11 +375,11 @@ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test4, TestSize.Level1) EXPECT_EQ(status, DistributedDB::DB_ERROR); } /** - * @tc.name: ParseHeadDataUserTest001 - * @tc.desc: test parse null data. - * @tc.type: FUNC - * @tc.author: guochao - */ + * @tc.name: ParseHeadDataUserTest001 + * @tc.desc: test parse null data. + * @tc.type: FUNC + * @tc.author: guochao + */ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest001, TestSize.Level1) { // 创建RouteHeadHandlerImpl实例 @@ -366,11 +402,11 @@ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest001, TestSize.Level1) EXPECT_EQ(userInfos.size(), 0); } /** - * @tc.name: ParseHeadDataUserTest002 - * @tc.desc: test totalLen < sizeof(RouteHead). - * @tc.type: FUNC - * @tc.author: guochao - */ + * @tc.name: ParseHeadDataUserTest002 + * @tc.desc: test totalLen < sizeof(RouteHead). + * @tc.type: FUNC + * @tc.author: guochao + */ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest002, TestSize.Level1) { // 创建RouteHeadHandlerImpl实例 @@ -394,11 +430,11 @@ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest002, TestSize.Level1) } /** - * @tc.name: ParseHeadDataUserTest003 - * @tc.desc: test totalLen < sizeof(RouteHead). - * @tc.type: FUNC - * @tc.author: guochao - */ + * @tc.name: ParseHeadDataUserTest003 + * @tc.desc: test totalLen < sizeof(RouteHead). + * @tc.type: FUNC + * @tc.author: guochao + */ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest003, TestSize.Level1) { // 创建RouteHeadHandlerImpl实例 @@ -415,7 +451,7 @@ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest003, TestSize.Level1) RouteHead head = { 0 }; head.version = RouteHead::VERSION; - head.dataLen = sizeof(data) - sizeof(RouteHead); + head.dataLen = static_cast(sizeof(data) - sizeof(RouteHead)); // 调用待测试方法 bool result = sendHandler->ParseHeadDataUser(data, sizeof(RouteHead), label, userInfos); @@ -426,11 +462,11 @@ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest003, TestSize.Level1) } /** - * @tc.name: UnPackData_InvalidMagic - * @tc.desc: test invalid magic. - * @tc.type: FUNC - * @tc.author: guochao - */ + * @tc.name: UnPackData_InvalidMagic + * @tc.desc: test invalid magic. + * @tc.type: FUNC + * @tc.author: guochao + */ HWTEST_F(SessionManagerTest, UnPackData_InvalidMagic, TestSize.Level1) { RouteHead *head = reinterpret_cast(dataBuffer); @@ -443,11 +479,11 @@ HWTEST_F(SessionManagerTest, UnPackData_InvalidMagic, TestSize.Level1) } /** - * @tc.name: UnPackData_VersionMismatch - * @tc.desc: test version mismatch. - * @tc.type: FUNC - * @tc.author: guochao - */ + * @tc.name: UnPackData_VersionMismatch + * @tc.desc: test version mismatch. + * @tc.type: FUNC + * @tc.author: guochao + */ HWTEST_F(SessionManagerTest, UnPackData_VersionMismatch, TestSize.Level1) { RouteHead *head = reinterpret_cast(dataBuffer); @@ -460,11 +496,11 @@ HWTEST_F(SessionManagerTest, UnPackData_VersionMismatch, TestSize.Level1) } /** - * @tc.name: UnPackData_ValidData - * @tc.desc: test valid data. - * @tc.type: FUNC - * @tc.author: guochao - */ + * @tc.name: UnPackData_ValidData + * @tc.desc: test valid data. + * @tc.type: FUNC + * @tc.author: guochao + */ HWTEST_F(SessionManagerTest, UnPackData_ValidData, TestSize.Level1) { ExtendInfo info; @@ -474,33 +510,4 @@ HWTEST_F(SessionManagerTest, UnPackData_ValidData, TestSize.Level1) EXPECT_TRUE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize)); EXPECT_EQ(unpackedSize, validTotalLen); } - -/** - * @tc.name: ParseHeadDataUser_OHOS_LoadMetaFailed - * @tc.desc: test load meta failed. - * @tc.type: FUNC - * @tc.author: guochao - */ -HWTEST_F(SessionManagerTest, ParseHeadDataUser_OHOS_LoadMetaFailed, TestSize.Level1) -{ - // 创建RouteHeadHandlerImpl实例 - const DistributedDB::ExtendInfo info = { - .appId = "otherAppId", .storeId = "test_store", .userId = "0", .dstTarget = "device123" - }; - auto sendHandler = RouteHeadHandlerImpl::Create(info); - ASSERT_NE(sendHandler, nullptr); - EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillOnce(Return(true)); - - string label = "test_label"; - - EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)).WillOnce(Return(false)); - - int foregroundUser = 100; - EXPECT_CALL(AccountDelegateMock::Init(), QueryForegroundUserId(_)).WillRepeatedly(DoAll(SetArgReferee<0>(foregroundUser), Return(true))); - - vector userInfos; - EXPECT_TRUE(sendHandler->ParseHeadDataUser(dataBuffer, validTotalLen, label, userInfos)); - ASSERT_EQ(userInfos.size(), 1); - EXPECT_EQ(userInfos[0].receiveUser, "100"); -} } // namespace \ No newline at end of file -- Gitee From 3572e14f74e803d5296e69e854ba12f0fd569868 Mon Sep 17 00:00:00 2001 From: zhangdi Date: Tue, 22 Apr 2025 23:42:25 +0800 Subject: [PATCH 193/225] =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E7=99=BD=E5=90=8D=E5=8D=95=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangdi --- .../app/src/kvstore_data_service.cpp | 1 + .../distributeddataservice/framework/BUILD.gn | 1 + .../device_sync_app_manager.cpp | 50 +++++++++++++++++++ .../device_sync_app/device_sync_app_manager.h | 39 +++++++++++++++ .../service/bootstrap/include/bootstrap.h | 1 + .../service/bootstrap/src/bootstrap.cpp | 14 ++++++ .../service/config/BUILD.gn | 1 + .../service/config/include/config_factory.h | 3 +- .../model/device_sync_app_white_list_config.h | 37 ++++++++++++++ .../config/include/model/global_config.h | 6 ++- .../service/config/src/config_factory.cpp | 9 +++- .../device_sync_app_white_list_config.cpp | 45 +++++++++++++++++ .../service/rdb/rdb_general_store.cpp | 7 ++- 13 files changed, 207 insertions(+), 7 deletions(-) mode change 100755 => 100644 services/distributeddataservice/app/src/kvstore_data_service.cpp create mode 100644 services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp create mode 100644 services/distributeddataservice/framework/include/device_sync_app/device_sync_app_manager.h create mode 100644 services/distributeddataservice/service/config/include/model/device_sync_app_white_list_config.h create mode 100644 services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp old mode 100755 new mode 100644 index b64886f8d..08d191b5f --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -350,6 +350,7 @@ void KvStoreDataService::LoadConfigs() Bootstrap::GetInstance().LoadBackup(executors_); Bootstrap::GetInstance().LoadCloud(); Bootstrap::GetInstance().LoadAppIdMappings(); + Bootstrap::GetInstance().LoadDeviceSyncAppWhiteLists(); } void KvStoreDataService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index a1ba24c67..a99bba56a 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -76,6 +76,7 @@ ohos_shared_library("distributeddatasvcfwk") { "cloud/sync_event.cpp", "cloud/sync_strategy.cpp", "communication/connect_manager.cpp", + "device_sync_app/device_sync_app_manager.cpp", "dfx/reporter.cpp", "directory/directory_manager.cpp", "dump/dump_manager.cpp", diff --git a/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp b/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp new file mode 100644 index 000000000..05cc45f39 --- /dev/null +++ b/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp @@ -0,0 +1,50 @@ +/* + * 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 "DeviceSyncAppManager" +#include "device_sync_app/device_sync_app_manager.h" + +#include "log_print.h" +#include "types.h" +#include "unistd.h" +namespace OHOS::DistributedData { +DeviceSyncAppManager::DeviceSyncAppManager() +{ +} + +DeviceSyncAppManager &DeviceSyncAppManager::GetInstance() +{ + static DeviceSyncAppManager instance; + return instance; +} + +void DeviceSyncAppManager::Initialize(const std::vector &lists) +{ + for (const auto &list : lists) { + whiteLists_.push_back(list); + } +} + +bool DeviceSyncAppManager::Check(const WhiteList &whiteList) +{ + for (auto &info : whiteLists_) { + if (info.appId == whiteList.appId && (info.bundleName == whiteList.bundleName) && + (info.version == whiteList.version)) { + return true; + } + } + return false; +} + +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/device_sync_app/device_sync_app_manager.h b/services/distributeddataservice/framework/include/device_sync_app/device_sync_app_manager.h new file mode 100644 index 000000000..664883bce --- /dev/null +++ b/services/distributeddataservice/framework/include/device_sync_app/device_sync_app_manager.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 DISTRIBUTEDDATAMGR_DEVICE_SYNC_APP_MANAGER_H +#define DISTRIBUTEDDATAMGR_DEVICE_SYNC_APP_MANAGER_H + +#include +#include +#include "visibility.h" +namespace OHOS::DistributedData { +class DeviceSyncAppManager { +public: + struct WhiteList { + std::string appId; + std::string bundleName; + uint32_t version; + }; + API_EXPORT static DeviceSyncAppManager &GetInstance(); + API_EXPORT void Initialize(const std::vector &lists); + API_EXPORT bool Check(const WhiteList &whiteList); + +private: + DeviceSyncAppManager(); + std::vector whiteLists_; +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_DEVICE_SYNC_APP_MANAGER_H \ No newline at end of file diff --git a/services/distributeddataservice/service/bootstrap/include/bootstrap.h b/services/distributeddataservice/service/bootstrap/include/bootstrap.h index 785eadae2..186217fc5 100644 --- a/services/distributeddataservice/service/bootstrap/include/bootstrap.h +++ b/services/distributeddataservice/service/bootstrap/include/bootstrap.h @@ -33,6 +33,7 @@ public: API_EXPORT void LoadBackup(std::shared_ptr executors); API_EXPORT void LoadAppIdMappings(); API_EXPORT void LoadThread(); + API_EXPORT void LoadDeviceSyncAppWhiteLists(); private: static constexpr const char *DEFAULT_LABEL = "distributeddata"; static constexpr const char *DEFAULT_META = "service_meta"; diff --git a/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp b/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp index 107ca6a66..41f1b755f 100644 --- a/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp +++ b/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp @@ -23,6 +23,7 @@ #include "checker/checker_manager.h" #include "cloud/cloud_config_manager.h" #include "config_factory.h" +#include "device_sync_app/device_sync_app_manager.h" #include "directory/directory_manager.h" #include "log_print.h" #include "thread/thread_manager.h" @@ -191,5 +192,18 @@ void Bootstrap::LoadThread() } ThreadManager::GetInstance().Initialize(config->minThreadNum, config->maxThreadNum, config->ipcThreadNum); } + +void Bootstrap::LoadDeviceSyncAppWhiteLists() +{ + auto *deviceSyncAppWhiteLists = ConfigFactory::GetInstance().GetDeviceSyncAppWhiteListConfig(); + if (deviceSyncAppWhiteLists == nullptr) { + return; + } + std::vector infos; + for (auto &info : deviceSyncAppWhiteLists->whiteLists) { + infos.push_back({ info.appId, info.bundleName, info.version }); + } + DeviceSyncAppManager::GetInstance().Initialize(infos); +} } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/config/BUILD.gn b/services/distributeddataservice/service/config/BUILD.gn index 4a23f2cd1..b5d636802 100644 --- a/services/distributeddataservice/service/config/BUILD.gn +++ b/services/distributeddataservice/service/config/BUILD.gn @@ -30,6 +30,7 @@ ohos_source_set("distributeddata_config") { "src/model/cloud_config.cpp", "src/model/component_config.cpp", "src/model/datashare_config.cpp", + "src/model/device_sync_app_white_list_config.cpp", "src/model/directory_config.cpp", "src/model/global_config.cpp", "src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/config/include/config_factory.h b/services/distributeddataservice/service/config/include/config_factory.h index 268ca1513..a5e9dbe08 100644 --- a/services/distributeddataservice/service/config/include/config_factory.h +++ b/services/distributeddataservice/service/config/include/config_factory.h @@ -33,7 +33,8 @@ public: API_EXPORT CloudConfig *GetCloudConfig(); API_EXPORT std::vector *GetAppIdMappingConfig(); API_EXPORT ThreadConfig *GetThreadConfig(); - API_EXPORT DataShareConfig *GetDataShareConfig(); + API_EXPORT DataShareConfig *GetDataShareConfig(); + API_EXPORT DeviceSyncAppWhiteListConfig *GetDeviceSyncAppWhiteListConfig(); private: static constexpr const char *CONF_PATH = "/system/etc/distributeddata/conf"; ConfigFactory(); diff --git a/services/distributeddataservice/service/config/include/model/device_sync_app_white_list_config.h b/services/distributeddataservice/service/config/include/model/device_sync_app_white_list_config.h new file mode 100644 index 000000000..03729b9c7 --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/device_sync_app_white_list_config.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_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DEVICE_SYNC_APP_WHITE_LIST_CONFIG_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DEVICE_SYNC_APP_WHITE_LIST_CONFIG_H + +#include "serializable/serializable.h" +namespace OHOS { +namespace DistributedData { +class DeviceSyncAppWhiteListConfig final : public Serializable { +public: + struct WhiteList final : public Serializable { + std::string appId; + std::string bundleName; + uint32_t version; + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; + }; + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; + + std::vector whiteLists; +}; +} // namespace DistributedData +} // namespace OHOS +#endif //OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DEVICE_SYNC_APP_WHITE_LIST_CONFIG_H diff --git a/services/distributeddataservice/service/config/include/model/global_config.h b/services/distributeddataservice/service/config/include/model/global_config.h index 1ce17a445..751b91f2e 100644 --- a/services/distributeddataservice/service/config/include/model/global_config.h +++ b/services/distributeddataservice/service/config/include/model/global_config.h @@ -20,10 +20,11 @@ #include "model/checker_config.h" #include "model/cloud_config.h" #include "model/component_config.h" -#include "model/datashare_config.h" +#include "model/datashare_config.h" #include "model/directory_config.h" #include "model/network_config.h" #include "model/thread_config.h" +#include "model/device_sync_app_white_list_config.h" #include "serializable/serializable.h" namespace OHOS { namespace DistributedData { @@ -41,7 +42,8 @@ public: CloudConfig *cloud = nullptr; std::vector *appIdMapping = nullptr; ThreadConfig *thread = nullptr; - DataShareConfig *dataShare = nullptr; + DataShareConfig *dataShare = nullptr; + DeviceSyncAppWhiteListConfig *deviceSyncAppWhiteList = nullptr; ~GlobalConfig(); bool Marshal(json &node) const override; bool Unmarshal(const json &node) override; diff --git a/services/distributeddataservice/service/config/src/config_factory.cpp b/services/distributeddataservice/service/config/src/config_factory.cpp index 52445b928..781e3b55b 100644 --- a/services/distributeddataservice/service/config/src/config_factory.cpp +++ b/services/distributeddataservice/service/config/src/config_factory.cpp @@ -92,9 +92,14 @@ ThreadConfig *ConfigFactory::GetThreadConfig() return config_.thread; } -DataShareConfig *ConfigFactory::GetDataShareConfig() +DataShareConfig *ConfigFactory::GetDataShareConfig() { - return config_.dataShare; + return config_.dataShare; +} + +DeviceSyncAppWhiteListConfig *ConfigFactory::GetDeviceSyncAppWhiteListConfig() +{ + return config_.deviceSyncAppWhiteList; } } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp b/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp new file mode 100644 index 000000000..0aa91246e --- /dev/null +++ b/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "model/device_sync_app_white_list_config.h" +namespace OHOS { +namespace DistributedData { +bool DeviceSyncAppWhiteListConfig::Marshal(Serializable::json &node) const +{ + SetValue(node[GET_NAME(whiteLists)], whiteLists); + return true; +} +bool DeviceSyncAppWhiteListConfig::Unmarshal(const Serializable::json &node) +{ + GetValue(node, GET_NAME(whiteLists), whiteLists); + return true; +} + +bool DeviceSyncAppWhiteListConfig::WhiteList::Marshal(Serializable::json &node) const +{ + SetValue(node[GET_NAME(appId)], appId); + SetValue(node[GET_NAME(bundleName)], bundleName); + SetValue(node[GET_NAME(version)], version); + return true; +} +bool DeviceSyncAppWhiteListConfig::WhiteList::Unmarshal(const Serializable::json &node) +{ + GetValue(node, GET_NAME(appId), appId); + GetValue(node, GET_NAME(bundleName), bundleName); + GetValue(node, GET_NAME(version), version); + return true; +} +} // namespace DistributedData +} // namespace OHOS diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.cpp b/services/distributeddataservice/service/rdb/rdb_general_store.cpp index 55beb04f8..34f613db9 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.cpp +++ b/services/distributeddataservice/service/rdb/rdb_general_store.cpp @@ -26,6 +26,7 @@ #include "cloud/cloud_mark.h" #include "cloud/cloud_store_types.h" #include "cloud/schema_meta.h" +#include "device_sync_app/device_sync_app_manager.h" #include "cloud_service.h" #include "commonevent/data_sync_event.h" #include "communicator/device_manager_adapter.h" @@ -927,8 +928,10 @@ int32_t RdbGeneralStore::SetDistributedTables(const std::vector &ta return GeneralError::E_ERROR; } auto [exist, database] = GetDistributedSchema(observer_.meta_); - if (exist) { - delegate_->SetDistributedSchema(GetGaussDistributedSchema(database)); + if (exist && type == DistributedTableType::DISTRIBUTED_DEVICE) { + auto force = DeviceSyncAppManager::GetInstance().Check( + {observer_.meta_.appId, observer_.meta_.bundleName, database.version}); + delegate_->SetDistributedSchema(GetGaussDistributedSchema(database), force); } CloudMark metaData(storeInfo_); if (MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData, true) && metaData.isClearWaterMark) { -- Gitee From b077b010db6430e466696c14f8936a8c55d5624a Mon Sep 17 00:00:00 2001 From: zhangdi Date: Wed, 23 Apr 2025 00:36:18 +0800 Subject: [PATCH 194/225] =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E7=99=BD=E5=90=8D=E5=8D=95=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangdi --- .../framework/device_sync_app/device_sync_app_manager.cpp | 5 +---- .../config/src/model/device_sync_app_white_list_config.cpp | 2 +- .../service/config/src/model/global_config.cpp | 7 +++++-- services/distributeddataservice/service/test/BUILD.gn | 5 ++++- .../service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn | 3 ++- .../service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn | 3 ++- .../test/fuzztest/objectservicestub_fuzzer/BUILD.gn | 3 ++- .../service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn | 3 ++- 8 files changed, 19 insertions(+), 12 deletions(-) mode change 100755 => 100644 services/distributeddataservice/service/test/BUILD.gn diff --git a/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp b/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp index 05cc45f39..e20ee46ef 100644 --- a/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp +++ b/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp @@ -15,9 +15,6 @@ #define LOG_TAG "DeviceSyncAppManager" #include "device_sync_app/device_sync_app_manager.h" -#include "log_print.h" -#include "types.h" -#include "unistd.h" namespace OHOS::DistributedData { DeviceSyncAppManager::DeviceSyncAppManager() { @@ -38,7 +35,7 @@ void DeviceSyncAppManager::Initialize(const std::vector &lists) bool DeviceSyncAppManager::Check(const WhiteList &whiteList) { - for (auto &info : whiteLists_) { + for (const auto &info : whiteLists_) { if (info.appId == whiteList.appId && (info.bundleName == whiteList.bundleName) && (info.version == whiteList.version)) { return true; diff --git a/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp b/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp index 0aa91246e..594d3f2ae 100644 --- a/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp +++ b/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 diff --git a/services/distributeddataservice/service/config/src/model/global_config.cpp b/services/distributeddataservice/service/config/src/model/global_config.cpp index d00583f24..1956f8218 100644 --- a/services/distributeddataservice/service/config/src/model/global_config.cpp +++ b/services/distributeddataservice/service/config/src/model/global_config.cpp @@ -30,7 +30,8 @@ bool GlobalConfig::Marshal(json &node) const SetValue(node[GET_NAME(cloud)], cloud); SetValue(node[GET_NAME(appIdMapping)], appIdMapping); SetValue(node[GET_NAME(thread)], thread); - SetValue(node[GET_NAME(dataShare)], dataShare); + SetValue(node[GET_NAME(dataShare)], dataShare); + SetValue(node[GET_NAME(deviceSyncAppWhiteList)], deviceSyncAppWhiteList); return true; } @@ -48,7 +49,8 @@ bool GlobalConfig::Unmarshal(const json &node) GetValue(node, GET_NAME(cloud), cloud); GetValue(node, GET_NAME(appIdMapping), appIdMapping); GetValue(node, GET_NAME(thread), thread); - GetValue(node, GET_NAME(dataShare), dataShare); + GetValue(node, GET_NAME(dataShare), dataShare); + GetValue(node, GET_NAME(deviceSyncAppWhiteList), deviceSyncAppWhiteList); return true; } @@ -62,6 +64,7 @@ GlobalConfig::~GlobalConfig() delete cloud; delete appIdMapping; delete thread; + delete deviceSyncAppWhiteList; } } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn old mode 100755 new mode 100644 index 022dd5ef9..153fa09f2 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -86,6 +86,7 @@ ohos_unittest("CloudDataTest") { "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", @@ -183,6 +184,7 @@ ohos_unittest("CloudServiceImplTest") { "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", @@ -656,9 +658,9 @@ ohos_unittest("RdbServiceImplTest") { } module_out_path = module_output_path sources = [ + "mock/checker_mock.cpp", "mock/db_change_data_mock.cpp", "mock/db_store_mock.cpp", - "mock/checker_mock.cpp", "rdb_service_impl_test.cpp", ] @@ -1683,6 +1685,7 @@ ohos_unittest("BootStrapMockTest") { "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn index 94c5b63cb..ca4c9f005 100644 --- a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn @@ -82,7 +82,8 @@ ohos_fuzztest("CloudServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", - "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn index c4b2cd891..87efa4b39 100644 --- a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn @@ -69,7 +69,8 @@ ohos_fuzztest("KvdbServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", - "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn index 5f3f05b54..e3d93e45b 100755 --- a/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn @@ -68,7 +68,8 @@ ohos_fuzztest("ObjectServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", - "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn index 302d59f33..e9d34a5d4 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn @@ -74,7 +74,8 @@ ohos_fuzztest("RdbServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", - "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", -- Gitee From 0588711b972f2c93fdd8940ffd1050ecd885b7ea Mon Sep 17 00:00:00 2001 From: wTong6 Date: Tue, 22 Apr 2025 15:16:45 +0800 Subject: [PATCH 195/225] test Signed-off-by: wTong6 --- .../service/test/cloud_service_impl_test.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/services/distributeddataservice/service/test/cloud_service_impl_test.cpp b/services/distributeddataservice/service/test/cloud_service_impl_test.cpp index 413807f6f..7f1ca2f0f 100644 --- a/services/distributeddataservice/service/test/cloud_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/cloud_service_impl_test.cpp @@ -272,6 +272,23 @@ HWTEST_F(CloudServiceImplTest, GetCloudInfoFromServer001, TestSize.Level0) EXPECT_EQ(status, CloudData::CloudService::SERVER_UNAVAILABLE); } +/** + * @tc.name: GetCloudInfoFromServer002 + * @tc.desc: Test GetCloudInfoFromServer functions with cloudinfo is empty. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudServiceImplTest, GetCloudInfoFromServer002, TestSize.Level0) +{ + ZLOGI("CloudServiceImplTest GetCloudInfoFromServer002 start"); + CloudServer cloudServer; + CloudServer::RegisterCloudInstance(&cloudServer); + int user = 100; + auto [status, result] = cloudServiceImpl_->GetCloudInfoFromServer(user); + EXPECT_EQ(status, E_ERROR); + CloudServer::instance_ = nullptr; +} + /** * @tc.name: ReleaseUserInfo001 * @tc.desc: Test ReleaseUserInfo functions with invalid parameter. -- Gitee From c0e2c22cadce4044a53d7338471d700694aa577d Mon Sep 17 00:00:00 2001 From: yangliu Date: Wed, 23 Apr 2025 11:28:33 +0800 Subject: [PATCH 196/225] fix Signed-off-by: yangliu --- .../distributeddataservice/app/src/kvstore_meta_manager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 06b07a9c1..304048400 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -584,8 +584,8 @@ void KvStoreMetaManager::CheckMetaDeviceId() deviceMeta.oldUuid = deviceMeta.newUuid; deviceMeta.newUuid = localUuid; MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true); - ZLOGI("meta changed! curruuid:%{public}s, olduuid:%{public}s", - deviceMeta.newUuid.c_str(), deviceMeta.oldUuid.c_str()); + ZLOGI("meta changed! curruuid:%{public}s, olduuid:%{public}s", Anonymous::Change(deviceMeta.newUuid).c_str(), + Anonymous::Change(deviceMeta.oldUuid).c_str()); } } -- Gitee From 71a630e9ea7030a8ceb2c39762a25c47c4acd782 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E5=AD=90=E6=9D=8E?= Date: Tue, 22 Apr 2025 20:24:21 +0800 Subject: [PATCH 197/225] service MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 木子李 --- .../service/udmf/preprocess/preprocess_utils.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index 0cf277aa7..b42a9d907 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -337,7 +337,7 @@ void PreProcessUtils::ProcessRecord(std::shared_ptr record, uint3 { record->ComputeUris([&uris, &isLocal, &tokenId] (UriInfo &uriInfo) { std::string newUriStr = ""; - if (isLocal) { + if (isLocal && uriInfo.authUri.empty()) { Uri tmpUri(uriInfo.oriUri); std::string path = tmpUri.GetPath(); std::string bundleName; @@ -353,7 +353,7 @@ void PreProcessUtils::ProcessRecord(std::shared_ptr record, uint3 } uriInfo.authUri = newUriStr; } else { - newUriStr = uriInfo.dfsUri; + newUriStr = isLocal ? uriInfo.authUri : uriInfo.dfsUri; } Uri uri(newUriStr); if (uri.GetAuthority().empty()) { -- Gitee From 6faf467e9f6394bd0fded50cf3061bb8eba0ee2b Mon Sep 17 00:00:00 2001 From: yanhui Date: Sat, 19 Apr 2025 18:12:18 +0800 Subject: [PATCH 198/225] =?UTF-8?q?session=E4=B8=AD=E5=A2=9E=E5=8A=A0store?= =?UTF-8?q?Id=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yanhui Change-Id: I2879464abe18be43d0b4ab5e2f9c9183234ef648 --- .../route_head_handler_impl.cpp | 48 ++++++++++++++++--- .../session_manager/route_head_handler_impl.h | 8 ++++ .../src/session_manager/session_manager.cpp | 3 ++ .../app/src/session_manager/session_manager.h | 1 + 4 files changed, 53 insertions(+), 7 deletions(-) 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 f52cde722..787729e59 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 @@ -113,7 +113,8 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize return DistributedDB::DB_ERROR; } size_t expectSize = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair) - + session_.targetUserIds.size() * sizeof(int) + sizeof(SessionAppId) + session_.appId.size(); + + session_.targetUserIds.size() * sizeof(int) + sizeof(SessionAppId) + session_.appId.size() + + sizeof(SessionStoreId) + session_.storeId.size(); // align message uint width headSize = GET_ALIGNED_SIZE(expectSize, ALIGN_WIDTH); @@ -194,16 +195,24 @@ bool RouteHeadHandlerImpl::PackDataBody(uint8_t *data, uint32_t totalLen) ptr += (sizeof(SessionUserPair) + session_.targetUserIds.size() * sizeof(int)); SessionAppId *appPair = reinterpret_cast(ptr); - ptr += sizeof(SessionAppId); - - uint8_t *end = data + totalLen; uint32_t appIdSize = session_.appId.size(); - ret = memcpy_s(appPair->appId, end - ptr, session_.appId.data(), appIdSize); + appPair->len = HostToNet(appIdSize); + ret = strcpy_s(appPair->appId, SessionAppId::MAX_APP_ID_LEN, session_.appId.c_str()); if (ret != 0) { ZLOGE("strcpy for app id failed, error:%{public}d", errno); return false; } - appPair->len = HostToNet(appIdSize); + ptr += (sizeof(SessionAppId) + appIdSize); + + uint8_t *end = data + totalLen; + SessionStoreId *storePair = reinterpret_cast(ptr); + uint32_t storeIdSize = session_.storeId.size(); + ret = memcpy_s(storePair->storeId, end - ptr, session_.storeId.data(), storeIdSize); + if (ret != 0) { + ZLOGE("strcpy for store id failed, error:%{public}d", errno); + return false; + } + storePair->len = HostToNet(storeIdSize); return true; } @@ -222,6 +231,9 @@ bool RouteHeadHandlerImpl::ParseHeadDataLen(const uint8_t *data, uint32_t totalL std::string RouteHeadHandlerImpl::ParseStoreId(const std::string &deviceId, const std::string &label) { + if (!session_.storeId.empty()) { + return session_.storeId; + } std::vector metaData; auto prefix = StoreMetaData::GetPrefix({ deviceId }); if (!MetaDataManager::GetInstance().LoadMeta(prefix, metaData)) { @@ -255,7 +267,7 @@ bool RouteHeadHandlerImpl::ParseHeadDataUser(const uint8_t *data, uint32_t total metaData.deviceId = session_.targetDeviceId; metaData.user = DEFAULT_USERID; metaData.bundleName = session_.appId; - metaData.storeId = storeId; + metaData.storeId = std::move(storeId); if (!MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData)) { int foregroundUserId = 0; AccountDelegate::GetInstance()->QueryForegroundUserId(foregroundUserId); @@ -369,6 +381,28 @@ bool RouteHeadHandlerImpl::UnPackDataBody(const uint8_t *data, uint32_t totalLen return false; } session_.appId.append(appId->appId, appIdLen); + leftSize -= (sizeof(SessionAppId) + appIdLen); + if (leftSize > 0) { + ptr += (sizeof(SessionAppId) + appIdLen); + return UnPackStoreId(ptr, leftSize); + } + return true; +} + +bool RouteHeadHandlerImpl::UnPackStoreId(const uint8_t *data, uint32_t leftSize) +{ + if (leftSize < sizeof(SessionStoreId)) { + ZLOGE("failed to parse store id, leftSize:%{public}d.", leftSize); + return false; + } + const uint8_t *ptr = data; + const SessionStoreId *storeId = reinterpret_cast(ptr); + auto storeIdLen = NetToHost(storeId->len); + if (leftSize - sizeof(SessionStoreId) < storeIdLen) { + ZLOGE("failed to parse store id, storeIdLen:%{public}d, leftSize:%{public}d.", storeIdLen, leftSize); + return false; + } + session_.storeId = std::string(storeId->storeId, storeIdLen); return true; } } // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h index f23360dd7..163d958c2 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h @@ -50,9 +50,16 @@ struct SessionUserPair { }; struct SessionAppId { + static constexpr int32_t MAX_APP_ID_LEN = 256; uint32_t len; char appId[0]; }; + +struct SessionStoreId { + static constexpr int32_t MAX_STORE_ID_LEN = 256; + uint32_t len; + char storeId[0]; +}; #pragma pack() class RouteHeadHandlerImpl : public DistributedData::RouteHeadHandler { @@ -74,6 +81,7 @@ private: bool UnPackDataHead(const uint8_t *data, uint32_t totalLen, RouteHead &routeHead); bool UnPackDataBody(const uint8_t *data, uint32_t totalLen); std::string ParseStoreId(const std::string &deviceId, const std::string &label); + bool UnPackStoreId(const uint8_t *data, uint32_t leftSize); std::string userId_; std::string appId_; diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.cpp b/services/distributeddataservice/app/src/session_manager/session_manager.cpp index 4b5d6eaae..1ef5c834a 100644 --- a/services/distributeddataservice/app/src/session_manager/session_manager.cpp +++ b/services/distributeddataservice/app/src/session_manager/session_manager.cpp @@ -44,6 +44,7 @@ Session SessionManager::GetSession(const SessionPoint &local, const std::string ZLOGD("begin. peer device:%{public}s", Anonymous::Change(targetDeviceId).c_str()); Session session; session.appId = local.appId; + session.storeId = local.storeId; session.sourceUserId = local.userId; session.sourceDeviceId = local.deviceId; session.targetDeviceId = targetDeviceId; @@ -163,6 +164,7 @@ bool Session::Marshal(json &node) const ret = SetValue(node[GET_NAME(sourceUserId)], sourceUserId) && ret; ret = SetValue(node[GET_NAME(targetUserIds)], targetUserIds) && ret; ret = SetValue(node[GET_NAME(appId)], appId) && ret; + ret = SetValue(node[GET_NAME(storeId)], storeId) && ret; return ret; } @@ -174,6 +176,7 @@ bool Session::Unmarshal(const json &node) ret = GetValue(node, GET_NAME(sourceUserId), sourceUserId) && ret; ret = GetValue(node, GET_NAME(targetUserIds), targetUserIds) && ret; ret = GetValue(node, GET_NAME(appId), appId) && ret; + ret = GetValue(node, GET_NAME(storeId), storeId) && ret; return ret; } } // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.h b/services/distributeddataservice/app/src/session_manager/session_manager.h index ca83970bc..c72c1bef1 100644 --- a/services/distributeddataservice/app/src/session_manager/session_manager.h +++ b/services/distributeddataservice/app/src/session_manager/session_manager.h @@ -39,6 +39,7 @@ public: uint32_t sourceUserId; std::vector targetUserIds; std::string appId; + std::string storeId; bool Marshal(json &node) const override; bool Unmarshal(const json &node) override; inline bool IsValid() -- Gitee From f2d4ca79e8e6e26d9a9642c68800bb26acf2ac70 Mon Sep 17 00:00:00 2001 From: Axi_Beft Date: Wed, 26 Mar 2025 11:05:21 +0800 Subject: [PATCH 199/225] object cppCheck fix Signed-off-by: Axi_Beft --- bundle.json | 1 + .../app/src/kvstore_data_service.cpp | 3 ++ .../service/data_share/BUILD.gn | 2 ++ .../data_share/data_share_service_impl.cpp | 29 ++++++++++++++---- .../data_share/data_share_service_impl.h | 1 + .../data_share/data_share_service_stub.cpp | 30 ++++++++++++++++++- .../data_share/data_share_service_stub.h | 1 + .../object/src/object_asset_machine.cpp | 8 ++--- .../service/object/src/object_manager.cpp | 4 +-- .../service/test/BUILD.gn | 2 ++ .../datashareservicestub_fuzzer/BUILD.gn | 2 ++ 11 files changed, 71 insertions(+), 12 deletions(-) diff --git a/bundle.json b/bundle.json index b1a8472db..e80707c82 100644 --- a/bundle.json +++ b/bundle.json @@ -81,6 +81,7 @@ "napi", "netmanager_base", "os_account", + "qos_manager", "relational_store", "resource_management", "safwk", diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index 8d732f7d0..5b034427d 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -319,6 +319,9 @@ void KvStoreDataService::OnStart() } AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); AddSystemAbilityListener(MEMORY_MANAGER_SA_ID); + AddSystemAbilityListener(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID); + AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN); + AddSystemAbilityListener(CONCURRENT_TASK_SERVICE_ID); RegisterStoreInfo(); Handler handlerStoreInfo = std::bind(&KvStoreDataService::DumpStoreInfo, this, std::placeholders::_1, std::placeholders::_2); diff --git a/services/distributeddataservice/service/data_share/BUILD.gn b/services/distributeddataservice/service/data_share/BUILD.gn index 2964c14db..d119714fd 100644 --- a/services/distributeddataservice/service/data_share/BUILD.gn +++ b/services/distributeddataservice/service/data_share/BUILD.gn @@ -132,6 +132,8 @@ ohos_source_set("data_share_service") { "json:nlohmann_json_static", "kv_store:datamgr_common", "kv_store:distributeddb", + "qos_manager:concurrent_task_client", + "qos_manager:qos", "relational_store:native_rdb", "relational_store:rdb_data_share_adapter", "samgr:samgr_proxy", diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp index 02b2ce855..8829f0151 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp @@ -24,6 +24,7 @@ #include "app_connect_manager.h" #include "common_event_manager.h" #include "common_event_support.h" +#include "concurrent_task_client.h" #include "data_ability_observer_interface.h" #include "data_share_profile_config.h" #include "dataobs_mgr_client.h" @@ -83,11 +84,17 @@ public: void DataShareServiceImpl::SystemAbilityStatusChangeListener::OnAddSystemAbility( int32_t systemAbilityId, const std::string &deviceId) { - if (systemAbilityId != COMMON_EVENT_SERVICE_ID) { - return; - } - ZLOGI("Common event service start. saId:%{public}d", systemAbilityId); - InitSubEvent(); + ZLOGI("saId:%{public}d", systemAbilityId); + if (systemAbilityId == COMMON_EVENT_SERVICE_ID) { + InitSubEvent(); + } else if (systemAbilityId == CONCURRENT_TASK_SERVICE_ID) { + std::unordered_map payload; + // get current thread pid + payload["pid"] = std::to_string(getpid()); + // request qos auth for current pid + OHOS::ConcurrentTask::ConcurrentTaskClient::GetInstance().RequestAuth(payload); + } + return; } DataShareServiceImpl::Factory::Factory() @@ -589,6 +596,7 @@ int32_t DataShareServiceImpl::OnBind(const BindInfo &binderInfo) DBDelegate::SetExecutorPool(binderInfo.executors); HiViewAdapter::GetInstance().SetThreadPool(binderInfo.executors); SubscribeCommonEvent(); + SubscribeConcurrentTask(); SubscribeTimeChanged(); SubscribeChange(); ZLOGI("end"); @@ -606,6 +614,17 @@ void DataShareServiceImpl::SubscribeCommonEvent() systemManager->SubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, callback); } +void DataShareServiceImpl::SubscribeConcurrentTask() +{ + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + ZLOGE("System mgr is nullptr"); + return; + } + sptr callback(new SystemAbilityStatusChangeListener()); + systemManager->SubscribeSystemAbility(CONCURRENT_TASK_SERVICE_ID, callback); +} + void DataShareServiceImpl::SubscribeChange() { EventCenter::GetInstance().Subscribe(RemoteChangeEvent::RDB_META_SAVE, [this](const Event &event) { diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.h b/services/distributeddataservice/service/data_share/data_share_service_impl.h index e4d0a7d9d..1b7e57ba6 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_impl.h +++ b/services/distributeddataservice/service/data_share/data_share_service_impl.h @@ -125,6 +125,7 @@ private: std::pair GetCallerInfo(std::string &bundleName, int32_t &appIndex); int32_t GetBMSAndMetaDataStatus(const std::string &uri, const int32_t tokenId); void SubscribeCommonEvent(); + void SubscribeConcurrentTask(); static void InitSubEvent(); void AutoLaunch(const DistributedData::Event &event); void SubscribeChange(); diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp index d0b000ee9..0fd187e9b 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp @@ -27,10 +27,25 @@ #include "ishared_result_set.h" #include "itypes_util.h" #include "log_print.h" +#include "qos.h" #include "utils/anonymous.h" namespace OHOS { namespace DataShare { + +class DataShareServiceStub::QosManager { +public: + QosManager() + { + // set thread qos QOS_USER_INTERACTIVE + QOS::SetThreadQos(QOS::QosLevel::QOS_USER_INTERACTIVE); + } + ~QosManager() + { + QOS::ResetThreadQos(); + } +}; + bool DataShareServiceStub::CheckInterfaceToken(MessageParcel &data) { auto localDescriptor = IDataShareService::GetDescriptor(); @@ -53,6 +68,8 @@ int32_t DataShareServiceStub::OnInsertEx(MessageParcel &data, MessageParcel &rep return IPC_STUB_INVALID_DATA_ERR; } auto [errCode, status] = InsertEx(uri, extUri, bucket); + ZLOGI("Insert uri:%{public}s, errCode:%{public}x, status:%{public}x", + DistributedData::Anonymous::Change(uri).c_str(), errCode, status); if (!ITypesUtil::Marshal(reply, errCode, status)) { ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status); return IPC_STUB_WRITE_PARCEL_ERR; @@ -72,6 +89,8 @@ int32_t DataShareServiceStub::OnUpdateEx(MessageParcel &data, MessageParcel &rep return IPC_STUB_INVALID_DATA_ERR; } auto [errCode, status] = UpdateEx(uri, extUri, predicate, bucket); + ZLOGI("Update uri:%{public}s, errCode:%{public}x, status:%{public}x", + DistributedData::Anonymous::Change(uri).c_str(), errCode, status); if (!ITypesUtil::Marshal(reply, errCode, status)) { ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status); return IPC_STUB_WRITE_PARCEL_ERR; @@ -89,6 +108,8 @@ int32_t DataShareServiceStub::OnDeleteEx(MessageParcel &data, MessageParcel &rep return IPC_STUB_INVALID_DATA_ERR; } auto [errCode, status] = DeleteEx(uri, extUri, predicate); + ZLOGI("Delete uri:%{public}s, errCode:%{public}x, status:%{public}x", + DistributedData::Anonymous::Change(uri).c_str(), errCode, status); if (!ITypesUtil::Marshal(reply, errCode, status)) { ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status); return IPC_STUB_WRITE_PARCEL_ERR; @@ -347,6 +368,12 @@ bool DataShareServiceStub::CheckSystemUidCallingPermission(uint32_t tokenId, uin int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply) { + // set thread qos + DataShareServiceStub::QosManager qos; + // check thread qos + QOS::QosLevel curLevel; + int qosRet = QOS::GetThreadQos(curLevel); + int tryTimes = TRY_TIMES; while (!isReady_.load() && tryTimes > 0) { tryTimes--; @@ -363,7 +390,8 @@ int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Me code = code - DATA_SHARE_CMD_SYSTEM_CODE; } if (code != DATA_SHARE_SERVICE_CMD_QUERY && code != DATA_SHARE_SERVICE_CMD_GET_SILENT_PROXY_STATUS) { - ZLOGI("code:%{public}u, callingPid:%{public}d", code, callingPid); + ZLOGI("code:%{public}u, callingPid:%{public}d, qosRet:%{public}d, curLevel:%{public}d", + code, callingPid, qosRet, curLevel); } if (!CheckInterfaceToken(data)) { return DATA_SHARE_ERROR; diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.h b/services/distributeddataservice/service/data_share/data_share_service_stub.h index b84c26967..aafe8e8cb 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_stub.h +++ b/services/distributeddataservice/service/data_share/data_share_service_stub.h @@ -27,6 +27,7 @@ public: void SetServiceReady(); private: + class QosManager; static constexpr std::chrono::milliseconds TIME_THRESHOLD = std::chrono::milliseconds(500); static bool CheckInterfaceToken(MessageParcel& data); bool CheckProxyCallingPermission(uint32_t tokenId); diff --git a/services/distributeddataservice/service/object/src/object_asset_machine.cpp b/services/distributeddataservice/service/object/src/object_asset_machine.cpp index dcb034ad9..6d1d11fb7 100644 --- a/services/distributeddataservice/service/object/src/object_asset_machine.cpp +++ b/services/distributeddataservice/service/object/src/object_asset_machine.cpp @@ -57,12 +57,12 @@ static int32_t Recover(int32_t eventId, ChangedAssetInfo& changedAsset, Asset& a static int32_t UpdateStore(ChangedAssetInfo& changedAsset); -static AutoCache::Store GetStore(ChangedAssetInfo& changedAsset); +static AutoCache::Store GetStore(const ChangedAssetInfo& changedAsset); static VBuckets GetMigratedData(AutoCache::Store& store, AssetBindInfo& assetBindInfo, const Asset& newAsset); static void MergeAssetData(VBucket& record, const Asset& newAsset, const AssetBindInfo& assetBindInfo); static void MergeAsset(Asset& oldAsset, const Asset& newAsset); static std::string BuildSql(const AssetBindInfo& bindInfo, Values& args); -static BindEvent::BindEventInfo MakeBindInfo(ChangedAssetInfo& changedAsset); +static BindEvent::BindEventInfo MakeBindInfo(const ChangedAssetInfo& changedAsset); static const DFAAction AssetDFA[STATUS_BUTT][EVENT_BUTT] = { { @@ -287,7 +287,7 @@ static void MergeAsset(Asset& oldAsset, const Asset& newAsset) oldAsset.path = newAsset.path; } -static AutoCache::Store GetStore(ChangedAssetInfo& changedAsset) +static AutoCache::Store GetStore(const ChangedAssetInfo& changedAsset) { StoreMetaData meta; meta.storeId = changedAsset.bindInfo.storeName; @@ -347,7 +347,7 @@ static int32_t Recover(int32_t eventId, ChangedAssetInfo& changedAsset, Asset& a return E_OK; } -static BindEvent::BindEventInfo MakeBindInfo(ChangedAssetInfo& changedAsset) +static BindEvent::BindEventInfo MakeBindInfo(const ChangedAssetInfo& changedAsset) { BindEvent::BindEventInfo bindEventInfo; bindEventInfo.bundleName = changedAsset.storeInfo.bundleName; diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 3e3c554ff..63f90ce8c 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -847,7 +847,7 @@ int32_t ObjectStoreManager::SaveToStore(const std::string &appId, const std::str saveInfoEntry.value = std::vector(saveInfoValue.begin(), saveInfoValue.end()); std::vector entries; entries.emplace_back(saveInfoEntry); - for (auto &item : data) { + for (const auto &item : data) { DistributedDB::Entry entry; std::string key = GetPropertyPrefix(appId, sessionId, toDeviceId) + timestamp + SEPERATOR + item.first; entry.key = std::vector(key.begin(), key.end()); @@ -1110,7 +1110,7 @@ SequenceSyncManager::Result SequenceSyncManager::Process( return ERR_SID_NOT_EXIST; } std::map syncResults; - for (auto &item : results) { + for (const auto &item : results) { syncResults[item.first] = item.second == DistributedDB::DBStatus::OK ? 0 : -1; } seqIdCallbackRelations_[sequenceId](syncResults); diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index c4d836733..133b8e5d1 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -1072,6 +1072,8 @@ ohos_unittest("DataShareServiceImplTest") { "json:nlohmann_json_static", "kv_store:distributeddata_inner", "kv_store:distributeddb", + "qos_manager:concurrent_task_client", + "qos_manager:qos", "relational_store:native_rdb", "relational_store:rdb_data_share_adapter", "resource_management:global_resmgr", diff --git a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn index 67dd09415..d9a46ea9f 100644 --- a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn @@ -129,6 +129,8 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "ipc:ipc_core", "kv_store:distributeddata_inner", "kv_store:distributeddb", + "qos_manager:concurrent_task_client", + "qos_manager:qos", "relational_store:native_rdb", "relational_store:rdb_data_share_adapter", "resource_management:global_resmgr", -- Gitee From c00aba9ead27509eb2c4855b001a71ae0a0f0f44 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Thu, 24 Apr 2025 03:42:09 +0000 Subject: [PATCH 200/225] =?UTF-8?q?=E7=94=A8=E4=BE=8B=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E6=95=B4=E6=94=B9-0424?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- services/distributeddataservice/service/test/BUILD.gn | 1 - 1 file changed, 1 deletion(-) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 153fa09f2..cc5dd09b6 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -2014,7 +2014,6 @@ group("unittest") { ":KvdbServiceImplTest", ":QueryHelperUnitTest", ":UpgradeMockTest", - ":UserDelegateMockTest", ] } -- Gitee From 490b02904818370ec02c4f0245558aa7cb9951c6 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Thu, 24 Apr 2025 05:56:39 +0000 Subject: [PATCH 201/225] =?UTF-8?q?=E7=94=A8=E4=BE=8B=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E6=95=B4=E6=94=B9-0424?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .../service/test/BUILD.gn | 1 + .../service/test/user_delegate_mock_test.cpp | 20 ------------------- 2 files changed, 1 insertion(+), 20 deletions(-) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index cc5dd09b6..153fa09f2 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -2014,6 +2014,7 @@ group("unittest") { ":KvdbServiceImplTest", ":QueryHelperUnitTest", ":UpgradeMockTest", + ":UserDelegateMockTest", ] } diff --git a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp index 373782b7e..ee950af35 100644 --- a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp +++ b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp @@ -76,26 +76,6 @@ HWTEST_F(UserDelegateMockTest, GetLocalUserStatus, TestSize.Level0) EXPECT_TRUE(vec.empty()); } -/** -* @tc.name: InitLocalUserMeta -* @tc.desc: test InitLocalUserMeta -* @tc.type: FUNC -* @tc.require: -*/ -HWTEST_F(UserDelegateMockTest, InitLocalUserMeta, TestSize.Level0) -{ - EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)).WillOnce(Return(false)); - bool ret = UserDelegate::GetInstance().InitLocalUserMeta(); - EXPECT_FALSE(ret); - - std::vector users; - EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) - .WillRepeatedly(DoAll(SetArgReferee<0>(users), Return(true))); - ret = UserDelegate::GetInstance().InitLocalUserMeta(); - UserDelegate::GetInstance().DeleteUsers("users"); - EXPECT_FALSE(ret); -} - /** * @tc.name: GetLocalUsers * @tc.desc: test GetLocalUsers -- Gitee From a6adf6300758dd5ecc802cf45d081b1e12370f9a Mon Sep 17 00:00:00 2001 From: suoqilong Date: Thu, 24 Apr 2025 07:29:56 +0000 Subject: [PATCH 202/225] =?UTF-8?q?=E7=94=A8=E4=BE=8B=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E6=95=B4=E6=94=B9-0424?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .../service/test/BUILD.gn | 1 - .../service/test/user_delegate_mock_test.cpp | 20 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 153fa09f2..cc5dd09b6 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -2014,7 +2014,6 @@ group("unittest") { ":KvdbServiceImplTest", ":QueryHelperUnitTest", ":UpgradeMockTest", - ":UserDelegateMockTest", ] } diff --git a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp index ee950af35..373782b7e 100644 --- a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp +++ b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp @@ -76,6 +76,26 @@ HWTEST_F(UserDelegateMockTest, GetLocalUserStatus, TestSize.Level0) EXPECT_TRUE(vec.empty()); } +/** +* @tc.name: InitLocalUserMeta +* @tc.desc: test InitLocalUserMeta +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UserDelegateMockTest, InitLocalUserMeta, TestSize.Level0) +{ + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)).WillOnce(Return(false)); + bool ret = UserDelegate::GetInstance().InitLocalUserMeta(); + EXPECT_FALSE(ret); + + std::vector users; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(users), Return(true))); + ret = UserDelegate::GetInstance().InitLocalUserMeta(); + UserDelegate::GetInstance().DeleteUsers("users"); + EXPECT_FALSE(ret); +} + /** * @tc.name: GetLocalUsers * @tc.desc: test GetLocalUsers -- Gitee From 41ed1549c70eb81bc4cb45459bf552df2308666f Mon Sep 17 00:00:00 2001 From: yanhui Date: Thu, 24 Apr 2025 20:35:11 +0800 Subject: [PATCH 203/225] =?UTF-8?q?=E6=94=B9=E7=94=A8appIdSize?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yanhui Change-Id: Iaa10858b1fd80e77da3910f66284580a08b7302d --- .../app/src/session_manager/route_head_handler_impl.cpp | 2 +- .../app/src/session_manager/route_head_handler_impl.h | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) 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 787729e59..d7feaea8e 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 @@ -197,7 +197,7 @@ bool RouteHeadHandlerImpl::PackDataBody(uint8_t *data, uint32_t totalLen) SessionAppId *appPair = reinterpret_cast(ptr); uint32_t appIdSize = session_.appId.size(); appPair->len = HostToNet(appIdSize); - ret = strcpy_s(appPair->appId, SessionAppId::MAX_APP_ID_LEN, session_.appId.c_str()); + ret = strcpy_s(appPair->appId, appIdSize, session_.appId.c_str()); if (ret != 0) { ZLOGE("strcpy for app id failed, error:%{public}d", errno); return false; diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h index 163d958c2..11583b7b1 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h @@ -50,13 +50,11 @@ struct SessionUserPair { }; struct SessionAppId { - static constexpr int32_t MAX_APP_ID_LEN = 256; uint32_t len; char appId[0]; }; struct SessionStoreId { - static constexpr int32_t MAX_STORE_ID_LEN = 256; uint32_t len; char storeId[0]; }; -- Gitee From 5bb779b72b2d08bc34e3405dac2ba1ae47144f41 Mon Sep 17 00:00:00 2001 From: guochao Date: Fri, 25 Apr 2025 17:09:06 +0800 Subject: [PATCH 204/225] add test Signed-off-by: guochao --- .../distributeddataservice/app/test/BUILD.gn | 1 + .../test/unittest/session_manager_test.cpp | 213 +++++++++++++----- .../service/test/mock/BUILD.gn | 9 + .../service/test/mock/auth_delegate_mock.cpp | 26 +++ .../service/test/mock/auth_delegate_mock.h | 38 ++++ .../test/mock/meta_data_manager_mock.cpp | 24 +- .../test/mock/meta_data_manager_mock.h | 23 +- .../service/test/mock/user_delegate_mock.cpp | 2 +- 8 files changed, 265 insertions(+), 71 deletions(-) create mode 100644 services/distributeddataservice/service/test/mock/auth_delegate_mock.cpp create mode 100644 services/distributeddataservice/service/test/mock/auth_delegate_mock.h diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index 384041b03..6d6ac6c66 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -185,6 +185,7 @@ ohos_unittest("SessionManagerTest") { deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/app/src/checker:distributeddata_checker", + "${data_service_path}/service/test/mock:distributeddata_mock_static", "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index 9c0ca691d..53a057e12 100644 --- a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -13,13 +13,15 @@ * limitations under the License. */ +#include "session_manager/session_manager.h" + #include "accesstoken_kit.h" #include "account_delegate_mock.h" +#include "auth_delegate_mock.h" #include "bootstrap.h" #include "device_manager_adapter.h" #include "device_manager_adapter_mock.h" #include "gtest/gtest.h" -#include "kvstore_meta_manager.h" #include "meta_data_manager_mock.h" #include "metadata/meta_data_manager.h" #include "metadata/store_meta_data.h" @@ -70,15 +72,50 @@ void GrantPermissionNative() class SessionManagerTest : public testing::Test { public: + void CreateUserStatus(std::vector &users) + { + UserStatus stat; + stat.id = 0; + UserStatus stat1; + stat.id = 1; + UserStatus stat2; + stat.id = 2; + UserStatus stat3; + stat.id = 3; + users.push_back(stat); + users.push_back(stat1); + users.push_back(stat2); + users.push_back(stat3); + } + void CreateStoreMetaData(std::vector &datas, SessionPoint local) + { + StoreMetaData data; + data.appId = local.appId; + data.storeId = local.storeId; + data.bundleName = "com.test.session"; + StoreMetaData data1; + data1.appId = local.appId; + data1.storeId = "local.storeId"; + data1.bundleName = "com.test.session1"; + StoreMetaData data2; + data2.appId = "local.appId"; + data2.storeId = local.storeId; + data2.bundleName = "com.test.session2"; + StoreMetaData data3; + data3.appId = "local.appId"; + data3.storeId = "local.storeId"; + data3.bundleName = "com.test.session3"; + datas.push_back(data); + datas.push_back(data1); + datas.push_back(data2); + datas.push_back(data3); + } static void SetUpTestCase() { auto executors = std::make_shared(12, 5); Bootstrap::GetInstance().LoadComponents(); Bootstrap::GetInstance().LoadDirectory(); Bootstrap::GetInstance().LoadCheckers(); - KvStoreMetaManager::GetInstance().BindExecutor(executors); - KvStoreMetaManager::GetInstance().InitMetaParameter(); - KvStoreMetaManager::GetInstance().InitMetaListener(); DeviceManagerAdapter::GetInstance().Init(executors); // init peer device @@ -116,6 +153,8 @@ public: BDeviceManagerAdapter::deviceManagerAdapter = deviceManagerAdapterMock; metaDataManagerMock = std::make_shared(); BMetaDataManager::metaDataManager = metaDataManagerMock; + metaDataMock = std::make_shared>(); + BMetaData::metaDataManager = metaDataMock; userDelegateMock = std::make_shared(); BUserDelegate::userDelegate = userDelegateMock; } @@ -139,6 +178,8 @@ public: BDeviceManagerAdapter::deviceManagerAdapter = nullptr; metaDataManagerMock = nullptr; BMetaDataManager::metaDataManager = nullptr; + metaDataMock = nullptr; + BMetaData::metaDataManager = nullptr; userDelegateMock = nullptr; BUserDelegate::userDelegate = nullptr; } @@ -152,31 +193,28 @@ public: void ConstructValidData() { constexpr size_t BUFFER_SIZE = sizeof(dataBuffer); - memset_s(dataBuffer, BUFFER_SIZE, 0, BUFFER_SIZE); // 清空缓冲区 + memset_s(dataBuffer, BUFFER_SIZE, 0, BUFFER_SIZE); - // 构建有效数据 RouteHead head{}; head.magic = RouteHead::MAGIC_NUMBER; head.version = RouteHead::VERSION; head.dataLen = sizeof(SessionDevicePair) + sizeof(SessionUserPair) + sizeof(uint32_t) * 1 - + sizeof(SessionAppId) + APP_STR_LEN; // 应用ID长度+内容 - head.checkSum = 0; // 假设校验和正确 + + sizeof(SessionAppId) + APP_STR_LEN; + head.checkSum = 0; - // 序列化头部 uint8_t *ptr = dataBuffer; size_t remaining = BUFFER_SIZE; - // 1. 写入RouteHead + // 1. write RouteHead errno_t err = memcpy_s(ptr, remaining, &head, sizeof(RouteHead)); ASSERT_EQ(err, 0) << "Failed to copy RouteHead"; ptr += sizeof(RouteHead); remaining -= sizeof(RouteHead); - // 2. 写入SessionDevicePair + // 2. write SessionDevicePair SessionDevicePair devPair{}; - // 安全初始化设备ID constexpr size_t DEV_ID_SIZE = sizeof(devPair.sourceId); - err = memset_s(devPair.sourceId, DEV_ID_SIZE, 'A', DEV_ID_SIZE - 1); // 留1字节给终止符 + err = memset_s(devPair.sourceId, DEV_ID_SIZE, 'A', DEV_ID_SIZE - 1); ASSERT_EQ(err, 0) << "Failed to init sourceId"; devPair.sourceId[DEV_ID_SIZE - 1] = '\0'; @@ -189,24 +227,22 @@ public: ptr += sizeof(SessionDevicePair); remaining -= sizeof(SessionDevicePair); - // 3. 写入SessionUserPair + // 3. write SessionUserPair SessionUserPair userPair{}; - userPair.sourceUserId = HostToNet(100U); // 注意字节序转换 + userPair.sourceUserId = HostToNet(100U); userPair.targetUserCount = HostToNet(1U); err = memcpy_s(ptr, remaining, &userPair, sizeof(SessionUserPair)); ASSERT_EQ(err, 0) << "Failed to copy SessionUserPair"; ptr += sizeof(SessionUserPair); remaining -= sizeof(SessionUserPair); - - // 写入目标用户ID uint32_t targetUser = HostToNet(200U); err = memcpy_s(ptr, remaining, &targetUser, sizeof(uint32_t)); ASSERT_EQ(err, 0) << "Failed to copy targetUser"; ptr += sizeof(uint32_t); remaining -= sizeof(uint32_t); - // 4. 写入SessionAppId + // 4. write SessionAppId SessionAppId appId{}; const char *appStr = "test"; @@ -217,19 +253,18 @@ public: ptr += sizeof(SessionAppId); remaining -= sizeof(SessionAppId); - // 写入应用ID内容 err = memcpy_s(ptr, remaining, appStr, APP_STR_LEN); ASSERT_EQ(err, 0) << "Failed to copy appId data"; ptr += APP_STR_LEN; remaining -= APP_STR_LEN; } - // 验证总长度 const size_t validTotalLen = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair) + sizeof(uint32_t) * 1 + sizeof(SessionAppId) + APP_STR_LEN; uint8_t dataBuffer[1024]; - static constexpr size_t APP_STR_LEN = 5; // 包括终止符 + static constexpr size_t APP_STR_LEN = 5; static inline std::shared_ptr deviceManagerAdapterMock = nullptr; static inline std::shared_ptr metaDataManagerMock = nullptr; + static inline std::shared_ptr> metaDataMock = nullptr; static inline std::shared_ptr userDelegateMock = nullptr; }; @@ -273,14 +308,10 @@ HWTEST_F(SessionManagerTest, PackAndUnPack01, TestSize.Level2) HWTEST_F(SessionManagerTest, GetHeadDataSize_Test1, TestSize.Level1) { ExtendInfo info; - // 创建RouteHeadHandlerImpl实例 RouteHeadHandlerImpl routeHeadHandlerImpl(info); uint32_t headSize = 0; - // 设置appId_为Bootstrap::GetInstance().GetProcessLabel() routeHeadHandlerImpl.appId_ = Bootstrap::GetInstance().GetProcessLabel(); - // 调用GetHeadDataSize方法 auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize); - // 验证返回状态和headSize的值 EXPECT_EQ(status, DistributedDB::OK); EXPECT_EQ(headSize, 0); } @@ -293,14 +324,10 @@ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test1, TestSize.Level1) HWTEST_F(SessionManagerTest, GetHeadDataSize_Test2, TestSize.Level1) { ExtendInfo info; - // 创建RouteHeadHandlerImpl实例 RouteHeadHandlerImpl routeHeadHandlerImpl(info); uint32_t headSize = 0; - // 设置appId_不等于Bootstrap::GetInstance().GetProcessLabel() routeHeadHandlerImpl.appId_ = "otherAppId"; - // 调用GetHeadDataSize方法 auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize); - // 验证返回状态和headSize的值 EXPECT_EQ(status, DistributedDB::OK); EXPECT_EQ(headSize, 0); } @@ -312,20 +339,15 @@ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test2, TestSize.Level1) */ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test3, TestSize.Level1) { - // 设置devInfo.osType等于OH_OS_TYPE DeviceInfo deviceInfo; deviceInfo.osType = OH_OS_TYPE; EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo)); ExtendInfo info; - // 创建RouteHeadHandlerImpl实例 RouteHeadHandlerImpl routeHeadHandlerImpl(info); uint32_t headSize = 0; - // 设置appId_不等于Bootstrap::GetInstance().GetProcessLabel() routeHeadHandlerImpl.appId_ = "otherAppId"; - // 调用GetHeadDataSize方法 auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize); - // 验证返回状态和headSize的值 - EXPECT_EQ(status, DistributedDB::OK); + EXPECT_EQ(status, DistributedDB::DB_ERROR); EXPECT_EQ(headSize, 0); } /** @@ -336,20 +358,21 @@ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test3, TestSize.Level1) */ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test4, TestSize.Level1) { + DeviceInfo deviceInfo; + deviceInfo.osType = OH_OS_TYPE; + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo)); + const DistributedDB::ExtendInfo info = { .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID }; auto sendHandler = RouteHeadHandlerImpl::Create(info); ASSERT_NE(sendHandler, nullptr); - // 设置devInfo.osType等于OH_OS_TYPE - DeviceInfo deviceInfo; - deviceInfo.osType = OH_OS_TYPE; - EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo)); + CapMetaData capMetaData; capMetaData.version = CapMetaData::CURRENT_VERSION; EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) .WillRepeatedly(DoAll(SetArgReferee<1>(capMetaData), Return(true))); - std::vector userStatus; UserStatus userStat1; UserStatus userStat2; @@ -363,9 +386,7 @@ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test4, TestSize.Level1) EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillRepeatedly(Return(userStatus)); uint32_t headSize = 0; - // 调用GetHeadDataSize方法 auto status = sendHandler->GetHeadDataSize(headSize); - // 验证返回状态和headSize的值 EXPECT_EQ(status, DistributedDB::OK); EXPECT_EQ(headSize, 0); @@ -382,22 +403,19 @@ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test4, TestSize.Level1) */ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest001, TestSize.Level1) { - // 创建RouteHeadHandlerImpl实例 + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true)); const DistributedDB::ExtendInfo info = { .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID }; auto sendHandler = RouteHeadHandlerImpl::Create(info); ASSERT_NE(sendHandler, nullptr); - // 创建测试数据 uint32_t totalLen = 10; std::string label = "testLabel"; std::vector userInfos; - // 调用待测试方法 bool result = sendHandler->ParseHeadDataUser(nullptr, totalLen, label, userInfos); - // 验证结果 EXPECT_FALSE(result); EXPECT_EQ(userInfos.size(), 0); } @@ -409,22 +427,19 @@ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest001, TestSize.Level1) */ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest002, TestSize.Level1) { - // 创建RouteHeadHandlerImpl实例 + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true)); const DistributedDB::ExtendInfo info = { .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID }; auto sendHandler = RouteHeadHandlerImpl::Create(info); ASSERT_NE(sendHandler, nullptr); - // 创建测试数据 uint8_t data[10] = { 0 }; std::string label = "testLabel"; std::vector userInfos; - // 调用待测试方法 bool result = sendHandler->ParseHeadDataUser(data, sizeof(RouteHead) - 1, label, userInfos); - // 验证结果 EXPECT_FALSE(result); EXPECT_EQ(userInfos.size(), 0); } @@ -437,14 +452,13 @@ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest002, TestSize.Level1) */ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest003, TestSize.Level1) { - // 创建RouteHeadHandlerImpl实例 + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true)); const DistributedDB::ExtendInfo info = { .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID }; auto sendHandler = RouteHeadHandlerImpl::Create(info); ASSERT_NE(sendHandler, nullptr); - // 创建测试数据 uint8_t data[10] = { 0 }; std::string label = "testLabel"; std::vector userInfos; @@ -453,10 +467,8 @@ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest003, TestSize.Level1) head.version = RouteHead::VERSION; head.dataLen = static_cast(sizeof(data) - sizeof(RouteHead)); - // 调用待测试方法 bool result = sendHandler->ParseHeadDataUser(data, sizeof(RouteHead), label, userInfos); - // 验证结果 EXPECT_FALSE(result); EXPECT_EQ(userInfos.size(), 0); } @@ -470,9 +482,8 @@ HWTEST_F(SessionManagerTest, ParseHeadDataUserTest003, TestSize.Level1) HWTEST_F(SessionManagerTest, UnPackData_InvalidMagic, TestSize.Level1) { RouteHead *head = reinterpret_cast(dataBuffer); - head->magic = 0xFFFF; // Invalid magic + head->magic = 0xFFFF; ExtendInfo info; - // 创建RouteHeadHandlerImpl实例 RouteHeadHandlerImpl routeHeadHandlerImpl(info); uint32_t unpackedSize; EXPECT_FALSE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize)); @@ -487,9 +498,8 @@ HWTEST_F(SessionManagerTest, UnPackData_InvalidMagic, TestSize.Level1) HWTEST_F(SessionManagerTest, UnPackData_VersionMismatch, TestSize.Level1) { RouteHead *head = reinterpret_cast(dataBuffer); - head->version = 0x00; // Invalid version + head->version = 0x00; ExtendInfo info; - // 创建RouteHeadHandlerImpl实例 RouteHeadHandlerImpl routeHeadHandlerImpl(info); uint32_t unpackedSize; EXPECT_FALSE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize)); @@ -504,10 +514,95 @@ HWTEST_F(SessionManagerTest, UnPackData_VersionMismatch, TestSize.Level1) HWTEST_F(SessionManagerTest, UnPackData_ValidData, TestSize.Level1) { ExtendInfo info; - // 创建RouteHeadHandlerImpl实例 RouteHeadHandlerImpl routeHeadHandlerImpl(info); uint32_t unpackedSize; EXPECT_TRUE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize)); EXPECT_EQ(unpackedSize, validTotalLen); } + +/** + * @tc.name: ShouldAddSystemUserWhenLocalUserIdIsSystem + * @tc.desc: test GetSession. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, ShouldAddSystemUserWhenLocalUserIdIsSystem, TestSize.Level1) +{ + SessionPoint local; + local.userId = UserDelegate::SYSTEM_USER; + local.appId = "test_app"; + local.deviceId = "local_device"; + local.storeId = "test_store"; + + std::vector users; + CreateUserStatus(users); + EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillOnce(Return(users)); + EXPECT_CALL(AuthHandlerMock::GetInstance(), CheckAccess(_, _, _, _)) + .WillOnce(Return(std::pair(true, true))) + .WillOnce(Return(std::pair(true, false))) + .WillOnce(Return(std::pair(false, true))) + .WillOnce(Return(std::pair(false, false))); + std::vector datas; + CreateStoreMetaData(datas, local); + EXPECT_CALL(*metaDataMock, LoadMeta(_, _, _)).WillRepeatedly(DoAll(SetArgReferee<1>(datas), Return(true))); + + Session session = SessionManager::GetInstance().GetSession(local, "target_device"); + ASSERT_EQ(2, session.targetUserIds.size()); + EXPECT_EQ(UserDelegate::SYSTEM_USER, session.targetUserIds[0]); +} + +/** + * @tc.name: ShouldReturnEarlyWhenGetSendAuthParamsFails + * @tc.desc: test GetSession. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, ShouldReturnEarlyWhenGetSendAuthParamsFails, TestSize.Level1) +{ + SessionPoint local; + local.userId = 100; + local.appId = "test_app"; + local.deviceId = "local_device"; + EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillOnce(Return(std::vector{})); + std::vector datas; + EXPECT_CALL(*metaDataMock, LoadMeta(_, _, _)).WillRepeatedly(Return(false)); + + Session session = SessionManager::GetInstance().GetSession(local, "target_device"); + + EXPECT_TRUE(session.targetUserIds.empty()); +} + +/** + * @tc.name: CheckSession + * @tc.desc: test CheckSession. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, CheckSession, TestSize.Level1) +{ + SessionPoint localSys; + localSys.userId = UserDelegate::SYSTEM_USER; + localSys.appId = "test_app"; + localSys.deviceId = "local_device"; + localSys.storeId = "test_store"; + SessionPoint localNormal; + localNormal.userId = 100; + localNormal.appId = "test_app"; + localNormal.deviceId = "local_device"; + localNormal.storeId = "test_store"; + std::vector datas; + CreateStoreMetaData(datas, localSys); + EXPECT_CALL(*metaDataMock, LoadMeta(_, _, _)) + .WillOnce(DoAll(SetArgReferee<1>(datas), Return(false))) + .WillRepeatedly(DoAll(SetArgReferee<1>(datas), Return(true))); + EXPECT_CALL(AuthHandlerMock::GetInstance(), CheckAccess(_, _, _, _)) + .WillOnce(Return(std::pair(false, true))) + .WillOnce(Return(std::pair(true, false))); + bool result = SessionManager::GetInstance().CheckSession(localSys, localNormal); + EXPECT_FALSE(result); + result = SessionManager::GetInstance().CheckSession(localSys, localNormal); + EXPECT_FALSE(result); + result = SessionManager::GetInstance().CheckSession(localNormal, localSys); + EXPECT_TRUE(result); +} } // namespace \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/BUILD.gn b/services/distributeddataservice/service/test/mock/BUILD.gn index a0833e470..ce0a05278 100644 --- a/services/distributeddataservice/service/test/mock/BUILD.gn +++ b/services/distributeddataservice/service/test/mock/BUILD.gn @@ -18,6 +18,7 @@ config("module_private_config") { include_dirs = [ "${data_service_path}/adapter/include/communicator", + "${data_service_path}/service/kvdb", "../../../framework/include/", "../../../service/rdb/", "./", @@ -27,6 +28,7 @@ config("module_private_config") { } ohos_static_library("distributeddata_mock_static") { + testonly = true branch_protector_ret = "pac_ret" sanitize = { cfi = true @@ -35,18 +37,25 @@ ohos_static_library("distributeddata_mock_static") { } sources = [ + "auth_delegate_mock.cpp", "cursor_mock.cpp", "db_change_data_mock.cpp", "db_store_mock.cpp", + "device_manager_adapter_mock.cpp", "general_store_mock.cpp", "kv_store_nb_delegate_mock.cpp", + "meta_data_manager_mock.cpp", "network_delegate_mock.cpp", "screen_lock_mock.cpp", + "user_delegate_mock.cpp", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] external_deps = [ + "device_manager:devicemanagersdk", + "googletest:gmock", + "googletest:gtest", "kv_store:distributeddata_mgr", "kv_store:distributeddb", "relational_store:native_rdb", diff --git a/services/distributeddataservice/service/test/mock/auth_delegate_mock.cpp b/services/distributeddataservice/service/test/mock/auth_delegate_mock.cpp new file mode 100644 index 000000000..7d1cf72bf --- /dev/null +++ b/services/distributeddataservice/service/test/mock/auth_delegate_mock.cpp @@ -0,0 +1,26 @@ +/* + * 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 "auth_delegate_mock.h" + +namespace OHOS { +namespace DistributedData { + +AuthHandler *AuthDelegate::GetInstance() +{ + return &(AuthHandlerMock::GetInstance()); +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/auth_delegate_mock.h b/services/distributeddataservice/service/test/mock/auth_delegate_mock.h new file mode 100644 index 000000000..4524aec56 --- /dev/null +++ b/services/distributeddataservice/service/test/mock/auth_delegate_mock.h @@ -0,0 +1,38 @@ +/* + * 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_DISTRIBUTEDDATA_AUTH_DELEGATE_MOCK_H +#define OHOS_DISTRIBUTEDDATA_AUTH_DELEGATE_MOCK_H + +#include + +#include + +#include "auth_delegate.h" +namespace OHOS { +namespace DistributedData { +class AuthHandlerMock : public AuthHandler { +public: + static AuthHandlerMock &GetInstance() + { + static AuthHandlerMock instance; + return instance; + } + MOCK_METHOD((std::pair), CheckAccess, + (int localUserId, int peerUserId, const std::string &peerDeviceId, const AclParams &aclParams), (override)); +}; +} // namespace DistributedData +} // namespace OHOS +#endif // OHOS_DISTRIBUTEDDATA_AUTH_DELEGATE_MOCK_H \ No newline at end of file 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 5923f7da6..6af7ba916 100644 --- a/services/distributeddataservice/service/test/mock/meta_data_manager_mock.cpp +++ b/services/distributeddataservice/service/test/mock/meta_data_manager_mock.cpp @@ -12,23 +12,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include #include "meta_data_manager_mock.h" +#include + +#include "metadata/capability_meta_data.h" + namespace OHOS::DistributedData { using namespace std; + OHOS::DistributedData::MetaDataManager &OHOS::DistributedData::MetaDataManager::GetInstance() { static MetaDataManager instance; return instance; } -OHOS::DistributedData::MetaDataManager::MetaDataManager() { } - -OHOS::DistributedData::MetaDataManager::~MetaDataManager() { } +OHOS::DistributedData::MetaDataManager::MetaDataManager() +{ +} +OHOS::DistributedData::MetaDataManager::~MetaDataManager() +{ +} bool OHOS::DistributedData::MetaDataManager::LoadMeta(const std::string &key, Serializable &value, bool isLocal) { return BMetaDataManager::metaDataManager->LoadMeta(key, value, isLocal); } -} \ No newline at end of file + +template<> +bool OHOS::DistributedData::MetaDataManager::LoadMeta( + const std::string &prefix, std::vector &values, bool isLocal) +{ + return BMetaData::metaDataManager->LoadMeta(prefix, values, isLocal); +} +} // namespace OHOS::DistributedData \ No newline at end of file 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 28b4562a6..6db1bf937 100644 --- a/services/distributeddataservice/service/test/mock/meta_data_manager_mock.h +++ b/services/distributeddataservice/service/test/mock/meta_data_manager_mock.h @@ -16,10 +16,11 @@ #define OHOS_META_DATA_MANAGER_MOCK_H #include + +#include "metadata/appid_meta_data.h" #include "metadata/meta_data_manager.h" -#include "metadata/strategy_meta_data.h" #include "metadata/store_meta_data.h" -#include "metadata/appid_meta_data.h" +#include "metadata/strategy_meta_data.h" namespace OHOS::DistributedData { class BMetaDataManager { @@ -27,13 +28,23 @@ public: virtual bool LoadMeta(const std::string &, Serializable &, bool) = 0; BMetaDataManager() = default; virtual ~BMetaDataManager() = default; -private: static inline std::shared_ptr metaDataManager = nullptr; }; - class MetaDataManagerMock : public BMetaDataManager { public: - MOCK_METHOD(bool, LoadMeta, (const std::string &, Serializable &, bool)); + MOCK_METHOD(bool, LoadMeta, (const std::string &, Serializable &, bool), (override)); +}; + +template class BMetaData { +public: + virtual bool LoadMeta(const std::string &, std::vector &, bool) = 0; + BMetaData() = default; + virtual ~BMetaData() = default; + static inline std::shared_ptr> metaDataManager = nullptr; +}; +template class MetaDataMock : public BMetaData { +public: + MOCK_METHOD(bool, LoadMeta, (const std::string &, std::vector &, bool), (override)); }; -} +} // namespace OHOS::DistributedData #endif //OHOS_META_DATA_MANAGER_MOCK_H diff --git a/services/distributeddataservice/service/test/mock/user_delegate_mock.cpp b/services/distributeddataservice/service/test/mock/user_delegate_mock.cpp index bc1d1353a..d013c3c11 100644 --- a/services/distributeddataservice/service/test/mock/user_delegate_mock.cpp +++ b/services/distributeddataservice/service/test/mock/user_delegate_mock.cpp @@ -91,7 +91,7 @@ bool UserDelegate::NotifyUserEvent(const UserDelegate::UserEvent &userEvent) void UserDelegate::LocalUserObserver::OnAccountChanged(const AccountEventInfo &eventInfo, int32_t timeout) { - return; + userDelegate_.NotifyUserEvent({}); } UserDelegate::LocalUserObserver::LocalUserObserver(UserDelegate &userDelegate) : userDelegate_(userDelegate) {} -- Gitee From af378c27e92e83db522a8f0bb0188c1135a2b1fd Mon Sep 17 00:00:00 2001 From: guochao Date: Fri, 25 Apr 2025 19:08:30 +0800 Subject: [PATCH 205/225] add cfi_blocklist.txt Signed-off-by: guochao --- cfi_blocklist.txt | 16 ++++++++++++++++ datamgr_service.gni | 2 ++ .../distributeddataservice/app/test/BUILD.gn | 1 + 3 files changed, 19 insertions(+) create mode 100644 cfi_blocklist.txt diff --git a/cfi_blocklist.txt b/cfi_blocklist.txt new file mode 100644 index 000000000..89d302fdc --- /dev/null +++ b/cfi_blocklist.txt @@ -0,0 +1,16 @@ +# 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. + +[cfi] +src:*third_party/googletest/googlemock/include/gmock/* +src:*third_party/googletest/googletest/include/gtest/* \ No newline at end of file diff --git a/datamgr_service.gni b/datamgr_service.gni index da3e7a494..7b327ccea 100644 --- a/datamgr_service.gni +++ b/datamgr_service.gni @@ -38,6 +38,8 @@ udmf_path = "//foundation/distributeddatamgr/udmf" dataobject_path = "//foundation/distributeddatamgr/data_object" +datamgr_service_path = "//foundation/distributeddatamgr/datamgr_service" + declare_args() { datamgr_service_power = true if (!defined(global_parts_info.power_manager_native_powermgr_client) || diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index 6d6ac6c66..392b903b0 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -154,6 +154,7 @@ ohos_unittest("SessionManagerTest") { cfi = true cfi_cross_dso = true debug = false + blocklist = "${datamgr_service_path}/cfi_blocklist.txt" } cflags_cc = [ "-DUT_TEST" ] -- Gitee From 3bfc33b43c55c3aa7971cc622991454279e55b8b Mon Sep 17 00:00:00 2001 From: guochao Date: Sat, 26 Apr 2025 14:55:47 +0800 Subject: [PATCH 206/225] =?UTF-8?q?=E8=B6=85=E5=A4=A7=E5=87=BD=E6=95=B0?= =?UTF-8?q?=EF=BC=8Cmagic=E6=95=B0=E5=AD=97=20Signed-off-by:=20guochao=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test/unittest/session_manager_test.cpp | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index 53a057e12..5cd44516a 100644 --- a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -15,6 +15,8 @@ #include "session_manager/session_manager.h" +#include + #include "accesstoken_kit.h" #include "account_delegate_mock.h" #include "auth_delegate_mock.h" @@ -33,6 +35,7 @@ #include "user_delegate_mock.h" #include "utils/endian_converter.h" + namespace { using namespace testing; using namespace testing::ext; @@ -46,6 +49,10 @@ using UserInfo = DistributedDB::UserInfo; constexpr const char *PEER_DEVICE_ID = "PEER_DEVICE_ID"; constexpr int PEER_USER_ID1 = 101; constexpr int PEER_USER_ID2 = 100; +constexpr int32_t USER_ID0 = 0; +constexpr int32_t USER_ID1 = 1; +constexpr int32_t USER_ID2 = 2; +constexpr int32_t USER_ID3 = 3; constexpr int METADATA_UID = 2000000; static constexpr int32_t OH_OS_TYPE = 10; @@ -75,13 +82,13 @@ public: void CreateUserStatus(std::vector &users) { UserStatus stat; - stat.id = 0; + stat.id = USER_ID0; UserStatus stat1; - stat.id = 1; + stat.id = USER_ID1; UserStatus stat2; - stat.id = 2; + stat.id = USER_ID2; UserStatus stat3; - stat.id = 3; + stat.id = USER_ID3; users.push_back(stat); users.push_back(stat1); users.push_back(stat2); @@ -205,13 +212,11 @@ public: uint8_t *ptr = dataBuffer; size_t remaining = BUFFER_SIZE; - // 1. write RouteHead errno_t err = memcpy_s(ptr, remaining, &head, sizeof(RouteHead)); ASSERT_EQ(err, 0) << "Failed to copy RouteHead"; ptr += sizeof(RouteHead); remaining -= sizeof(RouteHead); - // 2. write SessionDevicePair SessionDevicePair devPair{}; constexpr size_t DEV_ID_SIZE = sizeof(devPair.sourceId); err = memset_s(devPair.sourceId, DEV_ID_SIZE, 'A', DEV_ID_SIZE - 1); @@ -227,7 +232,6 @@ public: ptr += sizeof(SessionDevicePair); remaining -= sizeof(SessionDevicePair); - // 3. write SessionUserPair SessionUserPair userPair{}; userPair.sourceUserId = HostToNet(100U); userPair.targetUserCount = HostToNet(1U); @@ -242,7 +246,6 @@ public: ptr += sizeof(uint32_t); remaining -= sizeof(uint32_t); - // 4. write SessionAppId SessionAppId appId{}; const char *appStr = "test"; -- Gitee From 93925d3b313e40081083b1cb2d3bf6fa545e0454 Mon Sep 17 00:00:00 2001 From: guochao Date: Sun, 27 Apr 2025 14:58:09 +0800 Subject: [PATCH 207/225] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81=20?= =?UTF-8?q?Signed-off-by:=20guochao=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test/unittest/session_manager_test.cpp | 21 +++++-------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index 5cd44516a..5cb741e58 100644 --- a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -49,10 +49,6 @@ using UserInfo = DistributedDB::UserInfo; constexpr const char *PEER_DEVICE_ID = "PEER_DEVICE_ID"; constexpr int PEER_USER_ID1 = 101; constexpr int PEER_USER_ID2 = 100; -constexpr int32_t USER_ID0 = 0; -constexpr int32_t USER_ID1 = 1; -constexpr int32_t USER_ID2 = 2; -constexpr int32_t USER_ID3 = 3; constexpr int METADATA_UID = 2000000; static constexpr int32_t OH_OS_TYPE = 10; @@ -81,18 +77,11 @@ class SessionManagerTest : public testing::Test { public: void CreateUserStatus(std::vector &users) { - UserStatus stat; - stat.id = USER_ID0; - UserStatus stat1; - stat.id = USER_ID1; - UserStatus stat2; - stat.id = USER_ID2; - UserStatus stat3; - stat.id = USER_ID3; - users.push_back(stat); - users.push_back(stat1); - users.push_back(stat2); - users.push_back(stat3); + for (int32_t i = 0; i < 4; i++) { + UserStatus stat; + stat.id = i; + users.push_back(stat); + } } void CreateStoreMetaData(std::vector &datas, SessionPoint local) { -- Gitee From e36acecafa38a5d5c1db38ae05d9d4cb2f8cad4f Mon Sep 17 00:00:00 2001 From: guochao Date: Sun, 27 Apr 2025 15:59:43 +0800 Subject: [PATCH 208/225] fix magic num Signed-off-by: guochao --- .../app/test/unittest/session_manager_test.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index 5cb741e58..6a027c6b9 100644 --- a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -49,6 +49,7 @@ using UserInfo = DistributedDB::UserInfo; constexpr const char *PEER_DEVICE_ID = "PEER_DEVICE_ID"; constexpr int PEER_USER_ID1 = 101; constexpr int PEER_USER_ID2 = 100; +constexpr int32_t USER_MAXID = 4; constexpr int METADATA_UID = 2000000; static constexpr int32_t OH_OS_TYPE = 10; @@ -77,7 +78,7 @@ class SessionManagerTest : public testing::Test { public: void CreateUserStatus(std::vector &users) { - for (int32_t i = 0; i < 4; i++) { + for (int32_t i = 0; i < USER_MAXID; i++) { UserStatus stat; stat.id = i; users.push_back(stat); -- Gitee From 47f2140d81528bf9c94381aa6708cc6bd1d86cfa Mon Sep 17 00:00:00 2001 From: yanhui Date: Sun, 27 Apr 2025 12:54:58 +0800 Subject: [PATCH 209/225] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=8B=B7=E8=B4=9D?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E6=97=B6=E9=95=BF=E5=BA=A6=E7=BC=BA?= =?UTF-8?q?1=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yanhui Change-Id: I12c7fdb608180a010fb2896d55d9d9dc64e793e4 Signed-off-by: yanhui --- .../src/session_manager/route_head_handler_impl.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) 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 d7feaea8e..f8063b9c5 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 @@ -197,19 +197,22 @@ bool RouteHeadHandlerImpl::PackDataBody(uint8_t *data, uint32_t totalLen) SessionAppId *appPair = reinterpret_cast(ptr); uint32_t appIdSize = session_.appId.size(); appPair->len = HostToNet(appIdSize); - ret = strcpy_s(appPair->appId, appIdSize, session_.appId.c_str()); + uint8_t *end = data + totalLen; + ptr += sizeof(SessionAppId); + ret = memcpy_s(appPair->appId, end - ptr, session_.appId.c_str(), appIdSize); if (ret != 0) { - ZLOGE("strcpy for app id failed, error:%{public}d", errno); + ZLOGE("memcpy for app id failed, ret is %{public}d, leftSize is %{public}d, appIdSize is %{public}d", + ret, end - ptr, appIdSize); return false; } - ptr += (sizeof(SessionAppId) + appIdSize); + ptr += appIdSize; - uint8_t *end = data + totalLen; SessionStoreId *storePair = reinterpret_cast(ptr); uint32_t storeIdSize = session_.storeId.size(); ret = memcpy_s(storePair->storeId, end - ptr, session_.storeId.data(), storeIdSize); if (ret != 0) { - ZLOGE("strcpy for store id failed, error:%{public}d", errno); + ZLOGE("memcpy for store id failed, ret is %{public}d, leftSize is %{public}d, storeIdSize is %{public}d", + ret, end - ptr, storeIdSize); return false; } storePair->len = HostToNet(storeIdSize); -- Gitee From 1a63c6788dbc28e937221249866fd79288ab4a2d Mon Sep 17 00:00:00 2001 From: yanhui Date: Sun, 27 Apr 2025 18:00:10 +0800 Subject: [PATCH 210/225] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E6=89=93=E5=8D=B0=E6=A0=BC=E5=BC=8F=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yanhui Change-Id: Iec957585db784bd7acdb36b7e8dae15b546c8022 --- .../app/src/session_manager/route_head_handler_impl.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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 f8063b9c5..40d0403a4 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 @@ -201,8 +201,8 @@ bool RouteHeadHandlerImpl::PackDataBody(uint8_t *data, uint32_t totalLen) ptr += sizeof(SessionAppId); ret = memcpy_s(appPair->appId, end - ptr, session_.appId.c_str(), appIdSize); if (ret != 0) { - ZLOGE("memcpy for app id failed, ret is %{public}d, leftSize is %{public}d, appIdSize is %{public}d", - ret, end - ptr, appIdSize); + ZLOGE("memcpy for app id failed, ret is %{public}d, leftSize is %{public}u, appIdSize is %{public}u", + ret, static_cast(end - ptr), appIdSize); return false; } ptr += appIdSize; @@ -211,8 +211,8 @@ bool RouteHeadHandlerImpl::PackDataBody(uint8_t *data, uint32_t totalLen) uint32_t storeIdSize = session_.storeId.size(); ret = memcpy_s(storePair->storeId, end - ptr, session_.storeId.data(), storeIdSize); if (ret != 0) { - ZLOGE("memcpy for store id failed, ret is %{public}d, leftSize is %{public}d, storeIdSize is %{public}d", - ret, end - ptr, storeIdSize); + ZLOGE("memcpy for store id failed, ret is %{public}d, leftSize is %{public}u, storeIdSize is %{public}u", + ret, static_cast(end - ptr), storeIdSize); return false; } storePair->len = HostToNet(storeIdSize); -- Gitee From 87a5093b3347e9b5d68cc79424c81e53f6720b2c Mon Sep 17 00:00:00 2001 From: guochao Date: Sun, 27 Apr 2025 21:11:08 +0800 Subject: [PATCH 211/225] =?UTF-8?q?=E9=80=82=E9=85=8Dkvdbtest=20Signed-off?= =?UTF-8?q?-by:=20guochao=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/test/BUILD.gn | 8 +- .../service/test/kvdb_service_impl_test.cpp | 219 ++++++++++++------ 2 files changed, 160 insertions(+), 67 deletions(-) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 022dd5ef9..3c7201c8b 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -656,9 +656,9 @@ ohos_unittest("RdbServiceImplTest") { } module_out_path = module_output_path sources = [ + "mock/checker_mock.cpp", "mock/db_change_data_mock.cpp", "mock/db_store_mock.cpp", - "mock/checker_mock.cpp", "rdb_service_impl_test.cpp", ] @@ -1165,6 +1165,12 @@ ohos_unittest("DataShareServiceImplTest") { ohos_unittest("KvdbServiceImplTest") { module_out_path = module_output_path + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${datamgr_service_path}/cfi_blocklist.txt" + } sources = [ "${data_service_path}/app/src/kvstore_meta_manager.cpp", "kvdb_service_impl_test.cpp", diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index a59b778e2..523dbca32 100644 --- a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp @@ -13,10 +13,10 @@ * limitations under the License. */ #define LOG_TAG "KvdbServiceImplTest" -#include "kvdb_service_impl.h" - -#include #include +#include + +#include #include #include "bootstrap.h" @@ -27,18 +27,18 @@ #include "distributed_kv_data_manager.h" #include "event_center.h" #include "ipc_skeleton.h" -#include "kvdb_service_stub.h" #include "kvdb_query.h" +#include "kvdb_service_impl.h" +#include "kvdb_service_stub.h" #include "kvstore_death_recipient.h" #include "kvstore_meta_manager.h" #include "kvstore_sync_manager.h" #include "log_print.h" -#include #include "mock/access_token_mock.h" #include "mock/meta_data_manager_mock.h" +#include "nativetoken_kit.h" #include "network_delegate.h" #include "network_delegate_mock.h" -#include "nativetoken_kit.h" #include "token_setproc.h" #include "types.h" #include "utils/anonymous.h" @@ -66,6 +66,7 @@ using StoreMetaData = OHOS::DistributedData::StoreMetaData; using SyncEnd = OHOS::DistributedKv::KvStoreSyncManager::SyncEnd; using DBResult = std::map; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; +using DBLaunchParam = OHOS::DistributedKv::KVDBServiceImpl::DBLaunchParam; static OHOS::DistributedKv::StoreId storeId = { "kvdb_test_storeid" }; static OHOS::DistributedKv::AppId appId = { "ohos.test.kvdb" }; static constexpr const char *TEST_USER = "0"; @@ -75,6 +76,7 @@ class KvdbServiceImplTest : public testing::Test { public: static inline std::shared_ptr accTokenMock = nullptr; static inline std::shared_ptr metaDataManagerMock = nullptr; + static inline std::shared_ptr> metaDataMock = nullptr; static constexpr size_t NUM_MIN = 5; static constexpr size_t NUM_MAX = 12; static DistributedKvDataManager manager; @@ -92,7 +94,7 @@ public: static void RemoveAllStore(OHOS::DistributedKv::DistributedKvDataManager &manager); void SetUp(); void TearDown(); - + void CreateStoreMetaData(std::vector &datas, DBLaunchParam param); KvdbServiceImplTest(); protected: @@ -152,6 +154,8 @@ void KvdbServiceImplTest::SetUpTestCase(void) BAccessTokenKit::accessTokenkit = accTokenMock; metaDataManagerMock = std::make_shared(); BMetaDataManager::metaDataManager = metaDataManagerMock; + metaDataMock = std::make_shared>(); + BMetaData::metaDataManager = metaDataMock; NetworkDelegate::RegisterNetworkInstance(&delegate_); } @@ -165,6 +169,8 @@ void KvdbServiceImplTest::TearDownTestCase() BAccessTokenKit::accessTokenkit = nullptr; metaDataManagerMock = nullptr; BMetaDataManager::metaDataManager = nullptr; + metaDataMock = nullptr; + BMetaData::metaDataManager = nullptr; } void KvdbServiceImplTest::SetUp(void) @@ -193,7 +199,60 @@ void SyncEndCallback(const std::map &statu } } -KvdbServiceImplTest::KvdbServiceImplTest(void) {} +KvdbServiceImplTest::KvdbServiceImplTest(void) +{ +} + +void KvdbServiceImplTest::CreateStoreMetaData(std::vector &datas, DBLaunchParam param) +{ + std::vector metaData; + + // 1: storeType out of range. + StoreMetaData meta1; + meta1.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN - 1; + metaData.push_back(meta1); + + StoreMetaData meta2; + meta2.storeType = StoreMetaData::StoreType::STORE_KV_END + 1; + metaData.push_back(meta2); + + // 2: user ID mismatch. + StoreMetaData meta3; + meta3.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN; + meta3.user = "user2"; // param.userId = "user1" + metaData.push_back(meta3); + + // 3: appId equals to process label. + StoreMetaData meta4; + meta4.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN; + meta4.appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); + metaData.push_back(meta4); + + // 4: The identifier does not match and CompareTripleIdentifier is false. + StoreMetaData meta5; + meta5.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN; + meta5.storeId = "store_id_1"; + meta5.appId = "app_id_1"; + metaData.push_back(meta5); + + // 5: Normal execution logic. + StoreMetaData meta6; + meta6.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN; + meta6.user = param.userId; // param.userId = "user1" + meta6.appId = "valid_app_id"; + meta6.storeId = "store_id_2"; + meta6.tokenId = 123; + metaData.push_back(meta6); + + // 6: trigger SetEqualIdentifier. + StoreMetaData meta7; + meta7.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN; + meta7.user = param.userId; + meta7.appId = "valid_app_id"; + meta7.storeId = "store_id_3"; + meta7.tokenId = 456; + metaData.push_back(meta7); +} /** * @tc.name: KvdbServiceImpl001 @@ -231,8 +290,9 @@ HWTEST_F(KvdbServiceImplTest, KvdbServiceImpl001, TestSize.Level0) status = kvdbServiceImpl_->UnsubscribeSwitchData(appId); EXPECT_EQ(status, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return - (ATokenTypeEnum::TOKEN_NATIVE)).WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); status = kvdbServiceImpl_->Close(appId, id1, 0); EXPECT_EQ(status, Status::SUCCESS); } @@ -256,7 +316,7 @@ HWTEST_F(KvdbServiceImplTest, OnInitialize001, TestSize.Level0) auto event = std::make_unique(CloudEvent::CLOUD_SYNC, storeInfo); EXPECT_NE(event, nullptr); result = EventCenter::GetInstance().PostEvent(move(event)); - EXPECT_EQ(result, 1); // CODE_SYNC + EXPECT_EQ(result, 1); // CODE_SYNC auto event1 = std::make_unique(CloudEvent::CLEAN_DATA, storeInfo); EXPECT_NE(event1, nullptr); result = EventCenter::GetInstance().PostEvent(move(event1)); @@ -320,8 +380,9 @@ HWTEST_F(KvdbServiceImplTest, DeleteTest001, TestSize.Level0) Status status1 = manager.GetSingleKvStore(create, appId, storeId, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status1, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return - (ATokenTypeEnum::TOKEN_NATIVE)).WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); auto status = kvdbServiceImpl_->Delete(appId, storeId, 0); ZLOGI("DeleteTest001 status = :%{public}d", status); ASSERT_EQ(status, Status::SUCCESS); @@ -338,8 +399,9 @@ HWTEST_F(KvdbServiceImplTest, DeleteTest002, TestSize.Level0) ZLOGI("DeleteTest002 start"); AppId appId01 = { "ohos.kvdbserviceimpl.test01" }; StoreId storeId01 = { "meta_test_storeid" }; - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return - (ATokenTypeEnum::TOKEN_NATIVE)).WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); auto status = kvdbServiceImpl_->Delete(appId01, storeId01, 0); ZLOGI("DeleteTest002 status = :%{public}d", status); ASSERT_EQ(status, Status::SUCCESS); @@ -353,9 +415,11 @@ HWTEST_F(KvdbServiceImplTest, DeleteTest002, TestSize.Level0) */ HWTEST_F(KvdbServiceImplTest, DeleteTest003, TestSize.Level0) { - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); - EXPECT_CALL(*accTokenMock, GetHapTokenInfo(testing::_, testing::_)).WillOnce(testing::Return(-1)) + EXPECT_CALL(*accTokenMock, GetHapTokenInfo(testing::_, testing::_)) + .WillOnce(testing::Return(-1)) .WillRepeatedly(testing::Return(-1)); int32_t status = kvdbServiceImpl_->Delete(appId, storeId, 0); EXPECT_EQ(status, DistributedKv::ILLEGAL_STATE); @@ -369,9 +433,11 @@ HWTEST_F(KvdbServiceImplTest, DeleteTest003, TestSize.Level0) */ HWTEST_F(KvdbServiceImplTest, CloseTest001, TestSize.Level0) { - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); - EXPECT_CALL(*accTokenMock, GetHapTokenInfo(testing::_, testing::_)).WillOnce(testing::Return(-1)) + EXPECT_CALL(*accTokenMock, GetHapTokenInfo(testing::_, testing::_)) + .WillOnce(testing::Return(-1)) .WillRepeatedly(testing::Return(-1)); int32_t status = kvdbServiceImpl_->Close(appId, storeId, 0); EXPECT_EQ(status, DistributedKv::ILLEGAL_STATE); @@ -386,29 +452,29 @@ HWTEST_F(KvdbServiceImplTest, CloseTest001, TestSize.Level0) HWTEST_F(KvdbServiceImplTest, OnAsyncCompleteTest001, TestSize.Level0) { DistributedKv::Statistic upload; - upload.failed = 1; // test - upload.success = 1; // test - upload.total = 1; // test + upload.failed = 1; // test + upload.success = 1; // test + upload.total = 1; // test upload.untreated = 1; // test DistributedKv::Statistic download; - download.failed = 1; // test - download.success = 1; // test - download.total = 1; // test + download.failed = 1; // test + download.success = 1; // test + download.total = 1; // test download.untreated = 1; // test DistributedKv::TableDetail details; details.download = download; details.upload = upload; DistributedKv::ProgressDetail detail; - detail.code = 1; // test + detail.code = 1; // test detail.progress = 1; // test detail.details = details; sptr notifier; DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; - syncAgent.pid_ = 1; // test + syncAgent.pid_ = 1; // test syncAgent.switchesObserverCount_ = 1; // test syncAgent.appId_ = { "ohos.OnAsyncCompleteTest001.kvdb" }; syncAgent.notifier_ = notifier; - kvdbServiceImpl_->syncAgents_.Insert(100, syncAgent); // test + kvdbServiceImpl_->syncAgents_.Insert(100, syncAgent); // test kvdbServiceImpl_->OnAsyncComplete(1, 1, std::move(detail)); // test EXPECT_EQ(kvdbServiceImpl_->syncAgents_.Find(1).first, false); kvdbServiceImpl_->OnAsyncComplete(100, 1, std::move(detail)); // test @@ -464,7 +530,7 @@ HWTEST_F(KvdbServiceImplTest, UnregServiceNotifierTest001, TestSize.Level0) ASSERT_EQ(status1, Status::SUCCESS); sptr notifier; DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; - syncAgent.pid_ = 1; // test + syncAgent.pid_ = 1; // test syncAgent.switchesObserverCount_ = 1; // test syncAgent.appId_ = { "ohos.OnAsyncCompleteTest001.kvdb" }; syncAgent.notifier_ = notifier; @@ -548,11 +614,13 @@ HWTEST_F(KvdbServiceImplTest, EnableCapabilityTest001, TestSize.Level0) Status status1 = manager.GetSingleKvStore(create, appId, storeId, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status1, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); auto status = kvdbServiceImpl_->EnableCapability(appId, storeId, 0); ASSERT_EQ(status, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); status = kvdbServiceImpl_->EnableCapability(appId, storeId, 0); ASSERT_EQ(status, Status::ILLEGAL_STATE); @@ -569,7 +637,8 @@ HWTEST_F(KvdbServiceImplTest, GetInstIndexTest001, TestSize.Level0) Status status1 = manager.GetSingleKvStore(create, appId, storeId, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status1, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); auto status = kvdbServiceImpl_->GetInstIndex(100, appId); ASSERT_EQ(status, -1); @@ -587,13 +656,15 @@ HWTEST_F(KvdbServiceImplTest, IsNeedMetaSyncTest001, TestSize.Level0) ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status1, Status::SUCCESS); StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); - std::vector uuids{"uuidtest01"}; + std::vector uuids{ "uuidtest01" }; EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(true)).WillRepeatedly(testing::Return(true)); + .WillOnce(testing::Return(true)) + .WillRepeatedly(testing::Return(true)); auto status = kvdbServiceImpl_->IsNeedMetaSync(meta, uuids); ASSERT_EQ(status, false); EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(false)).WillRepeatedly(testing::Return(false)); + .WillOnce(testing::Return(false)) + .WillRepeatedly(testing::Return(false)); status = kvdbServiceImpl_->IsNeedMetaSync(meta, uuids); ASSERT_EQ(status, true); } @@ -611,11 +682,13 @@ HWTEST_F(KvdbServiceImplTest, GetDistributedDataMetaTest001, TestSize.Level0) ASSERT_EQ(status, Status::SUCCESS); std::string deviceId = "KvdbServiceImplTest_deviceId"; EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(false)).WillRepeatedly(testing::Return(false)); + .WillOnce(testing::Return(false)) + .WillRepeatedly(testing::Return(false)); auto meta = kvdbServiceImpl_->GetDistributedDataMeta(deviceId); ASSERT_EQ(meta.user, "0"); EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(true)).WillRepeatedly(testing::Return(true)); + .WillOnce(testing::Return(true)) + .WillRepeatedly(testing::Return(true)); meta = kvdbServiceImpl_->GetDistributedDataMeta(deviceId); ASSERT_EQ(meta.deviceId, deviceId); } @@ -651,7 +724,7 @@ HWTEST_F(KvdbServiceImplTest, DoSyncBeginTest001, TestSize.Level0) Status status = manager.GetSingleKvStore(create, appId, storeId, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status, Status::SUCCESS); - std::vector device1{"uuidtest01"}; + std::vector device1{ "uuidtest01" }; std::vector device2; StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); SyncInfo syncInfo; @@ -687,12 +760,14 @@ HWTEST_F(KvdbServiceImplTest, DoCompleteTest001, TestSize.Level0) DBResult dbResult; dbResult.insert_or_assign("DoCompleteTest_1", DBStatus::OK); dbResult.insert_or_assign("DoCompleteTest_1", DBStatus::DB_ERROR); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); status = kvdbServiceImpl_->DoComplete(meta, syncInfo, refCount, dbResult); ASSERT_EQ(status, Status::SUCCESS); syncInfo.seqId = std::numeric_limits::max(); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); status = kvdbServiceImpl_->DoComplete(meta, syncInfo, refCount, dbResult); ASSERT_EQ(status, Status::SUCCESS); @@ -712,7 +787,7 @@ HWTEST_F(KvdbServiceImplTest, ConvertDbStatusNativeTest001, TestSize.Level0) ASSERT_EQ(status, Status::DEVICE_NOT_ONLINE); DBStatus dbstatus = static_cast(DBStatus::OK - 1); status = kvdbServiceImpl_->ConvertDbStatusNative(dbstatus); - ASSERT_EQ(status, - 1); + ASSERT_EQ(status, -1); } /** @@ -765,12 +840,14 @@ HWTEST_F(KvdbServiceImplTest, DisableCapabilityTest001, TestSize.Level0) Status status1 = manager.GetSingleKvStore(create, appId, storeId, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status1, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); auto status = kvdbServiceImpl_->DisableCapability(appId, storeId, 0); ZLOGI("DisableCapabilityTest001 status = :%{public}d", status); ASSERT_EQ(status, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); status = kvdbServiceImpl_->EnableCapability(appId, storeId, 0); ASSERT_EQ(status, Status::ILLEGAL_STATE); @@ -790,12 +867,14 @@ HWTEST_F(KvdbServiceImplTest, SetCapabilityTest001, TestSize.Level0) ASSERT_EQ(status1, Status::SUCCESS); std::vector local; std::vector remote; - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); auto status = kvdbServiceImpl_->SetCapability(appId, storeId, 0, local, remote); ZLOGI("SetCapabilityTest001 status = :%{public}d", status); ASSERT_EQ(status, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); status = kvdbServiceImpl_->EnableCapability(appId, storeId, 0); ASSERT_EQ(status, Status::ILLEGAL_STATE); @@ -872,7 +951,7 @@ HWTEST_F(KvdbServiceImplTest, UnsubscribeTest001, TestSize.Level0) ASSERT_EQ(status1, Status::SUCCESS); sptr notifier; DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; - syncAgent.pid_ = 1; // test + syncAgent.pid_ = 1; // test syncAgent.switchesObserverCount_ = 1; // test syncAgent.appId_ = { "ohos.OnAsyncCompleteTest001.kvdb" }; syncAgent.notifier_ = notifier; @@ -896,14 +975,14 @@ HWTEST_F(KvdbServiceImplTest, GetBackupPasswordTest001, TestSize.Level0) ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status, Status::SUCCESS); std::vector> password; - status = kvdbServiceImpl_->GetBackupPassword - (appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::BACKUP_SECRET_KEY); + status = kvdbServiceImpl_->GetBackupPassword( + appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::BACKUP_SECRET_KEY); ASSERT_EQ(status, Status::ERROR); - status = kvdbServiceImpl_->GetBackupPassword - (appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::SECRET_KEY); + status = kvdbServiceImpl_->GetBackupPassword( + appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::SECRET_KEY); ASSERT_EQ(status, Status::ERROR); - status = kvdbServiceImpl_->GetBackupPassword - (appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::BUTTON); + status = kvdbServiceImpl_->GetBackupPassword( + appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::BUTTON); ASSERT_EQ(status, Status::ERROR); } @@ -929,7 +1008,8 @@ HWTEST_F(KvdbServiceImplTest, BeforeCreateTest001, TestSize.Level0) creates.cloudConfig.enableCloud = true; kvdbServiceImpl_->executors_ = std::make_shared(1, 1); EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(false)).WillRepeatedly(testing::Return(false)); + .WillOnce(testing::Return(false)) + .WillRepeatedly(testing::Return(false)); auto status = kvdbServiceImpl_->BeforeCreate(appId, storeId, creates); ASSERT_NE(status, Status::STORE_META_CHANGED); kvdbServiceImpl_->executors_ = nullptr; @@ -1061,6 +1141,7 @@ HWTEST_F(KvdbServiceImplTest, ResolveAutoLaunch, TestSize.Level0) EXPECT_EQ(status, Status::SUCCESS); std::string identifier = "identifier"; DistributedKv::KVDBServiceImpl::DBLaunchParam launchParam; + launchParam.userId = "user1"; auto result = kvdbServiceImpl_->ResolveAutoLaunch(identifier, launchParam); EXPECT_EQ(result, Status::STORE_NOT_FOUND); std::shared_ptr executors = std::make_shared(1, 0); @@ -1069,6 +1150,10 @@ HWTEST_F(KvdbServiceImplTest, ResolveAutoLaunch, TestSize.Level0) DistributedKv::KvStoreMetaManager::GetInstance().BindExecutor(executors); DistributedKv::KvStoreMetaManager::GetInstance().InitMetaParameter(); DistributedKv::KvStoreMetaManager::GetInstance().InitMetaListener(); + std::vector datas; + CreateStoreMetaData(datas, launchParam); + EXPECT_CALL(*metaDataMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillRepeatedly(testing::DoAll(testing::SetArgReferee<1>(datas), testing::Return(true))); result = kvdbServiceImpl_->ResolveAutoLaunch(identifier, launchParam); EXPECT_EQ(result, Status::SUCCESS); } @@ -1082,7 +1167,7 @@ HWTEST_F(KvdbServiceImplTest, ResolveAutoLaunch, TestSize.Level0) HWTEST_F(KvdbServiceImplTest, IsNeedSyncTest, TestSize.Level0) { StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); - std::vector devices= {"IsNeedSyncTest"}; + std::vector devices = { "IsNeedSyncTest" }; auto changes = kvdbServiceImpl_->IsNeedSync(meta, devices); EXPECT_EQ(changes, false); } @@ -1317,25 +1402,25 @@ HWTEST_F(KvdbServiceImplTest, DoCloudSync01, TestSize.Level0) HWTEST_F(KvdbServiceImplTest, OnAsyncCompleteTest002, TestSize.Level0) { DistributedKv::Statistic upload; - upload.failed = 1; // test - upload.success = 1; // test - upload.total = 1; // test + upload.failed = 1; // test + upload.success = 1; // test + upload.total = 1; // test upload.untreated = 1; // test DistributedKv::Statistic download; - download.failed = 1; // test - download.success = 1; // test - download.total = 1; // test + download.failed = 1; // test + download.success = 1; // test + download.total = 1; // test download.untreated = 1; // test DistributedKv::TableDetail details; details.download = download; details.upload = upload; DistributedKv::ProgressDetail detail; - detail.code = 1; // test + detail.code = 1; // test detail.progress = 1; // test detail.details = details; DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; sptr notifier = nullptr; - syncAgent.pid_ = 1; // test + syncAgent.pid_ = 1; // test syncAgent.switchesObserverCount_ = 1; // test syncAgent.appId_ = { "ohos.OnAsyncCompleteTest.kvdb" }; syncAgent.notifier_ = notifier; @@ -1359,7 +1444,7 @@ HWTEST_F(KvdbServiceImplTest, OnAsyncCompleteTest003, TestSize.Level0) { DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; sptr notifier; - syncAgent.pid_ = 1; // test + syncAgent.pid_ = 1; // test syncAgent.switchesObserverCount_ = 1; // test syncAgent.appId_ = { "ohos.OnAsyncCompleteTest001.kvdb" }; syncAgent.notifier_ = notifier; @@ -1431,12 +1516,14 @@ HWTEST_F(KvdbServiceImplTest, syncTest003, TestSize.Level0) SyncInfo syncInfo; syncInfo.seqId = std::numeric_limits::max(); EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(true)).WillRepeatedly(testing::Return(true)); + .WillOnce(testing::Return(true)) + .WillRepeatedly(testing::Return(true)); auto status = kvdbServiceImpl_->Sync(appId, storeId, 0, syncInfo); EXPECT_EQ(localMeta.HasPolicy(DistributedKv::IMMEDIATE_SYNC_ON_CHANGE), false); EXPECT_NE(status, Status::SUCCESS); EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(false)).WillRepeatedly(testing::Return(false)); + .WillOnce(testing::Return(false)) + .WillRepeatedly(testing::Return(false)); status = kvdbServiceImpl_->Sync(appId, storeId, 0, syncInfo); EXPECT_EQ(localMeta.HasPolicy(DistributedKv::IMMEDIATE_SYNC_ON_ONLINE), true); } @@ -1472,7 +1559,7 @@ HWTEST_F(KvdbServiceImplTest, GetSyncParamTest002, TestSize.Level0) HWTEST_F(KvdbServiceImplTest, SubscribeSwitchData, TestSize.Level0) { options_.isNeedCompress = false; - std::vector password {}; + std::vector password{}; StoreMetaData metaData; auto status = kvdbServiceImpl_->AfterCreate(appId, storeId, options_, password); ASSERT_EQ(status, Status::SUCCESS); -- Gitee From 723efe398fb845fedf149d835a8c0b18a511c646 Mon Sep 17 00:00:00 2001 From: guochao Date: Mon, 28 Apr 2025 00:25:21 +0800 Subject: [PATCH 212/225] fix magic num ,large function Signed-off-by: guochao --- .../test/unittest/session_manager_test.cpp | 86 ++++++++++++++----- .../service/test/kvdb_service_impl_test.cpp | 6 +- 2 files changed, 70 insertions(+), 22 deletions(-) diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index 6a027c6b9..0983ee13e 100644 --- a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -35,7 +35,6 @@ #include "user_delegate_mock.h" #include "utils/endian_converter.h" - namespace { using namespace testing; using namespace testing::ext; @@ -189,27 +188,54 @@ public: } void ConstructValidData() { - constexpr size_t BUFFER_SIZE = sizeof(dataBuffer); + const std::string storeId = "test_store"; + InitializeBuffer(); + ConstructRouteHead(storeId); + ConstructSessionDevicePair(); + ConstructSessionUserPair(); + ConstructSessionAppId(); + ConstructSessionStoreId(storeId); + + const size_t validlLen = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair) + + sizeof(uint32_t) * 1 + sizeof(SessionAppId) + APP_STR_LEN + sizeof(SessionStoreId) + + storeId.size(); + validTotalLen = validlLen; + } + + static inline std::shared_ptr deviceManagerAdapterMock = nullptr; + static inline std::shared_ptr metaDataManagerMock = nullptr; + static inline std::shared_ptr> metaDataMock = nullptr; + static inline std::shared_ptr userDelegateMock = nullptr; + +private: + void InitializeBuffer() + { memset_s(dataBuffer, BUFFER_SIZE, 0, BUFFER_SIZE); + ptr = dataBuffer; + remaining = BUFFER_SIZE; + } + void ConstructRouteHead(const std::string &storeId) + { RouteHead head{}; - head.magic = RouteHead::MAGIC_NUMBER; - head.version = RouteHead::VERSION; - head.dataLen = sizeof(SessionDevicePair) + sizeof(SessionUserPair) + sizeof(uint32_t) * 1 - + sizeof(SessionAppId) + APP_STR_LEN; + head.magic = HostToNet(RouteHead::MAGIC_NUMBER); + head.version = HostToNet(RouteHead::VERSION); + head.dataLen = HostToNet(sizeof(SessionDevicePair) + sizeof(SessionUserPair) + sizeof(uint32_t) * 1 + + sizeof(SessionAppId) + APP_STR_LEN + sizeof(SessionStoreId) + storeId.size()); head.checkSum = 0; - uint8_t *ptr = dataBuffer; - size_t remaining = BUFFER_SIZE; - errno_t err = memcpy_s(ptr, remaining, &head, sizeof(RouteHead)); ASSERT_EQ(err, 0) << "Failed to copy RouteHead"; ptr += sizeof(RouteHead); remaining -= sizeof(RouteHead); + } + void ConstructSessionDevicePair() + { SessionDevicePair devPair{}; constexpr size_t DEV_ID_SIZE = sizeof(devPair.sourceId); - err = memset_s(devPair.sourceId, DEV_ID_SIZE, 'A', DEV_ID_SIZE - 1); + + errno_t err = memset_s(devPair.sourceId, DEV_ID_SIZE, 'A', DEV_ID_SIZE - 1); ASSERT_EQ(err, 0) << "Failed to init sourceId"; devPair.sourceId[DEV_ID_SIZE - 1] = '\0'; @@ -221,27 +247,33 @@ public: ASSERT_EQ(err, 0) << "Failed to copy SessionDevicePair"; ptr += sizeof(SessionDevicePair); remaining -= sizeof(SessionDevicePair); + } + void ConstructSessionUserPair() + { SessionUserPair userPair{}; userPair.sourceUserId = HostToNet(100U); userPair.targetUserCount = HostToNet(1U); - err = memcpy_s(ptr, remaining, &userPair, sizeof(SessionUserPair)); + errno_t err = memcpy_s(ptr, remaining, &userPair, sizeof(SessionUserPair)); ASSERT_EQ(err, 0) << "Failed to copy SessionUserPair"; ptr += sizeof(SessionUserPair); remaining -= sizeof(SessionUserPair); + uint32_t targetUser = HostToNet(200U); err = memcpy_s(ptr, remaining, &targetUser, sizeof(uint32_t)); ASSERT_EQ(err, 0) << "Failed to copy targetUser"; ptr += sizeof(uint32_t); remaining -= sizeof(uint32_t); + } + void ConstructSessionAppId() + { SessionAppId appId{}; const char *appStr = "test"; - appId.len = HostToNet(static_cast(APP_STR_LEN)); - err = memcpy_s(ptr, remaining, &appId, sizeof(SessionAppId)); + errno_t err = memcpy_s(ptr, remaining, &appId, sizeof(SessionAppId)); ASSERT_EQ(err, 0) << "Failed to copy SessionAppId"; ptr += sizeof(SessionAppId); remaining -= sizeof(SessionAppId); @@ -251,14 +283,28 @@ public: ptr += APP_STR_LEN; remaining -= APP_STR_LEN; } - const size_t validTotalLen = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair) - + sizeof(uint32_t) * 1 + sizeof(SessionAppId) + APP_STR_LEN; + void ConstructSessionStoreId(const std::string &storeId) + { + SessionStoreId storeIdHeader{}; + storeIdHeader.len = HostToNet(static_cast(storeId.size())); + + errno_t err = memcpy_s(ptr, remaining, &storeIdHeader, sizeof(SessionStoreId)); + ASSERT_EQ(err, 0) << "Failed to copy storeId length"; + ptr += sizeof(SessionStoreId); + remaining -= sizeof(SessionStoreId); + + err = memcpy_s(ptr, remaining, storeId.c_str(), storeId.size()); + ASSERT_EQ(err, 0) << "Failed to copy storeId data"; + ptr += storeId.size(); + remaining -= storeId.size(); + } + size_t validTotalLen; uint8_t dataBuffer[1024]; - static constexpr size_t APP_STR_LEN = 5; - static inline std::shared_ptr deviceManagerAdapterMock = nullptr; - static inline std::shared_ptr metaDataManagerMock = nullptr; - static inline std::shared_ptr> metaDataMock = nullptr; - static inline std::shared_ptr userDelegateMock = nullptr; + static constexpr size_t APP_STR_LEN = 4; + uint8_t *ptr = dataBuffer; + size_t remaining = BUFFER_SIZE; + static constexpr size_t MAX_STORE_ID_LEN = 100; + static constexpr size_t BUFFER_SIZE = sizeof(dataBuffer) + sizeof(uint32_t) + MAX_STORE_ID_LEN; }; /** diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index 523dbca32..7b7d7382e 100644 --- a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp @@ -79,6 +79,8 @@ public: static inline std::shared_ptr> metaDataMock = nullptr; static constexpr size_t NUM_MIN = 5; static constexpr size_t NUM_MAX = 12; + static constexpr uint32_t TOKENID1 = 123; + static constexpr uint32_t TOKENID2 = 456; static DistributedKvDataManager manager; static Options create; static UserId userId; @@ -241,7 +243,7 @@ void KvdbServiceImplTest::CreateStoreMetaData(std::vector &datas, meta6.user = param.userId; // param.userId = "user1" meta6.appId = "valid_app_id"; meta6.storeId = "store_id_2"; - meta6.tokenId = 123; + meta6.tokenId = TOKENID1; metaData.push_back(meta6); // 6: trigger SetEqualIdentifier. @@ -250,7 +252,7 @@ void KvdbServiceImplTest::CreateStoreMetaData(std::vector &datas, meta7.user = param.userId; meta7.appId = "valid_app_id"; meta7.storeId = "store_id_3"; - meta7.tokenId = 456; + meta7.tokenId = TOKENID2; metaData.push_back(meta7); } -- Gitee From 033122a27d60818be274b77ff11ad236e72b81bd Mon Sep 17 00:00:00 2001 From: suoqilong Date: Mon, 28 Apr 2025 02:17:55 +0000 Subject: [PATCH 213/225] =?UTF-8?q?=E5=BC=82=E5=B8=B8=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=E6=95=B4=E6=94=B9-0428?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .../distributeddataservice/service/test/BUILD.gn | 1 + .../service/test/user_delegate_mock_test.cpp | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 17eb73404..503d6f059 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -2016,6 +2016,7 @@ group("unittest") { ":KvdbServiceImplTest", ":QueryHelperUnitTest", ":UpgradeMockTest", + ":UserDelegateMockTest", ] } diff --git a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp index 373782b7e..d59431f57 100644 --- a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp +++ b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp @@ -39,6 +39,11 @@ bool MetaDataManager::Subscribe(std::string prefix, Observer observer, bool isLo return false; } +bool MetaDataManager::SaveMeta(const std::string &key, const Serializable &value, bool isLocal) +{ + return true; +} + namespace OHOS::Test { namespace DistributedDataTest { class UserDelegateMockTest : public testing::Test { @@ -144,6 +149,13 @@ HWTEST_F(UserDelegateMockTest, Init, TestSize.Level0) ASSERT_NE(poolPtr, nullptr); UserDelegate::GetInstance().executors_ = poolPtr; ASSERT_NE(UserDelegate::GetInstance().executors_, nullptr); + + std::vector users = { 0 }; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .WillRepeatedly(([&users](std::vector &out) { + out = users; + })); + EXPECT_TRUE(UserDelegate::GetInstance().InitLocalUserMeta()); UserDelegate::GetInstance().Init(poolPtr); ASSERT_TRUE(UserDelegate::GetInstance().executors_ != nullptr); } -- Gitee From d6b3c3c94c5c75ab8a09c73ea7bef2b8fe1231ef Mon Sep 17 00:00:00 2001 From: suoqilong Date: Mon, 28 Apr 2025 03:13:35 +0000 Subject: [PATCH 214/225] =?UTF-8?q?=E5=BC=82=E5=B8=B8=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=E6=95=B4=E6=94=B9-0428?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .../service/test/user_delegate_mock_test.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp index d59431f57..f27921d18 100644 --- a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp +++ b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp @@ -154,6 +154,7 @@ HWTEST_F(UserDelegateMockTest, Init, TestSize.Level0) EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) .WillRepeatedly(([&users](std::vector &out) { out = users; + return true; })); EXPECT_TRUE(UserDelegate::GetInstance().InitLocalUserMeta()); UserDelegate::GetInstance().Init(poolPtr); -- Gitee From 45ae2f450f68f9137d71c7abdd4812894b2132db Mon Sep 17 00:00:00 2001 From: guochao Date: Mon, 28 Apr 2025 12:00:33 +0800 Subject: [PATCH 215/225] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20BUFFER=5FSIZE=20?= =?UTF-8?q?=E8=AE=A1=E7=AE=97=20Signed-off-by:=20guochao=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../app/test/unittest/session_manager_test.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index 0983ee13e..e009b52ad 100644 --- a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -303,8 +303,7 @@ private: static constexpr size_t APP_STR_LEN = 4; uint8_t *ptr = dataBuffer; size_t remaining = BUFFER_SIZE; - static constexpr size_t MAX_STORE_ID_LEN = 100; - static constexpr size_t BUFFER_SIZE = sizeof(dataBuffer) + sizeof(uint32_t) + MAX_STORE_ID_LEN; + static constexpr size_t BUFFER_SIZE = sizeof(dataBuffer); }; /** -- Gitee From b09d2af3594507ab39bfcd7fad9d34b413507160 Mon Sep 17 00:00:00 2001 From: Axi_Beft Date: Mon, 28 Apr 2025 22:34:41 +0800 Subject: [PATCH 216/225] data_share CodeCheck fix Signed-off-by: Axi_Beft --- .../subscriber_managers/published_data_subscriber_manager.h | 1 - 1 file changed, 1 deletion(-) diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h b/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h index 27e002d96..40a6fbf05 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h +++ b/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h @@ -37,7 +37,6 @@ struct PublishedDataKey { std::string key; std::string bundleName; int64_t subscriberId; - int32_t userId; }; class PublishedDataSubscriberManager { -- Gitee From 85d2335662dccc12192c45e8baca454d3cbfce02 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Tue, 29 Apr 2025 01:19:04 +0000 Subject: [PATCH 217/225] =?UTF-8?q?=E5=BC=82=E5=B8=B8=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=E6=95=B4=E6=94=B9-0428?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .../service/test/user_delegate_mock_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp index f27921d18..26cb1fc20 100644 --- a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp +++ b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp @@ -150,7 +150,7 @@ HWTEST_F(UserDelegateMockTest, Init, TestSize.Level0) UserDelegate::GetInstance().executors_ = poolPtr; ASSERT_NE(UserDelegate::GetInstance().executors_, nullptr); - std::vector users = { 0 }; + std::vector users = {1, 2, 3}; EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) .WillRepeatedly(([&users](std::vector &out) { out = users; -- Gitee From cb2bbe13296a2482d52852c79cbdbed91b428a73 Mon Sep 17 00:00:00 2001 From: suoqilong Date: Tue, 29 Apr 2025 11:14:51 +0000 Subject: [PATCH 218/225] =?UTF-8?q?=E5=BC=82=E5=B8=B8=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=E6=95=B4=E6=94=B9-0428?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .../service/test/user_delegate_mock_test.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp index 26cb1fc20..712caca91 100644 --- a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp +++ b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp @@ -95,7 +95,8 @@ HWTEST_F(UserDelegateMockTest, InitLocalUserMeta, TestSize.Level0) std::vector users; EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) - .WillRepeatedly(DoAll(SetArgReferee<0>(users), Return(true))); + .Times(1) + .WillOnce(DoAll(SetArgReferee<0>(users), Return(true))); ret = UserDelegate::GetInstance().InitLocalUserMeta(); UserDelegate::GetInstance().DeleteUsers("users"); EXPECT_FALSE(ret); @@ -145,17 +146,14 @@ HWTEST_F(UserDelegateMockTest, Init, TestSize.Level0) EXPECT_CALL(AccountDelegateMock::Init(), Subscribe(_)).WillRepeatedly(Return(0)); DeviceInfo devInfo = { .uuid = "HJJ4FGAGAAGA45WF3663FAGA" }; EXPECT_CALL(*devMgrAdapterMock, GetLocalDevice()).WillRepeatedly(Return(devInfo)); - std::shared_ptr poolPtr = std::make_shared(0, 1); + std::shared_ptr poolPtr = std::make_shared(1, 0); ASSERT_NE(poolPtr, nullptr); UserDelegate::GetInstance().executors_ = poolPtr; ASSERT_NE(UserDelegate::GetInstance().executors_, nullptr); - std::vector users = {1, 2, 3}; + std::vector users = {0, 1}; EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) - .WillRepeatedly(([&users](std::vector &out) { - out = users; - return true; - })); + .WillRepeatedly(DoAll(SetArgReferee<0>(users), Return(true))); EXPECT_TRUE(UserDelegate::GetInstance().InitLocalUserMeta()); UserDelegate::GetInstance().Init(poolPtr); ASSERT_TRUE(UserDelegate::GetInstance().executors_ != nullptr); -- Gitee From 3c2960035bd570e64c34ecd60bd444868ed2ebab Mon Sep 17 00:00:00 2001 From: changjiaxing Date: Wed, 30 Apr 2025 17:58:35 +0800 Subject: [PATCH 219/225] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=A9=BA=E5=8F=A3?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: changjiaxing Change-Id: I1ea200ec673648a54afa656b4bc5eeab6853457c --- .../distributeddataservice/app/src/checker/bundle_checker.cpp | 1 - .../distributeddataservice/service/rdb/rdb_service_impl.cpp | 3 ++- .../distributeddataservice/service/test/mock/checker_mock.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/services/distributeddataservice/app/src/checker/bundle_checker.cpp b/services/distributeddataservice/app/src/checker/bundle_checker.cpp index 674e09d59..b14a5fedd 100644 --- a/services/distributeddataservice/app/src/checker/bundle_checker.cpp +++ b/services/distributeddataservice/app/src/checker/bundle_checker.cpp @@ -114,7 +114,6 @@ bool BundleChecker::IsValid(const CheckerManager::StoreInfo &info) if (AccessTokenKit::GetHapTokenInfo(info.tokenId, tokenInfo) != RET_SUCCESS) { return false; } - return tokenInfo.bundleName == info.bundleName; } diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 30e197972..b2d0164d1 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -228,7 +228,8 @@ bool RdbServiceImpl::CheckAccess(const std::string& bundleName, const std::strin storeInfo.tokenId = IPCSkeleton::GetCallingTokenID(); storeInfo.bundleName = bundleName; storeInfo.storeId = RemoveSuffix(storeName); - return !CheckerManager::GetInstance().GetAppId(storeInfo).empty(); + + return CheckerManager::GetInstance().IsValid(storeInfo); } std::string RdbServiceImpl::ObtainDistributedTableName(const std::string &device, const std::string &table) diff --git a/services/distributeddataservice/service/test/mock/checker_mock.cpp b/services/distributeddataservice/service/test/mock/checker_mock.cpp index 22a2e748e..4adc8baa7 100644 --- a/services/distributeddataservice/service/test/mock/checker_mock.cpp +++ b/services/distributeddataservice/service/test/mock/checker_mock.cpp @@ -47,7 +47,7 @@ std::string CheckerMock::GetAppId(const CheckerManager::StoreInfo &info) bool CheckerMock::IsValid(const CheckerManager::StoreInfo &info) { - return true; + return !info.bundleName.empty(); } bool CheckerMock::SetDistrustInfo(const CheckerManager::Distrust &distrust) -- Gitee From 08c0f0823b98f5f616ebad056558130c8539e7f7 Mon Sep 17 00:00:00 2001 From: zhangdi Date: Mon, 5 May 2025 17:46:17 +0800 Subject: [PATCH 220/225] =?UTF-8?q?=E6=97=A5=E5=8E=86frezze=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E8=A7=A3=E5=86=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangdi --- .../service/rdb/rdb_general_store.cpp | 27 +++++++++++++------ .../service/rdb/rdb_general_store.h | 1 + 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.cpp b/services/distributeddataservice/service/rdb/rdb_general_store.cpp index edd37fd99..4c4354c47 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.cpp +++ b/services/distributeddataservice/service/rdb/rdb_general_store.cpp @@ -899,6 +899,20 @@ void RdbGeneralStore::Report(const std::string &faultType, int32_t errCode, cons Reporter::GetInstance()->CloudSyncFault()->Report(msg); } +int32_t RdbGeneralStore::SetReference(const std::vector &references) +{ + std::vector properties; + for (const auto &reference : references) { + properties.push_back({reference.sourceTable, reference.targetTable, reference.refFields}); + } + auto status = delegate_->SetReference(properties); + if (status != DistributedDB::DBStatus::OK && status != DistributedDB::DBStatus::PROPERTY_CHANGED) { + ZLOGE("distributed table set reference failed, err:%{public}d", status); + return GeneralError::E_ERROR; + } + return GeneralError::E_OK; +} + int32_t RdbGeneralStore::SetDistributedTables(const std::vector &tables, int32_t type, const std::vector &references) { @@ -919,14 +933,11 @@ int32_t RdbGeneralStore::SetDistributedTables(const std::vector &ta return GeneralError::E_ERROR; } } - std::vector properties; - for (const auto &reference : references) { - properties.push_back({ reference.sourceTable, reference.targetTable, reference.refFields }); - } - auto status = delegate_->SetReference(properties); - if (status != DistributedDB::DBStatus::OK && status != DistributedDB::DBStatus::PROPERTY_CHANGED) { - ZLOGE("distributed table set reference failed, err:%{public}d", status); - return GeneralError::E_ERROR; + if (type == DistributedTableType::DISTRIBUTED_CLOUD) { + auto status = SetReference(references); + if (status != GeneralError::E_OK) { + return GeneralError::E_ERROR; + } } auto [exist, database] = GetDistributedSchema(observer_.meta_); if (exist && type == DistributedTableType::DISTRIBUTED_DEVICE) { diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.h b/services/distributeddataservice/service/rdb/rdb_general_store.h index 3f2d394ef..dd7c60f61 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.h +++ b/services/distributeddataservice/service/rdb/rdb_general_store.h @@ -59,6 +59,7 @@ public: bool IsBound(uint32_t user) override; bool IsValid(); int32_t Execute(const std::string &table, const std::string &sql) override; + int32_t SetReference(const std::vector &references); int32_t SetDistributedTables(const std::vector &tables, int32_t type, const std::vector &references) override; int32_t SetTrackerTable(const std::string& tableName, const std::set& trackerColNames, -- Gitee From 64ff58d90dd9e47f7d5df48f4e21e3c8455c0aab Mon Sep 17 00:00:00 2001 From: zhangdi Date: Tue, 6 May 2025 20:56:52 +0800 Subject: [PATCH 221/225] =?UTF-8?q?UT=E5=A4=B1=E8=B4=A5=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangdi --- .../service/test/rdb_general_store_test.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index c6f60f81f..24e4dfab6 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -854,7 +854,7 @@ HWTEST_F(RdbGeneralStoreTest, Release, TestSize.Level1) HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) { std::vector tables = { "table1", "table2" }; - int32_t type = 0; + int32_t type = DistributedTableType::DISTRIBUTED_DEVICE; std::vector references; auto result = store->SetDistributedTables(tables, type, references); EXPECT_EQ(result, GeneralError::E_ALREADY_CLOSED); @@ -869,6 +869,9 @@ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) EXPECT_EQ(result, GeneralError::E_ERROR); MockRelationalStoreDelegate::gTestResult = true; result = store->SetDistributedTables(tables, type, references); + EXPECT_EQ(result, GeneralError::E_OK); + type = DistributedTableType::DISTRIBUTED_CLOUD; + result = store->SetDistributedTables(tables, type, references); EXPECT_EQ(result, GeneralError::E_ERROR); } -- Gitee From a9f17ecd33910b5f2938de96ca5604a044a37724 Mon Sep 17 00:00:00 2001 From: wTong6 Date: Tue, 29 Apr 2025 16:40:31 +0800 Subject: [PATCH 222/225] fix Signed-off-by: wTong6 --- .../adapter/dfx/test/BUILD.gn | 10 +- services/distributeddataservice/app/BUILD.gn | 3 +- .../distributeddataservice/app/test/BUILD.gn | 40 +++--- .../framework/test/BUILD.gn | 116 ++++++------------ .../service/test/BUILD.gn | 72 +++++------ 5 files changed, 95 insertions(+), 146 deletions(-) diff --git a/services/distributeddataservice/adapter/dfx/test/BUILD.gn b/services/distributeddataservice/adapter/dfx/test/BUILD.gn index 78a3fa45b..67f11fddb 100755 --- a/services/distributeddataservice/adapter/dfx/test/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/test/BUILD.gn @@ -36,6 +36,7 @@ ohos_unittest("DistributeddataDfxMSTTest") { external_deps = [ "c_utils:utils", "datamgr_service:distributeddatasvcfwk", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", @@ -43,11 +44,7 @@ ohos_unittest("DistributeddataDfxMSTTest") { "openssl:libcrypto_shared", ] ldflags = [ "-Wl,--exclude-libs,ALL" ] - deps = [ - "${data_service_path}/adapter/dfx:distributeddata_dfx", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", - ] + deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx" ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } @@ -77,6 +74,7 @@ ohos_unittest("DistributeddataDfxUTTest") { external_deps = [ "c_utils:utils", "datamgr_service:distributeddatasvcfwk", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", @@ -87,8 +85,6 @@ ohos_unittest("DistributeddataDfxUTTest") { deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx", "${data_service_path}/adapter/utils:distributeddata_utils", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index 4c0087d06..45849945d 100644 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -38,7 +38,6 @@ ohos_sa_profile("distributeddata_profile") { config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "${kv_store_common_path}", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", "${data_service_path}/adapter/include/account", @@ -169,4 +168,4 @@ ohos_shared_library("distributeddataservice") { subsystem_name = "distributeddatamgr" part_name = "datamgr_service" defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] -} +} \ No newline at end of file diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index 392b903b0..4feefbd64 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -19,12 +19,8 @@ module_output_path = "datamgr_service/datamgr_service/distributeddataservice" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", - "${kv_store_path}/frameworks/common", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/src", - "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", - "${kv_store_path}/interfaces/innerkits/distributeddata/include", "${data_service_path}/adapter/include/permission", "${data_service_path}/adapter/include/account", "${data_service_path}/adapter/include", @@ -42,9 +38,6 @@ config("module_private_config") { "${data_service_path}/app/src/session_manager", "${data_service_path}/service/kvdb", "${data_service_path}/service/test/mock", - "${device_manager_path}/interfaces/inner_kits/native_cpp/include", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", "../include", "../src", "../src/security", @@ -53,7 +46,6 @@ config("module_private_config") { "../../service/backup/include", "../../../../interfaces/innerkits/distributeddata", "../../service/dumper/include", - "//third_party/json/single_include", "${data_service_path}/adapter/include/communicator", ] @@ -110,7 +102,9 @@ ohos_unittest("KvStoreDataServiceTest") { "common_event_service:cesfwk_innerkits", "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", + "device_manager:devicemanagersdk", "file_api:securitylabel", + "googletest:gtest_main", "hicollie:libhicollie", "hilog:libhilog", "hisysevent:libhisysevent", @@ -118,6 +112,7 @@ ohos_unittest("KvStoreDataServiceTest") { "hitrace:libhitracechain", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "kv_store:distributeddb", "memmgr:memmgrclient", "safwk:system_ability_fwk", @@ -134,7 +129,6 @@ ohos_unittest("KvStoreDataServiceTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] part_name = "datamgr_service" } @@ -167,11 +161,17 @@ ohos_unittest("SessionManagerTest") { "c_utils:utils", "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", + "device_manager:devicemanagersdk", "file_api:securitylabel", "googletest:gmock", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", + "json:nlohmann_json_static", + "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", + "kv_store:distributeddb", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] @@ -186,13 +186,9 @@ ohos_unittest("SessionManagerTest") { deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/app/src/checker:distributeddata_checker", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", "${data_service_path}/service/test/mock:distributeddata_mock_static", - "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", ] part_name = "datamgr_service" @@ -237,13 +233,16 @@ ohos_unittest("KvStoreDataServiceClearTest") { "c_utils:utils", "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", + "device_manager:devicemanagersdk", "file_api:securitylabel", + "googletest:gtest_main", "hicollie:libhicollie", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", "hitrace:libhitracechain", "ipc:ipc_core", + "json:nlohmann_json_static", "kv_store:distributeddata_inner", "kv_store:distributeddata_mgr", "kv_store:distributeddb", @@ -265,7 +264,6 @@ ohos_unittest("KvStoreDataServiceClearTest") { "${data_service_path}/app/src/installer:distributeddata_installer", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] part_name = "datamgr_service" @@ -302,6 +300,7 @@ ohos_unittest("FeatureStubImplTest") { "c_utils:utils", "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", + "device_manager:devicemanagersdk", "file_api:securitylabel", "googletest:gtest_main", "hilog:libhilog", @@ -350,14 +349,5 @@ group("unittest") { ############################################################################### group("moduletest") { testonly = true - deps = [ - "//third_party/googletest:gmock", - "//third_party/googletest:gtest_main", - "//third_party/sqlite:sqlite", - ] - - deps += [ - #":DistributedDataAccountEventModuleTest", - ] } ############################################################################### diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn index 24a5a8d64..4417c7c7a 100644 --- a/services/distributeddataservice/framework/test/BUILD.gn +++ b/services/distributeddataservice/framework/test/BUILD.gn @@ -21,30 +21,19 @@ config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "${device_manager_path}/interfaces/inner_kits/native_cpp/include", - "../include/", - "../../service/bootstrap/include/", - "../../service/common/", - "../../service/rdb/", - "../../../../../relational_store/interfaces/inner_api/rdb/include", - "../../../../../relational_store/interfaces/inner_api/common_type/include", - "${kv_store_distributeddb_path}/interfaces/include", - "${kv_store_distributeddb_path}/include", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", - "${kv_store_common_path}", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/src", - "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", - "${kv_store_path}/interfaces/innerkits/distributeddata/include", + "${data_service_path}/service/bootstrap/include/", + "${data_service_path}/service/common/", + "${data_service_path}/service/rdb/", "${data_service_path}/adapter/include", "${data_service_path}/framework/include", "${data_service_path}/service/config/include", "${data_service_path}/app/src", "${data_service_path}/adapter/include/account", + "${data_service_path}/adapter/include/communicator", "${data_service_path}/app/src/security", "${data_service_path}/service/crypto/include", "${data_service_path}/service/matrix/include", - "//third_party/json/single_include", + "${data_service_path}/service/kvdb", ] cflags = [ "-Werror" ] ldflags = [ "-Wl,--whole-archive" ] @@ -61,17 +50,17 @@ ohos_unittest("CheckerManagerTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", ] deps = [ "${data_service_path}/app/src/checker:distributeddata_checker", - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", ] } @@ -83,15 +72,13 @@ ohos_unittest("EventCenterTest") { external_deps = [ "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", ] - deps = [ - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", - ] + deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] } ohos_unittest("SerializableTest") { @@ -105,16 +92,14 @@ ohos_unittest("SerializableTest") { "ability_base:base", "ability_base:want", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", ] - deps = [ - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", - ] + deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] } ohos_unittest("ServiceUtilsTest") { @@ -133,14 +118,13 @@ ohos_unittest("ServiceUtilsTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "json:nlohmann_json_static", ] - deps = [ - "${data_service_path}/framework:distributeddatasvcfwk", - "//third_party/googletest:gtest_main", - ] + deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] } ohos_unittest("StoreTest") { @@ -170,6 +154,7 @@ ohos_unittest("StoreTest") { "access_token:libnativetoken", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -183,7 +168,6 @@ ohos_unittest("StoreTest") { "${data_service_path}/service:distributeddatasvc", "${data_service_path}/service/common:distributeddata_common", "${data_service_path}/service/test/mock:distributeddata_mock_static", - "//third_party/googletest:gtest_main", ] } @@ -213,6 +197,11 @@ ohos_unittest("CloudInfoTest") { sources = [ "cloud_test.cpp" ] configs = [ ":module_private_config" ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] + + external_deps = [ + "json:nlohmann_json_static", + "kv_store:datamgr_common", + ] } ohos_unittest("EventTest") { @@ -227,6 +216,7 @@ ohos_unittest("GeneralStoreTest") { sources = [ "general_store_test.cpp" ] configs = [ ":module_private_config" ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] + external_deps = [ "kv_store:datamgr_common" ] } ohos_unittest("SubscriptionTest") { @@ -234,16 +224,18 @@ ohos_unittest("SubscriptionTest") { sources = [ "subscription_test.cpp" ] configs = [ ":module_private_config" ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] + external_deps = [ + "json:nlohmann_json_static", + "kv_store:datamgr_common", + ] } ohos_unittest("FeatureTest") { module_out_path = module_output_path sources = [ "feature_test.cpp" ] configs = [ ":module_private_config" ] - deps = [ - "${data_service_path}/framework:distributeddatasvcfwk", - "${kv_store_path}/interfaces/innerkits/distributeddata:distributeddata_inner", - ] + deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] + external_deps = [ "kv_store:distributeddata_inner" ] } ohos_unittest("MetaDataManagerTest") { @@ -255,14 +247,15 @@ ohos_unittest("MetaDataManagerTest") { external_deps = [ "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "json:nlohmann_json_static", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] } @@ -271,6 +264,7 @@ ohos_unittest("StoreMetaDataLocalTest") { sources = [ "store_meta_data_local_test.cpp" ] configs = [ ":module_private_config" ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] + external_deps = [ "json:nlohmann_json_static" ] } ohos_unittest("ConstantTest") { @@ -308,47 +302,22 @@ ohos_unittest("ServiceMetaDataTest") { configs = [ ":module_private_config" ] - include_dirs = [ - "${device_manager_path}/interfaces/inner_kits/native_cpp/include", - "../include/", - "../../service/bootstrap/include/", - "../../service/common/", - "../../service/rdb/", - "../../../../../relational_store/interfaces/inner_api/rdb/include", - "../../../../../relational_store/interfaces/inner_api/common_type/include", - "${kv_store_distributeddb_path}/interfaces/include", - "${kv_store_distributeddb_path}/include", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", - "${kv_store_common_path}", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/src", - "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", - "${kv_store_path}/interfaces/innerkits/distributeddata/include", - "${data_service_path}/adapter/include", - "${data_service_path}/framework/include", - "${data_service_path}/service/config/include", - "${data_service_path}/app/src", - "${data_service_path}/adapter/include/account", - "${data_service_path}/app/src/security", - "${data_service_path}/service/crypto/include", - "${data_service_path}/service/matrix/include", - "${data_service_path}/service/kvdb", - "//third_party/json/single_include", - "${data_service_path}/adapter/include/communicator", - ] - external_deps = [ "c_utils:utils", "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", + "device_manager:devicemanagersdk", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", "hitrace:libhitracechain", "ipc:ipc_core", + "json:nlohmann_json_static", "kv_store:distributeddata_inner", "kv_store:distributeddata_mgr", "kv_store:distributeddb", + "openssl:libcrypto_shared", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] @@ -360,11 +329,6 @@ ohos_unittest("ServiceMetaDataTest") { "${data_service_path}/app/src/checker:distributeddata_checker", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/kvdb:distributeddata_kvdb", - "${kv_store_distributeddb_path}:distributeddb", - "${kv_store_path}/interfaces/innerkits/distributeddata:distributeddata_inner", - "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", ] } diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 0a54979be..e1e2db2bd 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -128,6 +128,7 @@ ohos_unittest("CloudDataTest") { "bundle_framework:appexecfwk_core", "c_utils:utils", "device_manager:devicemanagersdk", + "googletest:gtest_main", "hicollie:libhicollie", "hilog:libhilog", "hisysevent:libhisysevent", @@ -145,9 +146,8 @@ ohos_unittest("CloudDataTest") { "${data_service_path}/adapter/account:distributeddata_account", "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/adapter/schema_helper:distributeddata_schema_helper", - "../../framework:distributeddatasvcfwk", + "${data_service_path}/framework:distributeddatasvcfwk", "mock:distributeddata_mock_static", - "//third_party/googletest:gtest_main", ] cflags = [ @@ -226,6 +226,7 @@ ohos_unittest("CloudServiceImplTest") { "bundle_framework:appexecfwk_core", "c_utils:utils", "device_manager:devicemanagersdk", + "googletest:gtest_main", "hicollie:libhicollie", "hilog:libhilog", "hisysevent:libhisysevent", @@ -245,7 +246,6 @@ ohos_unittest("CloudServiceImplTest") { "${data_service_path}/adapter/schema_helper:distributeddata_schema_helper", "../../framework:distributeddatasvcfwk", "mock:distributeddata_mock_static", - "//third_party/googletest:gtest_main", ] cflags = [ @@ -265,6 +265,7 @@ ohos_unittest("CloudTest") { "ability_base:base", "ability_base:want", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -275,7 +276,6 @@ ohos_unittest("CloudTest") { "../../framework:distributeddatasvcfwk", "../../service:distributeddatasvc", "mock:distributeddata_mock_static", - "//third_party/googletest:gtest_main", ] } @@ -304,6 +304,7 @@ ohos_unittest("ValueProxyServiceTest") { "ability_base:base", "ability_base:want", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -314,7 +315,6 @@ ohos_unittest("ValueProxyServiceTest") { "${relational_store_inner_api_path}:native_rdb_static", "../../framework:distributeddatasvcfwk", "../../service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] } @@ -328,16 +328,16 @@ ohos_unittest("ConfigFactoryTest") { "ability_base:base", "ability_base:want", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", ] deps = [ "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", ] } @@ -353,15 +353,15 @@ ohos_unittest("DirectoryManagerTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", ] deps = [ "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", ] } @@ -377,15 +377,15 @@ ohos_unittest("CryptoManagerTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", ] deps = [ "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", ] } @@ -411,16 +411,16 @@ ohos_unittest("DeviceMatrixTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", + "kv_store:distributeddb", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", ] } @@ -461,9 +461,11 @@ ohos_unittest("KVDBGeneralStoreTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddb", ] deps = [ @@ -471,8 +473,6 @@ ohos_unittest("KVDBGeneralStoreTest") { "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/kvdb:distributeddata_kvdb", - "${kv_store_distributeddb_path}:distributeddb", - "//third_party/googletest:gtest_main", ] } @@ -578,16 +578,16 @@ ohos_unittest("RdbResultSetImplTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddb", ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/framework:distributeddatasvcfwk", - "${kv_store_distributeddb_path}:distributeddb", "${relational_store_inner_api_path}:native_rdb_static", - "//third_party/googletest:gtest_main", ] } @@ -636,6 +636,7 @@ ohos_unittest("RdbServiceTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -646,7 +647,6 @@ ohos_unittest("RdbServiceTest") { "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", "${relational_store_inner_api_path}:native_rdb_static", - "//third_party/googletest:gtest_main", ] } @@ -737,6 +737,7 @@ ohos_unittest("ObjectAssetLoaderTest") { "c_utils:utils", "dfs_service:cloudsync_asset_kit_inner", "dfs_service:distributed_file_daemon_kit_inner", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", @@ -747,7 +748,6 @@ ohos_unittest("ObjectAssetLoaderTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] cflags = [ @@ -776,6 +776,7 @@ ohos_unittest("ObjectAssetMachineTest") { "c_utils:utils", "dfs_service:cloudsync_asset_kit_inner", "dfs_service:distributed_file_daemon_kit_inner", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", @@ -786,7 +787,6 @@ ohos_unittest("ObjectAssetMachineTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] } @@ -809,6 +809,7 @@ ohos_unittest("ObjectDmsHandlerTest") { external_deps = [ "c_utils:utils", "dmsfwk:distributed_sdk", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -817,7 +818,6 @@ ohos_unittest("ObjectDmsHandlerTest") { deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/framework:distributeddatasvcfwk", - "//third_party/googletest:gtest_main", ] cflags = [ @@ -873,6 +873,7 @@ ohos_unittest("ObjectManagerTest") { "dmsfwk:distributed_sdk", "googletest:gmock_main", "googletest:gtest_main", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", @@ -886,7 +887,6 @@ ohos_unittest("ObjectManagerTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] cflags = [ @@ -916,6 +916,7 @@ ohos_unittest("ObjectSnapshotTest") { "c_utils:utils", "dfs_service:cloudsync_asset_kit_inner", "dfs_service:distributed_file_daemon_kit_inner", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", @@ -926,7 +927,6 @@ ohos_unittest("ObjectSnapshotTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] } @@ -961,11 +961,13 @@ ohos_unittest("MetaDataTest") { "access_token:libtoken_setproc", "c_utils:utils", "dataclassification:data_transit_mgr", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", "json:nlohmann_json_static", "kv_store:distributeddata_inner", + "kv_store:distributeddb", ] deps = [ @@ -973,8 +975,6 @@ ohos_unittest("MetaDataTest") { "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/kvdb:distributeddata_kvdb", - "${kv_store_path}/frameworks/libs/distributeddb:distributeddb", - "//third_party/googletest:gtest_main", ] } @@ -1011,11 +1011,14 @@ ohos_unittest("UdmfRunTimeStoreTest") { "c_utils:utils", "dataclassification:data_transit_mgr", "dsoftbus:softbus_client", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "image_framework:image", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddb", + "openssl:libcrypto_shared", "samgr:samgr_proxy", "udmf:udmf_client", ] @@ -1025,9 +1028,6 @@ ohos_unittest("UdmfRunTimeStoreTest") { "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", "${data_service_path}/service/udmf:udmf_server", - "${kv_store_path}/frameworks/libs/distributeddb:distributeddb", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", ] defines = [ @@ -1140,6 +1140,7 @@ ohos_unittest("DataShareServiceImplTest") { "common_event_service:cesfwk_innerkits", "data_share:datashare_common", "device_manager:devicemanagersdk", + "googletest:gtest_main", "hicollie:libhicollie", "hilog:libhilog", "hisysevent:libhisysevent", @@ -1149,6 +1150,7 @@ ohos_unittest("DataShareServiceImplTest") { "json:nlohmann_json_static", "kv_store:distributeddata_inner", "kv_store:distributeddb", + "kv_store:distributeddb", "qos_manager:concurrent_task_client", "qos_manager:qos", "relational_store:native_rdb", @@ -1162,8 +1164,6 @@ ohos_unittest("DataShareServiceImplTest") { "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "${kv_store_distributeddb_path}:distributeddb", - "//third_party/googletest:gtest_main", ] } @@ -1214,10 +1214,12 @@ ohos_unittest("KvdbServiceImplTest") { "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", "googletest:gmock_main", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddb", "relational_store:native_rdb", ] @@ -1226,9 +1228,7 @@ ohos_unittest("KvdbServiceImplTest") { "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/kvdb:distributeddata_kvdb", - "${kv_store_path}/frameworks/libs/distributeddb:distributeddb", "mock:distributeddata_mock_static", - "//third_party/googletest:gtest_main", ] } @@ -1250,6 +1250,7 @@ ohos_unittest("DumpHelperTest") { external_deps = [ "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "kv_store:distributeddata_inner", "kv_store:distributeddb", @@ -1259,7 +1260,6 @@ ohos_unittest("DumpHelperTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] } @@ -1712,8 +1712,8 @@ ohos_unittest("BootStrapMockTest") { deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", + "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/backup:distributeddata_backup", - "../../framework:distributeddatasvcfwk", ] cflags = [ -- Gitee From ee6ba766b3ebbf74e5dbc45afbf9f806e1c0ba4d Mon Sep 17 00:00:00 2001 From: suoqilong Date: Wed, 7 May 2025 07:29:23 +0000 Subject: [PATCH 223/225] =?UTF-8?q?=E5=BC=82=E5=B8=B8=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=E6=95=B4=E6=94=B9-0428?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: suoqilong --- .../service/test/user_delegate_mock_test.cpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp index 712caca91..910e17ca9 100644 --- a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp +++ b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp @@ -41,6 +41,8 @@ bool MetaDataManager::Subscribe(std::string prefix, Observer observer, bool isLo bool MetaDataManager::SaveMeta(const std::string &key, const Serializable &value, bool isLocal) { + (void)key; + (void)value; return true; } @@ -89,7 +91,9 @@ HWTEST_F(UserDelegateMockTest, GetLocalUserStatus, TestSize.Level0) */ HWTEST_F(UserDelegateMockTest, InitLocalUserMeta, TestSize.Level0) { - EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)).WillOnce(Return(false)); + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .Times(1) + .WillOnce(Return(false)); bool ret = UserDelegate::GetInstance().InitLocalUserMeta(); EXPECT_FALSE(ret); @@ -148,15 +152,16 @@ HWTEST_F(UserDelegateMockTest, Init, TestSize.Level0) EXPECT_CALL(*devMgrAdapterMock, GetLocalDevice()).WillRepeatedly(Return(devInfo)); std::shared_ptr poolPtr = std::make_shared(1, 0); ASSERT_NE(poolPtr, nullptr); - UserDelegate::GetInstance().executors_ = poolPtr; - ASSERT_NE(UserDelegate::GetInstance().executors_, nullptr); + UserDelegate instance; + instance.executors_ = poolPtr; + ASSERT_NE(instance.executors_, nullptr); std::vector users = {0, 1}; EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) .WillRepeatedly(DoAll(SetArgReferee<0>(users), Return(true))); - EXPECT_TRUE(UserDelegate::GetInstance().InitLocalUserMeta()); - UserDelegate::GetInstance().Init(poolPtr); - ASSERT_TRUE(UserDelegate::GetInstance().executors_ != nullptr); + EXPECT_TRUE(instance.InitLocalUserMeta()); + instance.Init(poolPtr); + ASSERT_TRUE(instance.executors_ != nullptr); } } } \ No newline at end of file -- Gitee From 0d2ab91d01777282a91d55503f16036ecfd6128a Mon Sep 17 00:00:00 2001 From: gecheng Date: Sun, 4 May 2025 17:06:24 +0800 Subject: [PATCH 224/225] return errorcode Signed-off-by: gecheng --- .../distributeddataservice/framework/cloud/cloud_db.cpp | 8 ++++---- .../framework/include/cloud/cloud_db.h | 4 ++-- .../distributeddataservice/framework/test/cloud_test.cpp | 4 ++-- .../rust/extension/cloud_db_impl.cpp | 8 ++++++-- .../rust/extension/cloud_db_impl.h | 2 +- .../distributeddataservice/service/rdb/rdb_cloud.cpp | 9 +++++---- 6 files changed, 20 insertions(+), 15 deletions(-) diff --git a/services/distributeddataservice/framework/cloud/cloud_db.cpp b/services/distributeddataservice/framework/cloud/cloud_db.cpp index 863475888..3d916243e 100644 --- a/services/distributeddataservice/framework/cloud/cloud_db.cpp +++ b/services/distributeddataservice/framework/cloud/cloud_db.cpp @@ -40,14 +40,14 @@ int32_t CloudDB::BatchDelete(const std::string &table, VBuckets &extends) return E_NOT_SUPPORT; } -std::shared_ptr CloudDB::Query(const std::string &table, const VBucket &extend) +std::pair> CloudDB::Query(const std::string &table, const VBucket &extend) { - return nullptr; + return { E_NOT_SUPPORT, nullptr }; } -std::shared_ptr CloudDB::Query(GenQuery &query, const VBucket &extend) +std::pair> CloudDB::Query(GenQuery &query, const VBucket &extend) { - return nullptr; + return { E_NOT_SUPPORT, nullptr }; } int32_t CloudDB::PreSharing(const std::string &table, VBuckets &extend) diff --git a/services/distributeddataservice/framework/include/cloud/cloud_db.h b/services/distributeddataservice/framework/include/cloud/cloud_db.h index fcf7cfca5..589335632 100644 --- a/services/distributeddataservice/framework/include/cloud/cloud_db.h +++ b/services/distributeddataservice/framework/include/cloud/cloud_db.h @@ -40,9 +40,9 @@ public: virtual int32_t BatchDelete(const std::string &table, VBuckets &extends); - virtual std::shared_ptr Query(const std::string &table, const VBucket &extend); + virtual std::pair> Query(const std::string &table, const VBucket &extend); - virtual std::shared_ptr Query(GenQuery &query, const VBucket &extend); + virtual std::pair> Query(GenQuery &query, const VBucket &extend); virtual int32_t PreSharing(const std::string &table, VBuckets &extend); diff --git a/services/distributeddataservice/framework/test/cloud_test.cpp b/services/distributeddataservice/framework/test/cloud_test.cpp index 1940f95fc..5179ef017 100644 --- a/services/distributeddataservice/framework/test/cloud_test.cpp +++ b/services/distributeddataservice/framework/test/cloud_test.cpp @@ -502,9 +502,9 @@ HWTEST_F(ServicesCloudDBTest, CloudDB, TestSize.Level0) EXPECT_EQ(result1, GeneralError::E_NOT_SUPPORT); auto result2 = cloudDB.Query(table, extend); - EXPECT_EQ(result2, nullptr); + EXPECT_EQ(result2.second, nullptr); result2 = cloudDB.Query(query, extend); - EXPECT_EQ(result2, nullptr); + EXPECT_EQ(result2.second, nullptr); auto result3 = cloudDB.AliveTime(); EXPECT_EQ(result3, -1); diff --git a/services/distributeddataservice/rust/extension/cloud_db_impl.cpp b/services/distributeddataservice/rust/extension/cloud_db_impl.cpp index da137619b..3b042ba24 100644 --- a/services/distributeddataservice/rust/extension/cloud_db_impl.cpp +++ b/services/distributeddataservice/rust/extension/cloud_db_impl.cpp @@ -119,7 +119,7 @@ int32_t CloudDbImpl::BatchDelete(const std::string &table, DBVBuckets &extends) return ExtensionUtil::ConvertStatus(status); } -std::shared_ptr CloudDbImpl::Query(const std::string &table, const DBVBucket &extend) +std::pair> CloudDbImpl::Query(const std::string &table, const DBVBucket &extend) { std::string cursor; auto it = extend.find(DistributedData::SchemaMeta::CURSOR_FIELD); @@ -134,7 +134,11 @@ std::shared_ptr CloudDbImpl::Query(const std::string &table, const DBV }; OhCloudExtCloudDbData *cloudData = nullptr; auto status = OhCloudExtCloudDbBatchQuery(database_, &info, &cloudData); - return (status == ERRNO_SUCCESS && cloudData != nullptr) ? std::make_shared(cloudData) : nullptr; + if (status == ERRNO_SUCCESS && cloudData != nullptr) { + return std::make_pair(DBErr::E_OK, std::make_shared(cloudData)); + } + return status != ERRNO_SUCCESS ? std::make_pair(ExtensionUtil::ConvertStatus(status), nullptr) + : std::make_pair(DBErr::E_ERROR, nullptr); } int32_t CloudDbImpl::Lock() diff --git a/services/distributeddataservice/rust/extension/cloud_db_impl.h b/services/distributeddataservice/rust/extension/cloud_db_impl.h index 099bfaad0..5351ebbb9 100644 --- a/services/distributeddataservice/rust/extension/cloud_db_impl.h +++ b/services/distributeddataservice/rust/extension/cloud_db_impl.h @@ -36,7 +36,7 @@ public: int32_t BatchUpdate(const std::string &table, DBVBuckets &&values, DBVBuckets &extends) override; int32_t BatchUpdate(const std::string &table, DBVBuckets &&values, const DBVBuckets &extends) override; int32_t BatchDelete(const std::string &table, DBVBuckets &extends) override; - std::shared_ptr Query(const std::string &table, const DBVBucket &extend) override; + std::pair> Query(const std::string &table, const DBVBucket &extend) override; int32_t Lock() override; int32_t Heartbeat() override; int32_t Unlock() override; diff --git a/services/distributeddataservice/service/rdb/rdb_cloud.cpp b/services/distributeddataservice/service/rdb/rdb_cloud.cpp index 0a0726079..2043f3d02 100644 --- a/services/distributeddataservice/service/rdb/rdb_cloud.cpp +++ b/services/distributeddataservice/service/rdb/rdb_cloud.cpp @@ -76,17 +76,18 @@ DBStatus RdbCloud::Query(const std::string &tableName, DBVBucket &extend, std::v { auto [nodes, status] = ConvertQuery(extend); std::shared_ptr cursor = nullptr; + int32_t code = E_OK; if (status == GeneralError::E_OK && !nodes.empty()) { RdbQuery query; query.SetQueryNodes(tableName, std::move(nodes)); - cursor = cloudDB_->Query(query, ValueProxy::Convert(std::move(extend))); + std::tie(code, cursor) = cloudDB_->Query(query, ValueProxy::Convert(std::move(extend))); } else { - cursor = cloudDB_->Query(tableName, ValueProxy::Convert(std::move(extend))); + std::tie(code, cursor) = cloudDB_->Query(tableName, ValueProxy::Convert(std::move(extend))); } - if (cursor == nullptr) { + if (cursor == nullptr || code != E_OK) { ZLOGE("cursor is null, table:%{public}s, extend:%{public}zu", Anonymous::Change(tableName).c_str(), extend.size()); - return ConvertStatus(static_cast(E_ERROR)); + return ConvertStatus(static_cast(code != E_OK ? code : E_ERROR)); } int32_t count = cursor->GetCount(); data.reserve(count); -- Gitee From 231ef4edc7195053cc4b66d32857a29cb6ab2343 Mon Sep 17 00:00:00 2001 From: Jin1K <1061208093@qq.com> Date: Fri, 9 May 2025 10:29:37 +0800 Subject: [PATCH 225/225] optimize verify permission Signed-off-by: Jin1K <1061208093@qq.com> --- .../service/data_share/data_share_service_impl.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp index 6f1494aa9..4029047ba 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp @@ -1170,13 +1170,14 @@ bool DataShareServiceImpl::VerifyPermission(const std::string &bundleName, const } } else { Security::AccessToken::HapTokenInfo tokenInfo; - auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo); - if (result == Security::AccessToken::RET_SUCCESS && tokenInfo.bundleName == bundleName) { - return true; - } // Provider from ProxyData, which does not allow empty permissions and cannot be access without configured if (permission.empty()) { - ZLOGE("Permission empty! token:0x%{public}x, bundleName:%{public}s", tokenId, bundleName.c_str()); + ZLOGI("Permission empty! token:0x%{public}x, bundleName:%{public}s", tokenId, bundleName.c_str()); + auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo); + if (result == Security::AccessToken::RET_SUCCESS && tokenInfo.bundleName == bundleName) { + return true; + } + ZLOGE("Permission denied!"); return false; } // If the permission is NO_PERMISSION, access is also allowed -- Gitee