diff --git a/data_object/bundle.json b/data_object/bundle.json index 1c67d441cfddc847be2601c5837de2a45c13adcb..215ff8d1228763615fb77246f25288ef23dd7cd5 100644 --- a/data_object/bundle.json +++ b/data_object/bundle.json @@ -82,8 +82,7 @@ "test": [ "//foundation/distributeddatamgr/data_object/frameworks/innerkitsimpl/test/unittest:unittest", "//foundation/distributeddatamgr/data_object/frameworks/jskitsimpl/test/unittest:unittest", - "//foundation/distributeddatamgr/data_object/frameworks/innerkitsimpl/test/fuzztest/objectstore_fuzzer:fuzztest", - "//foundation/distributeddatamgr/data_object/frameworks/innerkitsimpl/test/distributedtest/data_object_test:distributedtest" + "//foundation/distributeddatamgr/data_object/frameworks/innerkitsimpl/test/fuzztest/objectstore_fuzzer:fuzztest" ] } } diff --git a/data_object/frameworks/innerkitsimpl/test/unittest/src/object_store_test.cpp b/data_object/frameworks/innerkitsimpl/test/unittest/src/object_store_test.cpp index 28736d92a8874a8fa1eee15322e915d74956ad06..8bc1f644d950eb046511f3d753c310ec5ba9dee7 100644 --- a/data_object/frameworks/innerkitsimpl/test/unittest/src/object_store_test.cpp +++ b/data_object/frameworks/innerkitsimpl/test/unittest/src/object_store_test.cpp @@ -332,6 +332,9 @@ HWTEST_F(NativeObjectStoreTest, DistributedObjectStoreImpl_Watch_002, TestSize.L status = objectStore->UnWatch(object1); EXPECT_EQ(ERR_DB_NOT_EXIST, status); + status = objectStore->UnWatch(object); + EXPECT_EQ(SUCCESS, status); + status = objectStore->DeleteObject(sessionId); EXPECT_EQ(SUCCESS, status); delete flatObjectStore; diff --git a/data_object/interfaces/jskits/distributed_data_object.js b/data_object/interfaces/jskits/distributed_data_object.js index f32a1ce45b47cd425a4000a449a4620f6844c59c..388106537f6b80c08a0bc6c9b454bbf23a52556e 100644 --- a/data_object/interfaces/jskits/distributed_data_object.js +++ b/data_object/interfaces/jskits/distributed_data_object.js @@ -151,7 +151,6 @@ function joinSession(version, obj, objectId, sessionId, context) { get: function () { console.info('start get ' + key); let result = object.get(key); - console.info('get ' + result); if (typeof result === 'string') { if (result.startsWith(STRING_TYPE)) { result = result.substr(STRING_TYPE.length); @@ -160,10 +159,10 @@ function joinSession(version, obj, objectId, sessionId, context) { } else if (result.startsWith(NULL_TYPE)) { result = null; } else { - console.error('error type ' + result); + console.error('error type'); } } - console.info('get ' + result + ' success'); + console.info('get success'); return result; }, set: function (newValue) { diff --git a/data_share/frameworks/native/consumer/src/datashare_connection.cpp b/data_share/frameworks/native/consumer/src/datashare_connection.cpp index 7ebc017f4d1be4ef3af6c477451b244b8d29c74d..5d13379039638c1233adcff0db6cbd3a9b5fa49a 100644 --- a/data_share/frameworks/native/consumer/src/datashare_connection.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_connection.cpp @@ -77,7 +77,12 @@ std::shared_ptr DataShareConnection::ConnectDataShareExtAbility( return dataShareProxy_; } auto reqUri = uri_.ToString().empty() ? uri.ToString() : uri_.ToString(); - ErrCode ret = AmsMgrProxy::GetInstance()->Connect(reqUri, this, token); + AmsMgrProxy* instance = AmsMgrProxy::GetInstance(); + if (instance == nullptr) { + LOG_ERROR("Connect: AmsMgrProxy::GetInstance failed"); + return nullptr; + } + ErrCode ret = instance->Connect(reqUri, this, token); if (ret != ERR_OK) { LOG_ERROR("connect ability failed, ret = %{public}d", ret); return nullptr; @@ -99,7 +104,12 @@ void DataShareConnection::DisconnectDataShareExtAbility() if (dataShareProxy_ == nullptr) { return; } - ErrCode ret = AmsMgrProxy::GetInstance()->DisConnect(this); + AmsMgrProxy* instance = AmsMgrProxy::GetInstance(); + if (instance == nullptr) { + LOG_ERROR("Disconnect: AmsMgrProxy::GetInstance failed"); + return; + } + ErrCode ret = instance->DisConnect(this); if (ret != ERR_OK) { LOG_ERROR("disconnect ability failed, ret = %{public}d", ret); return; diff --git a/data_share/frameworks/native/consumer/src/datashare_helper.cpp b/data_share/frameworks/native/consumer/src/datashare_helper.cpp index 94523c0ffb5e5e22a48da3bac2a1f9e9612f4fb5..9945a711825e30d59d1b985369add40f239b7357 100644 --- a/data_share/frameworks/native/consumer/src/datashare_helper.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_helper.cpp @@ -26,8 +26,6 @@ namespace OHOS { namespace DataShare { using namespace AppExecFwk; namespace { -static constexpr const char *SCHEME_DATASHARE = "datashare"; -static constexpr const char *SCHEME_DATASHARE_PROXY = "datashareproxy"; static constexpr const char *DATA_SHARE_PREFIX = "datashare:///"; static constexpr const char *FILE_PREFIX = "file://"; } // namespace @@ -72,7 +70,8 @@ std::string DataShareHelper::TransferUriPrefix(const std::string &originPrefix, * * @return Returns the created DataShareHelper instance. */ -std::shared_ptr DataShareHelper::Creator(const sptr &token, const std::string &strUri) +std::shared_ptr DataShareHelper::Creator( + const sptr &token, const std::string &strUri, const std::string &extUri) { if (token == nullptr) { LOG_ERROR("token == nullptr"); @@ -82,13 +81,13 @@ std::shared_ptr DataShareHelper::Creator(const sptr DataShareHelper::Creator(const string &strUri, LOG_ERROR("token is nullptr"); return nullptr; } - if (uri.GetScheme() != SCHEME_DATASHARE_PROXY) { - LOG_ERROR("the Scheme is not datashareproxy, Scheme: %{public}s", uri.GetScheme().c_str()); - return nullptr; - } if (options.isProxy_) { return CreateServiceHelper(bundleName); } diff --git a/data_share/frameworks/native/consumer/src/datashare_proxy.cpp b/data_share/frameworks/native/consumer/src/datashare_proxy.cpp index 83eda8f5636ae103e1b46f3e97922e6873a2e2fd..003e3b38216595bccfceb10bf7275f6296727b7a 100644 --- a/data_share/frameworks/native/consumer/src/datashare_proxy.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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/data_share/frameworks/native/proxy/include/ams_mgr_proxy.h b/data_share/frameworks/native/proxy/include/ams_mgr_proxy.h index 429eb9f3ff329da9850d331df2a0ee7fde9f4bc7..b1d6550cc3e102612b08a42a89a1c4c86512c1ba 100644 --- a/data_share/frameworks/native/proxy/include/ams_mgr_proxy.h +++ b/data_share/frameworks/native/proxy/include/ams_mgr_proxy.h @@ -21,10 +21,10 @@ #include "extension_manager_proxy.h" namespace OHOS::DataShare { -class AmsMgrProxy final : public std::enable_shared_from_this { +class AmsMgrProxy { public: ~AmsMgrProxy(); - static std::shared_ptr GetInstance(); + static AmsMgrProxy* GetInstance(); int Connect(const std::string &uri, const sptr &connect, const sptr &callerToken); int DisConnect(sptr connect); private: @@ -32,19 +32,18 @@ private: AmsMgrProxy() = default; class ServiceDeathRecipient : public IRemoteObject::DeathRecipient { public: - explicit ServiceDeathRecipient(std::weak_ptr owner) : owner_(owner) + explicit ServiceDeathRecipient(AmsMgrProxy* owner) : owner_(owner) { } void OnRemoteDied(const wptr &object) override { - auto owner = owner_.lock(); - if (owner != nullptr) { - owner->OnProxyDied(); + if (owner_ != nullptr) { + owner_->OnProxyDied(); } } private: - std::weak_ptr owner_; + AmsMgrProxy* owner_; }; void OnProxyDied(); bool ConnectSA(); diff --git a/data_share/frameworks/native/proxy/src/ams_mgr_proxy.cpp b/data_share/frameworks/native/proxy/src/ams_mgr_proxy.cpp index 1c0bcce8780a36e2b19305bcb46b81cb6e905c71..f1ac1d5b5ab09d354f68d9ee8ab427b5eef88609 100644 --- a/data_share/frameworks/native/proxy/src/ams_mgr_proxy.cpp +++ b/data_share/frameworks/native/proxy/src/ams_mgr_proxy.cpp @@ -22,6 +22,7 @@ #include "want.h" namespace OHOS::DataShare { + void AmsMgrProxy::OnProxyDied() { std::lock_guard lock(mutex_); @@ -40,9 +41,21 @@ AmsMgrProxy::~AmsMgrProxy() } } -std::shared_ptr AmsMgrProxy::GetInstance() +AmsMgrProxy* AmsMgrProxy::GetInstance() { - static std::shared_ptr proxy(new AmsMgrProxy()); + static AmsMgrProxy* proxy = nullptr; + if (proxy != nullptr) { + return proxy; + } + std::mutex premutex_; + std::lock_guard lock(premutex_); + if (proxy != nullptr) { + return proxy; + } + proxy = new AmsMgrProxy(); + if (proxy == nullptr) { + LOG_ERROR("new AmsMgrProxy failed"); + } return proxy; } @@ -80,7 +93,8 @@ bool AmsMgrProxy::ConnectSA() LOG_ERROR("Failed to GetSystemAbility."); return false; } - deathRecipient_ = new (std::nothrow) AmsMgrProxy::ServiceDeathRecipient(weak_from_this()); + + deathRecipient_ = new (std::nothrow) AmsMgrProxy::ServiceDeathRecipient(this); if (deathRecipient_ == nullptr) { LOG_ERROR("deathRecipient alloc failed."); return false; diff --git a/data_share/interfaces/inner_api/consumer/include/datashare_helper.h b/data_share/interfaces/inner_api/consumer/include/datashare_helper.h index 27b006c27f7ddd4e4336cae076f815db692ff6ff..c4053363734d9d77d589767aabb17e578b16e793 100644 --- a/data_share/interfaces/inner_api/consumer/include/datashare_helper.h +++ b/data_share/interfaces/inner_api/consumer/include/datashare_helper.h @@ -80,7 +80,8 @@ public: * * @return Returns the created DataShareHelper instance. */ - static std::shared_ptr Creator(const sptr &token, const std::string &strUri); + static std::shared_ptr Creator( + const sptr &token, const std::string &strUri, const std::string &extUri = ""); /** * @brief Creates a DataShareHelper instance with the Uri and {@link #CreateOptions} . diff --git a/data_share/test/native/unittest/mediadatashare_test/src/abnormal_branch_test.cpp b/data_share/test/native/unittest/mediadatashare_test/src/abnormal_branch_test.cpp index 68e6b59959deed2845e269c2da7b0cf35d4c6261..d569b7e35ec68748ee289d6e462557f4fe200c5d 100644 --- a/data_share/test/native/unittest/mediadatashare_test/src/abnormal_branch_test.cpp +++ b/data_share/test/native/unittest/mediadatashare_test/src/abnormal_branch_test.cpp @@ -129,18 +129,6 @@ HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_mReadOnlyInvalid_Test_001, TestS LOG_INFO("AbnormalBranchTest_mReadOnlyInvalid_Test_001::End"); } -HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_CreatorPossibleNull_Test_001, TestSize.Level0) -{ - LOG_INFO("AbnormalBranchTest_CreatorPossibleNull_Test_001::Start"); - std::string strUri; - CreateOptions options; - options.token_ = nullptr; - std::string bundleName; - std::shared_ptr dataHelper = DataShare::DataShareHelper::Creator(strUri, options, bundleName); - EXPECT_EQ(dataHelper, nullptr); - LOG_INFO("AbnormalBranchTest_CreatorPossibleNull_Test_001::End"); -} - HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_CreatorPossibleNull_Test_002, TestSize.Level0) { LOG_INFO("AbnormalBranchTest_CreatorPossibleNull_Test_002::Start"); diff --git a/data_share/test/native/unittest/mediadatashare_test/src/controller_test.cpp b/data_share/test/native/unittest/mediadatashare_test/src/controller_test.cpp index b727ef3af92f174c476d70b8306be93fba5e1d13..2f8a4590023326a8ceca7d130eebf18ebf0ca35e 100644 --- a/data_share/test/native/unittest/mediadatashare_test/src/controller_test.cpp +++ b/data_share/test/native/unittest/mediadatashare_test/src/controller_test.cpp @@ -72,7 +72,10 @@ HWTEST_F(ControllerTest, ControllerTest_ProviderImplInsertTest_002, TestSize.Lev Uri uri(""); sptr connection = new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); - auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + auto dataShareConnection = + std::shared_ptr(connection.GetRefPtr(), [holder = connection](const auto *) { + holder->DisconnectDataShareExtAbility(); + }); std::shared_ptr tempGenConProImp = std::make_shared(dataShareConnection, uri, nullptr); DataShare::DataShareValuesBucket valuesBucket; @@ -104,7 +107,10 @@ HWTEST_F(ControllerTest, ControllerTest_ProviderImplUpdateTest_002, TestSize.Lev Uri uri(""); sptr connection = new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); - auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + auto dataShareConnection = + std::shared_ptr(connection.GetRefPtr(), [holder = connection](const auto *) { + holder->DisconnectDataShareExtAbility(); + }); std::shared_ptr tempGenConProImp = std::make_shared(dataShareConnection, uri, nullptr); DataShare::DataSharePredicates predicates; @@ -135,7 +141,10 @@ HWTEST_F(ControllerTest, ControllerTest_ProviderImplDeleteTest_002, TestSize.Lev Uri uri(""); sptr connection = new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); - auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + auto dataShareConnection = + std::shared_ptr(connection.GetRefPtr(), [holder = connection](const auto *) { + holder->DisconnectDataShareExtAbility(); + }); std::shared_ptr tempGenConProImp = std::make_shared(dataShareConnection, uri, nullptr); DataShare::DataSharePredicates predicates; @@ -166,7 +175,10 @@ HWTEST_F(ControllerTest, ControllerTest_ProviderImplQueryTest_002, TestSize.Leve Uri uri(""); sptr connection = new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); - auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + auto dataShareConnection = + std::shared_ptr(connection.GetRefPtr(), [holder = connection](const auto *) { + holder->DisconnectDataShareExtAbility(); + }); std::shared_ptr tempGenConProImp = std::make_shared(dataShareConnection, uri, nullptr); DataShare::DataSharePredicates predicates; @@ -204,7 +216,10 @@ HWTEST_F(ControllerTest, ControllerTest_ExtSpecialControllerBatchInsertTest_002, Uri uri(""); sptr connection = new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); - auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + auto dataShareConnection = + std::shared_ptr(connection.GetRefPtr(), [holder = connection](const auto *) { + holder->DisconnectDataShareExtAbility(); + }); std::shared_ptr tempExtSpeCon = std::make_shared(dataShareConnection, uri, nullptr); DataShare::DataShareValuesBucket valuesBucket1; @@ -238,7 +253,10 @@ HWTEST_F(ControllerTest, ControllerTest_ExtSpecialControllerNormalizeUriTest_002 Uri uri(""); sptr connection = new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); - auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + auto dataShareConnection = + std::shared_ptr(connection.GetRefPtr(), [holder = connection](const auto *) { + holder->DisconnectDataShareExtAbility(); + }); std::shared_ptr tempExtSpeCon = std::make_shared(dataShareConnection, uri, nullptr); Uri result = tempExtSpeCon->NormalizeUri(uri); @@ -263,7 +281,10 @@ HWTEST_F(ControllerTest, ControllerTest_ExtSpecialControllerDenormalizeUriTest_0 Uri uri(""); sptr connection = new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); - auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + auto dataShareConnection = + std::shared_ptr(connection.GetRefPtr(), [holder = connection](const auto *) { + holder->DisconnectDataShareExtAbility(); + }); std::shared_ptr tempExtSpeCon = std::make_shared(dataShareConnection, uri, nullptr); Uri result = tempExtSpeCon->DenormalizeUri(uri); diff --git a/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp b/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp index 189ae9d5d3fd7310676547cecdd72e254e1000f7..6757f1748e200b46c26f31ddacbdd2444ee888be 100644 --- a/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp +++ b/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp @@ -1044,6 +1044,30 @@ HWTEST_F(MediaDataShareUnitTest, MediaDataShare_CRUD_Test_001, TestSize.Level0) LOG_INFO("MediaDataShare_CRUD_Test_001, End"); } +HWTEST_F(MediaDataShareUnitTest, MediaDataShare_NotImplPredicates_Test_zyp, TestSize.Level0) +{ + LOG_INFO("MediaDataShare_ImplPredicates_Test_001::Start"); + DataShare::DataSharePredicates predicates; + vector inColumn; + inColumn.push_back(1); + inColumn.push_back(2); + inColumn.push_back(3); + predicates.In("name", inColumn); + + std::vector operationItems = predicates.GetOperationList(); + std::string str = std::get(operationItems[0].singleParams[0]); + std::vector ret = std::get>(operationItems[0].multiParams[0]); + EXPECT_EQ(operationItems.size(), 1); + EXPECT_EQ(operationItems[0].singleParams[0].index(), 4); + EXPECT_EQ(str, "name"); + EXPECT_EQ(operationItems[0].multiParams[0].index(), 1); + for (int i = 0; i < ret.size(); i++) { + EXPECT_EQ(ret[i], i + 1); + } + operationItems.clear(); + LOG_INFO("MediaDataShare_ImplPredicates_Test_001, End"); +} + HWTEST_F(MediaDataShareUnitTest, MediaDataShare_NotImplPredicates_Test_001, TestSize.Level0) { LOG_INFO("MediaDataShare_NotImplPredicates_Test_001::Start"); diff --git a/data_share/test/native/unittest/mediadatashare_test/src/slientaccess_test.cpp b/data_share/test/native/unittest/mediadatashare_test/src/slientaccess_test.cpp index a007276a722f2545176806a6e258f67afff21d69..284815742ce34389bfba34bf29b19c457f3e8a58 100644 --- a/data_share/test/native/unittest/mediadatashare_test/src/slientaccess_test.cpp +++ b/data_share/test/native/unittest/mediadatashare_test/src/slientaccess_test.cpp @@ -20,6 +20,7 @@ #include "datashare_log.h" #include "hap_token_info.h" #include "iservice_registry.h" +#include "system_ability_definition.h" #include "token_setproc.h" namespace OHOS { diff --git a/datamgr_service/bundle.json b/datamgr_service/bundle.json index 1d4318ba4667304b6361a6b69fca1f599dd1a3b0..a837eb78f7b9f057c688c76a634c59f0a3da2f67 100644 --- a/datamgr_service/bundle.json +++ b/datamgr_service/bundle.json @@ -95,7 +95,57 @@ "//foundation/distributeddatamgr/datamgr_service/conf:build_module", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service/data_share:build_module" ], - "inner_kits": [], + "inner_kits": [ + { + "name": "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", + "header": { + "header_files": [ + "backuprule/backup_rule_manager.h", + "checker/checker_manager.h", + "cloud/asset_loader.h", + "cloud/change_event.h", + "cloud/cloud_db.h", + "cloud/cloud_event.h", + "cloud/cloud_info.h", + "cloud/cloud_server.h", + "cloud/schema_meta.h", + "cloud/subscription.h", + "cloud/sync_event.h", + "directory/directory_manager.h", + "error/general_error.h", + "eventcenter/event.h", + "eventcenter/event_center.h", + "feature/feature_system.h", + "metadata/appid_meta_data.h", + "metadata/capability_meta_data.h", + "metadata/capability_range.h", + "metadata/corrupted_meta_data.h", + "metadata/matrix_meta_data.h", + "metadata/meta_data.h", + "metadata/meta_data_manager.h", + "metadata/secret_key_meta_data.h", + "metadata/store_meta_data.h", + "metadata/store_meta_data_local.h", + "metadata/strategy_meta_data.h", + "metadata/user_meta_data.h", + "serializable/serializable.h", + "store/auto_cache.h", + "store/cursor.h", + "store/general_store.h", + "store/general_value.h", + "store/general_watcher.h", + "utils/anonymous.h", + "utils/block_integer.h", + "utils/constant.h", + "utils/converter.h", + "utils/crypto.h", + "utils/endian_converter.h", + "utils/ref_count.h" + ], + "header_base": "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework/include" + } + } + ], "test": [ "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/test:fuzztest", "//foundation/distributeddatamgr/datamgr_service:fuzztest", diff --git a/datamgr_service/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/datamgr_service/services/distributeddataservice/adapter/communicator/test/BUILD.gn index b3dbad12f7c0f3ef2c8067325330b2a9b202de2f..f94d733bedcf06136d80e5e6995bc7a43d063dda 100644 --- a/datamgr_service/services/distributeddataservice/adapter/communicator/test/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/adapter/communicator/test/BUILD.gn @@ -54,6 +54,9 @@ ohos_unittest("DeviceManagerAdapterTest") { "../src", ] external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", "dsoftbus:softbus_client", "hilog:libhilog", "ipc:ipc_core", diff --git a/datamgr_service/services/distributeddataservice/adapter/communicator/test/unittest/device_manager_adapter_test.cpp b/datamgr_service/services/distributeddataservice/adapter/communicator/test/unittest/device_manager_adapter_test.cpp index 6e0df49030359d4ac5d1015f104ae92cbe9c3714..2842a2fcefdd7e65c4e5ed016035e99afc23f545 100644 --- a/datamgr_service/services/distributeddataservice/adapter/communicator/test/unittest/device_manager_adapter_test.cpp +++ b/datamgr_service/services/distributeddataservice/adapter/communicator/test/unittest/device_manager_adapter_test.cpp @@ -16,12 +16,16 @@ #include "device_manager_adapter.h" #include "gtest/gtest.h" +#include "accesstoken_kit.h" #include "executor_pool.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" #include "types.h" namespace { using namespace testing::ext; using namespace OHOS::AppDistributedKv; using namespace OHOS::DistributedData; +using namespace OHOS::Security::AccessToken; class DeviceChangerListener final : public AppDeviceChangeListener { public: void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const override @@ -33,12 +37,34 @@ public: } }; +void GrantPermissionNative() +{ + const char **perms = new const char *[2]; + perms[0] = "ohos.permission.DISTRIBUTED_DATASYNC"; + perms[1] = "ohos.permission.ACCERSS_SERVICE_DM"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "distributed_data_test", + .aplStr = "system_basic", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete []perms; +} + class DeviceManagerAdapterTest : public testing::Test { public: static void SetUpTestCase(void) { size_t max = 12; size_t min = 5; + GrantPermissionNative(); DeviceManagerAdapter::GetInstance().Init(std::make_shared(max, min)); } static void TearDownTestCase(void) {} diff --git a/datamgr_service/services/distributeddataservice/app/test/BUILD.gn b/datamgr_service/services/distributeddataservice/app/test/BUILD.gn index f471e188e2aad5bb64b0a3904fa923d27d1aa264..0b51ae59ad2bc4827b40ed612f5bd74abad0d935 100644 --- a/datamgr_service/services/distributeddataservice/app/test/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/app/test/BUILD.gn @@ -135,6 +135,8 @@ ohos_unittest("SessionManagerTest") { external_deps = [ "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", "c_utils:utils", "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", diff --git a/datamgr_service/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/datamgr_service/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index 6320bfd6cc9a76cd8b41ce3330a8d242f62c708d..82c25f5637b964cfc9fa98b4e6beb12f1aa2a939 100644 --- a/datamgr_service/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/datamgr_service/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -19,8 +19,10 @@ #include "kvstore_meta_manager.h" #include "metadata/meta_data_manager.h" #include "metadata/store_meta_data.h" +#include "nativetoken_kit.h" #include "session_manager/route_head_handler_impl.h" #include "session_manager/upgrade_manager.h" +#include "token_setproc.h" #include "user_delegate.h" #include "gtest/gtest.h" @@ -33,6 +35,28 @@ using namespace OHOS::Security::AccessToken; constexpr const char *PEER_DEVICE_ID = "PEER_DEVICE_ID"; constexpr int PEER_USER_ID1 = 101; constexpr int PEER_USER_ID2 = 100; + +void GrantPermissionNative() +{ + const char **perms = new const char *[2]; + perms[0] = "ohos.permission.DISTRIBUTED_DATASYNC"; + perms[1] = "ohos.permission.ACCERSS_SERVICE_DM"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "distributed_data_test", + .aplStr = "system_basic", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete []perms; +} + class SessionManagerTest : public testing::Test { public: static void SetUpTestCase() @@ -75,6 +99,7 @@ public: metaData.uid = 2000000; metaData.storeType = 1; MetaDataManager::GetInstance().SaveMeta(metaData.GetKey(), metaData); + GrantPermissionNative(); } static void TearDownTestCase() { diff --git a/datamgr_service/services/distributeddataservice/framework/cloud/cloud_server.cpp b/datamgr_service/services/distributeddataservice/framework/cloud/cloud_server.cpp index 17c704a1b3fcf1a9dc109be2dfe503b549dc51c1..6dd12318ee303452334048e5ee74a393cdc73923 100644 --- a/datamgr_service/services/distributeddataservice/framework/cloud/cloud_server.cpp +++ b/datamgr_service/services/distributeddataservice/framework/cloud/cloud_server.cpp @@ -59,4 +59,8 @@ std::shared_ptr CloudServer::ConnectCloudDB(uint32_t tokenId, const Clo { return nullptr; } + +void CloudServer::Clean(int32_t userId) +{ +} } // namespace OHOS::DistributedData \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_server.h b/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_server.h index 709a0cbcf67c76fe768b1c3f58672ec3a2ce8754..ae6d50d1c94643a912fcf3a1822e3498d88eecc8 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_server.h +++ b/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_server.h @@ -33,6 +33,7 @@ public: virtual int32_t Unsubscribe(int32_t userId, const std::map> &dbs); virtual std::shared_ptr ConnectAssetLoader(uint32_t tokenId, const Database &dbMeta); virtual std::shared_ptr ConnectCloudDB(uint32_t tokenId, const Database &dbMeta); + virtual void Clean(int32_t userId); private: static CloudServer *instance_; diff --git a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index 596bd7dbfa63d7354dc51edbaa9c883be31a5fc9..972cc2124c123aff922512f2d4888160094bc501 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -63,8 +63,9 @@ CloudServiceImpl::CloudServiceImpl() int32_t CloudServiceImpl::EnableCloud(const std::string &id, const std::map &switches) { - CloudInfo cloudInfo; - auto status = GetCloudInfo(IPCSkeleton::GetCallingTokenID(), id, cloudInfo); + auto tokenId = IPCSkeleton::GetCallingTokenID(); + auto user = DistributedKv::AccountDelegate::GetInstance()->GetUserByToken(tokenId); + auto [status, cloudInfo] = GetCloudInfo(user); if (status != SUCCESS) { return status; } @@ -78,7 +79,7 @@ int32_t CloudServiceImpl::EnableCloud(const std::string &id, const std::map CloudServiceImpl::GetCloudInfo(int32_t userId) { CloudInfo cloudInfo; cloudInfo.user = userId; if (MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetKey(), cloudInfo, true)) { - return cloudInfo; + return { SUCCESS, cloudInfo }; } auto instance = CloudServer::GetInstance(); if (instance == nullptr) { - return cloudInfo; + return { SERVER_UNAVAILABLE, cloudInfo }; } cloudInfo = instance->GetServerInfo(userId); if (!cloudInfo.IsValid()) { ZLOGE("no cloud info %{public}d", userId); - return cloudInfo; + return { ERROR, cloudInfo }; } MetaDataManager::GetInstance().SaveMeta(cloudInfo.GetKey(), cloudInfo, true); - return cloudInfo; + return { SUCCESS, cloudInfo }; } -int32_t CloudServiceImpl::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) +int32_t CloudServiceImpl::OnAppUninstall( + const std::string &bundleName, int32_t user, int32_t index) { MetaDataManager::GetInstance().DelMeta(Subscription::GetRelationKey(user, bundleName), true); MetaDataManager::GetInstance().DelMeta(CloudInfo::GetSchemaKey(user, bundleName, index), true); @@ -499,6 +501,11 @@ bool CloudServiceImpl::DoSubscribe(int32_t user) ZLOGW("error, there is no cloud info for user(%{public}d)", sub.userId); return false; } + if (!sub.id.empty() && sub.id != cloudInfo.id) { + CleanSubscription(sub); + sub.id.clear(); + sub.expiresTime.clear(); + } ZLOGD("begin cloud:%{public}d user:%{public}d apps:%{public}zu", cloudInfo.enableCloud, sub.userId, cloudInfo.apps.size()); @@ -535,6 +542,25 @@ bool CloudServiceImpl::DoSubscribe(int32_t user) return subDbs.empty() && unsubDbs.empty(); } +void CloudServiceImpl::CleanSubscription(Subscription &sub) +{ + ZLOGD("id:%{public}s, size:%{public}zu", Anonymous::Change(sub.id).c_str(), sub.expiresTime.size()); + MetaDataManager::GetInstance().DelMeta(sub.GetKey(), true); + for (const auto &[bundle, expireTime] : sub.expiresTime) { + MetaDataManager::GetInstance().DelMeta(sub.GetRelationKey(bundle), true); + } +} + +bool CloudServiceImpl::CleanServer(int32_t user) +{ + auto instance = CloudServer::GetInstance(); + if (instance == nullptr) { + return true; + } + instance->Clean(user); + return true; +} + void CloudServiceImpl::Execute(Task task) { auto executor = executor_; diff --git a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h index 85096676eff7352c2ef236db4cc61ecd709d7e24..866e48357f41fb2c1df318dbb314984be7151cc2 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h @@ -69,7 +69,7 @@ private: bool UpdateCloudInfo(int32_t user); bool UpdateSchema(int32_t user); SchemaMeta GetSchemaMeta(int32_t userId, const std::string &bundleName, int32_t instanceId); - CloudInfo GetCloudInfo(int32_t userId); + std::pair GetCloudInfo(int32_t userId); int32_t GetCloudInfo(uint32_t tokenId, const std::string &id, CloudInfo &cloudInfo); int32_t GetCloudInfoFromMeta(CloudInfo &cloudInfo); int32_t GetCloudInfoFromServer(CloudInfo &cloudInfo); @@ -77,7 +77,9 @@ private: void GetSchema(const Event &event); Task GenTask(int32_t retry, int32_t user, Handles handles = { WORK_SUB }); void Execute(Task task); + void CleanSubscription(Subscription &sub); bool DoSubscribe(int32_t user); + bool CleanServer(int32_t user); int32_t DoClean(CloudInfo &cloudInfo, const std::map &actions); std::shared_ptr executor_; SyncManager syncManager_; @@ -85,6 +87,7 @@ private: static constexpr Handle WORK_CLOUD_INFO_UPDATE = &CloudServiceImpl::UpdateCloudInfo; static constexpr Handle WORK_SCHEMA_UPDATE = &CloudServiceImpl::UpdateSchema; static constexpr Handle WORK_SUB = &CloudServiceImpl::DoSubscribe; + static constexpr Handle WORK_CLEAN = &CloudServiceImpl::CleanServer; }; } // namespace OHOS::DistributedData diff --git a/datamgr_service/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp b/datamgr_service/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp index 5b0cfde9cb826ab757fb564a7cffd9ab273e54b5..d65d8f87f92087f471e4ea4c2bba18ca3551ebfc 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp +++ b/datamgr_service/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp @@ -21,6 +21,7 @@ #include "utils/anonymous.h" namespace OHOS::DataShare { +static constexpr int64_t MAX_MILLISECONDS = 31536000000; // 365 days SchedulerManager &SchedulerManager::GetInstance() { static SchedulerManager instance; @@ -64,7 +65,7 @@ void SchedulerManager::SetTimer( int64_t now = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()).count(); // reminder time must is in future - if (reminderTime <= now) { + if (reminderTime <= now || reminderTime - now >= MAX_MILLISECONDS) { ZLOGE("reminderTime is not in future, %{public}" PRId64 "%{public}" PRId64, reminderTime, now); return; } @@ -81,8 +82,11 @@ void SchedulerManager::SetTimer( // not find task in map, create new timer auto taskId = executor_->Schedule(duration, [key, dbPath, version, userId, this]() { ZLOGI("schedule notify start, uri is %{private}s, subscriberId is %{public}" PRId64 ", bundleName is " - "%{public}s", key.uri.c_str(), key.subscriberId, key.bundleName.c_str()); - timerCache_.erase(key); + "%{public}s", key.uri.c_str(), key.subscriberId, key.bundleName.c_str()); + { + std::lock_guard lock(mutex_); + timerCache_.erase(key); + } // 1. execute schedulerSQL in next time Execute(key, userId, dbPath, version); // 2. notify diff --git a/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/interface/src/document_store.cpp b/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/interface/src/document_store.cpp index 83dac352cad366aa5118b9e6b90b47bcb58e496a..e2bb9c25206b5b4711c32a5a15fb0c08d87b00f8 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/interface/src/document_store.cpp +++ b/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/interface/src/document_store.cpp @@ -620,43 +620,71 @@ Collection DocumentStore::GetCollection(std::string &collectionName) return Collection(collectionName, executor_); } -int JudgeViewType(const size_t &index, ValueObject &leafItem, bool &viewType) +int JudgeBoolViewType(const size_t index, ValueObject &leafItem, bool &viewType) { + if (leafItem.GetBoolValue()) { + if (index != 0 && !viewType) { + return -E_INVALID_ARGS; + } + viewType = true; + } else { + if (index != 0 && viewType) { + return E_INVALID_ARGS; + } + viewType = false; + } + return E_OK; +} + +int JudgeStringViewType(const size_t index, ValueObject &leafItem, bool &viewType) +{ + if (leafItem.GetStringValue() == "") { + if (index != 0 && !viewType) { + return -E_INVALID_ARGS; + } + viewType = true; + } else { + return -E_INVALID_ARGS; + } + return E_OK; +} + +int JudgeIntViewType(const size_t index, ValueObject &leafItem, bool &viewType) +{ + if (leafItem.GetIntValue() == 0) { + if (index != 0 && viewType) { + return -E_INVALID_ARGS; + } + viewType = false; + } else { + if (index != 0 && !viewType) { + return E_INVALID_ARGS; + } + viewType = true; + } + return E_OK; +} + +int JudgeViewType(const size_t index, ValueObject &leafItem, bool &viewType) +{ + int errCode = E_OK; switch (leafItem.GetValueType()) { case ValueObject::ValueType::VALUE_BOOL: - if (leafItem.GetBoolValue()) { - if (index != 0 && !viewType) { - return -E_INVALID_ARGS; - } - viewType = true; - } else { - if (index != 0 && viewType) { - return E_INVALID_ARGS; - } - viewType = false; + errCode = JudgeBoolViewType(index, leafItem, viewType); + if (errCode != E_OK) { + return errCode; } break; case ValueObject::ValueType::VALUE_STRING: - if (leafItem.GetStringValue() == "") { - if (index != 0 && !viewType) { - return -E_INVALID_ARGS; - } - viewType = true; - } else { - return -E_INVALID_ARGS; + errCode = JudgeStringViewType(index, leafItem, viewType); + if (errCode != E_OK) { + return errCode; } break; case ValueObject::ValueType::VALUE_NUMBER: - if (leafItem.GetIntValue() == 0) { - if (index != 0 && viewType) { - return -E_INVALID_ARGS; - } - viewType = false; - } else { - if (index != 0 && !viewType) { - return E_INVALID_ARGS; - } - viewType = true; + errCode = JudgeIntViewType(index, leafItem, viewType); + if (errCode != E_OK) { + return errCode; } break; default: diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp index 163734b4909cd0e0f61f9e7fe4f67df08b88cd65..15b2868ce1d21caf210b994d623286a9c5c22adc 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp @@ -26,7 +26,9 @@ using DataAssets = NativeRdb::ValueObject::Assets; std::vector RdbCloudDataTranslate::AssetToBlob(const Asset &asset) { std::vector rawData; - DataAsset dataAsset = ValueProxy::Asset(asset); + Asset dbAsset = asset; + dbAsset.flag = static_cast(DistributedDB::AssetOpType::NO_CHANGE); + DataAsset dataAsset = ValueProxy::Asset(std::move(dbAsset)); InnerAsset innerAsset(dataAsset); auto data = Serializable::Marshall(innerAsset); auto size = DistributedData::HostToNet((uint16_t)data.length()); diff --git a/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp b/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp index fb275826cfb3da220adfbe450bab9f1fe26faaf2..b8500014ed5f2fee7e61bd3d9005e0d6f29481e6 100644 --- a/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp @@ -14,9 +14,9 @@ */ #define LOG_TAG "CloudDataTest" #include - +#include "log_print.h" +#include "ipc_skeleton.h" #include "account/account_delegate.h" -#include "cloud/change_event.h" #include "cloud/cloud_event.h" #include "cloud/cloud_server.h" #include "cloud/schema_meta.h" @@ -24,24 +24,20 @@ #include "device_matrix.h" #include "eventcenter/event_center.h" #include "feature/feature_system.h" -#include "ipc_skeleton.h" -#include "log_print.h" #include "metadata/meta_data_manager.h" #include "metadata/store_meta_data.h" #include "metadata/store_meta_data_local.h" -#include "mock/cloud_server_mock.h" #include "mock/db_store_mock.h" -#include "mock/general_store_mock.h" -#include "rdb_query.h" #include "rdb_types.h" -#include "store/auto_cache.h" -#include "store/general_store.h" using namespace testing::ext; using namespace OHOS::DistributedData; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; namespace OHOS::Test { namespace DistributedDataTest { +static constexpr const char *TEST_CLOUD_BUNDLE = "test_cloud_bundleName"; +static constexpr const char *TEST_CLOUD_APPID = "test_cloud_appid"; +static constexpr const char *TEST_CLOUD_STORE = "test_cloud_database_name"; class CloudDataTest : public testing::Test { public: static void SetUpTestCase(void); @@ -49,62 +45,69 @@ public: void SetUp(); void TearDown(); - static CloudInfo CLOUD_INFO; - static SchemaMeta SCHEMA_META; - + static SchemaMeta schemaMeta_; protected: - static constexpr uint64_t REMAIN_SPACE = 1000; - static constexpr uint64_t TOTAL_SPACE = 2000; - static constexpr const char *TEST_CLOUD_BUNDLE = "test_cloud_bundleName"; - static constexpr const char *TEST_CLOUD_APPID = "test_cloud_appid"; - static constexpr const char *TEST_CLOUD_STORE = "test_cloud_database_name"; - static constexpr const char *TEST_DISTRIBUTED_DATA_BUNDLE = "test_distributeddata"; - static constexpr const char *TEST_DISTRIBUTED_DATA_STORE = "test_service_meta"; + static constexpr const char *TEST_DISTRIBUTEDDATA_BUNDLE = "test_distributeddata"; + static constexpr const char *TEST_DISTRIBUTEDDATA_STORE = "test_service_meta"; void InitMetaData(); - void InitCloudInfo(); void InitSchemaMeta(); - StoreMetaData GetStoreMetaData(); static std::shared_ptr dbStoreMock_; StoreMetaData metaData_; }; +class CloudServerMock : public CloudServer { +public: + CloudInfo GetServerInfo(int32_t userId) override; + SchemaMeta GetAppSchema(int32_t userId, const std::string &bundleName) override; + virtual ~CloudServerMock() = default; + static constexpr uint64_t REMAINSPACE = 1000; + static constexpr uint64_t TATALSPACE = 2000; +}; + +CloudInfo CloudServerMock::GetServerInfo(int32_t userId) +{ + CloudInfo cloudInfo; + cloudInfo.user = userId; + cloudInfo.id = "test_cloud_id"; + cloudInfo.remainSpace = REMAINSPACE; + cloudInfo.totalSpace = TATALSPACE; + cloudInfo.enableCloud = true; + + CloudInfo::AppInfo appInfo; + appInfo.bundleName = TEST_CLOUD_BUNDLE; + appInfo.appId = TEST_CLOUD_APPID; + appInfo.version = 1; + appInfo.cloudSwitch = true; + + cloudInfo.apps[TEST_CLOUD_BUNDLE] = std::move(appInfo); + return cloudInfo; +} + +SchemaMeta CloudServerMock::GetAppSchema(int32_t userId, const std::string &bundleName) +{ + return CloudDataTest::schemaMeta_; +} + std::shared_ptr CloudDataTest::dbStoreMock_ = std::make_shared(); -CloudInfo CloudDataTest::CLOUD_INFO; -SchemaMeta CloudDataTest::SCHEMA_META; +SchemaMeta CloudDataTest::schemaMeta_; void CloudDataTest::InitMetaData() { metaData_.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - metaData_.appId = TEST_DISTRIBUTED_DATA_BUNDLE; - metaData_.bundleName = TEST_DISTRIBUTED_DATA_BUNDLE; + metaData_.appId = TEST_DISTRIBUTEDDATA_BUNDLE; + metaData_.bundleName = TEST_DISTRIBUTEDDATA_BUNDLE; metaData_.tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); metaData_.user = std::to_string(DistributedKv::AccountDelegate::GetInstance()->GetUserByToken(metaData_.tokenId)); metaData_.area = OHOS::DistributedKv::EL1; metaData_.instanceId = 0; metaData_.isAutoSync = true; metaData_.storeType = 1; - metaData_.storeId = TEST_DISTRIBUTED_DATA_STORE; + metaData_.storeId = TEST_DISTRIBUTEDDATA_STORE; PolicyValue value; value.type = OHOS::DistributedKv::PolicyType::IMMEDIATE_SYNC_ON_ONLINE; } -void CloudDataTest::InitCloudInfo() -{ - CLOUD_INFO.id = "test_cloud_id"; - CLOUD_INFO.remainSpace = REMAIN_SPACE; - CLOUD_INFO.totalSpace = TOTAL_SPACE; - CLOUD_INFO.enableCloud = true; - - CloudInfo::AppInfo appInfo; - appInfo.bundleName = TEST_CLOUD_BUNDLE; - appInfo.appId = TEST_CLOUD_APPID; - appInfo.version = 1; - appInfo.cloudSwitch = true; - - CLOUD_INFO.apps[TEST_CLOUD_BUNDLE] = std::move(appInfo); -} - void CloudDataTest::InitSchemaMeta() { SchemaMeta::Field field1; @@ -125,31 +128,19 @@ void CloudDataTest::InitSchemaMeta() database.alias = "test_cloud_database_alias"; database.tables.emplace_back(table); - SCHEMA_META.version = 1; - SCHEMA_META.bundleName = TEST_DISTRIBUTED_DATA_BUNDLE; - SCHEMA_META.databases.emplace_back(database); -} - -StoreMetaData CloudDataTest::GetStoreMetaData() -{ - StoreMetaData storeMetaData; - storeMetaData.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - storeMetaData.bundleName = TEST_CLOUD_BUNDLE; - storeMetaData.storeId = TEST_CLOUD_STORE; - storeMetaData.instanceId = 0; - storeMetaData.isAutoSync = true; - storeMetaData.storeType = DistributedRdb::RDB_DEVICE_COLLABORATION; - storeMetaData.area = OHOS::DistributedKv::EL1; - storeMetaData.tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); - storeMetaData.user = - std::to_string(DistributedKv::AccountDelegate::GetInstance()->GetUserByToken(storeMetaData.tokenId)); - return storeMetaData; + schemaMeta_.version = 1; + schemaMeta_.bundleName = TEST_DISTRIBUTEDDATA_BUNDLE; + schemaMeta_.databases.emplace_back(database); } void CloudDataTest::SetUpTestCase(void) { - MetaDataManager::GetInstance().Initialize(dbStoreMock_, nullptr, nullptr); + MetaDataManager::GetInstance().Initialize(dbStoreMock_, nullptr, [](const auto &, auto) { + DeviceMatrix::GetInstance().OnChanged(DeviceMatrix::META_STORE_MASK); + }); + auto cloudServerMock = new CloudServerMock(); + CloudServer::RegisterCloudInstance(cloudServerMock); FeatureSystem::GetInstance().GetCreator("cloud")(); FeatureSystem::GetInstance().GetCreator("relational_store")(); } @@ -159,87 +150,49 @@ void CloudDataTest::TearDownTestCase() {} void CloudDataTest::SetUp() { InitMetaData(); - InitCloudInfo(); InitSchemaMeta(); MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_); - auto cloudServerMock = new CloudServerMock(CLOUD_INFO, { { TEST_CLOUD_BUNDLE, SCHEMA_META } }); - CloudServer::RegisterCloudInstance(cloudServerMock); + StoreMetaData storeMetaData; + storeMetaData.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + storeMetaData.bundleName = TEST_CLOUD_BUNDLE; + storeMetaData.storeId = TEST_CLOUD_STORE; + storeMetaData.instanceId = 0; + storeMetaData.isAutoSync = true; + storeMetaData.storeType = DistributedRdb::RDB_DEVICE_COLLABORATION; + storeMetaData.area = OHOS::DistributedKv::EL1; + storeMetaData.tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + storeMetaData.user = + std::to_string(DistributedKv::AccountDelegate::GetInstance()->GetUserByToken(storeMetaData.tokenId)); + MetaDataManager::GetInstance().SaveMeta(storeMetaData.GetKey(), storeMetaData); } -void CloudDataTest::TearDown() -{ - if (dbStoreMock_ != nullptr) { - dbStoreMock_->Reset(); - } -} +void CloudDataTest::TearDown() {} /** -* @tc.name: GetSchemaTest001 +* @tc.name: GetSchema * @tc.desc: GetSchema from cloud when no schema in meta. * @tc.type: FUNC * @tc.require: * @tc.author: ht */ -HWTEST_F(CloudDataTest, GetSchemaTest001, TestSize.Level0) +HWTEST_F(CloudDataTest, GetSchema, TestSize.Level0) { - ZLOGI("GetSchemaTest001 start"); - auto cloudInfo = CLOUD_INFO; + ZLOGI("CloudDataTest start"); + auto cloudServerMock = std::make_shared(); + auto cloudInfo = cloudServerMock->GetServerInfo( + DistributedKv::AccountDelegate::GetInstance()->GetUserByToken(OHOS::IPCSkeleton::GetCallingTokenID())); ASSERT_TRUE(MetaDataManager::GetInstance().DelMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), true)); SchemaMeta schemaMeta; - ASSERT_FALSE(MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true)); - CloudEvent::StoreInfo storeInfo{ IPCSkeleton::GetCallingTokenID(), TEST_CLOUD_BUNDLE, TEST_CLOUD_STORE, 0 }; + ASSERT_FALSE( + MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true)); + CloudEvent::StoreInfo storeInfo { OHOS::IPCSkeleton::GetCallingTokenID(), TEST_CLOUD_BUNDLE, TEST_CLOUD_STORE, 0 }; auto event = std::make_unique(CloudEvent::GET_SCHEMA, std::move(storeInfo)); EventCenter::GetInstance().PostEvent(move(event)); - ASSERT_TRUE(MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true)); - ASSERT_EQ(to_string(schemaMeta.Marshall()), to_string(SCHEMA_META.Marshall())); -} - -/** -* @tc.name: LocalChangeTest001 -* @tc.desc: do cloud sync. -* @tc.type: FUNC -* @tc.require: -* @tc.author: ht -*/ -HWTEST_F(CloudDataTest, LocalChangeTest001, TestSize.Level0) -{ - ZLOGI("LocalChangeTest001 start"); - auto cloudInfo = CLOUD_INFO; - MetaDataManager::GetInstance().SaveMeta(cloudInfo.GetKey(), cloudInfo, true); - auto schemaMeta = SCHEMA_META; - auto keys = cloudInfo.GetSchemaKey(); - for (auto &[bundleName, key] : keys) { - schemaMeta.bundleName = bundleName; - MetaDataManager::GetInstance().SaveMeta(key, schemaMeta, true); - } - using StoreType = DistributedData::StoreMetaData::StoreType; - auto storeMeta = GetStoreMetaData(); - storeMeta.storeType = StoreType::STORE_BUTT - 1; - - AutoCache::GetInstance().RegCreator(storeMeta.storeType, [](const StoreMetaData &metaData) -> GeneralStore* { - return new (std::nothrow) GeneralStoreMock(metaData); - }); - auto process = [this](const Event &event) { - auto &evt = static_cast(event); - auto storeInfo = evt.GetStoreInfo(); - StoreMetaData meta; - meta.storeId = storeInfo.storeName; - meta.bundleName = storeInfo.bundleName; - meta.user = std::to_string(storeInfo.user); - meta.instanceId = storeInfo.instanceId; - meta.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - ASSERT_TRUE(MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta)); - auto store = AutoCache::GetInstance().GetStore(meta, {}); - ASSERT_TRUE(store!= nullptr && store->IsValid()); - }; - EventCenter::GetInstance().Subscribe(CloudEvent::CLOUD_SYNC, process); - CloudEvent::StoreInfo storeInfo{ IPCSkeleton::GetCallingTokenID(), TEST_CLOUD_BUNDLE, TEST_CLOUD_STORE, 0 }; - auto query = std::make_shared(); - auto info = ChangeEvent::EventInfo(GeneralStore::CLOUD_TIME_FIRST, 0, false, query, nullptr); - auto evt = std::make_unique(std::move(storeInfo), std::move(info)); - EventCenter::GetInstance().PostEvent(std::move(evt)); + ASSERT_TRUE( + MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true)); + ASSERT_EQ(to_string(schemaMeta.Marshall()), to_string(schemaMeta_.Marshall())); } } // namespace DistributedDataTest } // namespace OHOS::Test diff --git a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp index df8c3984479cd4d5250e896e380aedb476b1e222..cd1e2df6145ae0f541d900eb5d181bc6f0541f61 100644 --- a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp @@ -310,12 +310,5 @@ DBStatus DBStoreMock::UpdateKey(const UpdateKeyCallback &callback) { return NOT_SUPPORT; } - -void DBStoreMock::Reset() -{ - entries_.Clear(); - localEntries_.Clear(); - observers_.Clear(); -} } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h index 74e8342e0a88bcaa51f5722f4b01602c374a5c39..e50def98c4a8d00c89840247d92c8dd87b508343 100644 --- a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h +++ b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h @@ -89,7 +89,6 @@ public: DBStatus GetKeys(const Key &keyPrefix, std::vector &keys) const override; size_t GetSyncDataSize(const std::string &device) const override; DBStatus UpdateKey(const UpdateKeyCallback &callback) override; - void Reset(); private: static const uint32_t DEFAULT_SIZE = 0; diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/types_util_test.cpp b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/types_util_test.cpp index 31b4b8f64ed017ea2171ed18c201987a9e81510c..f39b120627a08e1377fdc6ae729c7d474037aa6f 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/types_util_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/types_util_test.cpp @@ -30,6 +30,7 @@ using namespace testing::ext; using namespace OHOS::DistributedKv; using namespace OHOS; using var_t = std::variant; +namespace OHOS::Test { class TypesUtilTest : public testing::Test { public: class ITestRemoteObject : public IRemoteBroker { @@ -240,7 +241,6 @@ HWTEST_F(TypesUtilTest, UnmarshalFromBufferLimitTest001, TestSize.Level1) int32_t normalSize = 100; parcel.WriteInt32(normalSize); //normal size parcel.WriteInt32(ITypesUtil::MAX_COUNT + 1); //exceed MAX_COUNT - std::vector input; std::unique_ptr buffer = std::make_unique(normalSize); parcel.WriteRawData(buffer.get(), normalSize); @@ -264,3 +264,4 @@ HWTEST_F(TypesUtilTest, UnmarshalFromBufferLimitTest002, TestSize.Level1) ASSERT_FALSE(ITypesUtil::UnmarshalFromBuffer(parcel, output)); ASSERT_TRUE(output.empty()); } +} diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp index a5fb6aa7a0ffc67185a35b06eecd922521d04874..1a7fda6e875aa3cd34bf10f77b4fd50374860c5e 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp @@ -358,10 +358,10 @@ int CloudSyncer::FindDeletedListIndex(const std::vector> return -E_INTERNAL_ERROR; } -int CloudSyncer::SaveChangedData(SyncParam ¶m, int downIndex, const DataInfo &dataInfo, +int CloudSyncer::SaveChangedData(SyncParam ¶m, int dataIndex, const DataInfo &dataInfo, std::vector> &deletedList) { - OpType opType = param.downloadData.opType[downIndex]; + OpType opType = param.downloadData.opType[dataIndex]; Key hashKey = dataInfo.localInfo.logInfo.hashKey; if (param.deletePrimaryKeySet.find(hashKey) != param.deletePrimaryKeySet.end()) { if (opType == OpType::INSERT) { @@ -377,7 +377,7 @@ int CloudSyncer::SaveChangedData(SyncParam ¶m, int downIndex, const DataInfo opType = OpType::UPDATE; // only composite primary key needs to be processed. if (!param.isSinglePrimaryKey) { - param.withoutRowIdData.updateData.push_back(std::make_tuple(downIndex, + param.withoutRowIdData.updateData.push_back(std::make_tuple(dataIndex, param.changedData.primaryData[ChangeType::OP_UPDATE].size())); } } else if (opType == OpType::DELETE) { @@ -390,22 +390,22 @@ int CloudSyncer::SaveChangedData(SyncParam ¶m, int downIndex, const DataInfo } // INSERT: for no primary key or composite primary key situation if (!param.isSinglePrimaryKey && opType == OpType::INSERT) { - param.withoutRowIdData.insertData.push_back(downIndex); + param.withoutRowIdData.insertData.push_back(dataIndex); return E_OK; } switch (opType) { // INSERT: only for single primary key situation case OpType::INSERT: return SaveChangedDataByType( - param.downloadData.data[downIndex], param.changedData, dataInfo.localInfo, ChangeType::OP_INSERT); + param.downloadData.data[dataIndex], param.changedData, dataInfo.localInfo, ChangeType::OP_INSERT); case OpType::UPDATE: if (NeedSaveData(dataInfo.localInfo.logInfo, dataInfo.cloudLogInfo)) { - return SaveChangedDataByType(param.downloadData.data[downIndex], param.changedData, + return SaveChangedDataByType(param.downloadData.data[dataIndex], param.changedData, dataInfo.localInfo, ChangeType::OP_UPDATE); } break; case OpType::DELETE: - return SaveChangedDataByType(param.downloadData.data[downIndex], param.changedData, + return SaveChangedDataByType(param.downloadData.data[dataIndex], param.changedData, dataInfo.localInfo, ChangeType::OP_DELETE); default: break; @@ -491,7 +491,7 @@ bool CloudSyncer::IsDataContainAssets() -E_INTERNAL_ERROR); return false; } - if (hasTable && currentContext_.assetFields[currentContext_.tableName].empty()) { + if (currentContext_.assetFields[currentContext_.tableName].empty()) { LOGI("[CloudSyncer] Current table do not contain assets, thereby we needn't download assets"); return false; } @@ -617,7 +617,7 @@ int CloudSyncer::HandleDownloadResult(const std::string &tableName, DownloadComm return errCode; } -int CloudSyncer::CloudDbDownloadAssets(InnerProcessInfo &info, DownloadList &downloadList, bool willHandleResult, +int CloudSyncer::CloudDbDownloadAssets(InnerProcessInfo &info, const DownloadList &downloadList, bool willHandleResult, const std::set &dupHashKeySet, ChangedData &changedAssets) { int downloadStatus = E_OK; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h index 5258b042adf95fc3dcacbda625c534dd8dc63661..7df10a574ed581e9d9695e6a4048643608bf62db 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h @@ -243,7 +243,7 @@ protected: int DownloadAssets(InnerProcessInfo &info, const std::vector &pKColNames, const std::set &dupHashKeySet, ChangedData &changedAssets); - int CloudDbDownloadAssets(InnerProcessInfo &info, DownloadList &downloadList, bool willHandleResult, + int CloudDbDownloadAssets(InnerProcessInfo &info, const DownloadList &downloadList, bool willHandleResult, const std::set &dupHashKeySet, ChangedData &changedAssets); void GetDownloadItem(const DownloadList &downloadList, size_t i, DownloadItem &downloadItem); diff --git a/kv_store/frameworks/libs/distributeddb/test/fuzztest/cloudsync_fuzzer/cloudsync_fuzzer.cpp b/kv_store/frameworks/libs/distributeddb/test/fuzztest/cloudsync_fuzzer/cloudsync_fuzzer.cpp index d7d48af798a3e49bad2566b428b11f955f9087a7..f31f0610bff44069f10e9889c2ffc27eb2a5489f 100644 --- a/kv_store/frameworks/libs/distributeddb/test/fuzztest/cloudsync_fuzzer/cloudsync_fuzzer.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/fuzztest/cloudsync_fuzzer/cloudsync_fuzzer.cpp @@ -147,7 +147,7 @@ public: SQLiteUtils::ResetStatement(stmt, true, errCode); } - static Asset GenAsset(std::string name, std::string hash) + static Asset GenAsset(const std::string &name, const std::string &hash) { Asset asset; asset.name = name; @@ -181,7 +181,7 @@ public: if (errCode != E_OK) { break; } - std::vector assetsBlob; + std::vector assetVec(localAssets_.begin() + (i % size), localAssets_.end()); RuntimeContext::GetInstance()->AssetsToBlob(assetVec, assetBlob); errCode = SQLiteUtils::BindBlobToStatement(stmt, 4, assetBlob); // 4 is index of asserts diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_test.cpp index 328760930f55431619b5bc34848d28d0181ab11a..67504742e5c9a1fb23b3df82b4e435e13c850706 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_test.cpp @@ -1129,6 +1129,13 @@ HWTEST_F(DistributedDBInterfacesDataOperationTest, GetEntriesWithQuery002, TestS EXPECT_EQ(entries.size(), 3ul); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtrForQuery), OK); EXPECT_TRUE(g_mgr.DeleteKvStore("GetEntriesWithQuery002_002") == OK); + + QueryExpression expression; + EXPECT_TRUE(expression.GetErrFlag()); + expression.SetErrFlag(false); + EXPECT_FALSE(expression.GetErrFlag()); + expression.Reset(); + EXPECT_TRUE(expression.GetErrFlag()); } /** diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp index 4d9a77ddcdb095929a6f22bfceb7bd99b256eb3d..57f46909792534dfd2f1a91b1a3124896be00ce4 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp @@ -1049,4 +1049,25 @@ HWTEST_F(DistributedDBInterfacesRelationalSyncTest, SyncZeroBlobTest002, TestSiz }); EXPECT_EQ(resCnt, 1); EXPECT_EQ(ret, E_OK); -} \ No newline at end of file +} + +/** + * @tc.name: RuntimeConfig001 + * @tc.desc: Runtime config api + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBInterfacesRelationalSyncTest, RuntimeConfig001, TestSize.Level1) +{ + DBStatus status = RuntimeConfig::SetProcessLabel("", ""); + EXPECT_EQ(status, INVALID_ARGS); + status = RuntimeConfig::SetProcessLabel("DistributedDBInterfacesRelationalSyncTest", "RuntimeConfig001"); + EXPECT_EQ(status, OK); + status = RuntimeConfig::SetProcessCommunicator(nullptr); + if (!RuntimeContext::GetInstance()->IsCommunicatorAggregatorValid()) { + EXPECT_EQ(status, OK); + } + EXPECT_EQ(RuntimeConfig::IsProcessSystemApiAdapterValid(), + RuntimeContext::GetInstance()->IsProcessSystemApiAdapterValid()); +} diff --git a/preferences/frameworks/js/napi/common/include/js_ability.h b/preferences/frameworks/js/napi/common/include/js_ability.h index 0d5766daf840058ff22b4c6012a58885b2b85c77..fb114b557759ee56116fe8b25c974607eaed8fe9 100644 --- a/preferences/frameworks/js/napi/common/include/js_ability.h +++ b/preferences/frameworks/js/napi/common/include/js_ability.h @@ -26,16 +26,16 @@ namespace OHOS { namespace PreferencesJsKit { +namespace JSAbility { +enum CONTEXT_MODE { INIT = -1, FA = 0, STAGE = 1 }; struct ContextInfo { std::string bundleName; std::string preferencesDir; }; -class JSAbility final { -public: - static int GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, const bool &isStageMode, - ContextInfo &contextInfo); - static napi_status IsStageContext(napi_env env, napi_value value, bool &isStageMode); -}; +static CONTEXT_MODE gContextNode = INIT; +CONTEXT_MODE GetContextMode(napi_env env, napi_value value); +int GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, ContextInfo &contextInfo); +} // namespace JSAbility } // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/napi/common/include/napi_async_call.h b/preferences/frameworks/js/napi/common/include/napi_async_call.h index 1091538c57af522c60f481ef7e764479a04e91df..577e989de65bfe0ecf5168166ee341bde8b79f35 100644 --- a/preferences/frameworks/js/napi/common/include/napi_async_call.h +++ b/preferences/frameworks/js/napi/common/include/napi_async_call.h @@ -31,6 +31,10 @@ namespace PreferencesJsKit { using InputAction = std::function; using OutputAction = std::function; using ExecuteAction = std::function; +extern bool async; +extern bool sync; +#define ASYNC &async +#define SYNC &sync class BaseContext { public: @@ -39,6 +43,7 @@ public: virtual ~BaseContext(); napi_env env_ = nullptr; + bool isAsync_ = true; void *boundObj = nullptr; int execCode_ = ERR; std::shared_ptr error; @@ -50,6 +55,7 @@ public: OutputAction output_ = nullptr; ExecuteAction exec_ = nullptr; + napi_value result_ = nullptr; std::shared_ptr keep_; }; @@ -60,8 +66,12 @@ public: private: enum { ARG_ERROR, ARG_DATA, ARG_BUTT }; static void OnExecute(napi_env env, void *data); + static void OnComplete(napi_env env, void *data); + static void OnReturn(napi_env env, napi_status status, void *data); static void OnComplete(napi_env env, napi_status status, void *data); static void SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr error); + static napi_value Async(napi_env env, std::shared_ptr context); + static napi_value Sync(napi_env env, std::shared_ptr context); }; } // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/napi/common/mock/cross_platform/include/js_ability.h b/preferences/frameworks/js/napi/common/mock/cross_platform/include/js_ability.h index 0d747982997b20ad15a04b0546348752e6e68413..d6b864cdab580e117ad5f8ee4ed6e944eea8bbed 100644 --- a/preferences/frameworks/js/napi/common/mock/cross_platform/include/js_ability.h +++ b/preferences/frameworks/js/napi/common/mock/cross_platform/include/js_ability.h @@ -26,16 +26,16 @@ namespace OHOS { namespace PreferencesJsKit { +namespace JSAbility { +enum CONTEXT_MODE { INIT = -1, FA = 0, STAGE = 1 }; struct ContextInfo { std::string bundleName; std::string preferencesDir; }; -class JSAbility final { -public: - static int GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, const bool &isStageMode, - ContextInfo &contextInfo); - static napi_status IsStageContext(napi_env env, napi_value value, bool &isStageMode); -}; +static CONTEXT_MODE gContextNode = INIT; +CONTEXT_MODE GetContextMode(napi_env env, napi_value value); +int GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, ContextInfo &contextInfo); +} // namespace JSAbility } // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/napi/common/mock/cross_platform/src/js_ability.cpp b/preferences/frameworks/js/napi/common/mock/cross_platform/src/js_ability.cpp index e1322324a1f515e55f0949c93a64b2f7551abee1..eec988af07743b9c44d6506e369292acc75445aa 100644 --- a/preferences/frameworks/js/napi/common/mock/cross_platform/src/js_ability.cpp +++ b/preferences/frameworks/js/napi/common/mock/cross_platform/src/js_ability.cpp @@ -20,14 +20,13 @@ namespace OHOS { namespace PreferencesJsKit { -napi_status JSAbility::IsStageContext(napi_env env, napi_value value, bool &isStageMode) +namespace JSAbility { +CONTEXT_MODE GetContextMode(napi_env env, napi_value value) { - isStageMode = true; - return napi_ok; + return STAGE; } -int JSAbility::GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, const bool &isStageMode, - ContextInfo &contextInfo) +int GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, ContextInfo &contextInfo) { if (!dataGroupId.empty()) { return NativePreferences::E_NOT_SUPPORTED; @@ -40,5 +39,6 @@ int JSAbility::GetContextInfo(napi_env env, napi_value value, const std::string contextInfo.preferencesDir = stageContext->GetPreferencesDir(); return OK; } +} // namespace JSAbility } // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/napi/common/mock/include/js_ability.h b/preferences/frameworks/js/napi/common/mock/include/js_ability.h index cfe975fb6e0cdefb15157536f47a247c0baa1495..14b37a476a5690bb237e74942e34b9a8c932af2b 100644 --- a/preferences/frameworks/js/napi/common/mock/include/js_ability.h +++ b/preferences/frameworks/js/napi/common/mock/include/js_ability.h @@ -24,16 +24,16 @@ namespace OHOS { namespace PreferencesJsKit { +namespace JSAbility { +enum CONTEXT_MODE { INIT = -1, FA = 0, STAGE = 1 }; struct ContextInfo { std::string bundleName; std::string preferencesDir; }; -class JSAbility final { -public: - static int GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, const bool &isStageMode, - ContextInfo &contextInfo); - static napi_status IsStageContext(napi_env env, napi_value value, bool &isStageMode); -}; +static CONTEXT_MODE gContextNode = INIT; +CONTEXT_MODE GetContextMode(napi_env env, napi_value value); +int GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, ContextInfo &contextInfo); +} // namespace JSAbility } // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/napi/common/mock/src/js_ability.cpp b/preferences/frameworks/js/napi/common/mock/src/js_ability.cpp index 47ab875528ffee6d9a22c7017e2b286793edb80e..1271c741463ebdabe11b0f4e919858657ee0f0a8 100644 --- a/preferences/frameworks/js/napi/common/mock/src/js_ability.cpp +++ b/preferences/frameworks/js/napi/common/mock/src/js_ability.cpp @@ -22,14 +22,13 @@ namespace OHOS { namespace PreferencesJsKit { -napi_status JSAbility::IsStageContext(napi_env env, napi_value value, bool &isStageMode) +namespace JSAbility { +CONTEXT_MODE GetContextMode(napi_env env, napi_value value) { - isStageMode = true; - return napi_ok; + return STAGE; } -int JSAbility::GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, const bool &isStageMode, - ContextInfo &contextInfo) +int GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, ContextInfo &contextInfo) { if (!dataGroupId.empty()) { return NativePreferences::E_NOT_SUPPORTED; @@ -51,5 +50,6 @@ int JSAbility::GetContextInfo(napi_env env, napi_value value, const std::string #endif return OK; } +} // namespace JSAbility } // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/napi/common/src/js_ability.cpp b/preferences/frameworks/js/napi/common/src/js_ability.cpp index f27d3577a1d36684cd1aeba5f8d036771befb450..af23daa3581c7261238dfd2b5324ff39941d5c69 100644 --- a/preferences/frameworks/js/napi/common/src/js_ability.cpp +++ b/preferences/frameworks/js/napi/common/src/js_ability.cpp @@ -20,31 +20,37 @@ namespace OHOS { namespace PreferencesJsKit { -napi_status JSAbility::IsStageContext(napi_env env, napi_value value, bool &isStageMode) +namespace JSAbility { +CONTEXT_MODE GetContextMode(napi_env env, napi_value value) { - napi_status status = AbilityRuntime::IsStageContext(env, value, isStageMode); - return status; + if (gContextNode == INIT) { + bool isStageMode; + napi_status status = AbilityRuntime::IsStageContext(env, value, isStageMode); + gContextNode = (status == napi_ok && isStageMode) ? STAGE : FA; + LOG_INFO("set gContextNode = %{public}d", gContextNode); + } + return gContextNode; } -int JSAbility::GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, const bool &isStageMode, - ContextInfo &contextInfo) +int GetContextInfo(napi_env env, napi_value value, const std::string &dataGroupId, ContextInfo &contextInfo) { - if (isStageMode) { - auto stageContext = AbilityRuntime::GetStageModeContext(env, value); - if (stageContext == nullptr) { + if (GetContextMode(env, value) == STAGE) { + if (auto stageContext = AbilityRuntime::GetStageModeContext(env, value)) { + int errcode = stageContext->GetSystemPreferencesDir(dataGroupId, false, contextInfo.preferencesDir); + if (errcode != 0) { + LOG_ERROR("GetSystemPreferencesDir fails, rc = %{public}d", errcode); + return E_DATA_GROUP_ID_INVALID; + } + contextInfo.bundleName = stageContext->GetBundleName(); + return OK; + } else { LOG_ERROR("failed to get stage mode context."); return E_INNER_ERROR; } - - int errcode = stageContext->GetSystemPreferencesDir(dataGroupId, false, contextInfo.preferencesDir); - if (errcode != 0) { - return E_DATA_GROUP_ID_INVALID; - } - contextInfo.bundleName = stageContext->GetBundleName(); - return OK; } if (!dataGroupId.empty()) { + LOG_ERROR("dataGroupId should be empty in fa mode"); return E_NOT_STAGE_MODE; } @@ -62,5 +68,6 @@ int JSAbility::GetContextInfo(napi_env env, napi_value value, const std::string abilityContext->GetSystemPreferencesDir("", false, contextInfo.preferencesDir); return OK; } +} // namespace JSAbility } // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/napi/common/src/js_utils.cpp b/preferences/frameworks/js/napi/common/src/js_utils.cpp index df3f8f620386cda511ff92b9d36a253a2ea47751..54edff72327ccc2fa2491d0742b7c23624488432 100644 --- a/preferences/frameworks/js/napi/common/src/js_utils.cpp +++ b/preferences/frameworks/js/napi/common/src/js_utils.cpp @@ -36,6 +36,10 @@ int32_t JSUtils::Convert2NativeValue(napi_env env, napi_value jsValue, std::stri return EXCEED_MAX_LENGTH; } char *buffer = (char *)malloc(bufferSize + 1); + if (buffer == nullptr) { + LOG_ERROR("malloc failed, buffer is nullptr."); + return ERR; + } status = napi_get_value_string_utf8(env, jsValue, buffer, bufferSize + 1, &bufferSize); if (status != napi_ok) { free(buffer); diff --git a/preferences/frameworks/js/napi/common/src/napi_async_call.cpp b/preferences/frameworks/js/napi/common/src/napi_async_call.cpp index 8b2d1032a1355a364d8d4149b71152e0b748c9f2..a9ab59f545ce813e303cd1e581becc7ed1bf7977 100644 --- a/preferences/frameworks/js/napi/common/src/napi_async_call.cpp +++ b/preferences/frameworks/js/napi/common/src/napi_async_call.cpp @@ -18,6 +18,8 @@ namespace OHOS { namespace PreferencesJsKit { +bool async = true; // do not reset the value, used in DECLARE_NAPI_FUNCTION_WITH_DATA only +bool sync = !async; // do not reset the value, used in DECLARE_NAPI_FUNCTION_WITH_DATA only void BaseContext::SetAction( napi_env env, napi_callback_info info, InputAction input, ExecuteAction exec, OutputAction output) { @@ -25,7 +27,8 @@ void BaseContext::SetAction( size_t argc = MAX_INPUT_COUNT; napi_value self = nullptr; napi_value argv[MAX_INPUT_COUNT] = { nullptr }; - napi_status status = napi_get_cb_info(env, info, &argc, argv, &self, nullptr); + void *data = nullptr; + napi_status status = napi_get_cb_info(env, info, &argc, argv, &self, &data); napi_valuetype valueType = napi_undefined; if (status == napi_ok && argc > 0) { napi_typeof(env, argv[argc - 1], &valueType); @@ -34,6 +37,9 @@ void BaseContext::SetAction( argc = argc - 1; } } + if (data) { + isAsync_ = *reinterpret_cast(data); + } // int -->input_(env, argc, argv, self) if (status == napi_ok) { @@ -86,6 +92,11 @@ void AsyncCall::SetBusinessError(napi_env env, napi_value *businessError, std::s } napi_value AsyncCall::Call(napi_env env, std::shared_ptr context) +{ + return context->isAsync_ ? Async(env, context) : Sync(env, context); +} + +napi_value AsyncCall::Async(napi_env env, std::shared_ptr context) { napi_value promise = nullptr; @@ -105,6 +116,13 @@ napi_value AsyncCall::Call(napi_env env, std::shared_ptr context) return promise; } +napi_value AsyncCall::Sync(napi_env env, std::shared_ptr context) +{ + OnExecute(env, reinterpret_cast(context.get())); + OnComplete(env, reinterpret_cast(context.get())); + return context->result_; +} + void AsyncCall::OnExecute(napi_env env, void *data) { BaseContext *context = reinterpret_cast(data); @@ -114,24 +132,34 @@ void AsyncCall::OnExecute(napi_env env, void *data) context->exec_ = nullptr; } -void AsyncCall::OnComplete(napi_env env, napi_status status, void *data) +void AsyncCall::OnComplete(napi_env env, void *data) { BaseContext *context = reinterpret_cast(data); if (context->execCode_ != NativePreferences::E_OK) { context->SetError(std::make_shared(context->execCode_)); } - napi_value output = nullptr; // if async execute status is not napi_ok then un-execute out function if ((context->error == nullptr) && context->output_) { - context->output_(env, output); + context->output_(env, context->result_); } context->output_ = nullptr; +} + +void AsyncCall::OnComplete(napi_env env, napi_status status, void *data) +{ + OnComplete(env, data); + OnReturn(env, status, data); +} + +void AsyncCall::OnReturn(napi_env env, napi_status status, void *data) +{ + BaseContext *context = reinterpret_cast(data); napi_value result[ARG_BUTT] = { 0 }; // if out function status is ok then async renturn output data, else return error. if (context->error == nullptr) { napi_get_undefined(env, &result[ARG_ERROR]); - if (output != nullptr) { - result[ARG_DATA] = output; + if (context->result_ != nullptr) { + result[ARG_DATA] = context->result_; } else { napi_get_undefined(env, &result[ARG_DATA]); } diff --git a/preferences/frameworks/js/napi/preferences/src/napi_preferences.cpp b/preferences/frameworks/js/napi/preferences/src/napi_preferences.cpp index 612171712d26e5c7250c657f353fc3a3df817b08..2369c30af6d67bdf7cf57720137624315069462a 100644 --- a/preferences/frameworks/js/napi/preferences/src/napi_preferences.cpp +++ b/preferences/frameworks/js/napi/preferences/src/napi_preferences.cpp @@ -72,19 +72,20 @@ void PreferencesProxy::Destructor(napi_env env, void *nativeObject, void *finali void PreferencesProxy::Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { - DECLARE_NAPI_FUNCTION("put", SetValue), - DECLARE_NAPI_FUNCTION("putSync", SetValueSync), - DECLARE_NAPI_FUNCTION("get", GetValue), - DECLARE_NAPI_FUNCTION("getSync", GetValueSync), - DECLARE_NAPI_FUNCTION("getAll", GetAll), - DECLARE_NAPI_FUNCTION("getAllSync", GetAllSync), - DECLARE_NAPI_FUNCTION("delete", Delete), - DECLARE_NAPI_FUNCTION("deleteSync", DeleteSync), - DECLARE_NAPI_FUNCTION("clear", Clear), - DECLARE_NAPI_FUNCTION("clearSync", ClearSync), - DECLARE_NAPI_FUNCTION("has", HasKey), - DECLARE_NAPI_FUNCTION("hasSync", HasKeySync), - DECLARE_NAPI_FUNCTION("flush", Flush), + DECLARE_NAPI_FUNCTION_WITH_DATA("put", SetValue, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("putSync", SetValue, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("get", GetValue, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("getSync", GetValue, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("getAll", GetAll, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("getAllSync", GetAll, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("delete", Delete, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("deleteSync", Delete, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("clear", Clear, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("clearSync", Clear, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("has", HasKey, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("hasSync", HasKey, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("flush", Flush, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("flushSync", Flush, SYNC), DECLARE_NAPI_FUNCTION("on", RegisterObserver), DECLARE_NAPI_FUNCTION("off", UnRegisterObserver), }; @@ -189,20 +190,6 @@ napi_value PreferencesProxy::GetAll(napi_env env, napi_callback_info info) return AsyncCall::Call(env, context); } -napi_value PreferencesProxy::GetAllSync(napi_env env, napi_callback_info info) -{ - napi_value self = nullptr; - napi_get_cb_info(env, info, nullptr, nullptr, &self, nullptr); - PreferencesProxy *proxy = nullptr; - napi_unwrap(env, self, reinterpret_cast(&proxy)); - - auto context = std::make_shared(); - context->allElements = proxy->value_->GetAll(); - napi_value result = nullptr; - GetAllExecute(env, context, result); - return result; -} - napi_value PreferencesProxy::GetValue(napi_env env, napi_callback_info info) { LOG_DEBUG("GetValue start"); @@ -234,27 +221,6 @@ napi_value PreferencesProxy::GetValue(napi_env env, napi_callback_info info) return AsyncCall::Call(env, context); } -napi_value PreferencesProxy::GetValueSync(napi_env env, napi_callback_info info) -{ - napi_value self = nullptr; - size_t argc = 2; - napi_value argv[2] = { 0 }; - napi_get_cb_info(env, info, &argc, argv, &self, nullptr); - PRE_NAPI_ASSERT(env, argc == 2, std::make_shared("2")); - PreferencesProxy *proxy = nullptr; - napi_unwrap(env, self, reinterpret_cast(&proxy)); - - auto context = std::make_shared(); - PRE_NAPI_ASSERT(env, ParseKey(env, argv[0], context) == OK, context->error); - context->defValue = proxy->value_->Get(context->key, context->defValue); - // the return back value never be an int64_t type. - if (context->defValue.IsLong()) { - LOG_DEBUG("GetValue get default value."); - return argv[1]; - } - return JSUtils::Convert2JSValue(env, context->defValue.value_); -} - napi_value PreferencesProxy::SetValue(napi_env env, napi_callback_info info) { LOG_DEBUG("SetValue start"); @@ -280,24 +246,6 @@ napi_value PreferencesProxy::SetValue(napi_env env, napi_callback_info info) return AsyncCall::Call(env, context); } -napi_value PreferencesProxy::SetValueSync(napi_env env, napi_callback_info info) -{ - napi_value self = nullptr; - size_t argc = 2; - napi_value argv[2] = { 0 }; - napi_get_cb_info(env, info, &argc, argv, &self, nullptr); - PRE_NAPI_ASSERT(env, argc == 2, std::make_shared("2")); - PreferencesProxy *proxy = nullptr; - napi_unwrap(env, self, reinterpret_cast(&proxy)); - - auto context = std::make_shared(); - PRE_NAPI_ASSERT(env, ParseKey(env, argv[0], context) == OK, context->error); - PRE_NAPI_ASSERT(env, ParseDefValue(env, argv[1], context) == OK, context->error); - int errCode = proxy->value_->Put(context->key, context->defValue); - PRE_NAPI_ASSERT(env, errCode == E_OK, std::make_shared(errCode)); - return nullptr; -} - napi_value PreferencesProxy::Delete(napi_env env, napi_callback_info info) { LOG_DEBUG("Delete start"); @@ -322,23 +270,6 @@ napi_value PreferencesProxy::Delete(napi_env env, napi_callback_info info) return AsyncCall::Call(env, context); } -napi_value PreferencesProxy::DeleteSync(napi_env env, napi_callback_info info) -{ - napi_value self = nullptr; - size_t argc = 1; - napi_value argv[1] = { 0 }; - napi_get_cb_info(env, info, &argc, argv, &self, nullptr); - PRE_NAPI_ASSERT(env, argc == 1, std::make_shared("1")); - PreferencesProxy *proxy = nullptr; - napi_unwrap(env, self, reinterpret_cast(&proxy)); - - auto context = std::make_shared(); - PRE_NAPI_ASSERT(env, ParseKey(env, argv[0], context) == OK, context->error); - int errCode = proxy->value_->Delete(context->key); - PRE_NAPI_ASSERT(env, errCode == E_OK, std::make_shared(errCode)); - return nullptr; -} - napi_value PreferencesProxy::HasKey(napi_env env, napi_callback_info info) { LOG_DEBUG("HasKey start"); @@ -364,22 +295,6 @@ napi_value PreferencesProxy::HasKey(napi_env env, napi_callback_info info) return AsyncCall::Call(env, context); } -napi_value PreferencesProxy::HasKeySync(napi_env env, napi_callback_info info) -{ - napi_value self = nullptr; - size_t argc = 1; - napi_value argv[1] = { 0 }; - napi_get_cb_info(env, info, &argc, argv, &self, nullptr); - PRE_NAPI_ASSERT(env, argc == 1, std::make_shared("1")); - PreferencesProxy *proxy = nullptr; - napi_unwrap(env, self, reinterpret_cast(&proxy)); - - auto context = std::make_shared(); - PRE_NAPI_ASSERT(env, ParseKey(env, argv[0], context) == OK, context->error); - bool result = proxy->value_->HasKey(context->key); - return JSUtils::Convert2JSValue(env, result); -} - napi_value PreferencesProxy::Flush(napi_env env, napi_callback_info info) { LOG_DEBUG("Flush start"); @@ -398,7 +313,7 @@ napi_value PreferencesProxy::Flush(napi_env env, napi_callback_info info) LOG_DEBUG("Flush end."); }; context->SetAction(env, info, input, exec, output); - + PRE_CHECK_RETURN_NULL(context->error == nullptr || context->error->GetCode() == OK); return AsyncCall::Call(env, context); } @@ -426,18 +341,6 @@ napi_value PreferencesProxy::Clear(napi_env env, napi_callback_info info) return AsyncCall::Call(env, context); } -napi_value PreferencesProxy::ClearSync(napi_env env, napi_callback_info info) -{ - napi_value self = nullptr; - napi_get_cb_info(env, info, nullptr, nullptr, &self, nullptr); - PreferencesProxy *proxy = nullptr; - napi_unwrap(env, self, reinterpret_cast(&proxy)); - - int errCode = proxy->value_->Clear(); - PRE_NAPI_ASSERT(env, errCode == E_OK, std::make_shared(errCode)); - return nullptr; -} - napi_value PreferencesProxy::RegisterObserver(napi_env env, napi_callback_info info) { napi_value thiz = nullptr; diff --git a/preferences/frameworks/js/napi/preferences/src/napi_preferences_helper.cpp b/preferences/frameworks/js/napi/preferences/src/napi_preferences_helper.cpp index c137f6f1ba32525503c1bf28913626cee74aef68..8a9db647407a812aa337d968e7027d3d9cba2725 100644 --- a/preferences/frameworks/js/napi/preferences/src/napi_preferences_helper.cpp +++ b/preferences/frameworks/js/napi/preferences/src/napi_preferences_helper.cpp @@ -46,49 +46,25 @@ struct HelperAysncContext : public BaseContext { virtual ~HelperAysncContext(){}; }; -int ParseName(const napi_env env, const napi_value name, std::shared_ptr context) +int ParseParameters(const napi_env env, napi_value *argv, std::shared_ptr context) { - int status = JSUtils::Convert2NativeValue(env, name, context->name); - PRE_CHECK_RETURN_ERR_SET(status == OK && !context->name.empty(), - std::make_shared(NAME, "a without path non empty string.")); - size_t pos = context->name.find_first_of('/'); - PRE_CHECK_RETURN_ERR_SET(pos == std::string::npos, - std::make_shared(NAME, "a name string only without path.")); - return OK; -} - -int ParseGroupId(const napi_env env, const napi_value dataGroupId, std::shared_ptr context) -{ - int res = JSUtils::Convert2NativeValue(env, dataGroupId, context->dataGroupId); - PRE_CHECK_RETURN_ERR_SET(res == OK && !context->dataGroupId.empty(), - std::make_shared(DATA_GROUP_ID, "a non empty string.")); - return OK; -} - -int ParseParameters(const napi_env env, napi_value* argv, std::shared_ptr context) -{ - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[1], &valueType); - if (valueType == napi_string) { - PRE_CHECK_RETURN_ERR(ParseName(env, argv[1], context) == OK); - } else { - napi_value nameValue = nullptr; - napi_get_named_property(env, argv[1], NAME, &nameValue); - PRE_CHECK_RETURN_ERR(ParseName(env, nameValue, context) == OK); - bool hasDataGroupId = false; - napi_has_named_property(env, argv[1], DATA_GROUP_ID, &hasDataGroupId); - if (hasDataGroupId) { - napi_value dataGroupIdValue = nullptr; - napi_get_named_property(env, argv[1], DATA_GROUP_ID, &dataGroupIdValue); - PRE_CHECK_RETURN_ERR(ParseGroupId(env, dataGroupIdValue, context) == OK); + if (JSUtils::Convert2NativeValue(env, argv[1], context->name) != napi_ok) { + napi_value temp = nullptr; + napi_get_named_property(env, argv[1], NAME, &temp); + PRE_CHECK_RETURN_ERR_SET(temp && JSUtils::Convert2NativeValue(env, temp, context->name) == napi_ok, + std::make_shared(NAME, "a string.")); + + bool hasGroupId = false; + napi_has_named_property(env, argv[1], DATA_GROUP_ID, &hasGroupId); + if (hasGroupId) { + temp = nullptr; + napi_get_named_property(env, argv[1], DATA_GROUP_ID, &temp); + PRE_CHECK_RETURN_ERR_SET(JSUtils::Convert2NativeValue(env, temp, context->dataGroupId) == napi_ok, + std::make_shared(DATA_GROUP_ID, "a string.")); } } - bool isStageMode = false; - napi_status status = JSAbility::IsStageContext(env, argv[0], isStageMode); - PRE_CHECK_RETURN_ERR_SET(status == napi_ok, std::make_shared("context", "a Context.")); - - ContextInfo contextInfo; - int errCode = JSAbility::GetContextInfo(env, argv[0], context->dataGroupId, isStageMode, contextInfo); + JSAbility::ContextInfo contextInfo; + int errCode = JSAbility::GetContextInfo(env, argv[0], context->dataGroupId, contextInfo); PRE_CHECK_RETURN_ERR_SET(errCode == OK, std::make_shared(errCode)); context->bundleName = contextInfo.bundleName; @@ -119,29 +95,6 @@ napi_value GetPreferences(napi_env env, napi_callback_info info) return AsyncCall::Call(env, context); } -napi_value GetPreferencesSync(napi_env env, napi_callback_info info) -{ - napi_value self = nullptr; - size_t argc = 2; - napi_value argv[2] = { 0 }; - napi_get_cb_info(env, info, &argc, argv, &self, nullptr); - PRE_NAPI_ASSERT(env, argc == 2, std::make_shared("2")); - - auto context = std::make_shared(); - PRE_NAPI_ASSERT(env, ParseParameters(env, argv, context) == OK, context->error); - - int errCode = ERR; - Options options(context->path, context->bundleName, context->dataGroupId); - auto proxy = PreferencesHelper::GetPreferences(options, errCode); - PRE_NAPI_ASSERT(env, errCode == E_OK, std::make_shared(errCode)); - - napi_value result; - errCode = PreferencesProxy::NewInstance(env, proxy, &result); - - PRE_NAPI_ASSERT(env, errCode == E_OK, std::make_shared(errCode)); - return result; -} - napi_value DeletePreferences(napi_env env, napi_callback_info info) { auto context = std::make_shared(); @@ -162,22 +115,6 @@ napi_value DeletePreferences(napi_env env, napi_callback_info info) return AsyncCall::Call(env, context); } -napi_value DeletePreferencesSync(napi_env env, napi_callback_info info) -{ - napi_value self = nullptr; - size_t argc = 2; - napi_value argv[2] = { 0 }; - napi_get_cb_info(env, info, &argc, argv, &self, nullptr); - PRE_NAPI_ASSERT(env, argc == 2, std::make_shared("2")); - - auto context = std::make_shared(); - PRE_NAPI_ASSERT(env, ParseParameters(env, argv, context) == OK, context->error); - int errCode = PreferencesHelper::DeletePreferences(context->path); - - PRE_NAPI_ASSERT(env, errCode == E_OK, std::make_shared(errCode)); - return nullptr; -} - napi_value RemovePreferencesFromCache(napi_env env, napi_callback_info info) { auto context = std::make_shared(); @@ -198,31 +135,15 @@ napi_value RemovePreferencesFromCache(napi_env env, napi_callback_info info) return AsyncCall::Call(env, context); } -napi_value RemovePreferencesFromCacheSync(napi_env env, napi_callback_info info) -{ - napi_value self = nullptr; - size_t argc = 2; - napi_value argv[2] = { 0 }; - napi_get_cb_info(env, info, &argc, argv, &self, nullptr); - PRE_NAPI_ASSERT(env, argc == 2, std::make_shared("2")); - - auto context = std::make_shared(); - PRE_NAPI_ASSERT(env, ParseParameters(env, argv, context) == OK, context->error); - int errCode = PreferencesHelper::RemovePreferencesFromCache(context->path); - - PRE_NAPI_ASSERT(env, errCode == E_OK, std::make_shared(errCode)); - return nullptr; -} - napi_value InitPreferencesHelper(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("getPreferences", GetPreferences), - DECLARE_NAPI_FUNCTION("getPreferencesSync", GetPreferencesSync), - DECLARE_NAPI_FUNCTION("deletePreferences", DeletePreferences), - DECLARE_NAPI_FUNCTION("deletePreferencesSync", DeletePreferencesSync), - DECLARE_NAPI_FUNCTION("removePreferencesFromCache", RemovePreferencesFromCache), - DECLARE_NAPI_FUNCTION("removePreferencesFromCacheSync", RemovePreferencesFromCacheSync), + DECLARE_NAPI_FUNCTION_WITH_DATA("getPreferences", GetPreferences, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("getPreferencesSync", GetPreferences, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("deletePreferences", DeletePreferences, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("deletePreferencesSync", DeletePreferences, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("removePreferencesFromCache", RemovePreferencesFromCache, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("removePreferencesFromCacheSync", RemovePreferencesFromCache, SYNC), DECLARE_NAPI_PROPERTY("MAX_KEY_LENGTH", JSUtils::Convert2JSValue(env, Preferences::MAX_KEY_LENGTH)), DECLARE_NAPI_PROPERTY("MAX_VALUE_LENGTH", JSUtils::Convert2JSValue(env, Preferences::MAX_VALUE_LENGTH)), }; diff --git a/preferences/frameworks/js/napi/system_storage/src/napi_system_storage.cpp b/preferences/frameworks/js/napi/system_storage/src/napi_system_storage.cpp index 36689080b4d07e92e3209e8a86ed6c351c5e63c0..ae323d7513338d8d47a331db33f763926f76796d 100644 --- a/preferences/frameworks/js/napi/system_storage/src/napi_system_storage.cpp +++ b/preferences/frameworks/js/napi/system_storage/src/napi_system_storage.cpp @@ -166,8 +166,8 @@ void Complete(napi_env env, napi_status status, void *data) std::string GetPrefName(napi_env env) { - ContextInfo contextInfo; - JSAbility::GetContextInfo(env, nullptr, "", false, contextInfo); + JSAbility::ContextInfo contextInfo; + JSAbility::GetContextInfo(env, nullptr, "", contextInfo); return contextInfo.preferencesDir + "/default.xml"; } diff --git a/preferences/frameworks/native/include/preferences_xml_utils.h b/preferences/frameworks/native/include/preferences_xml_utils.h index 7ba5b86333c7acb20a81d3c8fd9c041f91c38035..2b46677fe5035befc1158762e8178756442f7524 100644 --- a/preferences/frameworks/native/include/preferences_xml_utils.h +++ b/preferences/frameworks/native/include/preferences_xml_utils.h @@ -35,8 +35,6 @@ public: static bool ReadSettingXml(const std::string &fileName, std::vector &settings); static bool WriteSettingXml(const std::string &fileName, std::vector &settings); static void LimitXmlPermission(const std::string &fileName); - static void XmlInitParser(); - static void XmlCleanupParser(); private: PreferencesXmlUtils() diff --git a/preferences/frameworks/native/platform/include/preferences_thread.h b/preferences/frameworks/native/platform/include/preferences_thread.h index 26bee1e4fd5f549bab1b43a2894c45cb7ef15fd6..75bea3ea5947ba5bd7aefa42131e7a7c4fae1455 100644 --- a/preferences/frameworks/native/platform/include/preferences_thread.h +++ b/preferences/frameworks/native/platform/include/preferences_thread.h @@ -21,7 +21,7 @@ #include namespace OHOS { namespace NativePreferences { -int PthreadSetNameNp(const std::string name); +int PthreadSetNameNp(const std::string &name); } // End of namespace NativePreferences } // End of namespace OHOS #endif // End of #ifndef PREFERENCES_THREAD_H \ No newline at end of file diff --git a/preferences/frameworks/native/platform/src/preferences_thread.cpp b/preferences/frameworks/native/platform/src/preferences_thread.cpp index fc537086ef69a0e60b375b6e72d8acaf87c0aa61..b2c436c8c413a8fa1787f64985ca14b2667cad60 100644 --- a/preferences/frameworks/native/platform/src/preferences_thread.cpp +++ b/preferences/frameworks/native/platform/src/preferences_thread.cpp @@ -15,7 +15,7 @@ #include "preferences_thread.h" namespace OHOS { namespace NativePreferences { -int PthreadSetNameNp(const std::string name) +int PthreadSetNameNp(const std::string &name) { return pthread_setname_np( #if !(defined(MAC_PLATFORM) || defined(IOS_PLATFORM)) diff --git a/preferences/frameworks/native/src/preferences_helper.cpp b/preferences/frameworks/native/src/preferences_helper.cpp index 797ce4442aece62ab6b1544b47b68b1dd430a01b..0bd21078ff2ef6cd4c3977d241a09361c3126354 100644 --- a/preferences/frameworks/native/src/preferences_helper.cpp +++ b/preferences/frameworks/native/src/preferences_helper.cpp @@ -44,12 +44,12 @@ std::string PreferencesHelper::GetRealPath(const std::string &path, int &errorCo errorCode = E_EMPTY_FILE_PATH; return ""; } - if (path.front() != '/' && path.at(1) != ':') { + if (path.front() != '/') { LOG_ERROR("The path can not be relative path."); errorCode = E_RELATIVE_PATH; return ""; } - if (strlen(path.c_str()) > PATH_MAX) { + if (path.length() > PATH_MAX) { LOG_ERROR("The path exceeds max length."); errorCode = E_PATH_EXCEED_MAX_LENGTH; return ""; @@ -60,8 +60,13 @@ std::string PreferencesHelper::GetRealPath(const std::string &path, int &errorCo errorCode = E_RELATIVE_PATH; return ""; } - std::string filePath = path.substr(0, pos); #if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) + if (path.at(1) != ':') { + LOG_ERROR("The path can not be relative path."); + errorCode = E_RELATIVE_PATH; + return ""; + } + std::string filePath = path.substr(0, pos); if (Access(filePath) != 0 && Mkdir(filePath)) { LOG_ERROR("Failed to create path"); errorCode = E_INVALID_FILE_PATH; diff --git a/preferences/frameworks/native/src/preferences_impl.cpp b/preferences/frameworks/native/src/preferences_impl.cpp index aff55641275501ad87dd6079832a6ac3958adb97..abe2bc050198a4dfc9f63fefb8da98532523e92a 100644 --- a/preferences/frameworks/native/src/preferences_impl.cpp +++ b/preferences/frameworks/native/src/preferences_impl.cpp @@ -16,7 +16,10 @@ #include "preferences_impl.h" #include +#include +#include #include +#include #include #include "executor_pool.h" @@ -24,6 +27,7 @@ #include "preferences_errno.h" #include "preferences_observer_stub.h" #include "preferences_xml_utils.h" +#include "securec.h" namespace OHOS { namespace NativePreferences { @@ -276,8 +280,8 @@ template void Convert2Element(Element &elem, const T &value) template void Convert2Element(Element &elem, const std::vector &value) { - elem.tag_ = GetTypeName(); - for (auto val : value) { + elem.tag_ = GetTypeName>(); + for (const T &val : value) { Element element; Convert2Element(element, val); elem.children_.push_back(element); @@ -316,7 +320,6 @@ bool PreferencesImpl::WriteSettingXml( Element elem; elem.key_ = it->first; PreferencesValue value = it->second; - WriteXmlElement(elem, value); settings.push_back(elem); } diff --git a/preferences/frameworks/native/src/preferences_xml_utils.cpp b/preferences/frameworks/native/src/preferences_xml_utils.cpp index 830374e56b0cfc6295f57cf3ab60a803aaa80f6e..74d02e151d423cb578b02bf803dd26aa3542849f 100644 --- a/preferences/frameworks/native/src/preferences_xml_utils.cpp +++ b/preferences/frameworks/native/src/preferences_xml_utils.cpp @@ -99,7 +99,7 @@ static xmlDoc *XmlReadFile(const std::string &fileName) if (doc != nullptr) { return doc; } - if (RenameToBrokenFile(fileName)) { + if (!RenameToBrokenFile(fileName)) { return doc; } } @@ -176,10 +176,6 @@ bool ParseNodeElement(const xmlNode *node, Element &element) /* static */ bool ParsePrimitiveNodeElement(const xmlNode *node, Element &element) { - if (node == nullptr) { - return false; - } - xmlChar *key = xmlGetProp(node, reinterpret_cast("key")); xmlChar *value = xmlGetProp(node, reinterpret_cast("value")); @@ -207,10 +203,6 @@ bool ParsePrimitiveNodeElement(const xmlNode *node, Element &element) /* static */ bool ParseStringNodeElement(const xmlNode *node, Element &element) { - if (node == nullptr) { - return false; - } - xmlChar *key = xmlGetProp(node, (const xmlChar *)"key"); xmlChar *text = xmlNodeGetContent(node); @@ -238,10 +230,6 @@ bool ParseStringNodeElement(const xmlNode *node, Element &element) /* static */ bool ParseArrayNodeElement(const xmlNode *node, Element &element) { - if (node == nullptr) { - return false; - } - xmlChar *key = xmlGetProp(node, (const xmlChar *)"key"); const xmlNode *children = node->children; @@ -460,17 +448,5 @@ void PreferencesXmlUtils::LimitXmlPermission(const std::string &fileName) } } } - -void PreferencesXmlUtils::XmlInitParser() -{ - xmlInitParser(); - LOG_DEBUG("Xml parser get ready."); -} - -void PreferencesXmlUtils::XmlCleanupParser() -{ - xmlCleanupParser(); - LOG_DEBUG("Xml parser clean up."); -} } // End of namespace NativePreferences } // End of namespace OHOS \ No newline at end of file diff --git a/preferences/test/js/unittest/preferences/src/PreferencesHelperJsunit.test.js b/preferences/test/js/unittest/preferences/src/PreferencesHelperJsunit.test.js index afce5544f276ecb9808dfdd75f3fbb1157cb7cc0..0d92d226aeb6b7a7e64fdbd1a17e63d5ca2e3dea 100644 --- a/preferences/test/js/unittest/preferences/src/PreferencesHelperJsunit.test.js +++ b/preferences/test/js/unittest/preferences/src/PreferencesHelperJsunit.test.js @@ -102,9 +102,10 @@ describe('PreferencesHelperJsunit', function () { it('testGetPreferencesHelper005', 0, async function (done) { try { await data_preferences.getPreferences(undefined, { name: NAME }); - } catch(err) { done(); - expect('401').assertEqual(err.code); + expect(mPreferences != null).assertTrue(); + } catch(err) { + expect(err).assertFail(); } }) @@ -116,9 +117,10 @@ describe('PreferencesHelperJsunit', function () { it('testGetPreferencesHelper006', 0, async function (done) { try { await data_preferences.getPreferences(null, { name: NAME }); - } catch(err) { done(); - expect('401').assertEqual(err.code); + expect(mPreferences != null).assertTrue(); + } catch(err) { + expect(err).assertFail(); } }) @@ -130,40 +132,6 @@ describe('PreferencesHelperJsunit', function () { it('testGetPreferencesHelper007', 0, async function (done) { try { await data_preferences.getPreferences({}, { name: NAME }); - } catch(err) { - done(); - expect('401').assertEqual(err.code); - } - }) - - /** - * @tc.name getPreferencesSync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_getPreferences_008 - * @tc.desc getPreferencesSync interface test - */ - it('testGetPreferencesHelper008', 0, async function (done) { - try { - let myContext = { - stageMode: true, - } - await data_preferences.getPreferences(myContext, { name: NAME }); - } catch(err) { - done(); - expect('15500000').assertEqual(err.code); - } - }) - - /** - * @tc.name getPreferencesSync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_getPreferences_009 - * @tc.desc getPreferencesSync interface test - */ - it('testGetPreferencesHelper009', 0, async function (done) { - try { - let myContext = { - stageMode: false, - } - mPreferences = await data_preferences.getPreferences(myContext, { name: NAME }); done(); expect(mPreferences != null).assertTrue(); } catch(err) { diff --git a/preferences/test/native/unittest/preferences_test.cpp b/preferences/test/native/unittest/preferences_test.cpp index 7fcabe300cc794c9b0f06f50e9b64a94c8eed452..a0982a18adf3e9987204a3ed86596b3aaf189f53 100644 --- a/preferences/test/native/unittest/preferences_test.cpp +++ b/preferences/test/native/unittest/preferences_test.cpp @@ -18,7 +18,10 @@ #include #include +#include #include +#include +#include #include #include "log_print.h" @@ -31,6 +34,16 @@ using namespace testing::ext; using namespace OHOS::NativePreferences; namespace { +const std::string LONG_KEY = std::string(Preferences::MAX_KEY_LENGTH, std::toupper('a')); +const std::string KEY_TEST_INT_ELEMENT = "key_test_int"; +const std::string KEY_TEST_LONG_ELEMENT = "key_test_long"; +const std::string KEY_TEST_FLOAT_ELEMENT = "key_test_float"; +const std::string KEY_TEST_DOUBLE_ELEMENT = "key_test_double"; +const std::string KEY_TEST_BOOL_ELEMENT = "key_test_bool"; +const std::string KEY_TEST_STRING_ELEMENT = "key_test_string"; +const std::string KEY_TEST_STRING_ARRAY_ELEMENT = "key_test_string_array"; +const std::string KEY_TEST_BOOL_ARRAY_ELEMENT = "key_test_bool_array"; +const std::string KEY_TEST_DOUBLE_ARRAY_ELEMENT = "key_test_double_array"; class PreferencesTest : public testing::Test { public: static void SetUpTestCase(void); @@ -39,29 +52,10 @@ public: void TearDown(); static std::shared_ptr pref; - - static const std::string LONG_KEY; - - static const std::string KEY_TEST_INT_ELEMENT; - static const std::string KEY_TEST_LONG_ELEMENT; - static const std::string KEY_TEST_FLOAT_ELEMENT; - static const std::string KEY_TEST_DOUBLE_ELEMENT; - static const std::string KEY_TEST_BOOL_ELEMENT; - static const std::string KEY_TEST_STRING_ELEMENT; }; std::shared_ptr PreferencesTest::pref = nullptr; -const std::string PreferencesTest::LONG_KEY = std::string(Preferences::MAX_KEY_LENGTH, std::toupper('a')); -; - -const std::string PreferencesTest::KEY_TEST_INT_ELEMENT = "key_test_int"; -const std::string PreferencesTest::KEY_TEST_LONG_ELEMENT = "key_test_long"; -const std::string PreferencesTest::KEY_TEST_FLOAT_ELEMENT = "key_test_float"; -const std::string PreferencesTest::KEY_TEST_DOUBLE_ELEMENT = "key_test_double"; -const std::string PreferencesTest::KEY_TEST_BOOL_ELEMENT = "key_test_bool"; -const std::string PreferencesTest::KEY_TEST_STRING_ELEMENT = "key_test_string"; - void PreferencesTest::SetUpTestCase(void) { int errCode = E_OK; @@ -112,9 +106,40 @@ void PreferencesObserverCounter::OnChange(const std::string &key) } } -const std::vector PreferencesObserverCounter::NOTIFY_KEYS_VECTOR = { PreferencesTest::KEY_TEST_INT_ELEMENT, - PreferencesTest::KEY_TEST_LONG_ELEMENT, PreferencesTest::KEY_TEST_FLOAT_ELEMENT, - PreferencesTest::KEY_TEST_BOOL_ELEMENT, PreferencesTest::KEY_TEST_STRING_ELEMENT }; +const std::vector PreferencesObserverCounter::NOTIFY_KEYS_VECTOR = { KEY_TEST_INT_ELEMENT, + KEY_TEST_LONG_ELEMENT, KEY_TEST_FLOAT_ELEMENT, KEY_TEST_BOOL_ELEMENT, KEY_TEST_STRING_ELEMENT }; + +class PreferencesObserverCrossProcess : public PreferencesObserver { +public: + virtual ~PreferencesObserverCrossProcess(); + void OnChange(const std::string &key) override; + void Wait(); + + std::mutex mut; + std::condition_variable cond; + std::string notifyKey; + bool result; +}; + +PreferencesObserverCrossProcess::~PreferencesObserverCrossProcess() +{ +} + +void PreferencesObserverCrossProcess::Wait() +{ + std::unique_lock lock(mut); + if (!result) { + cond.wait(lock, [this] { return result; }); + } +} + +void PreferencesObserverCrossProcess::OnChange(const std::string &key) +{ + std::unique_lock lock(mut); + notifyKey = key; + result = true; + cond.notify_all(); +} /** * @tc.name: NativePreferencesTest_001 @@ -125,13 +150,13 @@ const std::vector PreferencesObserverCounter::NOTIFY_KEYS_VECTOR = */ HWTEST_F(PreferencesTest, NativePreferencesTest_001, TestSize.Level1) { - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 2); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); + pref->PutInt(KEY_TEST_INT_ELEMENT, 2); + pref->PutString(KEY_TEST_STRING_ELEMENT, "test"); pref->FlushSync(); - int ret1 = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 6); + int ret1 = pref->GetInt(KEY_TEST_INT_ELEMENT, 6); EXPECT_EQ(ret1, 2); - std::string ret2 = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test1"); + std::string ret2 = pref->GetString(KEY_TEST_STRING_ELEMENT, "test1"); EXPECT_EQ(ret2, "test"); } @@ -150,7 +175,7 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_002, TestSize.Level1) ret = pref->HasKey(std::string()); EXPECT_EQ(ret, false); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); + pref->PutString(KEY_TEST_STRING_ELEMENT, "test"); ret = pref->HasKey(KEY_TEST_STRING_ELEMENT); EXPECT_EQ(ret, true); @@ -168,13 +193,13 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_002, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_003, TestSize.Level1) { - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test1"); + pref->PutString(KEY_TEST_STRING_ELEMENT, "test1"); - std::string ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "defaultvalue"); + std::string ret = pref->GetString(KEY_TEST_STRING_ELEMENT, "defaultvalue"); EXPECT_EQ(ret, "test1"); pref->Flush(); - ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "defaultvalue"); + ret = pref->GetString(KEY_TEST_STRING_ELEMENT, "defaultvalue"); EXPECT_EQ(ret, "test1"); } @@ -187,20 +212,20 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_003, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_004, TestSize.Level1) { - bool ret = pref->GetBool(PreferencesTest::LONG_KEY + 'x', true); + bool ret = pref->GetBool(LONG_KEY + 'x', true); EXPECT_EQ(ret, true); ret = pref->GetBool("", true); EXPECT_EQ(ret, true); - pref->PutBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, false); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "false"); + pref->PutBool(KEY_TEST_BOOL_ELEMENT, false); + pref->PutString(KEY_TEST_STRING_ELEMENT, "false"); pref->Flush(); - ret = pref->GetBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, true); + ret = pref->GetBool(KEY_TEST_BOOL_ELEMENT, true); EXPECT_EQ(ret, false); - ret = pref->GetBool(PreferencesTest::KEY_TEST_STRING_ELEMENT, true); + ret = pref->GetBool(KEY_TEST_STRING_ELEMENT, true); EXPECT_EQ(ret, true); } @@ -213,20 +238,20 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_004, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_005, TestSize.Level1) { - float ret = pref->GetFloat(PreferencesTest::LONG_KEY + 'x', 3.0f); + float ret = pref->GetFloat(LONG_KEY + 'x', 3.0f); EXPECT_EQ(ret, 3.0f); ret = pref->GetFloat("", 3.0f); EXPECT_EQ(ret, 3.0f); - pref->PutFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, 5.0f); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "5.0"); + pref->PutFloat(KEY_TEST_FLOAT_ELEMENT, 5.0f); + pref->PutString(KEY_TEST_STRING_ELEMENT, "5.0"); pref->Flush(); - ret = pref->GetFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, true); + ret = pref->GetFloat(KEY_TEST_FLOAT_ELEMENT, true); EXPECT_EQ(ret, 5.0f); - ret = pref->GetFloat(PreferencesTest::KEY_TEST_STRING_ELEMENT, 3.0f); + ret = pref->GetFloat(KEY_TEST_STRING_ELEMENT, 3.0f); EXPECT_EQ(ret, 3.0f); } @@ -239,20 +264,20 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_005, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_006, TestSize.Level1) { - int ret = pref->GetInt(PreferencesTest::LONG_KEY + 'x', 35); + int ret = pref->GetInt(LONG_KEY + 'x', 35); EXPECT_EQ(ret, 35); ret = pref->GetInt("", 35); EXPECT_EQ(ret, 35); - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 5); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "5"); + pref->PutInt(KEY_TEST_INT_ELEMENT, 5); + pref->PutString(KEY_TEST_STRING_ELEMENT, "5"); pref->Flush(); - ret = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 3); + ret = pref->GetInt(KEY_TEST_INT_ELEMENT, 3); EXPECT_EQ(ret, 5); - ret = pref->GetInt(PreferencesTest::KEY_TEST_STRING_ELEMENT, 3); + ret = pref->GetInt(KEY_TEST_STRING_ELEMENT, 3); EXPECT_EQ(ret, 3); } @@ -265,20 +290,20 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_006, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_007, TestSize.Level1) { - int64_t ret = pref->GetLong(PreferencesTest::LONG_KEY + 'x', 35L); + int64_t ret = pref->GetLong(LONG_KEY + 'x', 35L); EXPECT_EQ(ret, 35L); ret = pref->GetLong("", 35L); EXPECT_EQ(ret, 35L); - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 5); - pref->PutLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 5L); + pref->PutInt(KEY_TEST_INT_ELEMENT, 5); + pref->PutLong(KEY_TEST_LONG_ELEMENT, 5L); pref->Flush(); - ret = pref->GetLong(PreferencesTest::KEY_TEST_INT_ELEMENT, 3L); + ret = pref->GetLong(KEY_TEST_INT_ELEMENT, 3L); EXPECT_EQ(ret, 3L); - ret = pref->GetLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 3L); + ret = pref->GetLong(KEY_TEST_LONG_ELEMENT, 3L); EXPECT_EQ(ret, 5L); } @@ -291,20 +316,20 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_007, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_008, TestSize.Level1) { - std::string ret = pref->GetString(PreferencesTest::LONG_KEY + 'x', "test"); + std::string ret = pref->GetString(LONG_KEY + 'x', "test"); EXPECT_EQ(ret, "test"); ret = pref->GetString("", "test"); EXPECT_EQ(ret, "test"); - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 5); - pref->PutString(PreferencesTest::KEY_TEST_LONG_ELEMENT, "test"); + pref->PutInt(KEY_TEST_INT_ELEMENT, 5); + pref->PutString(KEY_TEST_LONG_ELEMENT, "test"); pref->Flush(); - ret = pref->GetString(PreferencesTest::KEY_TEST_INT_ELEMENT, "defaultvalue"); + ret = pref->GetString(KEY_TEST_INT_ELEMENT, "defaultvalue"); EXPECT_EQ(ret, "defaultvalue"); - ret = pref->GetString(PreferencesTest::KEY_TEST_LONG_ELEMENT, "defaultvalue"); + ret = pref->GetString(KEY_TEST_LONG_ELEMENT, "defaultvalue"); EXPECT_EQ(ret, "test"); } @@ -317,19 +342,19 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_008, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_009, TestSize.Level1) { - int ret0 = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, -1); + int ret0 = pref->GetInt(KEY_TEST_INT_ELEMENT, -1); EXPECT_EQ(ret0, -1); - float ret1 = pref->GetFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, 1.0f); + float ret1 = pref->GetFloat(KEY_TEST_FLOAT_ELEMENT, 1.0f); EXPECT_EQ(ret1, 1.0f); - int64_t ret2 = pref->GetLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 10000L); + int64_t ret2 = pref->GetLong(KEY_TEST_LONG_ELEMENT, 10000L); EXPECT_EQ(ret2, 10000L); - bool ret3 = pref->GetBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, true); + bool ret3 = pref->GetBool(KEY_TEST_BOOL_ELEMENT, true); EXPECT_EQ(ret3, true); - std::string ret4 = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); + std::string ret4 = pref->GetString(KEY_TEST_STRING_ELEMENT, "test"); EXPECT_EQ(ret4, "test"); } @@ -342,22 +367,22 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_009, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_010, TestSize.Level1) { - pref->PutBool(PreferencesTest::LONG_KEY + 'x', true); + pref->PutBool(LONG_KEY + 'x', true); pref->PutBool("", true); pref->Flush(); - bool ret = pref->GetBool(PreferencesTest::LONG_KEY + 'x', false); + bool ret = pref->GetBool(LONG_KEY + 'x', false); EXPECT_EQ(ret, false); ret = pref->GetBool("", false); EXPECT_EQ(ret, false); - pref->PutBool(PreferencesTest::LONG_KEY, true); - pref->PutBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, true); + pref->PutBool(LONG_KEY, true); + pref->PutBool(KEY_TEST_BOOL_ELEMENT, true); pref->Flush(); - ret = pref->GetBool(PreferencesTest::LONG_KEY, false); + ret = pref->GetBool(LONG_KEY, false); EXPECT_EQ(ret, true); - ret = pref->GetBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, false); + ret = pref->GetBool(KEY_TEST_BOOL_ELEMENT, false); EXPECT_EQ(ret, true); } @@ -370,22 +395,22 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_010, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_011, TestSize.Level1) { - pref->PutFloat(PreferencesTest::LONG_KEY + 'x', 3.0f); + pref->PutFloat(LONG_KEY + 'x', 3.0f); pref->PutFloat("", 3.0f); pref->Flush(); - float ret = pref->GetFloat(PreferencesTest::LONG_KEY + 'x', 1.0f); + float ret = pref->GetFloat(LONG_KEY + 'x', 1.0f); EXPECT_EQ(ret, 1.0f); ret = pref->GetFloat("", 1.0f); EXPECT_EQ(ret, 1.0f); - pref->PutFloat(PreferencesTest::LONG_KEY, 3.0f); - pref->PutFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, 3.0f); + pref->PutFloat(LONG_KEY, 3.0f); + pref->PutFloat(KEY_TEST_FLOAT_ELEMENT, 3.0f); pref->Flush(); - ret = pref->GetFloat(PreferencesTest::LONG_KEY, 1.0f); + ret = pref->GetFloat(LONG_KEY, 1.0f); EXPECT_EQ(ret, 3.0f); - ret = pref->GetFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, 1.0f); + ret = pref->GetFloat(KEY_TEST_FLOAT_ELEMENT, 1.0f); EXPECT_EQ(ret, 3.0f); } @@ -398,22 +423,22 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_011, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_012, TestSize.Level1) { - pref->PutInt(PreferencesTest::LONG_KEY + 'x', 3); + pref->PutInt(LONG_KEY + 'x', 3); pref->PutInt("", 3); pref->Flush(); - int ret = pref->GetInt(PreferencesTest::LONG_KEY + 'x', 1); + int ret = pref->GetInt(LONG_KEY + 'x', 1); EXPECT_EQ(ret, 1); ret = pref->GetInt("", 1); EXPECT_EQ(ret, 1); - pref->PutInt(PreferencesTest::LONG_KEY, 3); - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 3); + pref->PutInt(LONG_KEY, 3); + pref->PutInt(KEY_TEST_INT_ELEMENT, 3); pref->Flush(); - ret = pref->GetInt(PreferencesTest::LONG_KEY, 1); + ret = pref->GetInt(LONG_KEY, 1); EXPECT_EQ(ret, 3); - ret = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 1); + ret = pref->GetInt(KEY_TEST_INT_ELEMENT, 1); EXPECT_EQ(ret, 3); } @@ -426,22 +451,22 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_012, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_013, TestSize.Level1) { - pref->PutLong(PreferencesTest::LONG_KEY + 'x', 3L); + pref->PutLong(LONG_KEY + 'x', 3L); pref->PutLong("", 3L); pref->Flush(); - int64_t ret = pref->GetLong(PreferencesTest::LONG_KEY + 'x', 1L); + int64_t ret = pref->GetLong(LONG_KEY + 'x', 1L); EXPECT_EQ(ret, 1L); ret = pref->GetLong("", 1L); EXPECT_EQ(ret, 1L); - pref->PutLong(PreferencesTest::LONG_KEY, 3L); - pref->PutLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 3L); + pref->PutLong(LONG_KEY, 3L); + pref->PutLong(KEY_TEST_LONG_ELEMENT, 3L); pref->Flush(); - ret = pref->GetLong(PreferencesTest::LONG_KEY, 1L); + ret = pref->GetLong(LONG_KEY, 1L); EXPECT_EQ(ret, 3L); - ret = pref->GetLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 1L); + ret = pref->GetLong(KEY_TEST_LONG_ELEMENT, 1L); EXPECT_EQ(ret, 3L); } @@ -454,22 +479,22 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_013, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_014, TestSize.Level1) { - pref->PutString(PreferencesTest::LONG_KEY + 'x', "test"); + pref->PutString(LONG_KEY + 'x', "test"); pref->PutString("", "test"); pref->Flush(); - std::string ret = pref->GetString(PreferencesTest::LONG_KEY + 'x', "defaultValue"); + std::string ret = pref->GetString(LONG_KEY + 'x', "defaultValue"); EXPECT_EQ(ret, "defaultValue"); ret = pref->GetString("", "defaultValue"); EXPECT_EQ(ret, "defaultValue"); - pref->PutString(PreferencesTest::LONG_KEY, "test"); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); + pref->PutString(LONG_KEY, "test"); + pref->PutString(KEY_TEST_STRING_ELEMENT, "test"); pref->Flush(); - ret = pref->GetString(PreferencesTest::LONG_KEY, "defaultValue"); + ret = pref->GetString(LONG_KEY, "defaultValue"); EXPECT_EQ(ret, "test"); - ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "defaultValue"); + ret = pref->GetString(KEY_TEST_STRING_ELEMENT, "defaultValue"); EXPECT_EQ(ret, "test"); } @@ -506,13 +531,13 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_016, TestSize.Level1) std::shared_ptr counter = std::make_shared(); pref->RegisterObserver(counter); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); + pref->PutString(KEY_TEST_STRING_ELEMENT, "test"); pref->Flush(); EXPECT_EQ(static_cast(counter.get())->notifyTimes, 1); /* same value */ - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 2); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); + pref->PutInt(KEY_TEST_INT_ELEMENT, 2); + pref->PutString(KEY_TEST_STRING_ELEMENT, "test"); pref->Flush(); EXPECT_EQ(static_cast(counter.get())->notifyTimes, 2); @@ -531,15 +556,15 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_017, TestSize.Level1) std::shared_ptr counter = std::make_shared(); pref->RegisterObserver(counter); - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 2); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); + pref->PutInt(KEY_TEST_INT_ELEMENT, 2); + pref->PutString(KEY_TEST_STRING_ELEMENT, "test"); pref->Flush(); EXPECT_EQ(static_cast(counter.get())->notifyTimes, 2); pref->UnRegisterObserver(counter); - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 6); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test1"); + pref->PutInt(KEY_TEST_INT_ELEMENT, 6); + pref->PutString(KEY_TEST_STRING_ELEMENT, "test1"); pref->Flush(); EXPECT_EQ(static_cast(counter.get())->notifyTimes, 2); } @@ -553,20 +578,20 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_017, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_018, TestSize.Level1) { - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 3); + pref->PutString(KEY_TEST_STRING_ELEMENT, "test"); + pref->PutInt(KEY_TEST_INT_ELEMENT, 3); pref->Flush(); pref->Clear(); - std::string ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "defaultvalue"); + std::string ret = pref->GetString(KEY_TEST_STRING_ELEMENT, "defaultvalue"); EXPECT_EQ(ret, "defaultvalue"); - int ret1 = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 0); + int ret1 = pref->GetInt(KEY_TEST_INT_ELEMENT, 0); EXPECT_EQ(ret1, 0); pref->Flush(); - ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "defaultvalue"); + ret = pref->GetString(KEY_TEST_STRING_ELEMENT, "defaultvalue"); EXPECT_EQ(ret, "defaultvalue"); - ret1 = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 0); + ret1 = pref->GetInt(KEY_TEST_INT_ELEMENT, 0); EXPECT_EQ(ret1, 0); } @@ -579,20 +604,20 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_018, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_019, TestSize.Level1) { - double ret = pref->GetDouble(PreferencesTest::LONG_KEY + 'x', 35.99999); + double ret = pref->GetDouble(LONG_KEY + 'x', 35.99999); EXPECT_EQ(ret, 35.99999); ret = pref->GetDouble("", 35.99999); EXPECT_EQ(ret, 35.99999); - pref->PutDouble(PreferencesTest::KEY_TEST_DOUBLE_ELEMENT, (std::numeric_limits::max)()); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "5.99"); + pref->PutDouble(KEY_TEST_DOUBLE_ELEMENT, (std::numeric_limits::max)()); + pref->PutString(KEY_TEST_STRING_ELEMENT, "5.99"); pref->Flush(); - ret = pref->GetDouble(PreferencesTest::KEY_TEST_DOUBLE_ELEMENT, 3.99); + ret = pref->GetDouble(KEY_TEST_DOUBLE_ELEMENT, 3.99); EXPECT_EQ(ret, (std::numeric_limits::max)()); - ret = pref->GetDouble(PreferencesTest::KEY_TEST_STRING_ELEMENT, 3.99); + ret = pref->GetDouble(KEY_TEST_STRING_ELEMENT, 3.99); EXPECT_EQ(ret, 3.99); } @@ -607,13 +632,14 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_020, TestSize.Level1) { int errCode; std::shared_ptr pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); - pref1->PutDouble(PreferencesTest::KEY_TEST_DOUBLE_ELEMENT, (std::numeric_limits::max)()); + pref1->PutDouble(KEY_TEST_DOUBLE_ELEMENT, (std::numeric_limits::max)()); pref1->Flush(); PreferencesHelper::RemovePreferencesFromCache("/data/test/test1"); pref1.reset(); pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); - double ret = pref1->GetDouble(PreferencesTest::KEY_TEST_DOUBLE_ELEMENT); + double ret = pref1->GetDouble(KEY_TEST_DOUBLE_ELEMENT); EXPECT_EQ(ret, (std::numeric_limits::max)()); + PreferencesHelper::DeletePreferences("/data/test/test1"); } /** @@ -627,18 +653,19 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_021, TestSize.Level1) { int errCode; auto pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); - pref1->PutString(PreferencesTest::LONG_KEY, "test"); - pref1->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test1 test2"); + pref1->PutString(LONG_KEY, "test"); + pref1->PutString(KEY_TEST_STRING_ELEMENT, "test1 test2"); pref1->Flush(); PreferencesHelper::RemovePreferencesFromCache("/data/test/test1"); pref1.reset(); pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); - std::string ret = pref1->GetString(PreferencesTest::LONG_KEY); + std::string ret = pref1->GetString(LONG_KEY); EXPECT_EQ(ret, "test"); - ret = pref1->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT); + ret = pref1->GetString(KEY_TEST_STRING_ELEMENT); EXPECT_EQ(ret, "test1 test2"); + PreferencesHelper::DeletePreferences("/data/test/test1"); } /** @@ -650,14 +677,21 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_021, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_022, TestSize.Level1) { - pref->PutLong(PreferencesTest::LONG_KEY, 3L); - pref->PutLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 3L); - pref->Flush(); + int errCode; + auto pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + pref1->PutLong(LONG_KEY, 3L); + pref1->PutLong(KEY_TEST_LONG_ELEMENT, 3L); + pref1->Flush(); + + PreferencesHelper::RemovePreferencesFromCache("/data/test/test1"); + pref1.reset(); + pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); - int64_t ret = pref->GetLong(PreferencesTest::LONG_KEY); + int64_t ret = pref1->GetLong(LONG_KEY); EXPECT_EQ(ret, 3L); - ret = pref->GetLong(PreferencesTest::KEY_TEST_LONG_ELEMENT); + ret = pref1->GetLong(KEY_TEST_LONG_ELEMENT); EXPECT_EQ(ret, 3L); + PreferencesHelper::DeletePreferences("/data/test/test1"); } /** @@ -669,14 +703,21 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_022, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_023, TestSize.Level1) { - pref->PutInt(PreferencesTest::LONG_KEY, 3); - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 3); - pref->Flush(); + int errCode; + auto pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + pref1->PutInt(LONG_KEY, 3); + pref1->PutInt(KEY_TEST_INT_ELEMENT, 3); + pref1->Flush(); + + PreferencesHelper::RemovePreferencesFromCache("/data/test/test1"); + pref1.reset(); + pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); - int32_t ret = pref->GetInt(PreferencesTest::LONG_KEY); + int32_t ret = pref1->GetInt(LONG_KEY); EXPECT_EQ(ret, 3); - ret = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT); + ret = pref1->GetInt(KEY_TEST_INT_ELEMENT); EXPECT_EQ(ret, 3); + PreferencesHelper::DeletePreferences("/data/test/test1"); } /** @@ -688,14 +729,21 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_023, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_024, TestSize.Level1) { - pref->PutFloat(PreferencesTest::LONG_KEY, 3.0f); - pref->PutFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, 3.0f); - pref->Flush(); + int errCode; + auto pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + pref1->PutFloat(LONG_KEY, 3.0f); + pref1->PutFloat(KEY_TEST_FLOAT_ELEMENT, 3.0f); + pref1->Flush(); + + PreferencesHelper::RemovePreferencesFromCache("/data/test/test1"); + pref1.reset(); + pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); - float ret = pref->GetFloat(PreferencesTest::LONG_KEY); + float ret = pref1->GetFloat(LONG_KEY); EXPECT_EQ(ret, 3.0f); - ret = pref->GetFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT); + ret = pref1->GetFloat(KEY_TEST_FLOAT_ELEMENT); EXPECT_EQ(ret, 3.0f); + PreferencesHelper::DeletePreferences("/data/test/test1"); } /** @@ -707,14 +755,115 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_024, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_025, TestSize.Level1) { - pref->PutBool(PreferencesTest::LONG_KEY, true); - pref->PutBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, true); - pref->Flush(); + int errCode; + auto pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + pref1->PutBool(LONG_KEY, true); + pref1->PutBool(KEY_TEST_BOOL_ELEMENT, true); + pref1->Flush(); - bool ret = pref->GetBool(PreferencesTest::LONG_KEY); + PreferencesHelper::RemovePreferencesFromCache("/data/test/test1"); + pref1.reset(); + pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + + bool ret = pref1->GetBool(LONG_KEY); EXPECT_EQ(ret, true); - ret = pref->GetBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT); + ret = pref1->GetBool(KEY_TEST_BOOL_ELEMENT); EXPECT_EQ(ret, true); + PreferencesHelper::DeletePreferences("/data/test/test1"); +} + +/** + * @tc.name: NativePreferencesTest_026 + * @tc.desc: normal testcase of GetArray + * @tc.type: FUNC + * @tc.require: Na + * @tc.author: changjiaxing + */ +HWTEST_F(PreferencesTest, NativePreferencesTest_026, TestSize.Level1) +{ + int errCode; + auto pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + std::vector stringArray = { "str1", "str2" }; + std::vector boolArray = { false, true }; + std::vector doubleArray = { 0.1, 0.2 }; + pref1->Put(KEY_TEST_STRING_ARRAY_ELEMENT, stringArray); + pref1->Put(KEY_TEST_BOOL_ARRAY_ELEMENT, boolArray); + pref1->Put(KEY_TEST_DOUBLE_ARRAY_ELEMENT, doubleArray); + pref1->FlushSync(); + + PreferencesHelper::RemovePreferencesFromCache("/data/test/test1"); + pref1.reset(); + pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + + PreferencesValue defValue(static_cast(0)); + PreferencesValue stringArrayRes = pref1->Get(KEY_TEST_STRING_ARRAY_ELEMENT, defValue); + EXPECT_EQ(stringArrayRes.IsStringArray(), true); + EXPECT_EQ(static_cast>(stringArrayRes), stringArray); + + PreferencesValue boolArrayRes = pref1->Get(KEY_TEST_BOOL_ARRAY_ELEMENT, defValue); + EXPECT_EQ(boolArrayRes.IsBoolArray(), true); + EXPECT_EQ(static_cast>(boolArrayRes), boolArray); + + PreferencesValue doubleArrayRes = pref1->Get(KEY_TEST_DOUBLE_ARRAY_ELEMENT, defValue); + EXPECT_EQ(doubleArrayRes.IsDoubleArray(), true); + EXPECT_EQ(static_cast>(doubleArrayRes), doubleArray); + PreferencesHelper::DeletePreferences("/data/test/test1"); +} + +/** + * @tc.name: NativePreferencesTest_027 + * @tc.desc: normal testcase of GetAll + * @tc.type: FUNC + * @tc.require: Na + * @tc.author: changjiaxing + */ +HWTEST_F(PreferencesTest, NativePreferencesTest_027, TestSize.Level1) +{ + int errCode; + auto pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + + std::map map = { { KEY_TEST_INT_ELEMENT, 1 }, { KEY_TEST_FLOAT_ELEMENT, 0.1 }, + { KEY_TEST_BOOL_ELEMENT, false }, { KEY_TEST_STRING_ELEMENT, "test" } }; + + for (auto i : map) { + pref1->Put(i.first, i.second); + } + + auto ret = pref1->GetAll(); + + EXPECT_EQ(map.size(), ret.size()); + auto iter1 = map.begin(); + auto iter2 = ret.begin(); + for (;iter1 != map.end(); ++iter1, ++iter2) { + EXPECT_EQ(iter1->first, iter2->first); + bool isequa = false; + if (iter1->second == iter2->second) { + isequa = true; + } + EXPECT_TRUE(isequa); + } + PreferencesHelper::DeletePreferences("/data/test/test1"); +} + +/** + * @tc.name: NativePreferencesTest_028 + * @tc.desc: Cross process subscription testing + * @tc.type: FUNC + * @tc.require: Na + * @tc.author: changjiaxing + */ +HWTEST_F(PreferencesTest, NativePreferencesTest_028, TestSize.Level1) +{ + std::shared_ptr counter = std::make_shared(); + int ret = pref->RegisterObserver(counter, RegisterMode::MULTI_PRECESS_CHANGE); + EXPECT_EQ(ret, E_OK); + pref->PutString(KEY_TEST_STRING_ELEMENT, "test"); + pref->Flush(); + counter->Wait(); + EXPECT_EQ(counter->notifyKey, KEY_TEST_STRING_ELEMENT); + + ret = pref->UnRegisterObserver(counter, RegisterMode::MULTI_PRECESS_CHANGE); + EXPECT_EQ(ret, E_OK); } /** @@ -762,4 +911,4 @@ HWTEST_F(PreferencesTest, PreferencesValueTest_001, TestSize.Level1) std::vector retVectorString = PreferencesValue(valueVectorString); EXPECT_EQ(valueVectorString, retVectorString); } -} +} // namespace diff --git a/preferences/test/native/unittest/preferences_xml_utils_test.cpp b/preferences/test/native/unittest/preferences_xml_utils_test.cpp index af972ee6134f5685c98603d7cd7ff2a936b0a320..fa0ef6d7e8dc63b35d0882d9455985ded8bc24e9 100644 --- a/preferences/test/native/unittest/preferences_xml_utils_test.cpp +++ b/preferences/test/native/unittest/preferences_xml_utils_test.cpp @@ -17,11 +17,13 @@ #include +#include #include #include "preferences.h" #include "preferences_errno.h" #include "preferences_helper.h" +#include "include/preferences_impl.h" using namespace testing::ext; using namespace OHOS::NativePreferences; @@ -339,4 +341,56 @@ HWTEST_F(PreferencesXmlUtilsTest, ArrayNodeElementTest_006, TestSize.Level1) int ret = PreferencesHelper::DeletePreferences(file); EXPECT_EQ(ret, E_OK); } + +/** +* @tc.name: RenameToBrokenFileTest_001 +* @tc.desc: RenameToBrokenFile testcase of PreferencesXmlUtils +* @tc.type: FUNC +*/ +HWTEST_F(PreferencesXmlUtilsTest, RenameToBrokenFileTest_001, TestSize.Level1) +{ + std::string fileName = "/data/test/test01"; + // construct an unreadable file + std::ofstream oss(fileName); + oss << "corrupted"; + + std::vector settings; + Element elem; + elem.key_ = "intKey"; + elem.tag_ = "int"; + elem.value_ = "2"; + + settings.push_back(elem); + PreferencesXmlUtils::WriteSettingXml(PreferencesImpl::MakeFilePath(fileName, STR_BACKUP), settings); + + int errCode = E_OK; + std::shared_ptr pref = PreferencesHelper::GetPreferences(fileName, errCode); + EXPECT_EQ(errCode, E_OK); + + int value = pref->Get("intKey", 0); + EXPECT_EQ(value, 2); + + int ret = PreferencesHelper::DeletePreferences(fileName); + EXPECT_EQ(ret, E_OK); +} + +/** +* @tc.name: ReadSettingXml_001 +* @tc.desc: ReadSettingXml testcase of PreferencesXmlUtils, reading a corrupt file +* @tc.type: FUNC +*/ +HWTEST_F(PreferencesXmlUtilsTest, ReadSettingXml_001, TestSize.Level1) +{ + std::string fileName = "/data/test/test01"; + + std::ofstream oss(fileName); + oss << "corrupted"; + + int errCode = E_OK; + std::shared_ptr pref = PreferencesHelper::GetPreferences(fileName, errCode); + EXPECT_EQ(errCode, E_OK); + + int ret = PreferencesHelper::DeletePreferences(fileName); + EXPECT_EQ(ret, E_OK); +} } diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp index 160013779c4629e8def99cd7daab5b52691a6f60..5417b47529934a9c84a83114a3e516d2748ef8c8 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp @@ -165,7 +165,7 @@ napi_value RdbStoreProxy::InnerInitialize(napi_env env, napi_callback_info info, napi_status status = napi_wrap(env, self, proxy, finalize, nullptr, nullptr); if (status != napi_ok) { LOG_ERROR("RdbStoreProxy::Initialize napi_wrap failed! code:%{public}d!", status); - finalize(env, proxy, nullptr); + delete proxy; return nullptr; } return self; @@ -758,7 +758,7 @@ int ParseBindArgs(const napi_env env, const napi_value arg, std::shared_ptr; using OutputAction = std::function; using ExecuteAction = std::function; +extern bool async; +extern bool sync; +#define ASYNC &async +#define SYNC &sync class Context { public: @@ -39,6 +43,7 @@ public: virtual ~Context(); napi_env env_ = nullptr; + bool isAsync_ = true; void *boundObj = nullptr; std::shared_ptr error; @@ -50,6 +55,7 @@ public: int execCode_ = OK; OutputAction output_ = nullptr; ExecuteAction exec_ = nullptr; + napi_value result_ = nullptr; std::shared_ptr keep_; }; @@ -60,8 +66,12 @@ public: private: enum { ARG_ERROR, ARG_DATA, ARG_BUTT }; static void OnExecute(napi_env env, void *data); + static void OnComplete(napi_env env, void *data); + static void OnReturn(napi_env env, napi_status status, void *data); static void OnComplete(napi_env env, napi_status status, void *data); static void SetBusinessError(napi_env env, std::shared_ptr error, napi_value *businessError); + static napi_value Async(napi_env env, std::shared_ptr context); + static napi_value Sync(napi_env env, std::shared_ptr context); }; } // namespace RelationalStoreJsKit } // namespace OHOS diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_error.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_error.h index 1f1a6b70e9d5544d2e47b121862136a9f7a4ccd0..15472626716c56c08b2a450f6b8282518f7f8e7e 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_error.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_error.h @@ -16,7 +16,6 @@ #define RDB_JS_NAPI_ERROR_H #include -#include #include "logger.h" #include "rdb_errno.h" diff --git a/relational_store/frameworks/js/napi/relationalstore/src/napi_async_call.cpp b/relational_store/frameworks/js/napi/relationalstore/src/napi_async_call.cpp index 2ceff6f6319a4cab7cf807f3b6a0f841bbe03740..2b3984f9eab2db8292378f8c126e7df17858d467 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/napi_async_call.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/napi_async_call.cpp @@ -17,12 +17,15 @@ #include "logger.h" #include "napi_rdb_trace.h" +#include "rdb_errno.h" using namespace OHOS::Rdb; using namespace OHOS::AppDataMgrJsKit; namespace OHOS { namespace RelationalStoreJsKit { +bool async = true; // do not reset the value, used in DECLARE_NAPI_FUNCTION_WITH_DATA only +bool sync = !async; // do not reset the value, used in DECLARE_NAPI_FUNCTION_WITH_DATA only void Context::SetAction( napi_env env, napi_callback_info info, InputAction input, ExecuteAction exec, OutputAction output) { @@ -30,7 +33,8 @@ void Context::SetAction( size_t argc = MAX_INPUT_COUNT; napi_value self = nullptr; napi_value argv[MAX_INPUT_COUNT] = { nullptr }; - NAPI_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); + void *data = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &self, &data)); napi_valuetype valueType = napi_undefined; napi_typeof(env, argv[argc - 1], &valueType); @@ -39,6 +43,10 @@ void Context::SetAction( NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, argv[argc - 1], 1, &callback_)); argc = argc - 1; } + if (data) { + isAsync_ = *reinterpret_cast(data); + } + // int -->input_(env, argc, argv, self) input(env, argc, argv, self); @@ -104,6 +112,11 @@ void AsyncCall::SetBusinessError(napi_env env, std::shared_ptr error, nap } napi_value AsyncCall::Call(napi_env env, std::shared_ptr context) +{ + return context->isAsync_ ? Async(env, context) : Sync(env, context); +} + +napi_value AsyncCall::Async(napi_env env, std::shared_ptr context) { napi_value promise = nullptr; if (context->callback_ == nullptr) { @@ -122,6 +135,13 @@ napi_value AsyncCall::Call(napi_env env, std::shared_ptr context) return promise; } +napi_value AsyncCall::Sync(napi_env env, std::shared_ptr context) +{ + OnExecute(env, reinterpret_cast(context.get())); + OnComplete(env, reinterpret_cast(context.get())); + return context->result_; +} + void AsyncCall::OnExecute(napi_env env, void *data) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); @@ -132,25 +152,35 @@ void AsyncCall::OnExecute(napi_env env, void *data) context->exec_ = nullptr; } -void AsyncCall::OnComplete(napi_env env, napi_status status, void *data) +void AsyncCall::OnComplete(napi_env env, void *data) { - DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); Context *context = reinterpret_cast(data); if (context->execCode_ != NativeRdb::E_OK) { context->SetError(std::make_shared(context->execCode_)); } - napi_value output = nullptr; // if async execute status is not napi_ok then un-execute out function if ((context->error == nullptr) && context->output_) { - context->output_(env, output); + context->output_(env, context->result_); } context->output_ = nullptr; +} + +void AsyncCall::OnComplete(napi_env env, napi_status status, void *data) +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + OnComplete(env, data); + OnReturn(env, status, data); +} + +void AsyncCall::OnReturn(napi_env env, napi_status status, void *data) +{ + Context *context = reinterpret_cast(data); napi_value result[ARG_BUTT] = { 0 }; // if out function status is ok then async renturn output data, else return error. if (context->error == nullptr) { napi_get_undefined(env, &result[ARG_ERROR]); - if (output != nullptr) { - result[ARG_DATA] = output; + if (context->result_ != nullptr) { + result[ARG_DATA] = context->result_; } else { napi_get_undefined(env, &result[ARG_DATA]); } diff --git a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp index 0d137cc5be917fc9321f72e4f05be2f11f67568a..97c6a18abed27ec98f8d2589d739336996fc15c5 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp @@ -129,24 +129,30 @@ bool IsNapiTypeString(napi_env env, size_t argc, napi_value *argv, size_t arg) void RdbStoreProxy::Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { - DECLARE_NAPI_FUNCTION("delete", Delete), - DECLARE_NAPI_FUNCTION("update", Update), - DECLARE_NAPI_FUNCTION("insert", Insert), - DECLARE_NAPI_FUNCTION("batchInsert", BatchInsert), - DECLARE_NAPI_FUNCTION("querySql", QuerySql), - DECLARE_NAPI_FUNCTION("query", Query), -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) - DECLARE_NAPI_FUNCTION("remoteQuery", RemoteQuery), -#endif - DECLARE_NAPI_FUNCTION("executeSql", ExecuteSql), - DECLARE_NAPI_FUNCTION("replace", Replace), + DECLARE_NAPI_FUNCTION_WITH_DATA("delete", Delete, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("deleteSync", Delete, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("update", Update, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("updateSync", Update, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("insert", Insert, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("insertSync", Insert, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("batchInsert", BatchInsert, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("batchInsertSync", BatchInsert, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("querySql", QuerySql, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("querySqlSync", QuerySql, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("query", Query, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("querySync", Query, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("executeSql", ExecuteSql, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("executeSqlSync", ExecuteSql, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("replace", Replace, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("replaceSync", Replace, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("queryByStep", QueryByStep, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("queryByStepSync", QueryByStep, SYNC), DECLARE_NAPI_FUNCTION("backup", Backup), DECLARE_NAPI_FUNCTION("count", Count), DECLARE_NAPI_FUNCTION("addAttach", Attach), DECLARE_NAPI_FUNCTION("beginTransaction", BeginTransaction), DECLARE_NAPI_FUNCTION("rollBack", RollBack), DECLARE_NAPI_FUNCTION("commit", Commit), - DECLARE_NAPI_FUNCTION("queryByStep", QueryByStep), DECLARE_NAPI_FUNCTION("restore", Restore), DECLARE_NAPI_GETTER_SETTER("version", GetVersion, SetVersion), DECLARE_NAPI_GETTER("isInTransaction", IsInTransaction), @@ -155,6 +161,7 @@ void RdbStoreProxy::Init(napi_env env, napi_value exports) DECLARE_NAPI_GETTER("isReadOnly", IsReadOnly), DECLARE_NAPI_GETTER("isMemoryRdb", IsMemoryRdb), #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) + DECLARE_NAPI_FUNCTION("remoteQuery", RemoteQuery), DECLARE_NAPI_FUNCTION("setDistributedTables", SetDistributedTables), DECLARE_NAPI_FUNCTION("obtainDistributedTableName", ObtainDistributedTableName), DECLARE_NAPI_FUNCTION("sync", Sync), diff --git a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store_helper.cpp b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store_helper.cpp index 65ad7cab0a86c0d3aec8d062658dab2095d9ca4a..130b78157db7e667cac99b524a678e95af96c6bd 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store_helper.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store_helper.cpp @@ -260,8 +260,10 @@ napi_value InitRdbHelper(napi_env env, napi_value exports) { LOG_INFO("RelationalStoreJsKit::InitRdbHelper begin"); napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("getRdbStore", GetRdbStore), - DECLARE_NAPI_FUNCTION("deleteRdbStore", DeleteRdbStore), + DECLARE_NAPI_FUNCTION_WITH_DATA("getRdbStore", GetRdbStore, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("getRdbStoreSync", GetRdbStore, SYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("deleteRdbStore", DeleteRdbStore, ASYNC), + DECLARE_NAPI_FUNCTION_WITH_DATA("deleteRdbStoreSync", DeleteRdbStore, SYNC), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties)); LOG_INFO("RelationalStoreJsKit::InitRdbHelper end"); diff --git a/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp b/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp index b28a96f615972bb8aafaebb813a09e09d05bca2c..a1fb18aecfe9560d8534482e97bf18ebb76701c9 100644 --- a/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp +++ b/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp @@ -182,6 +182,7 @@ int SharedBlock::AllocRow() /* Fill in the row offset */ uint32_t *rowOffset = AllocRowOffset(); if (UNLIKELY(rowOffset == nullptr)) { + LOG_ERROR("SharedBlock::AllocRow() Failed in AllocRowOffset()."); return SHARED_BLOCK_NO_MEMORY; } @@ -206,7 +207,6 @@ int SharedBlock::FreeLastRow() if (mHeader->rowNums > 0) { mHeader->rowNums--; } - return SHARED_BLOCK_OK; } @@ -236,6 +236,8 @@ uint32_t *SharedBlock::AllocRowOffset() if (mHeader->groupOffset[groupPos] == 0) { mHeader->groupOffset[groupPos] = Alloc(sizeof(RowGroupHeader)); if (UNLIKELY(mHeader->groupOffset[groupPos] == 0)) { + LOG_ERROR("SharedBlock::AllocRowOffset() Failed to alloc group->nextGroupOffset " + "when while loop."); return nullptr; } } diff --git a/relational_store/frameworks/native/rdb/include/rdb_security_manager.h b/relational_store/frameworks/native/rdb/include/rdb_security_manager.h index 3f1c866bd71a1aa77b65fbc5f9e019a5186860f6..9b3c7c077fb3483895e8f67dfb1cd88d29a49b64 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_security_manager.h +++ b/relational_store/frameworks/native/rdb/include/rdb_security_manager.h @@ -78,6 +78,7 @@ public: static RdbSecurityManager &GetInstance(); void Init(const std::string &bundleName, const std::string &path); void UpdateKeyFile(); + bool CheckKeyDataFileExists(RdbSecurityManager::KeyFileType keyFile); private: RdbSecurityManager(); @@ -90,7 +91,6 @@ private: std::vector GenerateRootKeyAlias(); bool InitPath(const std::string &path); void ParsePath(const std::string &path); - bool CheckKeyDataFileExists(RdbSecurityManager::KeyFileType keyFile); std::vector GenerateRandomNum(int32_t len); bool SaveSecretKeyToFile(RdbSecurityManager::KeyFileType keyFile); bool SaveSecretKeyToDisk(const std::string &path, RdbSecretKeyData &keyData); diff --git a/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h b/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h index fff5d1bd13fbe1c77feac380db6e5ff3748e8c19..acc1ee9ec3d758c23732c1afa09c1377f950ae6f 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h +++ b/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h @@ -57,7 +57,7 @@ public: Observers ExportObservers(); - void ImportObservers(Observers & observers); + void ImportObservers(Observers &observers); int32_t GetSchema(const RdbSyncerParam ¶m) override; diff --git a/relational_store/frameworks/native/rdb/include/rdb_store_impl.h b/relational_store/frameworks/native/rdb/include/rdb_store_impl.h index 60ccb319a9880eeda54c7fac4caca660dea39fce..d77d726fd7967ff57c707da364199c1c75c25c39 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_store_impl.h +++ b/relational_store/frameworks/native/rdb/include/rdb_store_impl.h @@ -125,7 +125,6 @@ public: bool IsReadOnly() const override; bool IsMemoryRdb() const override; bool IsHoldingConnection() override; - int GiveConnectionTemporarily(int64_t milliseconds); #ifdef RDB_SUPPORT_ICU int ConfigLocale(const std::string localeStr); #endif @@ -168,8 +167,6 @@ public: private: int InnerOpen(); - int InnerInsert(int64_t &outRowId, const std::string &table, ValuesBucket values, - ConflictResolution conflictResolution); int CheckAttach(const std::string &sql); int BeginExecuteSql(const std::string &sql, SqliteConnection **connection); int FreeTransaction(SqliteConnection *connection, const std::string &sql); @@ -178,13 +175,13 @@ private: int GetDataBasePath(const std::string &databasePath, std::string &backupFilePath); int ExecuteSqlInner(const std::string &sql, const std::vector &bindArgs); int ExecuteGetLongInner(const std::string &sql, const std::vector &bindArgs); - void SetAssetStatusWhileInsert(ValueObject &val); + void SetAssetStatusWhileInsert(const ValueObject &val); void DoCloudSync(const std::string &table); int InnerBackup(const std::string databasePath, const std::vector destEncryptKey = std::vector()); std::map GetModifyTimeByRowId( const std::string &logTable, std::vector &keys); - std::string GetSqlArgs(size_t size); + inline std::string GetSqlArgs(size_t size); Uri GetUri(const std::string &event); int SubscribeLocal(const SubscribeOption& option, RdbStoreObserver *observer); int SubscribeLocalShared(const SubscribeOption& option, RdbStoreObserver *observer); @@ -210,7 +207,7 @@ private: std::shared_ptr pool_; mutable std::shared_mutex rwMutex_; - static inline constexpr uint32_t INTERVAL = 500; + static inline constexpr uint32_t INTERVAL = 200; static constexpr const char *ROW_ID = "ROWID"; std::set cloudTables_; diff --git a/relational_store/frameworks/native/rdb/include/security_policy.h b/relational_store/frameworks/native/rdb/include/security_policy.h index df1788c07254007017a803675e5022c02cab9815..0e032057e8ebe7db5186f4405c6f8b7ceb8bf241 100644 --- a/relational_store/frameworks/native/rdb/include/security_policy.h +++ b/relational_store/frameworks/native/rdb/include/security_policy.h @@ -25,9 +25,8 @@ public: static int SetSecurityLabel(const RdbStoreConfig &config); private: - static std::string GetSecurityLevelValue(SecurityLevel securityLevel); - static int SetFileSecurityLevel(const std::string &filePath, const std::string &securityLevel); - static std::string GetFileSecurityLevel(const std::string &filePath); + inline static std::string GetSecurityLevelValue(SecurityLevel securityLevel); + inline static std::string GetFileSecurityLevel(const std::string &filePath); }; } // namespace NativeRdb } // namespace OHOS diff --git a/relational_store/frameworks/native/rdb/include/sqlite_connection.h b/relational_store/frameworks/native/rdb/include/sqlite_connection.h index aedbad459877baecb422cef2cb675a4ea5e7947e..7419a52819358d1112cc7c0a7296c06ba4c596de 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_connection.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_connection.h @@ -35,8 +35,6 @@ public: ~SqliteConnection(); bool IsWriteConnection() const; int Prepare(const std::string &sql, bool &outIsReadOnly); - int PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, - std::vector &columnNames); int ExecuteSql(const std::string &sql, const std::vector &bindArgs = std::vector()); int ExecuteForChangedRowCount(int &changedRows, const std::string &sql, const std::vector &bindArgs); int ExecuteForLastInsertedRowId(int64_t &outRowId, const std::string &sql, diff --git a/relational_store/frameworks/native/rdb/include/sqlite_connection_pool.h b/relational_store/frameworks/native/rdb/include/sqlite_connection_pool.h index c20442269a64614607d1ff393747e4a7909b0fb7..2b4cf97d29c177cc5891d3e19482ae2baa7b2e80 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_connection_pool.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_connection_pool.h @@ -55,7 +55,6 @@ private: SqliteConnection *AcquireReadConnection(); void ReleaseReadConnection(SqliteConnection *connection); void CloseAllConnections(); - bool IsOverLength(const std::vector &newKey); int InnerReOpenReadConnections(); RdbStoreConfig config; diff --git a/relational_store/frameworks/native/rdb/include/sqlite_statement.h b/relational_store/frameworks/native/rdb/include/sqlite_statement.h index 2c2c3342c135739c55ee1bddb16a552992f1b898..dcfa00135ab6633731f785b72c0b47635973f488 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_statement.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_statement.h @@ -43,7 +43,6 @@ public: int GetSize(int index, size_t &size) const; int GetColumn(int index, ValueObject &value) const; bool IsReadOnly() const; - int GetNumParameters(int &numParams) const; sqlite3_stmt *GetSql3Stmt() const { return stmtHandle; diff --git a/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h b/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h index 0ed65a3b074b255a78242cb70f3a244a14f04910..78c66e3dad983ea8f9f87f706d72301c9213a214 100644 --- a/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h +++ b/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h @@ -80,7 +80,6 @@ public: bool IsReadOnly() const override; bool IsMemoryRdb() const override; bool IsHoldingConnection() override; - int GiveConnectionTemporarily(int64_t milliseconds); #ifdef RDB_SUPPORT_ICU int ConfigLocale(const std::string localeStr); #endif @@ -99,8 +98,6 @@ public: private: int InnerOpen(); - int InnerInsert(int64_t &outRowId, const std::string &table, ValuesBucket values, - ConflictResolution conflictResolution); int CheckAttach(const std::string &sql); bool PathToRealPath(const std::string &path, std::string &realPath); std::string ExtractFilePath(const std::string &fileFullName); @@ -111,11 +108,11 @@ private: int GetDataBasePath(const std::string &databasePath, std::string &backupFilePath); int ExecuteSqlInner(const std::string &sql, const std::vector &bindArgs); int ExecuteGetLongInner(const std::string &sql, const std::vector &bindArgs); - void SetAssetStatusWhileInsert(ValueObject &val); + void SetAssetStatusWhileInsert(const ValueObject &val); void DoCloudSync(const std::string &table); int InnerBackup(const std::string databasePath, const std::vector destEncryptKey = std::vector()); - + inline std::string GetSqlArgs(size_t size); const RdbStoreConfig rdbStoreConfig; SqliteConnectionPool *connectionPool; diff --git a/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h b/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h index 343b8d14fb95318a9b71a9c0bdeb8e0a07068172..68aabdb4c0656b9b740a4d3f54fe45827ef28d35 100644 --- a/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h +++ b/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h @@ -33,8 +33,6 @@ public: ~SqliteConnection(); bool IsWriteConnection() const; int Prepare(const std::string &sql, bool &outIsReadOnly); - int PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, - std::vector &columnNames); int ExecuteSql(const std::string &sql, const std::vector &bindArgs = std::vector()); int ExecuteForChangedRowCount(int &changedRows, const std::string &sql, const std::vector &bindArgs); int ExecuteForLastInsertedRowId(int64_t &outRowId, const std::string &sql, diff --git a/relational_store/frameworks/native/rdb/mock/include/sqlite_connection_pool.h b/relational_store/frameworks/native/rdb/mock/include/sqlite_connection_pool.h index c20442269a64614607d1ff393747e4a7909b0fb7..2b4cf97d29c177cc5891d3e19482ae2baa7b2e80 100644 --- a/relational_store/frameworks/native/rdb/mock/include/sqlite_connection_pool.h +++ b/relational_store/frameworks/native/rdb/mock/include/sqlite_connection_pool.h @@ -55,7 +55,6 @@ private: SqliteConnection *AcquireReadConnection(); void ReleaseReadConnection(SqliteConnection *connection); void CloseAllConnections(); - bool IsOverLength(const std::vector &newKey); int InnerReOpenReadConnections(); RdbStoreConfig config; diff --git a/relational_store/frameworks/native/rdb/mock/include/sqlite_statement.h b/relational_store/frameworks/native/rdb/mock/include/sqlite_statement.h index 2c2c3342c135739c55ee1bddb16a552992f1b898..dcfa00135ab6633731f785b72c0b47635973f488 100644 --- a/relational_store/frameworks/native/rdb/mock/include/sqlite_statement.h +++ b/relational_store/frameworks/native/rdb/mock/include/sqlite_statement.h @@ -43,7 +43,6 @@ public: int GetSize(int index, size_t &size) const; int GetColumn(int index, ValueObject &value) const; bool IsReadOnly() const; - int GetNumParameters(int &numParams) const; sqlite3_stmt *GetSql3Stmt() const { return stmtHandle; diff --git a/relational_store/frameworks/native/rdb/src/rdb_security_manager.cpp b/relational_store/frameworks/native/rdb/src/rdb_security_manager.cpp index 92371ec25818ae8ae6396efdced76b7a409139f0..b9695668d586c0c4744a7beb09e73ea0b656581a 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_security_manager.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_security_manager.cpp @@ -567,7 +567,6 @@ bool RdbSecurityManager::LoadSecretKeyFromDisk(const std::string &keyPath, RdbSe RdbPassword RdbSecurityManager::GetRdbPassword(KeyFileType keyFile) { - LOG_INFO("GetRdbPassword Begin."); if (!CheckKeyDataFileExists(keyFile)) { if (!SaveSecretKeyToFile(keyFile)) { LOG_ERROR("Failed to save key."); diff --git a/relational_store/frameworks/native/rdb/src/rdb_store_config.cpp b/relational_store/frameworks/native/rdb/src/rdb_store_config.cpp index 200db05035453aff082fb4b1359a405e4bdbf6bc..4c04b9baab0f883aa78685ff273d77e8f6705f9a 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_store_config.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_store_config.cpp @@ -183,7 +183,7 @@ void RdbStoreConfig::SetReadOnly(bool readOnly) #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) int RdbStoreConfig::SetDistributedType(DistributedType type) { - if (type < DistributedType::RDB_DEVICE_COLLABORATION || type >= DistributedType::RDB_DISTRIBUTED_TYPE_MAX) { + if (type != DistributedType::RDB_DEVICE_COLLABORATION) { LOG_ERROR("type is invalid"); return E_ERROR; } diff --git a/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp b/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp index 827a87e88d9f32b364c19824aa5fce0c4534a151..abb3212bf504a76de52e67c3f7ceb5713da7f008 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp @@ -197,6 +197,7 @@ std::map RdbStoreImpl::GetModifyTimeByRowId( } return result; } +#endif std::string RdbStoreImpl::GetSqlArgs(size_t size) { @@ -206,7 +207,6 @@ std::string RdbStoreImpl::GetSqlArgs(size_t size) } return args; } -#endif RdbStoreImpl::RdbStoreImpl(const RdbStoreConfig &config, int &errCode) : rdbStoreConfig(config), connectionPool(nullptr), isOpen(true), path(config.GetPath()), orgPath(config.GetPath()), @@ -258,7 +258,7 @@ int RdbStoreImpl::BatchInsert(int64_t &outInsertNum, const std::string &table, } // prepare batch data & sql std::vector>> vecVectorObj; - for (auto iter = initialBatchValues.begin(); iter != initialBatchValues.end(); iter++) { + for (auto iter = initialBatchValues.begin(); iter != initialBatchValues.end(); ++iter) { auto values = (*iter).GetAll(); vecVectorObj.push_back(GetInsertParams(values, table)); } @@ -292,7 +292,7 @@ int RdbStoreImpl::BatchInsert(int64_t &outInsertNum, const std::string &table, } // batch insert the values - for (auto iter = vecVectorObj.begin(); iter != vecVectorObj.end(); iter++) { + for (auto iter = vecVectorObj.begin(); iter != vecVectorObj.end(); ++iter) { outInsertNum++; errCode = connection->ExecuteSql(iter->first, iter->second); if (errCode != E_OK) { @@ -311,24 +311,29 @@ int RdbStoreImpl::BatchInsert(int64_t &outInsertNum, const std::string &table, std::pair> RdbStoreImpl::GetInsertParams( std::map &valuesMap, const std::string &table) { - std::stringstream sql; + std::string sql; std::vector bindArgs; - sql << "INSERT INTO " << table << '('; + sql.append("INSERT INTO ").append(table).append("("); + size_t bindArgsSize = valuesMap.size(); + if (bindArgsSize == 0) { + sql.append(") VALUES ()"); + return std::make_pair(sql, bindArgs); + } + + bindArgs.reserve(bindArgsSize); + auto valueIter = valuesMap.begin(); + sql.append(valueIter->first); + bindArgs.push_back(valueIter->second); + ++valueIter; // prepare batch values & sql.columnName - for (auto valueIter = valuesMap.begin(); valueIter != valuesMap.end(); valueIter++) { - sql << ((valueIter == valuesMap.begin()) ? "" : ","); - sql << valueIter->first; + for (; valueIter != valuesMap.end(); ++valueIter) { + sql.append(",").append(valueIter->first); bindArgs.push_back(valueIter->second); } + sql.append(") VALUES (").append(GetSqlArgs(bindArgsSize)).append(")"); // prepare sql.value - sql << ") VALUES ("; - for (size_t i = 0; i < valuesMap.size(); i++) { - sql << ((i == 0) ? "?" : ",?"); - } - sql << ')'; - // put sql & vec into map - return std::make_pair(sql.str(), bindArgs); + return std::make_pair(sql, bindArgs); } int RdbStoreImpl::Replace(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) @@ -338,18 +343,12 @@ int RdbStoreImpl::Replace(int64_t &outRowId, const std::string &table, const Val int RdbStoreImpl::InsertWithConflictResolution(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues, ConflictResolution conflictResolution) -{ - return InnerInsert(outRowId, table, initialValues, conflictResolution); -} - -int RdbStoreImpl::InnerInsert(int64_t &outRowId, const std::string &table, - ValuesBucket values, ConflictResolution conflictResolution) { if (table.empty()) { return E_EMPTY_TABLE_NAME; } - if (values.IsEmpty()) { + if (initialValues.IsEmpty()) { return E_EMPTY_VALUES_BUCKET; } @@ -359,14 +358,14 @@ int RdbStoreImpl::InnerInsert(int64_t &outRowId, const std::string &table, return errCode; } - std::stringstream sql; - sql << "INSERT" << conflictClause << " INTO " << table << '('; - + std::string sql; + sql.append("INSERT").append(conflictClause).append(" INTO ").append(table).append("("); + size_t bindArgsSize = initialValues.values_.size(); std::vector bindArgs; + bindArgs.reserve(bindArgsSize); const char *split = ""; - for (auto &[key, val] : values.values_) { - sql << split; - sql << key; // columnName + for (const auto &[key, val] : initialValues.values_) { + sql.append(split).append(key); if (val.GetType() == ValueObject::TYPE_ASSETS && conflictResolution == ConflictResolution::ON_CONFLICT_REPLACE) { return E_INVALID_ARGS; @@ -378,18 +377,18 @@ int RdbStoreImpl::InnerInsert(int64_t &outRowId, const std::string &table, split = ","; } - sql << ") VALUES ("; - for (size_t i = 0; i < bindArgs.size(); i++) { - sql << ((i == 0) ? "?" : ",?"); + sql.append(") VALUES ("); + if (bindArgsSize > 0) { + sql.append(GetSqlArgs(bindArgsSize)); } - sql << ')'; + sql.append(")"); SqliteConnection *connection = connectionPool->AcquireConnection(false); if (connection == nullptr) { return E_CON_OVER_LIMIT; } - errCode = connection->ExecuteForLastInsertedRowId(outRowId, sql.str(), bindArgs); + errCode = connection->ExecuteForLastInsertedRowId(outRowId, sql, bindArgs); connectionPool->ReleaseConnection(connection); if (errCode == E_OK) { DoCloudSync(table); @@ -397,7 +396,7 @@ int RdbStoreImpl::InnerInsert(int64_t &outRowId, const std::string &table, return errCode; } -void RdbStoreImpl::SetAssetStatusWhileInsert(ValueObject &val) +void RdbStoreImpl::SetAssetStatusWhileInsert(const ValueObject &val) { if (val.GetType() == ValueObject::TYPE_ASSET) { auto *asset = Traits::get_if(&val.value); @@ -466,24 +465,25 @@ int RdbStoreImpl::UpdateWithConflictResolution(int &changedRows, const std::stri return errCode; } - std::stringstream sql; - sql << "UPDATE" << conflictClause << " " << table << " SET "; - + std::string sql; + sql.append("UPDATE").append(conflictClause).append(" ").append(table).append(" SET "); std::vector tmpBindArgs; + size_t tmpBindSize = values.values_.size() + bindArgs.size(); + tmpBindArgs.reserve(tmpBindSize); const char *split = ""; for (auto &[key, val] : values.values_) { - sql << split; - if (val.GetType() == ValueObject::TYPE_ASSETS) { - sql << key << "=merge_assets(" << key << ", ?)"; // columnName + sql.append(split); + if (val.GetType() != ValueObject::TYPE_ASSETS) { + sql.append(key).append("=?"); // columnName } else { - sql << key << "=?"; // columnName + sql.append(key).append("=merge_assets(").append(key).append(", ?)"); // columnName } tmpBindArgs.push_back(val); // columnValue split = ","; } if (!whereClause.empty()) { - sql << " WHERE " << whereClause; + sql.append(" WHERE ").append(whereClause); } tmpBindArgs.insert(tmpBindArgs.end(), bindArgs.begin(), bindArgs.end()); @@ -493,7 +493,7 @@ int RdbStoreImpl::UpdateWithConflictResolution(int &changedRows, const std::stri return E_CON_OVER_LIMIT; } - errCode = connection->ExecuteForChangedRowCount(changedRows, sql.str(), tmpBindArgs); + errCode = connection->ExecuteForChangedRowCount(changedRows, sql, tmpBindArgs); connectionPool->ReleaseConnection(connection); if (errCode == E_OK) { DoCloudSync(table); @@ -523,10 +523,10 @@ int RdbStoreImpl::Delete(int &deletedRows, const std::string &table, const std:: return E_EMPTY_TABLE_NAME; } - std::stringstream sql; - sql << "DELETE FROM " << table; + std::string sql; + sql.append("DELETE FROM ").append(table); if (!whereClause.empty()) { - sql << " WHERE " << whereClause; + sql.append(" WHERE ").append(whereClause); } SqliteConnection *connection = connectionPool->AcquireConnection(false); @@ -534,7 +534,7 @@ int RdbStoreImpl::Delete(int &deletedRows, const std::string &table, const std:: return E_CON_OVER_LIMIT; } - int errCode = connection->ExecuteForChangedRowCount(deletedRows, sql.str(), bindArgs); + int errCode = connection->ExecuteForChangedRowCount(deletedRows, sql, bindArgs); connectionPool->ReleaseConnection(connection); if (errCode == E_OK) { DoCloudSync(table); @@ -878,33 +878,10 @@ int RdbStoreImpl::BeginExecuteSql(const std::string &sql, SqliteConnection **con return E_OK; } bool RdbStoreImpl::IsHoldingConnection() - { return connectionPool != nullptr; } -int RdbStoreImpl::GiveConnectionTemporarily(int64_t milliseconds) -{ - SqliteConnection *connection = connectionPool->AcquireConnection(false); - if (connection == nullptr) { - return E_CON_OVER_LIMIT; - } - - if (connection->IsInTransaction()) { - return E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY; - } - int errCode = BeginTransaction(); - if (errCode != E_OK) { - return errCode; - } - std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); - errCode = RollBack(); - if (errCode != E_OK) { - return errCode; - } - - return errCode; -} /** * Attaches a database. @@ -1204,9 +1181,6 @@ std::string RdbStoreImpl::GetName() void RdbStoreImpl::DoCloudSync(const std::string &table) { #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) - if (pool_ == nullptr) { - return; - } { std::shared_lock lock(rwMutex_); if (cloudTables_.empty() || (!table.empty() && cloudTables_.find(table) == cloudTables_.end())) { @@ -1220,7 +1194,7 @@ void RdbStoreImpl::DoCloudSync(const std::string &table) } auto empty = syncTables_->empty(); if (table.empty()) { - syncTables_->insert(cloudTables_.begin(), cloudTables_.end()); + syncTables_->insert(cloudTables_.begin(), cloudTables_.end()); } else { syncTables_->insert(table); } @@ -1228,6 +1202,9 @@ void RdbStoreImpl::DoCloudSync(const std::string &table) return; } } + if (pool_ == nullptr) { + return; + } auto interval = std::chrono::duration_cast(std::chrono::milliseconds(INTERVAL)); pool_->Schedule(interval, [this]() { diff --git a/relational_store/frameworks/native/rdb/src/security_policy.cpp b/relational_store/frameworks/native/rdb/src/security_policy.cpp index 69e1973838abcc7e4d13e4a87e8b3f96a15fbe2e..75c46ec7c776ca811efdc217857a5f7e82dec3d1 100644 --- a/relational_store/frameworks/native/rdb/src/security_policy.cpp +++ b/relational_store/frameworks/native/rdb/src/security_policy.cpp @@ -22,14 +22,6 @@ namespace OHOS { namespace NativeRdb { using namespace OHOS::Rdb; - -int SecurityPolicy::SetFileSecurityLevel(const std::string &filePath, const std::string &securityLevel) -{ - bool result = FileManagement::ModuleSecurityLabel::SecurityLabel::SetSecurityLabel(filePath, securityLevel); - LOG_INFO("Set database securityLabel:%{public}s, result:%{public}d.", securityLevel.c_str(), result); - return result ? E_OK : E_ERROR; -} - std::string SecurityPolicy::GetSecurityLevelValue(SecurityLevel securityLevel) { switch (securityLevel) { @@ -56,11 +48,16 @@ int SecurityPolicy::SetSecurityLabel(const RdbStoreConfig &config) if (config.GetStorageMode() != StorageMode::MODE_MEMORY && config.GetSecurityLevel() != SecurityLevel::LAST) { std::string currentLevel = GetFileSecurityLevel(config.GetPath()); std::string toSetLevel = GetSecurityLevelValue(config.GetSecurityLevel()); - LOG_INFO("Security level current is %{public}s to %{public}s.", currentLevel.c_str(), toSetLevel.c_str()); + int errCode = E_OK; if (currentLevel.empty()) { - return SetFileSecurityLevel(config.GetPath(), toSetLevel); + errCode = FileManagement::ModuleSecurityLabel::SecurityLabel::SetSecurityLabel(config.GetPath(), + toSetLevel) ? E_OK : E_ERROR; + } else { + errCode = currentLevel == toSetLevel ? E_OK : E_ERROR; } - return currentLevel == toSetLevel ? E_OK : E_ERROR; + LOG_INFO("Set security level from %{public}s to %{public}s, result:%{public}d.", currentLevel.c_str(), + toSetLevel.c_str(), errCode); + return errCode; } return E_OK; } diff --git a/relational_store/frameworks/native/rdb/src/shared_block_serializer_info.cpp b/relational_store/frameworks/native/rdb/src/shared_block_serializer_info.cpp index 9a3a918ab5a312507eafe4981ab6dc8fcbe4a5c9..6c104a4e4601a7d7f66be4ad418163ac9322392f 100644 --- a/relational_store/frameworks/native/rdb/src/shared_block_serializer_info.cpp +++ b/relational_store/frameworks/native/rdb/src/shared_block_serializer_info.cpp @@ -46,11 +46,12 @@ int SharedBlockSerializerInfo::Reset(int startPos) { int status = sharedBlock_->Clear(); if (status != AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { - LOG_ERROR("reset : Failed in clearing, error=%{public}d", status); + LOG_ERROR("SharedBlockSerializerInfo::Reset() Failed in Clear(), error=%{public}d.", status); return SQLITE_ERROR; } status = sharedBlock_->SetColumnNum(anumColumns); if (status != AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { + LOG_ERROR("SharedBlockSerializerInfo::Reset() Failed in SetColumnNum(), error=%{public}d.", status); return SQLITE_ERROR; } astartPos = startPos; diff --git a/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp b/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp index 6ed2890dceda43f4bc123aab43b67506ec21af7a..b5344be8fd25ccf1c48357e9d9ed1766941b0b7b 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp @@ -105,9 +105,6 @@ int SqliteConnection::InnerOpen(const RdbStoreConfig &config) } stepStatement = std::make_shared(); - if (stepStatement == nullptr) { - return E_STEP_STATEMENT_NOT_INIT; - } #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) bool isDbFileExist = access(dbPath.c_str(), F_OK) == 0; if (!isDbFileExist && (!config.IsCreateNecessary())) { @@ -298,12 +295,13 @@ int SqliteConnection::SetEncryptKey(const RdbStoreConfig &config) { #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) std::vector key = config.GetEncryptKey(); - RdbPassword rdbPwd; + bool isKeyExpired = false; if (config.IsEncrypt()) { RdbSecurityManager::GetInstance().Init(config.GetBundleName(), config.GetPath()); - rdbPwd = RdbSecurityManager::GetInstance().GetRdbPassword(RdbKeyFile::PUB_KEY_FILE); + auto rdbPwd = RdbSecurityManager::GetInstance().GetRdbPassword(RdbKeyFile::PUB_KEY_FILE); key.assign(key.size(), 0); key = std::vector(rdbPwd.GetData(), rdbPwd.GetData() + rdbPwd.GetSize()); + isKeyExpired = rdbPwd.isKeyExpired; } else if (key.empty()) { return E_OK; } @@ -311,8 +309,22 @@ int SqliteConnection::SetEncryptKey(const RdbStoreConfig &config) int errCode = sqlite3_key(dbHandle, static_cast(key.data()), static_cast(key.size())); key.assign(key.size(), 0); if (errCode != SQLITE_OK) { - LOG_ERROR("SqliteConnection SetEncryptKey fail, err = %{public}d", errCode); - return SQLiteError::ErrNo(errCode); + if (RdbSecurityManager::GetInstance().CheckKeyDataFileExists(RdbKeyFile::PUB_KEY_FILE_NEW_KEY)) + { + auto rdbPwd = RdbSecurityManager::GetInstance().GetRdbPassword(RdbKeyFile::PUB_KEY_FILE_NEW_KEY); + key = std::vector(rdbPwd.GetData(), rdbPwd.GetData() + rdbPwd.GetSize()); + errCode = sqlite3_key(dbHandle, static_cast(key.data()), static_cast(key.size())); + key.assign(key.size(), 0); + if (errCode != SQLITE_OK) { + LOG_ERROR("SqliteConnection SetEncryptKey fail with new key, err = %{public}d", errCode); + return SQLiteError::ErrNo(errCode); + } + RdbSecurityManager::GetInstance().UpdateKeyFile(); + } + if (errCode != SQLITE_OK) { + LOG_ERROR("SqliteConnection SetEncryptKey fail, err = %{public}d", errCode); + return SQLiteError::ErrNo(errCode); + } } errCode = ExecuteSql(GlobalExpr::CODEC_HMAC_ALGO); @@ -326,8 +338,8 @@ int SqliteConnection::SetEncryptKey(const RdbStoreConfig &config) return errCode; } - if (rdbPwd.isKeyExpired) { - rdbPwd = RdbSecurityManager::GetInstance().GetRdbPassword(RdbKeyFile::PUB_KEY_FILE_NEW_KEY); + if (isKeyExpired) { + auto rdbPwd = RdbSecurityManager::GetInstance().GetRdbPassword(RdbKeyFile::PUB_KEY_FILE_NEW_KEY); if (!rdbPwd.IsValid()) { RdbSecurityManager::GetInstance().DelRdbSecretDataFile(RdbKeyFile::PUB_KEY_FILE_NEW_KEY); LOG_ERROR("new key is not valid."); @@ -507,38 +519,6 @@ int SqliteConnection::Prepare(const std::string &sql, bool &outIsReadOnly) return E_OK; } -int SqliteConnection::PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, - std::vector &columnNames) -{ - int errCode = statement.Prepare(dbHandle, sql); - if (errCode != E_OK) { - return errCode; - } - - errCode = statement.GetColumnCount(numParameters); - if (errCode != E_OK) { - return errCode; - } - - int columnCount; - errCode = statement.GetColumnCount(columnCount); - if (errCode != E_OK) { - return errCode; - } - for (int i = 0; i < columnCount; i++) { - std::string name; - statement.GetColumnName(i, name); - columnNames.push_back(name); - } - outIsReadOnly = statement.IsReadOnly(); - - errCode = statement.GetNumParameters(numParameters); - if (errCode != E_OK) { - return errCode; - } - - return E_OK; -} int SqliteConnection::PrepareAndBind(const std::string &sql, const std::vector &bindArgs) { @@ -842,6 +822,7 @@ int SqliteConnection::ExecuteForSharedBlock(int &rowNum, std::string sql, const } if (!ResetStatement(&sharedBlockInfo)) { + LOG_ERROR("ExecuteForSharedBlock:ResetStatement Failed."); return E_ERROR; } rowNum = static_cast(GetCombinedData(sharedBlockInfo.startPos, sharedBlockInfo.totalRows)); diff --git a/relational_store/frameworks/native/rdb/src/sqlite_connection_pool.cpp b/relational_store/frameworks/native/rdb/src/sqlite_connection_pool.cpp index a66ae880563bfe5fd9a549bbf5f5df084e2073f1..1ede34955adae91d2a27529a4599f5f1206eb9bf 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_connection_pool.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_connection_pool.cpp @@ -211,17 +211,6 @@ void SqliteConnectionPool::ReleaseReadConnection(SqliteConnection *connection) readCondition.notify_one(); } -bool SqliteConnectionPool::IsOverLength(const std::vector &newKey) -{ - if (newKey.empty()) { - return false; - } - - std::stringstream ss; - copy(newKey.begin(), newKey.end(), std::ostream_iterator(ss, "")); - return ss.str().length() > LIMITATION; -} - int SqliteConnectionPool::InnerReOpenReadConnections() { int errCode = E_OK; diff --git a/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp b/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp index a99338a1d2ec739304825d5e0af0c9622e329acb..0b6f64028b5b4d8a44496f85a9ba1157b92c2a97 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp @@ -215,19 +215,6 @@ int SqliteStatement::GetColumnCount(int &count) const return E_OK; } -/** - * Obtains the number that the statement has. - */ -int SqliteStatement::GetNumParameters(int &numParams) const -{ - if (stmtHandle == nullptr) { - LOG_ERROR("invalid statement."); - return E_INVALID_STATEMENT; - } - numParams = numParameters; - return E_OK; -} - int SqliteStatement::GetColumnName(int index, std::string &columnName) const { int ret = IsValid(index); diff --git a/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h b/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h index d322b0f22bbdfdc79baf4b9a00c006f28106bcb4..84e854af67af94fede1116fa7a8ffdb86c7a1313 100644 --- a/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h +++ b/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h @@ -30,7 +30,6 @@ public: TRANS_NOTIFY_DATA_CHANGE, TRANS_BUTT, }; - enum Action : int32_t { CLEAR_CLOUD_INFO, CLEAR_CLOUD_DATA_AND_INFO, diff --git a/relational_store/interfaces/inner_api/rdb/BUILD.gn b/relational_store/interfaces/inner_api/rdb/BUILD.gn index a0b22c987d4d3aec227d82e8d69a2806ecc6e966..9dd419b1438c02feeba3eaa871f88a6fd41b2936 100644 --- a/relational_store/interfaces/inner_api/rdb/BUILD.gn +++ b/relational_store/interfaces/inner_api/rdb/BUILD.gn @@ -70,7 +70,7 @@ if (is_ohos && !build_ohos_sdk) { ] } - config(" ") { + config("native_rdb_public_config") { visibility = [ ":*" ] include_dirs = [ diff --git a/relational_store/test/js/clouddata/unittest/config.json b/relational_store/test/js/clouddata/unittest/config.json index 0683f3ff23bf4b2573c8603ecfc799114baafc1c..a14bac40f3003bb31eb3b2d59aa6c77f29f99ae1 100644 --- a/relational_store/test/js/clouddata/unittest/config.json +++ b/relational_store/test/js/clouddata/unittest/config.json @@ -17,6 +17,7 @@ "name": ".MyApplication", "deviceType": [ "tablet", + "2in1", "default", "phone" ], diff --git a/relational_store/test/js/rdb/performance/src/PredicatestPerf.js b/relational_store/test/js/rdb/performance/src/PredicatestPerf.js index d94ebaa247b277b17ecbd9d9bdce0b07f0e55c4a..7bcf8e5a95c36dcbfe4ee72b5ef5162937627809 100644 --- a/relational_store/test/js/rdb/performance/src/PredicatestPerf.js +++ b/relational_store/test/js/rdb/performance/src/PredicatestPerf.js @@ -24,7 +24,7 @@ const BASE_COUNT_FIRST = 200; const BASE_COUNT_SECOND = 10; const BASE_LINE_TABLE = 500; // callback tablet base line const BASE_LINE_PHONE = 1000; // callback phone base line -const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; +const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceInfo.deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('predicatesPerf', function () { beforeAll(async function () { diff --git a/relational_store/test/js/rdb/performance/src/RdbHelperCallbackPerf.js b/relational_store/test/js/rdb/performance/src/RdbHelperCallbackPerf.js index b2e250f112dabcbf337864b5c655512a04a8f77e..f72768a2b319941943fb5d61da3a99e3d3f789a4 100644 --- a/relational_store/test/js/rdb/performance/src/RdbHelperCallbackPerf.js +++ b/relational_store/test/js/rdb/performance/src/RdbHelperCallbackPerf.js @@ -29,7 +29,7 @@ var rdbStore = undefined; const BASE_COUNT = 2000; // loop times const BASE_LINE_TABLE = 2500; // callback tablet base line const BASE_LINE_PHONE = 3000; // callback phone base line -const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; +const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceInfo.deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('rdbHelperCallbackPerf', function () { beforeAll(async function () { diff --git a/relational_store/test/js/rdb/performance/src/RdbHelperPromisePerf.js b/relational_store/test/js/rdb/performance/src/RdbHelperPromisePerf.js index 6e53ee4fe5ada7962cb076e8e826f93129259b71..619003ac419210415e97d674206f880213d5e751 100644 --- a/relational_store/test/js/rdb/performance/src/RdbHelperPromisePerf.js +++ b/relational_store/test/js/rdb/performance/src/RdbHelperPromisePerf.js @@ -29,7 +29,7 @@ var rdbStore = undefined; const BASE_COUNT = 2000; // loop times const BASE_LINE_TABLE = 2500; // callback tablet base line const BASE_LINE_PHONE = 3000; // callback phone base line -const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; +const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceInfo.deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('rdbHelperPromisePerf', function () { beforeAll(async function () { diff --git a/relational_store/test/js/rdb/performance/src/RdbStoreCallbackPerf.js b/relational_store/test/js/rdb/performance/src/RdbStoreCallbackPerf.js index c9d4baeb7a914c029ad0465c05091eef1efe5a2c..243bb63dcd6709f18c2314c121fc199f2acac95d 100644 --- a/relational_store/test/js/rdb/performance/src/RdbStoreCallbackPerf.js +++ b/relational_store/test/js/rdb/performance/src/RdbStoreCallbackPerf.js @@ -32,7 +32,7 @@ const BASE_COUNT = 1000; // loop times const INSERT_BASE_COUNT = 300; const BASE_LINE_TABLE = 1800; // callback tablet base line const BASE_LINE_PHONE = 7000; // callback phone base line -const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; +const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceInfo.deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('rdbStoreCallbackPerf', function () { beforeAll(async function () { diff --git a/relational_store/test/js/rdb/performance/src/RdbStoreOthersCallbackPerf.js b/relational_store/test/js/rdb/performance/src/RdbStoreOthersCallbackPerf.js index 5af7e211015225102052ac5dba6c4098cdaeb13a..87d11c05961fdd97990af9868def8af11e8f21d8 100644 --- a/relational_store/test/js/rdb/performance/src/RdbStoreOthersCallbackPerf.js +++ b/relational_store/test/js/rdb/performance/src/RdbStoreOthersCallbackPerf.js @@ -32,7 +32,7 @@ const BASE_COUNT = 1000; // loop times const SPECIAL_BASE_COUNT = 300; const BASE_LINE_TABLE = 1800; // callback tablet base line const BASE_LINE_PHONE = 15000; // callback phone base line -const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; +const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceInfo.deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('rdbStoreOthersCallbackPerf', function () { beforeAll(async function () { diff --git a/relational_store/test/js/rdb/performance/src/RdbStorePromisePerf.js b/relational_store/test/js/rdb/performance/src/RdbStorePromisePerf.js index 31441729f648965d99f6d219c41f4341c32984ca..f7ea8a3b858c8fd32c8b3e2d846ffd4bc19de74a 100644 --- a/relational_store/test/js/rdb/performance/src/RdbStorePromisePerf.js +++ b/relational_store/test/js/rdb/performance/src/RdbStorePromisePerf.js @@ -31,7 +31,7 @@ var rdbStore = undefined; const BASE_COUNT = 1000; // loop times const BASE_LINE_TABLE = 1800; // callback tablet base line const BASE_LINE_PHONE = 3000; // callback phone base line -const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; +const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceInfo.deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('rdbStorePromisePerf', function () { beforeAll(async function () { diff --git a/relational_store/test/js/rdb/performance/src/RdbStoreSyncPerf.js b/relational_store/test/js/rdb/performance/src/RdbStoreSyncPerf.js index 6e01807bc727f7e67197d5b1e53b8504212223ca..5d0bc10154da9ecbdf410d084c9a137f68767091 100644 --- a/relational_store/test/js/rdb/performance/src/RdbStoreSyncPerf.js +++ b/relational_store/test/js/rdb/performance/src/RdbStoreSyncPerf.js @@ -31,7 +31,7 @@ var rdbStore = undefined; const BASE_COUNT = 1000; // loop times const BASE_LINE_TABLE = 2500; // callback tablet base line const BASE_LINE_PHONE = 3000; // callback phone base line -const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; +const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceInfo.deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('rdbStoreSyncPerf', function () { diff --git a/relational_store/test/js/rdb/performance/src/ResultSetPerf.js b/relational_store/test/js/rdb/performance/src/ResultSetPerf.js index a29d8fe3cfaa2914050df5a5ff690382974189a0..384a20132b8196e727b90d9b9360531c8f57866a 100644 --- a/relational_store/test/js/rdb/performance/src/ResultSetPerf.js +++ b/relational_store/test/js/rdb/performance/src/ResultSetPerf.js @@ -32,7 +32,7 @@ const BASE_COUNT = 2000; // loop times const SPECIAL_BASE_COUNT = 12000; const BASE_LINE_TABLE = 500; // callback tablet base line const BASE_LINE_PHONE = 1000; // callback phone base line -const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; +const BASE_LINE = (deviceInfo.deviceType == "tablet" || deviceInfo.deviceType == "2in1") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('resultSetPerf', function () { beforeAll(async function () { diff --git a/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js index c6d40d6583f341596dd2e0103358d1d4adffbdb0..ba726dd042efd219039e3f4cc748ae791b3d64f2 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js @@ -20,6 +20,11 @@ const TAG = "[RDB_JSKITS_TEST_Distributed]" const STORE_NAME = "distributed_rdb.db" var rdbStore = undefined; +function storeObserver(devices) { + console.info(TAG + devices + " dataChange"); + expect(devices).assertEqual(null) +} + describe('rdbStoreDistributedTest', function () { beforeAll(async function (done) { console.info(TAG + 'beforeAll') @@ -89,7 +94,6 @@ describe('rdbStoreDistributedTest', function () { try { await rdbStore.setDistributedTables([]) console.log(TAG + "set none to be distributed table success"); - expect(rdbStore).assertEqual(rdbStore) } catch (err) { console.log(TAG + "set none to be distributed table failed"); expect(null).assertFail(); @@ -108,7 +112,6 @@ describe('rdbStoreDistributedTest', function () { try { await rdbStore.setDistributedTables(['employee']) console.log(TAG + "set employee to be distributed table success"); - expect(rdbStore).assertEqual(rdbStore) } catch (err) { console.log(TAG + "set employee to be distributed table failed"); expect(null).assertFail(); @@ -127,7 +130,6 @@ describe('rdbStoreDistributedTest', function () { try { await rdbStore.setDistributedTables(['employee', 'product']) console.log(TAG + "set employee and product to be distributed table success"); - expect(rdbStore).assertEqual(rdbStore) } catch (err) { console.log(TAG + "set employee and product to be distributed table failed"); expect(null).assertFail(); @@ -285,51 +287,60 @@ describe('rdbStoreDistributedTest', function () { /** * @tc.name sync test * @tc.number SUB_DDM_AppDataFWK_JSRDB_Distributed_011 - * @tc.desc sync test + * @tc.desc normal testcase for synchronization operation of interface 'inDevices' */ - it('testRdbStoreDistributed0011', 0, async function (done) { + it('testRdbStoreDistributed0011', 0, async function () { console.log(TAG + "************* testRdbStoreDistributed0011 start *************"); let predicates = new dataRdb.RdbPredicates("employee") predicates = predicates.inDevices(["12345678abcd"]); - rdbStore.sync(dataRdb.SyncMode.SYNC_MODE_PUSH, predicates); - console.log(TAG + "sync push success"); - expect(rdbStore).assertEqual(rdbStore); - rdbStore.sync(dataRdb.SyncMode.SYNC_MODE_PULL, predicates); - console.log(TAG + "sync pull success"); - expect(rdbStore).assertEqual(rdbStore); - done(); + try { + rdbStore.sync(dataRdb.SyncMode.SYNC_MODE_PUSH, predicates); + console.log(TAG + "sync push success"); + } catch (err) { + console.log(TAG + "sync push" + err); + expect().assertFail(); + } + try { + rdbStore.sync(dataRdb.SyncMode.SYNC_MODE_PULL, predicates); + console.log(TAG + "sync pull success"); + } catch (err) { + console.log(TAG + "sync push" + err); + expect().assertFail(); + } console.log(TAG + "************* testRdbStoreDistributed0011 end *************"); }) /** * @tc.name subscribe test * @tc.number SUB_DDM_AppDataFWK_JSRDB_Distributed_012 - * @tc.desc subscribe test + * @tc.desc normal testcase for subscription data changes of interface 'on' */ - it('testRdbStoreDistributed0012', 0, async function (done) { + it('testRdbStoreDistributed0012', 0, async function () { console.log(TAG + "************* testRdbStoreDistributed0012 start *************"); - rdbStore.on("dataChange", dataRdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (device) => { - console.log(TAG + device + " dataChange"); - }); - console.log(TAG + "on dataChange success"); - expect(rdbStore).assertEqual(rdbStore); - done() + try { + rdbStore.on("dataChange", dataRdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); + console.log(TAG + "on dataChange success"); + } catch (err) { + console.log(TAG + "on dataChange" + err); + expect().assertFail(); + } console.log(TAG + "************* testRdbStoreDistributed0012 end *************"); }) /** * @tc.name subscribe test * @tc.number SUB_DDM_AppDataFWK_JSRDB_Distributed_013 - * @tc.desc subscribe test + * @tc.desc normal testcase for unsubscribe data changes of interface 'off' */ - it('testRdbStoreDistributed0013', 0, async function (done) { + it('testRdbStoreDistributed0013', 0, async function () { console.log(TAG + "************* testRdbStoreDistributed0013 start *************"); - rdbStore.off("dataChange", dataRdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (device) => { - console.log(TAG + device + " dataChange"); - }); - console.log(TAG + "off dataChange success"); - expect(rdbStore).assertEqual(rdbStore); - done() + try { + rdbStore.off("dataChange", dataRdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); + console.log(TAG + "off dataChange success"); + } catch (err) { + console.log(TAG + "off dataChange" + err); + expect().assertFail(); + } console.log(TAG + "************* testRdbStoreDistributed0013 end *************"); }) console.log(TAG + "*************Unit Test End*************"); diff --git a/relational_store/test/native/dataability/unittest/data_ability_predicates_test.cpp b/relational_store/test/native/dataability/unittest/data_ability_predicates_test.cpp index 5954dc81c943650e9e8d4a335e4fdb3cc78c6fe8..ed94a1713c87058fd2c1c2e9d89df0ef2b78962f 100644 --- a/relational_store/test/native/dataability/unittest/data_ability_predicates_test.cpp +++ b/relational_store/test/native/dataability/unittest/data_ability_predicates_test.cpp @@ -18,6 +18,7 @@ #include "data_ability_predicates.h" #include "refbase.h" +#include "predicates_utils.h" using namespace testing::ext; using namespace OHOS::NativeRdb; @@ -396,4 +397,28 @@ HWTEST_F(DataAbilityPredicatesTest, DataAbilityPredicates_015, TestSize.Level1) OHOS::sptr dataAbilityPredicatesRead = parcel.ReadParcelable(); EXPECT_EQ(nullptr, dataAbilityPredicatesRead); +} + +/* * + * @tc.name: DataAbilityPredicates_016 + * @tc.desc: test SetAttributes + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(DataAbilityPredicatesTest, DataAbilityPredicates_016, TestSize.Level1) +{ + OHOS::NativeRdb::AbsPredicates predicates; + bool isDistinct = true; + std::string index = "test"; + std::string group = "test"; + std::string order = ""; + int limit = 1; + int offset = 0; + PredicatesUtils::SetAttributes(&predicates, isDistinct, index, group, order, limit, offset); + EXPECT_EQ(isDistinct, predicates.IsDistinct()); + EXPECT_EQ(index, predicates.GetIndex()); + EXPECT_EQ(group, predicates.GetGroup()); + EXPECT_EQ(order, predicates.GetOrder()); + EXPECT_EQ(limit, predicates.GetLimit()); + EXPECT_EQ(offset, predicates.GetOffset()); } \ No newline at end of file diff --git a/relational_store/test/native/rdb/BUILD.gn b/relational_store/test/native/rdb/BUILD.gn index 9a28a1e64c9245282ea602fd18cee21551e2d526..54c8dc6cc887500c88337969ddd20f0bbd6f8ab9 100644 --- a/relational_store/test/native/rdb/BUILD.gn +++ b/relational_store/test/native/rdb/BUILD.gn @@ -58,6 +58,7 @@ ohos_unittest("NativeRdbTest") { "unittest/rdb_step_result_set_test.cpp", "unittest/rdb_store_concurrent_test.cpp", "unittest/rdb_store_config_test.cpp", + "unittest/rdb_store_impl_test.cpp", "unittest/rdb_store_interface_test.cpp", "unittest/rdb_store_rekey_test.cpp", "unittest/rdb_store_subscribe_test.cpp", diff --git a/relational_store/test/native/rdb/distributedtest/rdb_store_impl_test/distributed_test.cpp b/relational_store/test/native/rdb/distributedtest/rdb_store_impl_test/distributed_test.cpp index 3482e061ff45f188cda8df1c78a525ea793add25..08c72d10717b1d50952799311706c000d671000a 100644 --- a/relational_store/test/native/rdb/distributedtest/rdb_store_impl_test/distributed_test.cpp +++ b/relational_store/test/native/rdb/distributedtest/rdb_store_impl_test/distributed_test.cpp @@ -26,6 +26,7 @@ #include "rdb_open_callback.h" #include "rdb_store_impl.h" #include "rdb_types.h" +#include "result_set_proxy.h" #include @@ -73,7 +74,6 @@ class DmDeathCallback : public DmInitCallback { public: explicit DmDeathCallback() {} void OnRemoteDied() override {} - }; void DistributedTest::InitDevManager() @@ -163,6 +163,49 @@ HWTEST_F(DistributedTest, RemoteQuery001, TestSize.Level1) EXPECT_TRUE(ret > 0); EXPECT_EQ(returvalue, "zhangsan"); } + + +/** + * @tc.name: ResultSetProxy001 + * @tc.desc: Abnormal testcase of distributed ResultSetProxy, if resultSet is Empty + * @tc.type: FUNC + */ +HWTEST_F(DistributedTest, ResultSetProxy001, TestSize.Level1) +{ + int errCode = 0; + std::shared_ptr resultSet; + ColumnType columnType; + errCode = resultSet->GetColumnType(1, columnType); + EXPECT_NE(E_OK, errCode); + + std::string columnName; + errCode = resultSet->GetColumnName(1, columnName); + EXPECT_NE(E_OK, errCode); + + std::vector blob; + errCode = resultSet->GetBlob(1, blob); + EXPECT_NE(E_OK, errCode); + + std::string getStringvalue; + errCode = resultSet->GetString(1, getStringvalue); + EXPECT_NE(E_OK, errCode); + + int getIntvalue; + errCode = resultSet->GetInt(1, getIntvalue); + EXPECT_NE(E_OK, errCode); + + int64_t getLongvalue; + errCode = resultSet->GetLong(1, getLongvalue); + EXPECT_NE(E_OK, errCode); + + double getDoublevalue; + errCode = resultSet->GetDouble(1, getDoublevalue); + EXPECT_NE(E_OK, errCode); + + bool isNull; + errCode = resultSet->IsColumnNull(1, isNull); + EXPECT_NE(E_OK, errCode); +} } int main(int argc, char *argv[]) diff --git a/relational_store/test/native/rdb/unittest/rdb_attach_test.cpp b/relational_store/test/native/rdb/unittest/rdb_attach_test.cpp index 5fba0e4429adfeeef90b51eaf0f4418f56be33f4..aedbacc427e174f381522238e99989bca69c74e7 100644 --- a/relational_store/test/native/rdb/unittest/rdb_attach_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_attach_test.cpp @@ -169,6 +169,53 @@ HWTEST_F(RdbAttachTest, RdbStore_Attach_002, TestSize.Level1) EXPECT_EQ(ret, E_OK); } + +/* * + * @tc.name: RdbStore_Attach_003 + * @tc.desc: Abnormal testCase for Attach + * @tc.type: FUNC + */ +HWTEST_F(RdbAttachTest, RdbStore_Attach_003, TestSize.Level2) +{ + const std::string alias = "attached"; + std::vector destEncryptKey; + RdbStoreConfig config(RdbAttachTest::MAIN_DATABASE_NAME); + MainOpenCallback helper; + int errCode = E_OK; + + // journal mode is wal + std::shared_ptr store1 = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(nullptr, store1); + EXPECT_EQ(E_OK, errCode); + + int ret = store1->Attach(alias, RdbAttachTest::ATTACHED_DATABASE_NAME, destEncryptKey); + EXPECT_EQ(E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE, ret); + RdbHelper::DeleteRdbStore(RdbAttachTest::MAIN_DATABASE_NAME); + + // journal mode is TRUNCATE + // destEncryptKey is empty and isEncrypt_ is false + config.SetJournalMode(JournalMode::MODE_TRUNCATE); + std::shared_ptr store2 = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(nullptr, store2); + EXPECT_EQ(E_OK, errCode); + ret = store2->Attach(alias, RdbAttachTest::ATTACHED_DATABASE_NAME, destEncryptKey); + EXPECT_EQ(E_OK, ret); + + // destEncryptKey is not empty and isEncrypt_ is false + destEncryptKey = {1}; + ret = store2->Attach(alias, RdbAttachTest::ATTACHED_DATABASE_NAME, destEncryptKey); + EXPECT_NE(E_OK, ret); + RdbHelper::DeleteRdbStore(RdbAttachTest::MAIN_DATABASE_NAME); + + // destEncryptKey is not empty and isEncrypt_ is true + config.SetEncryptStatus(true); + std::shared_ptr store3 = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(nullptr, store3); + EXPECT_EQ(E_OK, errCode); + ret = store3->Attach(alias, RdbAttachTest::ATTACHED_DATABASE_NAME, destEncryptKey); + EXPECT_NE(E_OK, ret); +} + void RdbAttachTest::QueryCheck1(std::shared_ptr &store) const { std::shared_ptr resultSet = store->QuerySql("SELECT * FROM test1"); diff --git a/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp b/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp index be02a4c791d43f8892c4aaf12f0a3a586f5a886c..1383971fb26c6f978bc6c011ba0ced7091a24edf 100644 --- a/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp @@ -198,3 +198,70 @@ HWTEST_F(RdbStoreDistributedTest, RdbStore_Distributed_003, TestSize.Level2) EXPECT_EQ("", rdbStore->ObtainDistributedTableName("123456", "employee", errCode)); EXPECT_EQ(-1, errCode); } + +/** + * @tc.name: RdbStore_Distributed_Test_004 + * @tc.desc: Abnormal testCase of SetDistributedTables + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreDistributedTest, RdbStore_Distributed_Test_004, TestSize.Level2) +{ + int errCode; + std::vector tables; + OHOS::DistributedRdb::DistributedConfig distributedConfig; + + // if tabels empty, return ok + errCode = rdbStore->SetDistributedTables(tables, 1, distributedConfig); + EXPECT_EQ(E_OK, errCode); + + // if tabels not empty, IPC_SEND failed + tables.push_back("employee"); + errCode = rdbStore->SetDistributedTables(tables, 1, distributedConfig); + EXPECT_NE(E_OK, errCode); + + std::string path = RdbStoreDistributedTest::DRDB_PATH + "test.db"; + RdbStoreConfig config(path); + TestOpenCallback callback; + std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, callback, errCode); + EXPECT_NE(nullptr, store); + + // if tabels not empty, bundleName empty + errCode = store->SetDistributedTables(tables, 1, distributedConfig); + EXPECT_EQ(E_INVALID_ARGS, errCode); + + RdbHelper::DeleteRdbStore(path); +} + +/** + * @tc.name: RdbStore_Distributed_Test_005 + * @tc.desc: Normal testCase of Sync + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreDistributedTest, RdbStore_Distributed_Test_005, TestSize.Level2) +{ + int errCode; + OHOS::DistributedRdb::SyncOption option = { OHOS::DistributedRdb::TIME_FIRST, false }; + AbsRdbPredicates predicate("employee"); + std::vector tables; + + // get rdb service succeeded, if configuration file has already been configured + errCode = rdbStore->Sync(option, predicate, nullptr); + EXPECT_EQ(E_OK, errCode); + + errCode = rdbStore->Sync(option, tables, nullptr); + EXPECT_EQ(E_OK, errCode); + + std::string path = RdbStoreDistributedTest::DRDB_PATH + "test.db"; + RdbStoreConfig config(path); + TestOpenCallback callback; + std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, callback, errCode); + EXPECT_NE(nullptr, store); + + // get rdb service failed, if not configured + errCode = store->Sync(option, predicate, nullptr); + EXPECT_EQ(E_INVALID_ARGS, errCode); + errCode = store->Sync(option, tables, nullptr); + EXPECT_EQ(E_INVALID_ARGS, errCode); + + RdbHelper::DeleteRdbStore(path); +} \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp b/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp index 808e483022df9b9c62a558a0c0259fb55d186e6e..c56bbf578bda63d2880f464b2526f697389f1fd5 100644 --- a/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp @@ -242,3 +242,44 @@ HWTEST_F(RdbExecuteTest, RdbStore_Execute_003, TestSize.Level1) EXPECT_EQ(ret, E_OK); EXPECT_EQ(journalMode, "wal"); } + +/** + * @tc.name: RdbStore_Execute_004 + * @tc.desc: Abnormal testCase for ExecuteAndGetString, if sqlstatementtype is special + * @tc.type: FUNC + */ +HWTEST_F(RdbExecuteTest, RdbStore_Execute_004, TestSize.Level4) +{ + std::shared_ptr &store = RdbExecuteTest::store; + + std::string outValue; + int ret = store->ExecuteAndGetString(outValue, "BEGIN;"); + EXPECT_NE(E_OK, ret); +} + +/** + * @tc.name: RdbStore_Execute_005 + * @tc.desc: Abnormal testCase for ExecuteForLastInsertedRowId, if sql is invalid + * @tc.type: FUNC + * @tc.type: FUNC + */ +HWTEST_F(RdbExecuteTest, RdbStore_Execute_005, TestSize.Level4) +{ + std::shared_ptr &store = RdbExecuteTest::store; + int64_t outValue; + int ret = store->ExecuteForLastInsertedRowId(outValue, "", {}); + EXPECT_NE(E_OK, ret); +} + +/** + * @tc.name: RdbStore_Execute_006 + * @tc.desc: Abnormal testCase for ExecuteForChangedRowCount, if sql is invalid + * @tc.type: FUNC + */ +HWTEST_F(RdbExecuteTest, RdbStore_Execute_006, TestSize.Level4) +{ + std::shared_ptr &store = RdbExecuteTest::store; + int64_t outValue; + int ret = store->ExecuteForChangedRowCount(outValue, "", {}); + EXPECT_NE(E_OK, ret); +} \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/rdb_open_callback_test.cpp b/relational_store/test/native/rdb/unittest/rdb_open_callback_test.cpp index 8caf0e3306ce0be495f07cc66f3aed13dde08792..00c565841a6841c72b536874a1157d2e234be3ba 100644 --- a/relational_store/test/native/rdb/unittest/rdb_open_callback_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_open_callback_test.cpp @@ -25,8 +25,8 @@ #include "rdb_helper.h" using namespace testing::ext; -using namespace OHOS::NativeRdb; using namespace OHOS::Rdb; +using namespace OHOS::NativeRdb; class RdbOpenCallbackTest : public testing::Test { public: diff --git a/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp b/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp index 394e7cd7462b1af108985f5f26107183c3c001d8..8a2e406e91400de32e8d8398e08253e833dac1e9 100644 --- a/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp @@ -692,8 +692,7 @@ void RdbStorePredicateTest::BasicDataTypeTest(RdbPredicates predicates1) EXPECT_EQ(3, valueInt); predicates1.Clear(); - std::vector blob = {1, 2, 3}; - predicates1.EqualTo("blobValue", blob); + predicates1.EqualTo("blobValue", std::vector{1, 2, 3}); std::shared_ptr allDataTypes9 = RdbStorePredicateTest::store->Query(predicates1, columns); int count = 0; allDataTypes9->GetRowCount(count); @@ -929,6 +928,12 @@ HWTEST_F(RdbStorePredicateTest, RdbStore_GreaterThanOrEqualTo_006, TestSize.Leve predicates1.GreaterThanOrEqualTo("timeValue", std::to_string(calendarTime).c_str()); std::shared_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); EXPECT_EQ(3, ResultSize(allDataTypes6)); + + // Abnormal testCase of RdbPredicates for GreaterThanOrEqualTo if field is empty + predicates1.Clear(); + predicates1.GreaterThanOrEqualTo("", "1"); + std::shared_ptr allDataTypes7 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes7)); } /* * @@ -1685,6 +1690,35 @@ HWTEST_F(RdbStorePredicateTest, RdbStore_GetDistributedPredicates_027, TestSize. EXPECT_EQ(distributedRdbPredicates.operations_[0].values_[0], "ABCDEFGHIJKLMN"); } +/* * + * @tc.name: RdbStore_NotInMethod_028 + * @tc.desc: Abnormal testCase of RdbPredicates for notIn method + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_NotInMethod_028, TestSize.Level1) +{ + std::vector columns; + std::vector arg; + int count = 0; + + // RdbPredicates field is empty + RdbPredicates rdbPredicates1("AllDataType"); + rdbPredicates1.NotIn("", arg); + std::shared_ptr resultSet1 = RdbStorePredicateTest::store->Query(rdbPredicates1, columns); + resultSet1->GetRowCount(count); + EXPECT_EQ(3, count); + resultSet1->Close(); + + // RdbPredicates values is empty + RdbPredicates rdbPredicates2("AllDataType"); + rdbPredicates2.NotIn("integerValue", arg); + std::shared_ptr resultSet2 = RdbStorePredicateTest::store->Query(rdbPredicates2, columns); + resultSet2->GetRowCount(count); + EXPECT_EQ(3, count); + resultSet2->Close(); +} + /* * * @tc.name: RdbStore_EndWrap_001 * @tc.desc: Abnormal testCase of RdbPredicates for EndWrap, fail to add ')' @@ -1957,6 +1991,23 @@ HWTEST_F(RdbStorePredicateTest, RdbStore_OrderByDesc_001, TestSize.Level1) allDataTypes->Close(); } +/* * + * @tc.name: RdbStore_OrderByDesc_002 + * @tc.desc: Normal testCase of RdbPredicates for OrderByDesc + * @tc.type: FUNC + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_OrderByDesc_002, TestSize.Level2) +{ + RdbPredicates predicates("AllDataType"); + predicates.OrderByDesc("id"); + predicates.OrderByDesc("integerValue"); + + std::vector columns; + std::shared_ptr allDataTypes = RdbStorePredicateTest::store->Query(predicates, columns); + EXPECT_EQ(3, ResultSize(allDataTypes)); + allDataTypes->Close(); +} + /* * * @tc.name: RdbStore_OrderByAsc_001 * @tc.desc: Abnormal testCase of RdbPredicates for OrderByAsc, if field is '' @@ -1973,6 +2024,23 @@ HWTEST_F(RdbStorePredicateTest, RdbStore_OrderByAsc_001, TestSize.Level1) allDataTypes->Close(); } +/* * + * @tc.name: RdbStore_OrderByAsc_002 + * @tc.desc: Normal testCase of RdbPredicates for OrderByAsc + * @tc.type: FUNC + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_OrderByAsc_002, TestSize.Level2) +{ + RdbPredicates predicates("AllDataType"); + predicates.OrderByAsc("id"); + predicates.OrderByAsc("integerValue"); + + std::vector columns; + std::shared_ptr allDataTypes = RdbStorePredicateTest::store->Query(predicates, columns); + EXPECT_EQ(3, ResultSize(allDataTypes)); + allDataTypes->Close(); +} + /* * * @tc.name: RdbStore_Limit_001 * @tc.desc: Abnormal testCase of RdbPredicates for OrderByAsc, if set limit param twice @@ -2061,6 +2129,22 @@ HWTEST_F(RdbStorePredicateTest, RdbStore_GroupBy_002, TestSize.Level1) allDataTypes->Close(); } +/* * + * @tc.name: RdbStore_GroupBy_003 + * @tc.desc: Abnormal testCase of RdbPredicates for GroupBy, if fields is invalid + * @tc.type: FUNC + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_GroupBy_003, TestSize.Level1) +{ + RdbPredicates predicates("AllDataType"); + predicates.GroupBy({""}); + + std::vector columns; + std::shared_ptr allDataTypes = RdbStorePredicateTest::store->Query(predicates, columns); + EXPECT_EQ(3, ResultSize(allDataTypes)); + allDataTypes->Close(); +} + /* * * @tc.name: RdbStore_IndexedBy_001 * @tc.desc: Abnormal testCase of RdbPredicates for IndexedBy, if field is '' diff --git a/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp b/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp index 8db62591c97d273d2af94ff546b73becc04e7ace..577a3e799cf18d06a84239084f9ed252306b12dd 100644 --- a/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp @@ -25,8 +25,8 @@ #include "unistd.h" using namespace testing::ext; -using namespace OHOS::NativeRdb; using namespace OHOS::Rdb; +using namespace OHOS::NativeRdb; class RdbStoreConfigTest : public testing::Test { public: diff --git a/relational_store/test/native/rdb/unittest/rdb_store_impl_test.cpp b/relational_store/test/native/rdb/unittest/rdb_store_impl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69990fa8bc1fa7251bd993e903e42bfd999404ce --- /dev/null +++ b/relational_store/test/native/rdb/unittest/rdb_store_impl_test.cpp @@ -0,0 +1,486 @@ +/* + * 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 + +#include +#include + +#include "common.h" +#include "rdb_errno.h" +#include "rdb_helper.h" +#include "rdb_open_callback.h" +#include "rdb_store_impl.h" +#include "sqlite_connection.h" + +using namespace testing::ext; +using namespace OHOS::NativeRdb; + +class RdbStoreImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static const std::string DATABASE_NAME; + static std::shared_ptr store; +}; + +const std::string RdbStoreImplTest::DATABASE_NAME = RDB_TEST_PATH + "stepResultSet_impl_test.db"; +std::shared_ptr RdbStoreImplTest::store = nullptr; + +class RdbStoreImplTestOpenCallback : public RdbOpenCallback { +public: + int OnCreate(RdbStore &store) override; + int OnUpgrade(RdbStore &store, int oldVersion, int newVersion) override; +}; + +int RdbStoreImplTestOpenCallback::OnCreate(RdbStore &store) +{ + return E_OK; +} + +int RdbStoreImplTestOpenCallback::OnUpgrade(RdbStore &store, int oldVersion, int newVersion) +{ + return E_OK; +} + +void RdbStoreImplTest::SetUpTestCase(void) +{ + int errCode = E_OK; + RdbHelper::DeleteRdbStore(DATABASE_NAME); + RdbStoreConfig config(RdbStoreImplTest::DATABASE_NAME); + RdbStoreImplTestOpenCallback helper; + RdbStoreImplTest::store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(RdbStoreImplTest::store, nullptr); + EXPECT_EQ(errCode, E_OK); +} + +void RdbStoreImplTest::TearDownTestCase(void) +{ + RdbHelper::ClearCache(); + RdbHelper::DeleteRdbStore(RdbStoreImplTest::DATABASE_NAME); +} + +void RdbStoreImplTest::SetUp(void) {} + +void RdbStoreImplTest::TearDown(void) {} + + +/* * + * @tc.name: GetModifyTimeByRowIdTest_001 + * @tc.desc: Normal testCase for GetModifyTime, get timestamp by id + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, GetModifyTimeByRowIdTest_001, TestSize.Level2) +{ + RdbStoreImplTest::store->ExecuteSql("CREATE TABLE naturalbase_rdb_aux_rdbstoreimpltest_integer_log " + "(id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER, data_key INTEGER, " + "data3 FLOAT, data4 BLOB, data5 BOOLEAN);"); + int64_t rowId; + ValuesBucket valuesBucket; + valuesBucket.PutInt("data_key", ValueObject(1)); + valuesBucket.PutInt("timestamp", ValueObject(1000000000)); + int errorCode = RdbStoreImplTest::store->Insert(rowId, + "naturalbase_rdb_aux_rdbstoreimpltest_integer_log", valuesBucket); + EXPECT_EQ(E_OK, errorCode); + EXPECT_EQ(1, rowId); + + std::vector PKey = {1}; + auto result = RdbStoreImplTest::store->GetModifyTime("rdbstoreimpltest_integer", "ROWID", PKey); + int size = result.size(); + EXPECT_EQ(1, size); + EXPECT_EQ(100000, int64_t(result[1])); + + RdbStoreImplTest::store->ExecuteSql("DROP TABLE IF EXISTS naturalbase_rdb_aux_rdbstoreimpltest_integer_log"); +} + + +/* * + * @tc.name: GetModifyTimeByRowIdTest_002 + * @tc.desc: Abnormal testCase for GetModifyTime, get timestamp by id, + * resultSet is empty or table name is not exist + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, GetModifyTimeByRowIdTest_002, TestSize.Level2) +{ + RdbStoreImplTest::store->ExecuteSql("CREATE TABLE naturalbase_rdb_aux_rdbstoreimpltest_integer_log " + "(id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER, data_key INTEGER, " + "data3 FLOAT, data4 BLOB, data5 BOOLEAN);"); + int64_t rowId; + ValuesBucket valuesBucket; + valuesBucket.PutInt("data_key", ValueObject(2)); + int errorCode = RdbStoreImplTest::store->Insert(rowId, + "naturalbase_rdb_aux_rdbstoreimpltest_integer_log", valuesBucket); + EXPECT_EQ(E_OK, errorCode); + EXPECT_EQ(1, rowId); + + // resultSet is empty + std::vector PKey = {1}; + auto result = RdbStoreImplTest::store->GetModifyTime("rdbstoreimpltest_integer", "ROWID", PKey); + int size = result.size(); + EXPECT_EQ(0, size); + + // table name is not exist , resultSet is null + result = RdbStoreImplTest::store->GetModifyTime("test", "ROWID", PKey); + size = result.size(); + EXPECT_EQ(0, size); + + RdbStoreImplTest::store->ExecuteSql("DROP TABLE IF EXISTS naturalbase_rdb_aux_rdbstoreimpltest_integer_log"); +} + +/* * + * @tc.name: GetModifyTime_001 + * @tc.desc: Abnormal testCase for GetModifyTime, tablename columnName, keys is empty, + * and resultSet is null or empty + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, GetModifyTime_001, TestSize.Level2) +{ + RdbStoreImplTest::store->ExecuteSql("CREATE TABLE naturalbase_rdb_aux_rdbstoreimpltest_integer_log " + "(id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER, data_key INTEGER, " + "data3 FLOAT, data4 BLOB, data5 BOOLEAN);"); + + // table name is "" + std::vector PKey = {1}; + std::map result = RdbStoreImplTest::store->GetModifyTime("", "data_key", PKey); + int size = result.size(); + EXPECT_EQ(0, size); + + // table name is not exist , query resultSet is null + result = RdbStoreImplTest::store->GetModifyTime("test", "data_key", PKey); + size = result.size(); + EXPECT_EQ(0, size); + + // columnName is "" + result = RdbStoreImplTest::store->GetModifyTime("test", "", PKey); + size = result.size(); + EXPECT_EQ(0, size); + + // keys is empty + std::vector emptyPRIKey; + result = RdbStoreImplTest::store->GetModifyTime("test", "data_key", emptyPRIKey); + size = result.size(); + EXPECT_EQ(0, size); + + RdbStoreImplTest::store->ExecuteSql("DROP TABLE IF EXISTS naturalbase_rdb_aux_rdbstoreimpltest_integer_log"); +} + +/* * + * @tc.name: GetModifyTime_002 + * @tc.desc: Abnormal testCase for GetModifyTime, get timestamp by data3 ,if query resultSet is empty + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, GetModifyTime_002, TestSize.Level2) +{ + RdbStoreImplTest::store->ExecuteSql("CREATE TABLE naturalbase_rdb_aux_rdbstoreimpltest_integer_log " + "(id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER, hash_key INTEGER, " + "data3 FLOAT, data4 BLOB, data5 BOOLEAN);"); + + std::vector PKey = {1}; + auto result = RdbStoreImplTest::store->GetModifyTime("rdbstoreimpltest_integer", "data3", PKey); + int size = result.size(); + EXPECT_EQ(0, size); + + RdbStoreImplTest::store->ExecuteSql("DROP TABLE IF EXISTS naturalbase_rdb_aux_rdbstoreimpltest_integer_log"); +} + +/* * + * @tc.name: Rdb_BatchInsertTest_001 + * @tc.desc: Abnormal testCase for BatchInsert, if initialBatchValues is empty + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_BatchInsertTest_001, TestSize.Level2) +{ + std::vector valuesBuckets; + int64_t insertNum = 1; + int ret = store->BatchInsert(insertNum, "test", valuesBuckets); + EXPECT_EQ(0, insertNum); + EXPECT_EQ(E_OK, ret); +} + +/* * + * @tc.name: Rdb_QueryTest_001 + * @tc.desc: Abnormal testCase for Query, if table name is empty + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_QueryTest_001, TestSize.Level2) +{ + int errCode = E_OK; + RdbStoreImplTest::store->Query(errCode, true, "", {}, "", + std::vector {}, "", "", "", 1, 0); + EXPECT_NE(E_OK, errCode); +} + +/* * + * @tc.name: Rdb_QueryTest_002 + * @tc.desc: Normal testCase for Query, get * form test + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_QueryTest_002, TestSize.Level2) +{ + store->ExecuteSql("CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, data1 TEXT, " + "data2 INTEGER, data3 FLOAT, data4 BLOB, data5 BOOLEAN);"); + int errCode = E_OK; + RdbStoreImplTest::store->Query(errCode, true, "test", {}, + "", std::vector {}, "", "", "", 1, 0); + EXPECT_EQ(E_OK, errCode); + + store->ExecuteSql("DROP TABLE IF EXISTS test"); +} + +/* * + * @tc.name: Rdb_RemoteQueryTest_001 + * @tc.desc: Abnormal testCase for RemoteQuery + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_RemoteQueryTest_001, TestSize.Level2) +{ + int errCode = E_OK; + AbsRdbPredicates predicates("test"); + predicates.EqualTo("id", 1); + + // GetRdbService failed if rdbstoreconfig bundlename_ empty + auto ret = RdbStoreImplTest::store->RemoteQuery("", predicates, {}, errCode); + EXPECT_EQ(E_INVALID_ARGS, errCode); + EXPECT_EQ(nullptr, ret); + RdbHelper::DeleteRdbStore(RdbStoreImplTest::DATABASE_NAME); + + RdbStoreConfig config(RdbStoreImplTest::DATABASE_NAME); + config.SetName("RdbStore_impl_test.db"); + config.SetBundleName("com.example.distributed.rdb"); + RdbStoreImplTestOpenCallback helper; + std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_EQ(E_OK, errCode); + + // GetRdbService succeeded if configuration file has already been configured + ret = RdbStoreImplTest::store->RemoteQuery("", predicates, {}, errCode); + EXPECT_NE(E_OK, errCode); + EXPECT_EQ(nullptr, ret); + + RdbHelper::DeleteRdbStore(RdbStoreImplTest::DATABASE_NAME); +} + +/* * + * @tc.name: Rdb_RollbackTest_001 + * @tc.desc: Abnormal testCase for Rollback + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_RollbackTest_001, TestSize.Level2) +{ + int ret = RdbStoreImplTest::store->RollBack(); + EXPECT_EQ(OHOS::NativeRdb::E_NO_TRANSACTION_IN_SESSION, ret); +} + +/* * + * @tc.name: Rdb_CommitTest_001 + * @tc.desc: Abnormal testCase for Commit,if not use BeginTransaction + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_CommitTest_001, TestSize.Level2) +{ + int ret = RdbStoreImplTest::store->Commit(); + EXPECT_EQ(E_OK, ret); +} + +/* * + * @tc.name: Rdb_BackupTest_001 + * @tc.desc: Abnormal testCase for Backup + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_BackupTest_001, TestSize.Level2) +{ + int errCode = E_OK; + std::string databasePath = RDB_TEST_PATH + "test.db"; + std::vector destEncryptKey; + // isEncrypt_ is false, and destEncryptKey is emtpy + errCode = RdbStoreImplTest::store->Backup(databasePath, destEncryptKey); + EXPECT_EQ(E_OK, errCode); + RdbHelper::DeleteRdbStore(databasePath); + + // isEncrypt_ is false, and destEncryptKey is not emtpy + destEncryptKey.push_back(1); + errCode = RdbStoreImplTest::store->Backup(databasePath, destEncryptKey); + EXPECT_EQ(E_OK, errCode); + RdbHelper::DeleteRdbStore(DATABASE_NAME); + RdbHelper::DeleteRdbStore(databasePath); + + RdbStoreConfig config(RdbStoreImplTest::DATABASE_NAME); + config.SetEncryptStatus(true); + RdbStoreImplTestOpenCallback helper; + std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_EQ(E_OK, errCode); + + // isEncrypt_ is true, and destEncryptKey is not emtpy + errCode = RdbStoreImplTest::store->Backup(databasePath, destEncryptKey); + EXPECT_EQ(E_OK, errCode); + RdbHelper::DeleteRdbStore(databasePath); + + // isEncrypt_ is true, and destEncryptKey is not emtpy + destEncryptKey.pop_back(); + errCode = RdbStoreImplTest::store->Backup(databasePath, destEncryptKey); + EXPECT_EQ(E_OK, errCode); + RdbHelper::DeleteRdbStore(databasePath); + RdbHelper::DeleteRdbStore(DATABASE_NAME); +} + +/* * + * @tc.name: Rdb_SqlitConnectionTest_001 + * @tc.desc: Abnormal testCase for SetPageSize, + * return ok if open db again and set same page size + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_SqlitConnectionTest_001, TestSize.Level2) +{ + const std::string DATABASE_NAME = RDB_TEST_PATH + "SqlitConnectionOpenTest.db"; + int errCode = E_OK; + RdbStoreConfig config(DATABASE_NAME); + config.SetReadOnly(false); + config.SetPageSize(1024); + SqliteConnection* connection = SqliteConnection::Open(config, true, errCode); + EXPECT_NE(nullptr, connection); + int64_t value = 0; + errCode = connection->ExecuteGetLong(value, "PRAGMA page_size"); + EXPECT_EQ(E_OK, errCode); + EXPECT_EQ(1024, value); + + auto tmp = SqliteConnection::Open(config, true, errCode); + EXPECT_NE(nullptr, tmp); +} + +#ifdef RDB_SUPPORT_ICU +/* * + * @tc.name: Rdb_SqlitConnectionPoolTest_001 + * @tc.desc: Abnormal testCase for ConfigLocale + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_SqlitConnectionPoolTest_001, TestSize.Level2) +{ + const std::string DATABASE_NAME = RDB_TEST_PATH + "SqlitConnectionOpenTest.db"; + int errCode = E_OK; + RdbStoreConfig config(DATABASE_NAME); + config.SetReadConSize(1); + config.SetStorageMode(StorageMode::MODE_DISK); + + RdbStoreImplTestOpenCallback helper; + std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_EQ(E_OK, errCode); + + // error condition does not affect the current program + errCode = store->ConfigLocale("AbnormalTest"); + EXPECT_EQ(E_OK, errCode); + + SqliteConnectionPool* connectionPool = SqliteConnectionPool::Create(config, errCode); + EXPECT_NE(nullptr, connectionPool); + EXPECT_EQ(E_OK, errCode); + + // connecting database + auto connection = connectionPool->AcquireConnection(true); + EXPECT_NE(nullptr, connection); + errCode = connectionPool->ConfigLocale("AbnormalTest"); + EXPECT_EQ(OHOS::NativeRdb::E_NO_ROW_IN_QUERY, errCode); + + RdbHelper::DeleteRdbStore(DATABASE_NAME); + connectionPool->ReleaseConnection(connection); + delete connectionPool; +} +#endif + +/* * + * @tc.name: Rdb_SqlitConnectionPoolTest_002 + * @tc.desc: Abnormal testCase for AcquireConnection/AcquireTransaction + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_SqlitConnectionPoolTest_002, TestSize.Level2) +{ + const std::string DATABASE_NAME = RDB_TEST_PATH + "SqlitConnectionTest.db"; + int errCode = E_OK; + RdbStoreConfig config(DATABASE_NAME); + config.SetReadConSize(1); + config.SetStorageMode(StorageMode::MODE_DISK); + SqliteConnectionPool* connectionPool = SqliteConnectionPool::Create(config, errCode); + EXPECT_NE(nullptr, connectionPool); + EXPECT_EQ(E_OK, errCode); + + // repeat AcquireReadConnection without release + auto connection = connectionPool->AcquireConnection(true); + EXPECT_NE(nullptr, connection); + connection = connectionPool->AcquireConnection(true); + EXPECT_EQ(nullptr, connection); + connectionPool->ReleaseConnection(connection); + + // repeat AcquireWriteConnection without release + connection = connectionPool->AcquireConnection(false); + EXPECT_NE(nullptr, connection); + connection = connectionPool->AcquireConnection(false); + EXPECT_EQ(nullptr, connection); + connectionPool->ReleaseConnection(connection); + + // repeat AcquireTransaction without release + errCode = connectionPool->AcquireTransaction(); + EXPECT_EQ(E_OK, errCode); + errCode = connectionPool->AcquireTransaction(); + EXPECT_NE(E_OK, errCode); + connectionPool->ReleaseTransaction(); + + delete connectionPool; +} + + +/* * + * @tc.name: Rdb_SqlitConnectionPoolTest_003 + * @tc.desc: Abnormal testCase for ChangeDbFileForRestore + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_SqlitConnectionPoolTest_0023, TestSize.Level2) +{ + const std::string DATABASE_NAME = RDB_TEST_PATH + "SqlitConnectionTest.db"; + int errCode = E_OK; + RdbStoreConfig config(DATABASE_NAME); + config.SetReadConSize(1); + config.SetStorageMode(StorageMode::MODE_DISK); + SqliteConnectionPool* connectionPool = SqliteConnectionPool::Create(config, errCode); + EXPECT_NE(nullptr, connectionPool); + EXPECT_EQ(E_OK, errCode); + + + const std::string newPath = DATABASE_NAME; + const std::string backupPath = DATABASE_NAME; + const std::vector newKey; + + // newPath == currentPath, writeConnectionUsed == true + auto connection = connectionPool->AcquireConnection(false); + errCode = connectionPool->ChangeDbFileForRestore(newPath, backupPath, newKey); + EXPECT_EQ(E_ERROR, errCode); + connectionPool->ReleaseConnection(connection); + + // newPath == currentPath, idleReadConnectionCount != readConnectionCount + connection = connectionPool->AcquireConnection(true); + errCode = connectionPool->ChangeDbFileForRestore(newPath, backupPath, newKey); + EXPECT_EQ(E_ERROR, errCode); + connectionPool->ReleaseConnection(connection); + + + // newPath == currentPath + errCode = connectionPool->ChangeDbFileForRestore(newPath, backupPath, newKey); + EXPECT_NE(E_OK, errCode); + // newPath != currentPath + const std::string newPath2 = RDB_TEST_PATH + "tmp.db"; + errCode = connectionPool->ChangeDbFileForRestore(newPath2, backupPath, newKey); + EXPECT_EQ(E_ERROR, errCode); + + delete connectionPool; +} diff --git a/relational_store/test/native/rdb/unittest/rdb_utils_test.cpp b/relational_store/test/native/rdb/unittest/rdb_utils_test.cpp index 6a8456104f1eb34dce299685aa35d42504c616fc..c4603eb73a09d0f918e023156528c483a9d9d99f 100644 --- a/relational_store/test/native/rdb/unittest/rdb_utils_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_utils_test.cpp @@ -70,3 +70,23 @@ HWTEST_F(RdbUtilsTest, RdbStore_SqliteUtils_003, TestSize.Level2) { EXPECT_EQ("abc***", SqliteUtils::Anonymous("abc/def")); } + +/** + * @tc.name: RdbStore_SqliteUtils_004 + * @tc.desc: Abnormal testCase of string_utils for SurroundWithQuote, if value is "" + * @tc.type: FUNC + */ +HWTEST_F(RdbUtilsTest, RdbStore_SqliteUtils_004, TestSize.Level2) +{ + EXPECT_EQ("", StringUtils::SurroundWithQuote("", "\"")); +} + +/** + * @tc.name: RdbStore_SqliteUtils_005 + * @tc.desc: Normal testCase of string_utils for SurroundWithQuote + * @tc.type: FUNC + */ +HWTEST_F(RdbUtilsTest, RdbStore_SqliteUtils_005, TestSize.Level1) +{ + EXPECT_EQ("\"AND\"", StringUtils::SurroundWithQuote("AND", "\"")); +} diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 276b2813a900555090beb9dcf53e59457cbacac8..ebc80fba26981a29386ee0fcdbae9688dfc90d59 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -99,30 +99,30 @@ target_include_directories(PerferencesTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/. target_include_directories(PerferencesTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../preferences/frameworks/native/platform/include) #************************************************PerferencesTest end************************************************# -#************************************************dataShareTest start************************************************# +#************************************************DataShareTest start************************************************# file(GLOB_RECURSE dataShareTestSrc ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/test/native/unittest/*.cpp) -add_executable(dataShareTest ${dataShareTestSrc} ${mainSrc} ${serviceSrc}) -target_link_libraries(dataShareTest ${links} gtest_main gcov data_share) -target_include_directories(dataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/common/include) -target_include_directories(dataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/test/native/unittest/mediadatashare_test/include) -target_include_directories(dataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/consumer/controller/common) -target_include_directories(dataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/consumer/controller/provider/include) -target_include_directories(dataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/consumer/controller/service/include) -target_include_directories(dataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/consumer/include) -target_include_directories(dataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/provider/include) -target_include_directories(dataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/proxy/include) -#************************************************dataShareTest end************************************************# +add_executable(DataShareTest ${dataShareTestSrc} ${mainSrc} ${serviceSrc}) +target_link_libraries(DataShareTest ${links} gtest_main gcov data_share) +target_include_directories(DataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/common/include) +target_include_directories(DataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/test/native/unittest/mediadatashare_test/include) +target_include_directories(DataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/consumer/controller/common) +target_include_directories(DataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/consumer/controller/provider/include) +target_include_directories(DataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/consumer/controller/service/include) +target_include_directories(DataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/consumer/include) +target_include_directories(DataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/provider/include) +target_include_directories(DataShareTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_share/frameworks/native/proxy/include) +#************************************************DataShareTest end************************************************# -#************************************************dataObjectTest start************************************************# +#************************************************DataObjectTest start************************************************# aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/test/unittest/mock/src dataObjectTestSrc) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/test/unittest/src dataObjectTestSrc) -add_executable(dataObjectTest ${dataObjectTestSrc} ${mainSrc} ${serviceSrc}) -target_link_libraries(dataObjectTest ${links} gtest_main gcov data_object distributeddb) -target_include_directories(dataObjectTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/include/adaptor) -target_include_directories(dataObjectTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/include/common) -target_include_directories(dataObjectTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/include/communicator) -target_include_directories(dataObjectTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/test/unittest/mock/include) -#************************************************dataObjectTest end************************************************# +add_executable(DataObjectTest ${dataObjectTestSrc} ${mainSrc} ${serviceSrc}) +target_link_libraries(DataObjectTest ${links} gtest_main gcov data_object distributeddb) +target_include_directories(DataObjectTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/include/adaptor) +target_include_directories(DataObjectTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/include/common) +target_include_directories(DataObjectTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/include/communicator) +target_include_directories(DataObjectTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/test/unittest/mock/include) +#************************************************DataObjectTest end************************************************# #************************************************UdmfTest start************************************************# aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../udmf/framework/innerkitsimpl/test/unittest UdmfTestSrc) diff --git a/udmf/README_zh.md b/udmf/README_zh.md index 4b8036d809aaccf5373aa020bdfc704bc0b2c646..24cd95f3f9394bf9d3ee53f7f11855472cbb0def 100644 --- a/udmf/README_zh.md +++ b/udmf/README_zh.md @@ -73,11 +73,6 @@ foundation/distributeddatamgr/udmf # udmf统一数据管理部件 │ │ ├── common # js接口公共工具类 │ │ |── data # 统一数据公共接口实现 | | └── unittest # js单元测试目录 -│ ├── manager # 数据管理核心类 -| | ├── lifecycle # 生命周期管理 -| | ├── permission # 权限管理 -│ │ ├── preprocess # 预处理 -│ │ └── store # 存储策略 │ └── service # 服务模块 ├── interfaces # udmf对外接口声明 │ ├── innerkits # nativie接口声明 @@ -88,10 +83,6 @@ foundation/distributeddatamgr/udmf # udmf统一数据管理部件 │ ├── common # napi工具类声明 │ ├── data # napi数据封装声明 │ └── module # 统一数据模块注册 -├── service # udmf服务框架代码 -│ ├── include # 服务端声明 -│ ├── src # 服务端具体实现 -| └── test # 测试目录 ├── BUILD.gn # 编译配置文件 ├── bundle.json # 模块配置文件 ├── LICENSE # License文件