From f2b50cecc3f094889fd3186987ed4a4428a1dab7 Mon Sep 17 00:00:00 2001 From: htt1997 Date: Fri, 16 Dec 2022 16:56:17 +0800 Subject: [PATCH 001/191] =?UTF-8?q?rdb=E5=9B=9E=E8=BF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: htt1997 --- .../innerkitsimpl/rdb/include/irdb_service.h | 28 -- .../innerkitsimpl/rdb/include/rdb_manager.h | 32 -- .../innerkitsimpl/rdb/include/rdb_notifier.h | 83 ---- .../innerkitsimpl/rdb/include/rdb_service.h | 78 --- .../innerkitsimpl/rdb/include/rdb_types.h | 110 ----- .../rdb/include/rdb_types_util.h | 42 -- .../innerkitsimpl/rdb/src/rdb_manager.cpp | 24 - .../rdb/src/rdb_manager_impl.cpp | 149 ------ .../innerkitsimpl/rdb/src/rdb_manager_impl.h | 75 --- .../innerkitsimpl/rdb/src/rdb_notifier.cpp | 168 ------- .../rdb/src/rdb_service_proxy.cpp | 445 ------------------ .../innerkitsimpl/rdb/src/rdb_service_proxy.h | 94 ---- .../innerkitsimpl/rdb/src/rdb_types_util.cpp | 71 --- interfaces/innerkits/distributeddata/BUILD.gn | 12 +- 14 files changed, 1 insertion(+), 1410 deletions(-) delete mode 100644 frameworks/innerkitsimpl/rdb/include/irdb_service.h delete mode 100644 frameworks/innerkitsimpl/rdb/include/rdb_manager.h delete mode 100644 frameworks/innerkitsimpl/rdb/include/rdb_notifier.h delete mode 100644 frameworks/innerkitsimpl/rdb/include/rdb_service.h delete mode 100644 frameworks/innerkitsimpl/rdb/include/rdb_types.h delete mode 100644 frameworks/innerkitsimpl/rdb/include/rdb_types_util.h delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_manager.cpp delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h delete mode 100644 frameworks/innerkitsimpl/rdb/src/rdb_types_util.cpp diff --git a/frameworks/innerkitsimpl/rdb/include/irdb_service.h b/frameworks/innerkitsimpl/rdb/include/irdb_service.h deleted file mode 100644 index e820d704d6c..00000000000 --- a/frameworks/innerkitsimpl/rdb/include/irdb_service.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DISTRIBUTEDDATAFWK_IRDB_SERVICE_H -#define DISTRIBUTEDDATAFWK_IRDB_SERVICE_H - -#include - -#include -#include "rdb_service.h" -#include "rdb_types.h" -namespace OHOS::DistributedRdb { -class IRdbService : public RdbService, public IRemoteBroker { -}; -} // namespace OHOS::DistributedRdb -#endif diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_manager.h b/frameworks/innerkitsimpl/rdb/include/rdb_manager.h deleted file mode 100644 index a34dc828a53..00000000000 --- a/frameworks/innerkitsimpl/rdb/include/rdb_manager.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DISTRIBUTED_RDB_MANAGER_H -#define DISTRIBUTED_RDB_MANAGER_H - -#include -#include -#include - -#include "rdb_service.h" -#include "rdb_types.h" - -namespace OHOS::DistributedRdb { -class RdbManager { -public: - static std::shared_ptr GetRdbService(const RdbSyncerParam& param); -}; -} // namespace OHOS::DistributedRdb -#endif diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_notifier.h b/frameworks/innerkitsimpl/rdb/include/rdb_notifier.h deleted file mode 100644 index 7887ec9766c..00000000000 --- a/frameworks/innerkitsimpl/rdb/include/rdb_notifier.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DISTRIBUTED_RDB_NOTIFIER_H -#define DISTRIBUTED_RDB_NOTIFIER_H - -#include -#include -#include - -#include "rdb_types.h" - -namespace OHOS::DistributedRdb { -class IRdbNotifier : public IRemoteBroker { -public: - enum { - RDB_NOTIFIER_CMD_SYNC_COMPLETE, - RDB_NOTIFIER_CMD_DATA_CHANGE, - RDB_NOTIFIER_CMD_MAX - }; - - virtual int32_t OnComplete(uint32_t seqNum, const SyncResult& result) = 0; - - virtual int32_t OnChange(const std::string& storeName, const std::vector& devices) = 0; - - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedRdb.IRdbNotifier"); -}; - -class RdbNotifierProxy : public IRemoteProxy { -public: - explicit RdbNotifierProxy(const sptr& object); - virtual ~RdbNotifierProxy() noexcept; - - int32_t OnComplete(uint32_t seqNum, const SyncResult& result) override; - - int32_t OnChange(const std::string& storeName, const std::vector& devices) override; - -private: - static inline BrokerDelegator delegator_; -}; - -using RdbSyncCompleteNotifier = std::function; -using RdbDataChangeNotifier = std::function&)>; - -class RdbNotifierStub : public IRemoteStub { -public: - RdbNotifierStub(const RdbSyncCompleteNotifier&, const RdbDataChangeNotifier&); - virtual ~RdbNotifierStub() noexcept; - - int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; - - int32_t OnCompleteInner(MessageParcel& data, MessageParcel& reply); - int32_t OnComplete(uint32_t seqNum, const SyncResult& result) override; - - int32_t OnChangeInner(MessageParcel&data, MessageParcel& reply); - int32_t OnChange(const std::string& storeName, const std::vector& devices) override; - -private: - bool CheckInterfaceToken(MessageParcel& data); - - using RequestHandle = int32_t (RdbNotifierStub::*)(MessageParcel&, MessageParcel&); - static constexpr RequestHandle HANDLES[RDB_NOTIFIER_CMD_MAX] = { - [RDB_NOTIFIER_CMD_SYNC_COMPLETE] = &RdbNotifierStub::OnCompleteInner, - [RDB_NOTIFIER_CMD_DATA_CHANGE] = &RdbNotifierStub::OnChangeInner, - }; - - RdbSyncCompleteNotifier completeNotifier_; - RdbDataChangeNotifier changeNotifier_; -}; -} // namespace OHOS::DistributedRdb -#endif diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_service.h b/frameworks/innerkitsimpl/rdb/include/rdb_service.h deleted file mode 100644 index e21c99e0ad5..00000000000 --- a/frameworks/innerkitsimpl/rdb/include/rdb_service.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DISTRIBUTED_RDB_SERVICE_H -#define DISTRIBUTED_RDB_SERVICE_H - -#include -#include -#include "iremote_broker.h" -#include "iremote_object.h" -#include "rdb_types.h" - -namespace OHOS { -namespace DistributedRdb { -class RdbService { -public: - enum { - RDB_SERVICE_CMD_OBTAIN_TABLE, - RDB_SERVICE_CMD_INIT_NOTIFIER, - RDB_SERVICE_CMD_SET_DIST_TABLE, - RDB_SERVICE_CMD_SYNC, - RDB_SERVICE_CMD_ASYNC, - RDB_SERVICE_CMD_SUBSCRIBE, - RDB_SERVICE_CMD_UNSUBSCRIBE, - RDB_SERVICE_CMD_REMOTE_QUERY, - RDB_SERVICE_CREATE_RDB_TABLE, - RDB_SERVICE_DESTROY_RDB_TABLE, - RDB_SERVICE_CMD_MAX - }; - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedRdb.IRdbService"); - virtual std::string ObtainDistributedTableName(const std::string &device, const std::string &table) = 0; - - virtual int32_t SetDistributedTables(const RdbSyncerParam ¶m, const std::vector &tables) = 0; - - virtual int32_t Sync(const RdbSyncerParam ¶m, const SyncOption &option, const RdbPredicates &predicates, - const SyncCallback &callback) = 0; - - virtual int32_t Subscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, - RdbStoreObserver *observer) = 0; - - virtual int32_t UnSubscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, - RdbStoreObserver *observer) = 0; - - virtual int32_t RemoteQuery(const RdbSyncerParam ¶m, const std::string &device, const std::string &sql, - const std::vector &selectionArgs, sptr &resultSet) = 0; - virtual int32_t CreateRDBTable(const RdbSyncerParam ¶m, const std::string &writePermission, - const std::string &readPermission) = 0; - - virtual int32_t DestroyRDBTable(const RdbSyncerParam ¶m) = 0; - - virtual int32_t InitNotifier(const RdbSyncerParam ¶m, const sptr notifier) = 0; - -protected: - virtual int32_t DoSync(const RdbSyncerParam ¶m, const SyncOption &option, const RdbPredicates &predicates, - SyncResult &result) = 0; - - virtual int32_t DoAsync(const RdbSyncerParam ¶m, uint32_t seqNum, const SyncOption &option, - const RdbPredicates &predicates) = 0; - - virtual int32_t DoSubscribe(const RdbSyncerParam ¶m) = 0; - - virtual int32_t DoUnSubscribe(const RdbSyncerParam ¶m) = 0; -}; -} -} // namespace OHOS::DistributedRdb -#endif diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_types.h b/frameworks/innerkitsimpl/rdb/include/rdb_types.h deleted file mode 100644 index 998260ab248..00000000000 --- a/frameworks/innerkitsimpl/rdb/include/rdb_types.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DISTRIBUTEDDATAFWK_RDB_TYPES_H -#define DISTRIBUTEDDATAFWK_RDB_TYPES_H - -#include -#include -#include -#include - -namespace OHOS::DistributedRdb { -enum RdbStatus { - RDB_OK, - RDB_ERROR, -}; - -enum RdbDistributedType { - RDB_DEVICE_COLLABORATION = 10, - RDB_DISTRIBUTED_TYPE_MAX -}; - -struct RdbSyncerParam { - std::string bundleName_; - std::string hapName_; - std::string storeName_; - int32_t area_ = 0; - int32_t level_ = 0; - int32_t type_ = RDB_DEVICE_COLLABORATION; - bool isAutoSync_ = false; - bool isEncrypt_ = false; - std::vector password_; -}; - -enum SyncMode : int32_t { - PUSH, - PULL, -}; - -struct SyncOption { - SyncMode mode; - bool isBlock; -}; - -using SyncResult = std::map; // networkId -using SyncCallback = std::function; - -enum RdbPredicateOperator { - EQUAL_TO, - NOT_EQUAL_TO, - AND, - OR, - ORDER_BY, - LIMIT, - OPERATOR_MAX -}; - -struct RdbPredicateOperation { - RdbPredicateOperator operator_; - std::string field_; - std::vector values_; -}; - -struct RdbPredicates { - inline void AddOperation(const RdbPredicateOperator op, const std::string& field, - const std::string& value) - { - operations_.push_back({ op, field, { value } }); - } - inline void AddOperation(const RdbPredicateOperator op, const std::string& field, - const std::vector& values) - { - operations_.push_back({ op, field, values }); - } - - std::string table_; - std::vector devices_; - std::vector operations_; -}; - -enum SubscribeMode { - REMOTE, - SUBSCRIBE_MODE_MAX -}; - -struct SubscribeOption { - SubscribeMode mode; -}; - -class RdbStoreObserver { -public: - virtual void OnChange(const std::vector& devices) = 0; // networkid -}; - -struct DropOption { -}; -} // namespace OHOS::DistributedRdb -#endif diff --git a/frameworks/innerkitsimpl/rdb/include/rdb_types_util.h b/frameworks/innerkitsimpl/rdb/include/rdb_types_util.h deleted file mode 100644 index d63275fffb1..00000000000 --- a/frameworks/innerkitsimpl/rdb/include/rdb_types_util.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DISTRIBUTED_RDB_RDB_TYPES_UTIL_H -#define DISTRIBUTED_RDB_RDB_TYPES_UTIL_H -#include "itypes_util.h" -#include "rdb_types.h" -namespace OHOS::ITypesUtil { -using SyncerParam = DistributedRdb::RdbSyncerParam; -using SyncOption = DistributedRdb::SyncOption; -using RdbPredicates = DistributedRdb::RdbPredicates; -using RdbOperation = DistributedRdb::RdbPredicateOperation; -template<> -bool Marshalling(const SyncerParam &input, MessageParcel &data); -template<> -bool Unmarshalling(SyncerParam &output, MessageParcel &data); -template<> -bool Marshalling(const SyncOption &input, MessageParcel &data); -template<> -bool Unmarshalling(SyncOption &output, MessageParcel &data); -template<> -bool Marshalling(const RdbPredicates &input, MessageParcel &data); -template<> -bool Unmarshalling(RdbPredicates &output, MessageParcel &data); -template<> -bool Marshalling(const RdbOperation &input, MessageParcel &data); -template<> -bool Unmarshalling(RdbOperation &output, MessageParcel &data); -} -#endif // DISTRIBUTED_RDB_RDB_TYPES_UTIL_H diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_manager.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_manager.cpp deleted file mode 100644 index 76bddfc3e5a..00000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_manager.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "rdb_manager.h" -#include "rdb_manager_impl.h" - -namespace OHOS::DistributedRdb { -std::shared_ptr RdbManager::GetRdbService(const RdbSyncerParam& param) -{ - return RdbManagerImpl::GetInstance().GetRdbService(param); -} -} // namespace OHOS::DistributedRdb diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp deleted file mode 100644 index bd87ee4029e..00000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "RdbManagerImpl" - -#include "rdb_manager_impl.h" - -#include -#include "iservice_registry.h" -#include "ipc_skeleton.h" -#include "system_ability_definition.h" - -#include "log_print.h" -#include "ikvstore_data_service.h" -#include "irdb_service.h" -#include "rdb_service_proxy.h" - -namespace OHOS::DistributedRdb { -static sptr GetDistributedDataManager() -{ - int retry = 0; - while (++retry <= RdbManagerImpl::GET_SA_RETRY_TIMES) { - auto manager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (manager == nullptr) { - ZLOGE("get system ability manager failed"); - return nullptr; - } - ZLOGI("get distributed data manager %{public}d", retry); - auto remoteObject = manager->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); - if (remoteObject == nullptr) { - std::this_thread::sleep_for(std::chrono::seconds(RdbManagerImpl::RETRY_INTERVAL)); - continue; - } - ZLOGI("get distributed data manager success"); - return iface_cast(remoteObject); - } - - ZLOGE("get distributed data manager failed"); - return nullptr; -} - -static void LinkToDeath(const sptr& remote) -{ - auto& manager = RdbManagerImpl::GetInstance(); - sptr deathRecipient = - new(std::nothrow) RdbManagerImpl::ServiceDeathRecipient(&manager); - if (!remote->AddDeathRecipient(deathRecipient)) { - ZLOGE("add death recipient failed"); - } - ZLOGE("success"); -} - -RdbManagerImpl::RdbManagerImpl() -{ - ZLOGI("construct"); -} - -RdbManagerImpl::~RdbManagerImpl() -{ - ZLOGI("destroy"); -} - -RdbManagerImpl& RdbManagerImpl::GetInstance() -{ - static RdbManagerImpl manager; - return manager; -} - -sptr RdbManagerImpl::GetRdbService() -{ - if (distributedDataMgr_ == nullptr) { - distributedDataMgr_ = GetDistributedDataManager(); - } - if (distributedDataMgr_ == nullptr) { - ZLOGE("get distributed data manager failed"); - return nullptr; - } - - auto remote = distributedDataMgr_->GetFeatureInterface("relational_store"); - if (remote == nullptr) { - ZLOGE("get rdb service failed"); - return nullptr; - } - return iface_cast(remote); -} - -std::shared_ptr RdbManagerImpl::GetRdbService(const RdbSyncerParam& param) -{ - std::lock_guard lock(mutex_); - if (rdbService_ != nullptr) { - return rdbService_; - } - auto service = GetRdbService(); - if (service == nullptr) { - return nullptr; - } - if (service->InitNotifier(param) != RDB_OK) { - ZLOGE("init notifier failed"); - return nullptr; - } - sptr serviceBase = service; - LinkToDeath(serviceBase->AsObject().GetRefPtr()); - rdbService_ = std::shared_ptr(service.GetRefPtr(), [holder = service] (const auto*) {}); - bundleName_ = param.bundleName_; - return rdbService_; -} - -void RdbManagerImpl::OnRemoteDied() -{ - ZLOGI("rdb service has dead!!"); - auto proxy = std::static_pointer_cast(rdbService_); - auto observers = proxy->ExportObservers(); - ResetServiceHandle(); - - std::this_thread::sleep_for(std::chrono::seconds(WAIT_TIME)); - RdbSyncerParam param; - param.bundleName_ = bundleName_; - auto service = GetRdbService(param); - if (service == nullptr) { - return; - } - proxy = std::static_pointer_cast(service); - if (proxy == nullptr) { - return; - } - ZLOGI("restore observer"); - proxy->ImportObservers(observers); -} - -void RdbManagerImpl::ResetServiceHandle() -{ - ZLOGI("enter"); - std::lock_guard lock(mutex_); - distributedDataMgr_ = nullptr; - rdbService_ = nullptr; -} -} // namespace OHOS::DistributedRdb diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h b/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h deleted file mode 100644 index fd88e514f0e..00000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DISTRIBUTED_RDB_MANAGER_IMPL_H -#define DISTRIBUTED_RDB_MANAGER_IMPL_H - -#include -#include -#include - -#include "refbase.h" -#include "iremote_object.h" -#include "concurrent_map.h" -#include "rdb_types.h" - -namespace OHOS::DistributedKv { -class KvStoreDataServiceProxy; -} - -namespace OHOS::DistributedRdb { -class RdbService; -class RdbServiceProxy; -class RdbManagerImpl { -public: - static constexpr int GET_SA_RETRY_TIMES = 3; - static constexpr int RETRY_INTERVAL = 1; - static constexpr int WAIT_TIME = 2; - - static RdbManagerImpl &GetInstance(); - - std::shared_ptr GetRdbService(const RdbSyncerParam& param); - - void OnRemoteDied(); - - class ServiceDeathRecipient : public IRemoteObject::DeathRecipient { - public: - explicit ServiceDeathRecipient(RdbManagerImpl* owner) : owner_(owner) {} - void OnRemoteDied(const wptr &object) override - { - if (owner_ != nullptr) { - owner_->OnRemoteDied(); - } - } - private: - RdbManagerImpl* owner_; - }; - -private: - RdbManagerImpl(); - - ~RdbManagerImpl(); - - sptr GetRdbService(); - - void ResetServiceHandle(); - - std::mutex mutex_; - sptr distributedDataMgr_; - std::shared_ptr rdbService_; - std::string bundleName_; -}; -} // namespace OHOS::DistributedRdb -#endif diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp deleted file mode 100644 index bffd4c33ec1..00000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "RdbNotifier" - -#include "rdb_notifier.h" -#include -#include "itypes_util.h" -#include "log_print.h" - - -namespace OHOS::DistributedRdb { -RdbNotifierProxy::RdbNotifierProxy(const sptr &object) - : IRemoteProxy(object) -{ - ZLOGI("construct"); -} - -RdbNotifierProxy::~RdbNotifierProxy() noexcept -{ - ZLOGI("destroy"); -} - -int32_t RdbNotifierProxy::OnComplete(uint32_t seqNum, const SyncResult &result) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbNotifier::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return RDB_ERROR; - } - if (!data.WriteUint32(seqNum)) { - ZLOGE("write seq num failed"); - return RDB_ERROR; - } - if (!ITypesUtil::Marshalling(result, data)) { - return RDB_ERROR; - } - - MessageParcel reply; - MessageOption option(MessageOption::TF_ASYNC); - if (Remote()->SendRequest(RDB_NOTIFIER_CMD_SYNC_COMPLETE, data, reply, option) != 0) { - ZLOGE("send request failed"); - return RDB_ERROR; - } - return RDB_OK; -} - -int RdbNotifierProxy::OnChange(const std::string& storeName, const std::vector &devices) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbNotifier::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return RDB_ERROR; - } - if (!data.WriteString(storeName)) { - ZLOGE("write store name failed"); - return RDB_ERROR; - } - if (!data.WriteStringVector(devices)) { - ZLOGE("write devices failed"); - return RDB_ERROR; - } - - MessageParcel reply; - MessageOption option(MessageOption::TF_ASYNC); - if (Remote()->SendRequest(RDB_NOTIFIER_CMD_DATA_CHANGE, data, reply, option) != 0) { - ZLOGE("send request failed"); - return RDB_ERROR; - } - return RDB_OK; -} - -RdbNotifierStub::RdbNotifierStub(const RdbSyncCompleteNotifier& completeNotifier, - const RdbDataChangeNotifier& changeNotifier) - : IRemoteStub(), completeNotifier_(completeNotifier), changeNotifier_(changeNotifier) -{ - ZLOGI("construct"); -} - -RdbNotifierStub::~RdbNotifierStub() noexcept -{ - ZLOGI("destroy"); -} - -bool RdbNotifierStub::CheckInterfaceToken(MessageParcel& data) -{ - auto localDescriptor = IRdbNotifier::GetDescriptor(); - auto remoteDescriptor = data.ReadInterfaceToken(); - if (remoteDescriptor != localDescriptor) { - ZLOGE("interface token is not equal"); - return false; - } - return true; -} - -int RdbNotifierStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, - MessageOption &option) -{ - ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid()); - if (!CheckInterfaceToken(data)) { - return RDB_ERROR; - } - - if (code >= 0 && code < RDB_NOTIFIER_CMD_MAX) { - return (this->*HANDLES[code])(data, reply); - } - - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); -} - -int32_t RdbNotifierStub::OnCompleteInner(MessageParcel &data, MessageParcel &reply) -{ - uint32_t seqNum; - if (!data.ReadUint32(seqNum)) { - ZLOGI("read seq num failed"); - return RDB_ERROR; - } - SyncResult result; - if (!ITypesUtil::Unmarshal(data, result)) { - ZLOGE("read sync result failed"); - return RDB_ERROR; - } - return OnComplete(seqNum, result); -} - -int32_t RdbNotifierStub::OnComplete(uint32_t seqNum, const SyncResult &result) -{ - if (completeNotifier_) { - completeNotifier_(seqNum, result); - } - return RDB_OK; -} - -int32_t RdbNotifierStub::OnChangeInner(MessageParcel &data, MessageParcel &reply) -{ - std::string storeName; - if (!data.ReadString(storeName)) { - ZLOGE("read store name failed"); - return RDB_ERROR; - } - std::vector devices; - if (!data.ReadStringVector(&devices)) { - ZLOGE("read devices failed"); - return RDB_ERROR; - } - return OnChange(storeName, devices); -} - -int32_t RdbNotifierStub::OnChange(const std::string& storeName, const std::vector &devices) -{ - if (changeNotifier_) { - changeNotifier_(storeName, devices); - } - return RDB_OK; -} -} // namespace OHOS::DistributedRdb diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp deleted file mode 100644 index faee47d6d7a..00000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp +++ /dev/null @@ -1,445 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "RdbServiceProxy" - -#include "rdb_service_proxy.h" -#include "itypes_util.h" -#include "log_print.h" - -namespace OHOS::DistributedRdb { -RdbServiceProxy::RdbServiceProxy(const sptr &object) - : IRemoteProxy(object) -{ - ZLOGI("construct"); -} - -void RdbServiceProxy::OnSyncComplete(uint32_t seqNum, const SyncResult &result) -{ - syncCallbacks_.ComputeIfPresent(seqNum, [&result] (const auto& key, const SyncCallback& callback) { - callback(result); - return true; - }); - syncCallbacks_.Erase(seqNum); -} - -void RdbServiceProxy::OnDataChange(const std::string& storeName, const std::vector &devices) -{ - ZLOGI("%{public}s", storeName.c_str()); - auto name = RemoveSuffix(storeName); - observers_.ComputeIfPresent( - name, [&devices] (const auto& key, const ObserverMapValue& value) { - for (const auto& observer : value.first) { - observer->OnChange(devices); - } - return true; - }); -} - -std::string RdbServiceProxy::ObtainDistributedTableName(const std::string &device, const std::string &table) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return ""; - } - if (!ITypesUtil::Marshal(data, device, table)) { - ZLOGE("write to message parcel failed"); - return ""; - } - - MessageParcel reply; - MessageOption option; - if (Remote()->SendRequest(RDB_SERVICE_CMD_OBTAIN_TABLE, data, reply, option) != 0) { - ZLOGE("send request failed"); - return ""; - } - return reply.ReadString(); -} - -int32_t RdbServiceProxy::InitNotifier(const RdbSyncerParam& param) -{ - notifier_ = new (std::nothrow) RdbNotifierStub( - [this] (uint32_t seqNum, const SyncResult& result) { - OnSyncComplete(seqNum, result); - }, - [this] (const std::string& storeName, const std::vector& devices) { - OnDataChange(storeName, devices); - } - ); - if (notifier_ == nullptr) { - ZLOGE("create notifier failed"); - return RDB_ERROR; - } - - if (InitNotifier(param, notifier_->AsObject().GetRefPtr()) != RDB_OK) { - notifier_ = nullptr; - return RDB_ERROR; - } - - ZLOGI("success"); - return RDB_OK; -} - -int32_t RdbServiceProxy::InitNotifier(const RdbSyncerParam ¶m, const sptr notifier) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return RDB_ERROR; - } - if (!ITypesUtil::Marshal(data, param, notifier)) { - ZLOGE("write to message parcel failed"); - return RDB_ERROR; - } - - MessageParcel reply; - MessageOption option; - if (Remote()->SendRequest(RDB_SERVICE_CMD_INIT_NOTIFIER, data, reply, option) != 0) { - ZLOGE("send request failed"); - return RDB_ERROR; - } - - int32_t res = RDB_ERROR; - return reply.ReadInt32(res) ? res : RDB_ERROR; -} - -uint32_t RdbServiceProxy::GetSeqNum() -{ - return seqNum_++; -} - -int32_t RdbServiceProxy::DoSync(const RdbSyncerParam& param, const SyncOption &option, - const RdbPredicates &predicates, SyncResult& result) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return RDB_ERROR; - } - if (!ITypesUtil::Marshal(data, param, option, predicates)) { - ZLOGE("write to message parcel failed"); - return RDB_ERROR; - } - - MessageParcel reply; - MessageOption opt; - if (Remote()->SendRequest(RDB_SERVICE_CMD_SYNC, data, reply, opt) != 0) { - ZLOGE("send request failed"); - return RDB_ERROR; - } - - if (!ITypesUtil::Unmarshal(reply, result)) { - ZLOGE("read result failed"); - return RDB_ERROR; - } - return RDB_OK; -} - -int32_t RdbServiceProxy::DoSync(const RdbSyncerParam& param, const SyncOption &option, - const RdbPredicates &predicates, const SyncCallback& callback) -{ - SyncResult result; - if (DoSync(param, option, predicates, result) != RDB_OK) { - ZLOGI("failed"); - return RDB_ERROR; - } - ZLOGI("success"); - - if (callback != nullptr) { - callback(result); - } - return RDB_OK; -} - -int32_t RdbServiceProxy::DoAsync(const RdbSyncerParam& param, uint32_t seqNum, const SyncOption &option, - const RdbPredicates &predicates) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return RDB_ERROR; - } - if (!ITypesUtil::Marshal(data, param, seqNum, option, predicates)) { - ZLOGE("write to message parcel failed"); - return RDB_ERROR; - } - - MessageParcel reply; - MessageOption opt; - if (Remote()->SendRequest(RDB_SERVICE_CMD_ASYNC, data, reply, opt) != 0) { - ZLOGE("send request failed"); - return RDB_ERROR; - } - - int32_t res = RDB_ERROR; - return reply.ReadInt32(res) ? res : RDB_ERROR; -} - -int32_t RdbServiceProxy::DoAsync(const RdbSyncerParam& param, const SyncOption &option, - const RdbPredicates &predicates, const SyncCallback& callback) -{ - uint32_t num = GetSeqNum(); - if (!syncCallbacks_.Insert(num, callback)) { - ZLOGI("insert callback failed"); - return RDB_ERROR; - } - ZLOGI("num=%{public}u", num); - - if (DoAsync(param, num, option, predicates) != RDB_OK) { - ZLOGE("failed"); - syncCallbacks_.Erase(num); - return RDB_ERROR; - } - - ZLOGI("success"); - return RDB_OK; -} - -int32_t RdbServiceProxy::SetDistributedTables(const RdbSyncerParam& param, const std::vector &tables) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return RDB_ERROR; - } - if (!ITypesUtil::Marshal(data, param, tables)) { - ZLOGE("write to message parcel failed"); - return RDB_ERROR; - } - - MessageParcel reply; - MessageOption option; - if (Remote()->SendRequest(RDB_SERVICE_CMD_SET_DIST_TABLE, data, reply, option) != 0) { - ZLOGE("send request failed"); - return RDB_ERROR; - } - - int32_t res = RDB_ERROR; - return reply.ReadInt32(res) ? res : RDB_ERROR; -} - -int32_t RdbServiceProxy::Sync(const RdbSyncerParam& param, const SyncOption &option, - const RdbPredicates &predicates, const SyncCallback &callback) -{ - if (option.isBlock) { - return DoSync(param, option, predicates, callback); - } - return DoAsync(param, option, predicates, callback); -} - -std::string RdbServiceProxy::RemoveSuffix(const std::string& name) -{ - std::string suffix(".db"); - auto pos = name.rfind(suffix); - if (pos == std::string::npos || pos < name.length() - suffix.length()) { - return name; - } - return { name, 0, pos }; -} - -int32_t RdbServiceProxy::Subscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, - RdbStoreObserver *observer) -{ - if (option.mode != SubscribeMode::REMOTE) { - ZLOGE("subscribe mode invalid"); - return RDB_ERROR; - } - if (DoSubscribe(param) != RDB_OK) { - ZLOGI("communicate to server failed"); - return RDB_ERROR; - } - auto name = RemoveSuffix(param.storeName_); - observers_.Compute( - name, [observer] (const auto& key, ObserverMapValue& value) { - for (const auto& element : value.first) { - if (element == observer) { - ZLOGE("duplicate observer"); - return true; - } - } - value.first.push_back(observer); - return true; - }); - return RDB_OK; -} - -int32_t RdbServiceProxy::DoSubscribe(const RdbSyncerParam ¶m) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return RDB_ERROR; - } - if (!ITypesUtil::Marshalling(param, data)) { - ZLOGE("write to message parcel failed"); - return RDB_ERROR; - } - - MessageParcel reply; - MessageOption option; - if (Remote()->SendRequest(RDB_SERVICE_CMD_SUBSCRIBE, data, reply, option) != 0) { - ZLOGE("send request failed"); - return RDB_ERROR; - } - - int32_t res = RDB_ERROR; - return reply.ReadInt32(res) ? res : RDB_ERROR; -} - -int32_t RdbServiceProxy::UnSubscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, - RdbStoreObserver *observer) -{ - DoUnSubscribe(param); - auto name = RemoveSuffix(param.storeName_); - observers_.ComputeIfPresent( - name, [observer](const auto& key, ObserverMapValue& value) { - ZLOGI("before remove size=%{public}d", static_cast(value.first.size())); - value.first.remove(observer); - ZLOGI("after remove size=%{public}d", static_cast(value.first.size())); - return !(value.first.empty()); - }); - return RDB_OK; -} - -int32_t RdbServiceProxy::DoUnSubscribe(const RdbSyncerParam ¶m) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return RDB_ERROR; - } - if (!ITypesUtil::Marshalling(param, data)) { - ZLOGE("write to message parcel failed"); - return RDB_ERROR; - } - - MessageParcel reply; - MessageOption option; - if (Remote()->SendRequest(RDB_SERVICE_CMD_UNSUBSCRIBE, data, reply, option) != 0) { - ZLOGE("send request failed"); - return RDB_ERROR; - } - - int32_t res = RDB_ERROR; - return reply.ReadInt32(res) ? res : RDB_ERROR; -} - -int32_t RdbServiceProxy::RemoteQuery(const RdbSyncerParam& param, const std::string& device, const std::string& sql, - const std::vector& selectionArgs, sptr& resultSet) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return RDB_ERROR; - } - if (!ITypesUtil::Marshal(data, param, device, sql, selectionArgs)) { - ZLOGE("write to message parcel failed"); - return RDB_ERROR; - } - - MessageParcel reply; - MessageOption option; - if (Remote()->SendRequest(RDB_SERVICE_CMD_REMOTE_QUERY, data, reply, option) != 0) { - ZLOGE("send request failed"); - return RDB_ERROR; - } - - int32_t status = reply.ReadInt32(); - if (status != RdbStatus::RDB_OK) { - ZLOGE("remote query failed, server side status is %{public}d", status); - return status; - } - - sptr remote = reply.ReadRemoteObject(); - if (remote == nullptr) { - ZLOGE("read remote object is null"); - return RDB_ERROR; - } - resultSet = remote; - return RDB_OK; -} - -RdbServiceProxy::ObserverMap RdbServiceProxy::ExportObservers() -{ - return observers_; -} - -void RdbServiceProxy::ImportObservers(ObserverMap &observers) -{ - ZLOGI("enter"); - SubscribeOption option {SubscribeMode::REMOTE}; - observers.ForEach([this, &option](const std::string& key, const ObserverMapValue& value) { - for (auto& observer : value.first) { - Subscribe(value.second, option, observer); - } - return false; - }); -} -int32_t RdbServiceProxy::CreateRDBTable( - const RdbSyncerParam ¶m, const std::string &writePermission, const std::string &readPermission) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return RDB_ERROR; - } - if (!ITypesUtil::Marshal(data, param, writePermission, readPermission)) { - ZLOGE("write to message parcel failed"); - return RDB_ERROR; - } - - MessageParcel reply; - MessageOption option; - if (Remote()->SendRequest(RDB_SERVICE_CREATE_RDB_TABLE, data, reply, option) != 0) { - ZLOGE("send request failed"); - return RDB_ERROR; - } - - int32_t status = reply.ReadInt32(); - if (status != RdbStatus::RDB_OK) { - ZLOGE("remote query failed, server side status is %{public}d", status); - return status; - } - return RDB_OK; -} - -int32_t RdbServiceProxy::DestroyRDBTable(const RdbSyncerParam ¶m) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(IRdbService::GetDescriptor())) { - ZLOGE("write descriptor failed"); - return RDB_ERROR; - } - if (!ITypesUtil::Marshal(data, param)) { - ZLOGE("write to message parcel failed"); - return RDB_ERROR; - } - - MessageParcel reply; - MessageOption option; - if (Remote()->SendRequest(RDB_SERVICE_DESTROY_RDB_TABLE, data, reply, option) != 0) { - ZLOGE("send request failed"); - return RDB_ERROR; - } - - int32_t status = reply.ReadInt32(); - if (status != RdbStatus::RDB_OK) { - ZLOGE("remote query failed, server side status is %{public}d", status); - return status; - } - return RDB_OK; -} -} // namespace OHOS::DistributedRdb diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h b/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h deleted file mode 100644 index f31499107e0..00000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DISTRIBUTED_RDB_SERVICE_PROXY_H -#define DISTRIBUTED_RDB_SERVICE_PROXY_H - -#include -#include -#include -#include "irdb_service.h" -#include "rdb_notifier.h" -#include "concurrent_map.h" - -namespace OHOS::DistributedRdb { -class RdbServiceProxy : public IRemoteProxy { -public: - using ObserverMapValue = std::pair, RdbSyncerParam>; - using ObserverMap = ConcurrentMap; - - explicit RdbServiceProxy(const sptr& object); - - std::string ObtainDistributedTableName(const std::string& device, const std::string& table) override; - - int32_t InitNotifier(const RdbSyncerParam& param); - int32_t InitNotifier(const RdbSyncerParam& param, const sptr notifier) override; - - int32_t SetDistributedTables(const RdbSyncerParam& param, const std::vector& tables) override; - - int32_t Sync(const RdbSyncerParam& param, const SyncOption& option, - const RdbPredicates& predicates, const SyncCallback& callback) override; - - int32_t Subscribe(const RdbSyncerParam& param, const SubscribeOption& option, - RdbStoreObserver *observer) override; - - int32_t UnSubscribe(const RdbSyncerParam& param, const SubscribeOption& option, - RdbStoreObserver *observer) override; - int32_t RemoteQuery(const RdbSyncerParam& param, const std::string& device, const std::string& sql, - const std::vector& selectionArgs, sptr& resultSet) override; - - int32_t CreateRDBTable( - const RdbSyncerParam ¶m, const std::string &writePermission, const std::string &readPermission) override; - int32_t DestroyRDBTable(const RdbSyncerParam ¶m) override; - ObserverMap ExportObservers(); - - void ImportObservers(ObserverMap& observers); - -protected: - int32_t DoSync(const RdbSyncerParam& param, const SyncOption& option, - const RdbPredicates& predicates, SyncResult& result) override; - - int32_t DoAsync(const RdbSyncerParam& param, uint32_t seqNum, const SyncOption& option, - const RdbPredicates& predicates) override; - - int32_t DoSubscribe(const RdbSyncerParam& param) override; - - int32_t DoUnSubscribe(const RdbSyncerParam& param) override; - -private: - uint32_t GetSeqNum(); - - int32_t DoSync(const RdbSyncerParam& param, const SyncOption& option, - const RdbPredicates& predicates, const SyncCallback& callback); - - int32_t DoAsync(const RdbSyncerParam& param, const SyncOption& option, - const RdbPredicates& predicates, const SyncCallback& callback); - - void OnSyncComplete(uint32_t seqNum, const SyncResult& result); - - void OnDataChange(const std::string& storeName, const std::vector& devices); - - std::string RemoveSuffix(const std::string& name); - - std::atomic seqNum_ {}; - - ConcurrentMap syncCallbacks_; - ObserverMap observers_; - sptr notifier_; - - static inline BrokerDelegator delegator_; -}; -} // namespace OHOS::DistributedRdb -#endif diff --git a/frameworks/innerkitsimpl/rdb/src/rdb_types_util.cpp b/frameworks/innerkitsimpl/rdb/src/rdb_types_util.cpp deleted file mode 100644 index 1666628e687..00000000000 --- a/frameworks/innerkitsimpl/rdb/src/rdb_types_util.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "rdb_types_util.h" -namespace OHOS::ITypesUtil { -template<> -bool Marshalling(const SyncerParam &input, MessageParcel &data) -{ - return ITypesUtil::Marshal(data, input.bundleName_, input.hapName_, input.storeName_, input.area_, - input.level_, input.type_, input.isAutoSync_, input.isEncrypt_, input.password_); -} -template<> -bool Unmarshalling(SyncerParam &output, MessageParcel &data) -{ - return ITypesUtil::Unmarshal(data, output.bundleName_, output.hapName_, output.storeName_, output.area_, - output.level_, output.type_, output.isAutoSync_, output.isEncrypt_, output.password_); -} - -template<> -bool Marshalling(const SyncOption &input, MessageParcel &data) -{ - return ITypesUtil::Marshal(data, static_cast(input.mode), input.isBlock); -} - -template<> -bool Unmarshalling(SyncOption &output, MessageParcel &data) -{ - int32_t mode = static_cast(output.mode); - auto ret = ITypesUtil::Unmarshal(data, mode, output.isBlock); - output.mode = static_cast(mode); - return ret; -} - -template<> -bool Marshalling(const RdbPredicates &input, MessageParcel &data) -{ - return ITypesUtil::Marshal(data, input.table_, input.devices_, input.operations_); -} -template<> -bool Unmarshalling(RdbPredicates &output, MessageParcel &data) -{ - return ITypesUtil::Unmarshal(data, output.table_, output.devices_, output.operations_); -} - -template<> -bool Marshalling(const RdbOperation &input, MessageParcel &data) -{ - return ITypesUtil::Marshal(data, static_cast(input.operator_), input.field_, input.values_); -} - -template<> -bool Unmarshalling(RdbOperation &output, MessageParcel &data) -{ - int32_t option; - auto ret = ITypesUtil::Unmarshal(data, option, output.field_, output.values_); - output.operator_ = static_cast(option); - return ret; -} -} \ No newline at end of file diff --git a/interfaces/innerkits/distributeddata/BUILD.gn b/interfaces/innerkits/distributeddata/BUILD.gn index b5e4f1f4248..f157d37d4e9 100644 --- a/interfaces/innerkits/distributeddata/BUILD.gn +++ b/interfaces/innerkits/distributeddata/BUILD.gn @@ -27,8 +27,6 @@ config("distributeddatafwk_config") { "../../../frameworks/innerkitsimpl/distributeddatafwk/include", "../../../frameworks/innerkitsimpl/distributeddatafwk/src", "../../../frameworks/common", - "../../../frameworks/innerkitsimpl/rdb/include", - "../../../frameworks/innerkitsimpl/rdb/src", "../../../frameworks/innerkitsimpl/object/include", "../../../frameworks/innerkitsimpl/kvdb/include", "../../../frameworks/innerkitsimpl/kvdb/src", @@ -48,7 +46,6 @@ config("distributeddatafwk_public_config") { include_dirs = [ "include", - "../../../frameworks/innerkitsimpl/rdb/include", "../../../frameworks/innerkitsimpl/object/include", "../../../frameworks/innerkitsimpl/distributeddatafwk/include", "//commonlibrary/c_utils/base/include", @@ -76,13 +73,6 @@ ohos_shared_library("distributeddata_inner") { "include/types.h", ] - rdb_sources = [ - "../../../frameworks/innerkitsimpl/rdb/src/rdb_manager.cpp", - "../../../frameworks/innerkitsimpl/rdb/src/rdb_manager_impl.cpp", - "../../../frameworks/innerkitsimpl/rdb/src/rdb_notifier.cpp", - "../../../frameworks/innerkitsimpl/rdb/src/rdb_service_proxy.cpp", - "../../../frameworks/innerkitsimpl/rdb/src/rdb_types_util.cpp", - ] object_sources = [ "../../../frameworks/innerkitsimpl/object/src/iobject_callback.cpp", "../../../frameworks/innerkitsimpl/object/src/object_service_proxy.cpp", @@ -107,7 +97,7 @@ ohos_shared_library("distributeddata_inner") { "../../../frameworks/innerkitsimpl/kvdb/src/task_executor.cpp", ] - sources = old_sources + rdb_sources + kvdb_sources + object_sources + sources = old_sources + kvdb_sources + object_sources configs = [ ":distributeddatafwk_config" ] -- Gitee From c8a77cb4bbe4f79c7e11d8926b519a7cdbbbcbf4 Mon Sep 17 00:00:00 2001 From: ylq121 Date: Mon, 19 Dec 2022 19:46:46 +0800 Subject: [PATCH 002/191] AutoSyncTimerDeBUG Signed-off-by: ylq121 --- .../kvdb/include/auto_sync_timer.h | 5 +- .../kvdb/src/auto_sync_timer.cpp | 17 +++--- .../kvdb/test/auto_sync_timer_test.cpp | 53 +++++++++++++++++++ 3 files changed, 67 insertions(+), 8 deletions(-) diff --git a/frameworks/innerkitsimpl/kvdb/include/auto_sync_timer.h b/frameworks/innerkitsimpl/kvdb/include/auto_sync_timer.h index 1e3c9182785..b6053a40337 100644 --- a/frameworks/innerkitsimpl/kvdb/include/auto_sync_timer.h +++ b/frameworks/innerkitsimpl/kvdb/include/auto_sync_timer.h @@ -15,6 +15,7 @@ #ifndef SDB_AUTO_SYNC_TIMER_H #define SDB_AUTO_SYNC_TIMER_H #include +#include #include "concurrent_map.h" #include "kvdb_service.h" @@ -32,13 +33,13 @@ private: static constexpr size_t SYNC_STORE_NUM = 10; AutoSyncTimer() = default; ~AutoSyncTimer() = default; - std::map> GetStoreIds(); + std::map> GetStoreIds(); std::function ProcessTask(); void StartTimer(); void StopTimer(); void AddSyncStores(const std::string &appId, std::set storeIds); bool HasSyncStores(); - ConcurrentMap> stores_; + ConcurrentMap> stores_; TaskScheduler::TaskId delaySyncTaskId_; TaskScheduler::TaskId forceSyncTaskId_; std::mutex mutex_; diff --git a/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp b/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp index 8e2051fba56..2a0c849aa52 100644 --- a/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp +++ b/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp @@ -48,8 +48,13 @@ void AutoSyncTimer::DoAutoSync(const std::string &appId, std::set store void AutoSyncTimer::AddSyncStores(const std::string &appId, std::set storeIds) { - stores_.Compute(appId, [&storeIds](const auto &key, std::set &value) { - value.merge(std::move(storeIds)); + stores_.Compute(appId, [&storeIds](const auto &key, std::vector &value) { + std::set tempStores(value.begin(), value.end()); + for (auto it = storeIds.begin(); it != storeIds.end(); it++) { + if (!tempStores.count(*it)) { + value.push_back(*it); + } + } return !value.empty(); }); } @@ -59,11 +64,11 @@ bool AutoSyncTimer::HasSyncStores() return !stores_.Empty(); } -std::map> AutoSyncTimer::GetStoreIds() +std::map> AutoSyncTimer::GetStoreIds() { - std::map> stores; + std::map> stores; int count = SYNC_STORE_NUM; - stores_.EraseIf([&stores, &count](const std::string &key, std::set &value) { + stores_.EraseIf([&stores, &count](const std::string &key, std::vector &value) { int size = value.size(); if (size <= count) { stores.insert({ key, std::move(value) }); @@ -72,7 +77,7 @@ std::map> AutoSyncTimer::GetStoreIds() } auto &innerStore = stores[key]; for (auto it = value.begin(); it != value.end() && count > 0;) { - innerStore.insert(*it); + innerStore.push_back(*it); it = value.erase(it); count--; } diff --git a/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp b/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp index 2bd082b4dd0..87f4e7b53c7 100644 --- a/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp +++ b/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp @@ -227,4 +227,57 @@ HWTEST_F(AutoSyncTimerTest, SingleWriteOvertenKVStores, TestSize.Level1) ASSERT_EQ(it->second.count("ut_test_store9"), 1); ASSERT_EQ(it->second.count("ut_test_store10"), 1); } + +/** +* @tc.name: MultiWriteOvertenKVStores +* @tc.desc: mulity wirte +* @tc.type: FUNC +* @tc.require: I4XVQQ +* @tc.author: YangQing +*/ +HWTEST_F(AutoSyncTimerTest, MultiWriteOvertenKVStores, TestSize.Level1) +{ + auto *instance = KVDBServiceMock::GetInstance(); + ASSERT_NE(instance, nullptr); + instance->ResetToZero(); + instance->startTime = time_point_cast(system_clock::now()).time_since_epoch().count(); + instance->endTime = 0; + instance->values_.clear(); + std::atomic_bool finished = false; + std::thread thread([&finished] { + while (!finished.load()) { + AutoSyncTimer::GetInstance().DoAutoSync("ut_test", { + { "ut_test_store0" }, + { "ut_test_store1" }, + { "ut_test_store2" }, + { "ut_test_store3" }, + { "ut_test_store4" }, + { "ut_test_store5" }, + { "ut_test_store6" }, + { "ut_test_store7" }, + { "ut_test_store8" }, + { "ut_test_store9" }, + { "ut_test_store10" }, + }); + usleep(40); + } + }); + EXPECT_EQ(static_cast(instance->GetCallCount(1)), 1); + ASSERT_GE(instance->endTime - instance->startTime, 200); + ASSERT_LT(instance->endTime - instance->startTime, 250); + finished.store(true); + thread.join(); + EXPECT_EQ(static_cast(instance->GetCallCount(11)), 11); + auto it = instance->values_.find("ut_test"); + ASSERT_EQ(it->second.count("ut_test_store0"), 1); + ASSERT_EQ(it->second.count("ut_test_store1"), 1); + ASSERT_EQ(it->second.count("ut_test_store2"), 1); + ASSERT_EQ(it->second.count("ut_test_store3"), 1); + ASSERT_EQ(it->second.count("ut_test_store4"), 1); + ASSERT_EQ(it->second.count("ut_test_store5"), 1); + ASSERT_EQ(it->second.count("ut_test_store6"), 1); + ASSERT_EQ(it->second.count("ut_test_store7"), 1); + ASSERT_EQ(it->second.count("ut_test_store8"), 1); + ASSERT_EQ(it->second.count("ut_test_store9"), 1); + ASSERT_EQ(it->second.count("ut_test_store10"), 1); } \ No newline at end of file -- Gitee From 06b170157ad0051554a48674cb5e29962fc7ffb9 Mon Sep 17 00:00:00 2001 From: ylq121 Date: Mon, 19 Dec 2022 20:34:07 +0800 Subject: [PATCH 003/191] xiugai Signed-off-by: ylq121 --- frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp b/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp index 87f4e7b53c7..75468660142 100644 --- a/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp +++ b/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp @@ -280,4 +280,5 @@ HWTEST_F(AutoSyncTimerTest, MultiWriteOvertenKVStores, TestSize.Level1) ASSERT_EQ(it->second.count("ut_test_store8"), 1); ASSERT_EQ(it->second.count("ut_test_store9"), 1); ASSERT_EQ(it->second.count("ut_test_store10"), 1); +} } \ No newline at end of file -- Gitee From e7f95e146fb40b359793917af56f1f8c2374ec5a Mon Sep 17 00:00:00 2001 From: qing Date: Sat, 24 Dec 2022 11:26:26 +0800 Subject: [PATCH 004/191] xiugai2 Signed-off-by: qing --- frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp b/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp index 2a0c849aa52..1672316b552 100644 --- a/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp +++ b/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp @@ -76,11 +76,13 @@ std::map> AutoSyncTimer::GetStoreIds() return true; } auto &innerStore = stores[key]; - for (auto it = value.begin(); it != value.end() && count > 0;) { + auto it = value.begin(); + while (it != value.end() && count > 0) { innerStore.push_back(*it); - it = value.erase(it); + it++; count--; } + value.erase(value.begin(),it); return value.empty(); }); return stores; -- Gitee From 74930e43b66530bfdb72f9f8f1839723161ed64f Mon Sep 17 00:00:00 2001 From: qing Date: Mon, 26 Dec 2022 09:30:50 +0800 Subject: [PATCH 005/191] xiugai Signed-off-by: qing --- frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp b/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp index 1672316b552..02277982d6f 100644 --- a/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp +++ b/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp @@ -51,7 +51,7 @@ void AutoSyncTimer::AddSyncStores(const std::string &appId, std::set st stores_.Compute(appId, [&storeIds](const auto &key, std::vector &value) { std::set tempStores(value.begin(), value.end()); for (auto it = storeIds.begin(); it != storeIds.end(); it++) { - if (!tempStores.count(*it)) { + if (tempStores.count(*it) == 0) { value.push_back(*it); } } -- Gitee From c812191c7ca778fb51e1d86038602b05bfc29dcd Mon Sep 17 00:00:00 2001 From: zqq Date: Tue, 27 Dec 2022 19:46:11 +0800 Subject: [PATCH 006/191] add ut Signed-off-by: zqq --- .../distributeddb_communicator_deep_test.cpp | 297 ++++++++++++++++++ .../communicator/mock_process_communicator.h | 37 +++ 2 files changed, 334 insertions(+) create mode 100644 frameworks/libs/distributeddb/test/unittest/common/communicator/mock_process_communicator.h diff --git a/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp index 5bf3155565c..99d51401a86 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp @@ -20,7 +20,9 @@ #include "distributeddb_communicator_common.h" #include "distributeddb_tools_unit_test.h" #include "log_print.h" +#include "network_adapter.h" #include "message.h" +#include "mock_process_communicator.h" #include "serial_buffer.h" using namespace std; @@ -560,3 +562,298 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, ReliableOnline001, TestSize.Level2) AdapterStub::DisconnectAdapterStub(g_envDeviceB.adapterHandle, g_envDeviceC.adapterHandle); AdapterStub::DisconnectAdapterStub(g_envDeviceC.adapterHandle, g_envDeviceA.adapterHandle); } + +/** + * @tc.name: NetworkAdapter001 + * @tc.desc: Test networkAdapter start func + * @tc.type: FUNC + * @tc.require: AR000BVDGJ + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBCommunicatorDeepTest, NetworkAdapter001, TestSize.Level1) +{ + auto processCommunicator = std::make_shared(); + EXPECT_CALL(*processCommunicator, Stop).WillRepeatedly([]() { + return OK; + }); + /** + * @tc.steps: step1. adapter start with empty label + * @tc.expected: step1. start failed + */ + auto adapter = std::make_shared(""); + EXPECT_EQ(adapter->StartAdapter(), -E_INVALID_ARGS); + /** + * @tc.steps: step2. adapter start with not empty label but processCommunicator is null + * @tc.expected: step2. start failed + */ + adapter = std::make_shared("label"); + EXPECT_EQ(adapter->StartAdapter(), -E_INVALID_ARGS); + /** + * @tc.steps: step3. processCommunicator start not ok + * @tc.expected: step3. start failed + */ + adapter = std::make_shared("label", processCommunicator); + EXPECT_CALL(*processCommunicator, Start).WillRepeatedly([](const std::string &) { + return DB_ERROR; + }); + EXPECT_EQ(adapter->StartAdapter(), -E_PERIPHERAL_INTERFACE_FAIL); + /** + * @tc.steps: step4. processCommunicator reg not ok + * @tc.expected: step4. start failed + */ + EXPECT_CALL(*processCommunicator, Start).WillRepeatedly([](const std::string &) { + return OK; + }); + EXPECT_CALL(*processCommunicator, RegOnDataReceive).WillRepeatedly([](const OnDataReceive &) { + return DB_ERROR; + }); + EXPECT_EQ(adapter->StartAdapter(), -E_PERIPHERAL_INTERFACE_FAIL); + EXPECT_CALL(*processCommunicator, RegOnDataReceive).WillRepeatedly([](const OnDataReceive &) { + return OK; + }); + EXPECT_CALL(*processCommunicator, RegOnDeviceChange).WillRepeatedly([](const OnDeviceChange &) { + return DB_ERROR; + }); + EXPECT_EQ(adapter->StartAdapter(), -E_PERIPHERAL_INTERFACE_FAIL); + /** + * @tc.steps: step5. processCommunicator reg ok + * @tc.expected: step5. start success + */ + EXPECT_CALL(*processCommunicator, RegOnDeviceChange).WillRepeatedly([](const OnDeviceChange &) { + return OK; + }); + EXPECT_CALL(*processCommunicator, GetLocalDeviceInfos).WillRepeatedly([]() { + DeviceInfos deviceInfos; + deviceInfos.identifier = "DEVICES_A"; // local is deviceA + return deviceInfos; + }); + EXPECT_CALL(*processCommunicator, GetRemoteOnlineDeviceInfosList).WillRepeatedly([]() { + std::vector res; + DeviceInfos deviceInfos; + deviceInfos.identifier = "DEVICES_A"; // search local is deviceA + res.push_back(deviceInfos); + deviceInfos.identifier = "DEVICES_B"; // search remote is deviceB + res.push_back(deviceInfos); + return res; + }); + EXPECT_CALL(*processCommunicator, IsSameProcessLabelStartedOnPeerDevice).WillRepeatedly([](const DeviceInfos &) { + return false; + }); + EXPECT_EQ(adapter->StartAdapter(), E_OK); + RuntimeContext::GetInstance()->StopTaskPool(); +} + +/** + * @tc.name: NetworkAdapter002 + * @tc.desc: Test networkAdapter get mtu func + * @tc.type: FUNC + * @tc.require: AR000BVDGJ + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBCommunicatorDeepTest, NetworkAdapter002, TestSize.Level1) +{ + auto processCommunicator = std::make_shared(); + auto adapter = std::make_shared("label", processCommunicator); + /** + * @tc.steps: step1. processCommunicator return 0 mtu + * @tc.expected: step1. adapter will adjust to min mtu + */ + EXPECT_CALL(*processCommunicator, GetMtuSize).WillRepeatedly([]() { + return 0u; + }); + EXPECT_EQ(adapter->GetMtuSize(), DBConstant::MIN_MTU_SIZE); + /** + * @tc.steps: step2. processCommunicator return 2 max mtu + * @tc.expected: step2. adapter will return min mtu util re make + */ + EXPECT_CALL(*processCommunicator, GetMtuSize).WillRepeatedly([]() { + return 2 * DBConstant::MAX_MTU_SIZE; + }); + EXPECT_EQ(adapter->GetMtuSize(), DBConstant::MIN_MTU_SIZE); + adapter = std::make_shared("label", processCommunicator); + EXPECT_EQ(adapter->GetMtuSize(), DBConstant::MAX_MTU_SIZE); +} + +/** + * @tc.name: NetworkAdapter003 + * @tc.desc: Test networkAdapter get timeout func + * @tc.type: FUNC + * @tc.require: AR000BVDGJ + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBCommunicatorDeepTest, NetworkAdapter003, TestSize.Level1) +{ + auto processCommunicator = std::make_shared(); + auto adapter = std::make_shared("label", processCommunicator); + /** + * @tc.steps: step1. processCommunicator return 0 timeout + * @tc.expected: step1. adapter will adjust to min timeout + */ + EXPECT_CALL(*processCommunicator, GetTimeout).WillRepeatedly([]() { + return 0u; + }); + EXPECT_EQ(adapter->GetTimeout(), DBConstant::MIN_TIMEOUT); + /** + * @tc.steps: step2. processCommunicator return 2 max timeout + * @tc.expected: step2. adapter will adjust to max timeout + */ + EXPECT_CALL(*processCommunicator, GetTimeout).WillRepeatedly([]() { + return 2 * DBConstant::MAX_TIMEOUT; + }); + EXPECT_EQ(adapter->GetTimeout(), DBConstant::MAX_TIMEOUT); +} + +/** + * @tc.name: NetworkAdapter004 + * @tc.desc: Test networkAdapter send bytes func + * @tc.type: FUNC + * @tc.require: AR000BVDGJ + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBCommunicatorDeepTest, NetworkAdapter004, TestSize.Level1) +{ + auto processCommunicator = std::make_shared(); + auto adapter = std::make_shared("label", processCommunicator); + + EXPECT_CALL(*processCommunicator, SendData).WillRepeatedly([](const DeviceInfos &, const uint8_t *, uint32_t) { + return OK; + }); + /** + * @tc.steps: step1. adapter send data with error param + * @tc.expected: step1. adapter send failed + */ + auto data = std::make_shared(1u); + EXPECT_EQ(adapter->SendBytes("DEVICES_B", nullptr, 1), -E_INVALID_ARGS); + EXPECT_EQ(adapter->SendBytes("DEVICES_B", data.get(), 0), -E_INVALID_ARGS); + /** + * @tc.steps: step2. adapter send data with right param + * @tc.expected: step2. adapter send ok + */ + EXPECT_EQ(adapter->SendBytes("DEVICES_B", data.get(), 1), E_OK); + RuntimeContext::GetInstance()->StopTaskPool(); +} + +namespace { +void InitAdapter(const std::shared_ptr &adapter, + const std::shared_ptr &processCommunicator, + OnDataReceive &onDataReceive, OnDeviceChange &onDataChange) +{ + EXPECT_CALL(*processCommunicator, Stop).WillRepeatedly([]() { + return OK; + }); + EXPECT_CALL(*processCommunicator, Start).WillRepeatedly([](const std::string &) { + return OK; + }); + EXPECT_CALL(*processCommunicator, RegOnDataReceive).WillRepeatedly( + [&onDataReceive](const OnDataReceive &callback) { + onDataReceive = callback; + return OK; + }); + EXPECT_CALL(*processCommunicator, RegOnDeviceChange).WillRepeatedly( + [&onDataChange](const OnDeviceChange &callback) { + onDataChange = callback; + return OK; + }); + EXPECT_CALL(*processCommunicator, GetRemoteOnlineDeviceInfosList).WillRepeatedly([]() { + std::vector res; + return res; + }); + EXPECT_CALL(*processCommunicator, IsSameProcessLabelStartedOnPeerDevice).WillRepeatedly([](const DeviceInfos &) { + return false; + }); + EXPECT_EQ(adapter->StartAdapter(), E_OK); +} +} +/** + * @tc.name: NetworkAdapter005 + * @tc.desc: Test networkAdapter receive data func + * @tc.type: FUNC + * @tc.require: AR000BVDGJ + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBCommunicatorDeepTest, NetworkAdapter005, TestSize.Level1) +{ + auto processCommunicator = std::make_shared(); + auto adapter = std::make_shared("label", processCommunicator); + OnDataReceive onDataReceive; + OnDeviceChange onDeviceChange; + InitAdapter(adapter, processCommunicator, onDataReceive, onDeviceChange); + ASSERT_NE(onDataReceive, nullptr); + /** + * @tc.steps: step1. adapter recv data with error param + */ + auto data = std::make_shared(1); + DeviceInfos deviceInfos; + onDataReceive(deviceInfos, nullptr, 1); + onDataReceive(deviceInfos, data.get(), 0); + /** + * @tc.steps: step2. adapter recv data with no permission + */ + EXPECT_CALL(*processCommunicator, CheckAndGetDataHeadInfo).WillRepeatedly( + [](const uint8_t *, uint32_t, uint32_t &, std::vector &) { + return NO_PERMISSION; + }); + onDataReceive(deviceInfos, data.get(), 1); + EXPECT_CALL(*processCommunicator, CheckAndGetDataHeadInfo).WillRepeatedly( + [](const uint8_t *, uint32_t, uint32_t &, std::vector &userIds) { + userIds.emplace_back("1"); + return OK; + }); + /** + * @tc.steps: step3. adapter recv data with no callback + */ + onDataReceive(deviceInfos, data.get(), 1); + adapter->RegBytesReceiveCallback([](const std::string &, const uint8_t *, uint32_t, const std::string &) { + }, nullptr); + onDataReceive(deviceInfos, data.get(), 1); + RuntimeContext::GetInstance()->StopTaskPool(); +} + +/** + * @tc.name: NetworkAdapter006 + * @tc.desc: Test networkAdapter device change func + * @tc.type: FUNC + * @tc.require: AR000BVDGJ + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBCommunicatorDeepTest, NetworkAdapter006, TestSize.Level1) +{ + auto processCommunicator = std::make_shared(); + auto adapter = std::make_shared("label", processCommunicator); + OnDataReceive onDataReceive; + OnDeviceChange onDeviceChange; + InitAdapter(adapter, processCommunicator, onDataReceive, onDeviceChange); + ASSERT_NE(onDeviceChange, nullptr); + DeviceInfos deviceInfos; + /** + * @tc.steps: step1. onDeviceChange with no same process + */ + onDeviceChange(deviceInfos, true); + /** + * @tc.steps: step2. onDeviceChange with same process + */ + EXPECT_CALL(*processCommunicator, IsSameProcessLabelStartedOnPeerDevice).WillRepeatedly([](const DeviceInfos &) { + return true; + }); + onDeviceChange(deviceInfos, true); + adapter->RegTargetChangeCallback([](const std::string &, bool) { + }, nullptr); + onDeviceChange(deviceInfos, false); + /** + * @tc.steps: step3. adapter send data with db_error + * @tc.expected: step3. adapter send failed + */ + onDeviceChange(deviceInfos, true); + EXPECT_CALL(*processCommunicator, SendData).WillRepeatedly([](const DeviceInfos &, const uint8_t *, uint32_t) { + return DB_ERROR; + }); + EXPECT_CALL(*processCommunicator, IsSameProcessLabelStartedOnPeerDevice).WillRepeatedly([](const DeviceInfos &) { + return false; + }); + auto data = std::make_shared(1); + EXPECT_EQ(adapter->SendBytes("", data.get(), 1), -E_PERIPHERAL_INTERFACE_FAIL); + RuntimeContext::GetInstance()->StopTaskPool(); + EXPECT_EQ(adapter->IsDeviceOnline(""), false); + ExtendInfo info; + EXPECT_EQ(adapter->GetExtendHeaderHandle(info), nullptr); +} \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/unittest/common/communicator/mock_process_communicator.h b/frameworks/libs/distributeddb/test/unittest/common/communicator/mock_process_communicator.h new file mode 100644 index 00000000000..3f0e2771a97 --- /dev/null +++ b/frameworks/libs/distributeddb/test/unittest/common/communicator/mock_process_communicator.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef MOCK_PROCESS_COMMUNICATOR_H +#define MOCK_PROCESS_COMMUNICATOR_H +#include +#include "iprocess_communicator.h" + +namespace DistributedDB { +class MockProcessCommunicator : public IProcessCommunicator { +public: + MOCK_METHOD1(Start, DBStatus(const std::string &)); + MOCK_METHOD0(Stop, DBStatus()); + MOCK_METHOD1(RegOnDeviceChange, DBStatus(const OnDeviceChange &)); + MOCK_METHOD1(RegOnDataReceive, DBStatus(const OnDataReceive &)); + MOCK_METHOD3(SendData, DBStatus(const DeviceInfos &, const uint8_t *, uint32_t)); + MOCK_METHOD0(GetMtuSize, uint32_t()); + MOCK_METHOD0(GetTimeout, uint32_t()); + MOCK_METHOD0(GetLocalDeviceInfos, DeviceInfos()); + MOCK_METHOD0(GetRemoteOnlineDeviceInfosList, std::vector()); + MOCK_METHOD1(IsSameProcessLabelStartedOnPeerDevice, bool(const DeviceInfos &)); + MOCK_METHOD4(CheckAndGetDataHeadInfo, DBStatus(const uint8_t *, uint32_t, uint32_t &, + std::vector &)); +}; +} +#endif // MOCK_PROCESS_COMMUNICATOR_H -- Gitee From f738c6fbcf765ea4fc8e5e1afe864926645a916e Mon Sep 17 00:00:00 2001 From: saikit Date: Thu, 29 Dec 2022 14:04:00 +0800 Subject: [PATCH 007/191] add ut to increase branch coverage Signed-off-by: saikit Change-Id: If57fb699a698c5000c940b8bd249837108702b57 --- .../distributeddb_communicator_deep_test.cpp | 29 +- ...qlite_single_ver_natural_executor_test.cpp | 287 ++++++++++++++++++ 2 files changed, 295 insertions(+), 21 deletions(-) diff --git a/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp index 99d51401a86..e5a96775640 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp @@ -14,6 +14,7 @@ */ #include +#include #include #include #include "db_errno.h" @@ -573,9 +574,7 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, ReliableOnline001, TestSize.Level2) HWTEST_F(DistributedDBCommunicatorDeepTest, NetworkAdapter001, TestSize.Level1) { auto processCommunicator = std::make_shared(); - EXPECT_CALL(*processCommunicator, Stop).WillRepeatedly([]() { - return OK; - }); + EXPECT_CALL(*processCommunicator, Stop()).WillRepeatedly(testing::Return(OK)); /** * @tc.steps: step1. adapter start with empty label * @tc.expected: step1. start failed @@ -593,35 +592,23 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, NetworkAdapter001, TestSize.Level1) * @tc.expected: step3. start failed */ adapter = std::make_shared("label", processCommunicator); - EXPECT_CALL(*processCommunicator, Start).WillRepeatedly([](const std::string &) { - return DB_ERROR; - }); + EXPECT_CALL(*processCommunicator, Start).WillRepeatedly(testing::Return(DB_ERROR)); EXPECT_EQ(adapter->StartAdapter(), -E_PERIPHERAL_INTERFACE_FAIL); /** * @tc.steps: step4. processCommunicator reg not ok * @tc.expected: step4. start failed */ - EXPECT_CALL(*processCommunicator, Start).WillRepeatedly([](const std::string &) { - return OK; - }); - EXPECT_CALL(*processCommunicator, RegOnDataReceive).WillRepeatedly([](const OnDataReceive &) { - return DB_ERROR; - }); + EXPECT_CALL(*processCommunicator, Start).WillRepeatedly(testing::Return(OK)); + EXPECT_CALL(*processCommunicator, RegOnDataReceive).WillRepeatedly(testing::Return(DB_ERROR)); EXPECT_EQ(adapter->StartAdapter(), -E_PERIPHERAL_INTERFACE_FAIL); - EXPECT_CALL(*processCommunicator, RegOnDataReceive).WillRepeatedly([](const OnDataReceive &) { - return OK; - }); - EXPECT_CALL(*processCommunicator, RegOnDeviceChange).WillRepeatedly([](const OnDeviceChange &) { - return DB_ERROR; - }); + EXPECT_CALL(*processCommunicator, RegOnDataReceive).WillRepeatedly(testing::Return(OK)); + EXPECT_CALL(*processCommunicator, RegOnDeviceChange).WillRepeatedly(testing::Return(DB_ERROR)); EXPECT_EQ(adapter->StartAdapter(), -E_PERIPHERAL_INTERFACE_FAIL); /** * @tc.steps: step5. processCommunicator reg ok * @tc.expected: step5. start success */ - EXPECT_CALL(*processCommunicator, RegOnDeviceChange).WillRepeatedly([](const OnDeviceChange &) { - return OK; - }); + EXPECT_CALL(*processCommunicator, RegOnDeviceChange).WillRepeatedly(testing::Return(OK)); EXPECT_CALL(*processCommunicator, GetLocalDeviceInfos).WillRepeatedly([]() { DeviceInfos deviceInfos; deviceInfos.identifier = "DEVICES_A"; // local is deviceA diff --git a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp index b535fde5a0a..eb8023319da 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp @@ -18,6 +18,8 @@ #include "db_constant.h" #include "db_common.h" #include "distributeddb_storage_single_ver_natural_store_testcase.h" +#include "kvdb_pragma.h" +#include "storage_engine_manager.h" using namespace testing::ext; using namespace DistributedDB; @@ -484,4 +486,289 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, InvalidSync001, item.writeTimestamp = 1; item.flag = DataItem::REMOTE_DEVICE_DATA_MISS_QUERY; EXPECT_EQ(g_handle->SaveSyncDataItem(item, info, time, &data, true), E_OK); +} + +/** + * @tc.name: ConnectionTest001 + * @tc.desc: Failed to get the keys + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ConnectionTest001, TestSize.Level1) +{ + /** + * @tc.steps: step1. the dataType is error + * @tc.expected: step1. Expect -E_INVALID_ARGS + */ + IOption option; + option.dataType = IOption::SYNC_DATA + 1; + vector keys; + EXPECT_EQ(g_connection->GetKeys(option, KEY_1, keys), -E_INVALID_ARGS); + + /** + * @tc.steps: step2. Get keys in cacheDB state + * @tc.expected: step2. Expect -E_EKEYREVOKED + */ + int errCode = E_OK; + SQLiteSingleVerStorageEngine *storageEngine = + static_cast(StorageEngineManager::GetStorageEngine(g_property, errCode)); + ASSERT_EQ(errCode, E_OK); + ASSERT_NE(storageEngine, nullptr); + storageEngine->SetEngineState(EngineState::CACHEDB); + option.dataType = IOption::LOCAL_DATA; + EXPECT_EQ(g_connection->GetKeys(option, KEY_1, keys), -E_EKEYREVOKED); + storageEngine->Release(); + + /** + * @tc.steps: step3. Get keys in null db connection + * @tc.expected: step3. Expect -E_NOT_INIT + */ + std::unique_ptr emptyConn = + std::make_unique(nullptr); + ASSERT_NE(emptyConn, nullptr); + EXPECT_EQ(emptyConn->GetKeys(option, KEY_1, keys), -E_NOT_INIT); +} + +/** + * @tc.name: ConnectionTest002 + * @tc.desc: Push and delete on empty connect + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ConnectionTest002, TestSize.Level1) +{ + std::unique_ptr emptyConn = + std::make_unique(nullptr); + IOption option = {IOption::LOCAL_DATA}; + std::vector entries; + EXPECT_EQ(emptyConn->PutBatch(option, entries), -E_INVALID_DB); + std::vector keys; + EXPECT_EQ(emptyConn->DeleteBatch(option, keys), -E_INVALID_DB); + option.dataType = IOption::SYNC_DATA; + EXPECT_EQ(emptyConn->PutBatch(option, entries), -E_INVALID_DB); + EXPECT_EQ(emptyConn->DeleteBatch(option, keys), -E_INVALID_DB); +} + +/** + * @tc.name: ConnectionTest003 + * @tc.desc: Failed to Put and Delete + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ConnectionTest003, TestSize.Level1) +{ + /** + * @tc.steps: step1. Only change the storageEngine to cacheDB + * @tc.expected: step1. Expect -1 + */ + int errCode = E_OK; + SQLiteSingleVerStorageEngine *storageEngine = + static_cast(StorageEngineManager::GetStorageEngine(g_property, errCode)); + ASSERT_EQ(errCode, E_OK); + ASSERT_NE(storageEngine, nullptr); + storageEngine->SetEngineState(EngineState::CACHEDB); + IOption option = {IOption::SYNC_DATA}; + std::vector entries; + entries.push_back(ENTRY_1); + g_store->ReleaseHandle(g_handle); + EXPECT_EQ(g_connection->PutBatch(option, entries), -1); // -1 is sqlite error + std::vector keys; + keys.push_back(KEY_1); + EXPECT_EQ(g_connection->DeleteBatch(option, keys), -1); + + /** + * @tc.steps: step2.Change to LOCAL_DATA option + * @tc.expected: step2. Expect -1 + */ + option.dataType = IOption::LOCAL_DATA; + EXPECT_EQ(g_connection->PutBatch(option, entries), -1); + EXPECT_EQ(g_connection->DeleteBatch(option, keys), -1); + + /** + * @tc.steps: step3. Table sync_data adds a column to make the num of cols equal to the cacheDB + * @tc.expected: step3. Expect E_OK + */ + sqlite3 *db; + ASSERT_TRUE(sqlite3_open_v2((g_testDir + g_databaseName).c_str(), + &db, SQLITE_OPEN_URI | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nullptr) == SQLITE_OK); + string addSync = "alter table sync_data add column version INT"; + ASSERT_TRUE(SQLiteUtils::ExecuteRawSQL(db, addSync) == E_OK); + sqlite3_close_v2(db); + option.dataType = IOption::SYNC_DATA; + EXPECT_EQ(g_connection->PutBatch(option, entries), E_OK); + storageEngine->Release(); +} + +/** + * @tc.name: ConnectionTest004 + * @tc.desc: Failed to GetResultSet + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ConnectionTest004, TestSize.Level1) +{ + /** + * @tc.steps: step1. the db is null + * @tc.expected: step1. Expect -E_INVALID_DB + */ + g_store->ReleaseHandle(g_handle); + IOption option; + option.dataType = IOption::SYNC_DATA; + IKvDBResultSet *set = nullptr; + Query query = Query::Select(); + std::unique_ptr emptyConn = + std::make_unique(nullptr); + EXPECT_EQ(emptyConn->GetResultSet(option, KEY_1, set), -E_INVALID_DB); + emptyConn->ReleaseResultSet(set); + + /** + * @tc.steps: step2. get in transaction + * @tc.expected: step2. Expect -E_BUSY + */ + g_connection->StartTransaction(); + EXPECT_EQ(g_connection->GetResultSet(option, query, set), -E_BUSY); + g_connection->RollBack(); + + /** + * @tc.steps: step3. change the storageEngine to cacheDB + * @tc.expected: step3. Expect -E_EKEYREVOKED + */ + int errCode = E_OK; + SQLiteSingleVerStorageEngine *storageEngine = + static_cast(StorageEngineManager::GetStorageEngine(g_property, errCode)); + ASSERT_EQ(errCode, E_OK); + ASSERT_NE(storageEngine, nullptr); + storageEngine->SetEngineState(EngineState::CACHEDB); + EXPECT_EQ(g_connection->GetResultSet(option, query, set), -E_EKEYREVOKED); + EXPECT_EQ(g_connection->GetResultSet(option, KEY_1, set), -E_EKEYREVOKED); + storageEngine->Release(); +} + +/** + * @tc.name: PragmaTest001 + * @tc.desc: Calling Pragma incorrectly + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, PragmaTest001, TestSize.Level1) +{ + /** + * @tc.steps: step1. the parameter is null + * @tc.expected: step1. Expect -E_INVALID_ARGS + */ + EXPECT_EQ(g_connection->Pragma(PRAGMA_RESULT_SET_CACHE_MAX_SIZE, nullptr), -E_INVALID_ARGS); + EXPECT_EQ(g_connection->Pragma(PRAGMA_RESULT_SET_CACHE_MODE, nullptr), -E_INVALID_ARGS); + EXPECT_EQ(g_connection->Pragma(PRAGMA_SET_AUTO_LIFE_CYCLE, nullptr), -E_INVALID_ARGS); + EXPECT_EQ(g_connection->Pragma(PRAGMA_UNPUBLISH_SYNC, nullptr), -E_INVALID_ARGS); + EXPECT_EQ(g_connection->Pragma(PRAGMA_PUBLISH_LOCAL, nullptr), -E_INVALID_ARGS); + EXPECT_EQ(g_connection->Pragma(PRAGMA_GET_DEVICE_IDENTIFIER_OF_ENTRY, nullptr), -E_INVALID_ARGS); + EXPECT_EQ(g_connection->Pragma(PRAGMA_SET_MAX_LOG_LIMIT, nullptr), -E_INVALID_ARGS); + EXPECT_EQ(g_connection->Pragma(PRAGMA_GET_IDENTIFIER_OF_DEVICE, nullptr), -E_INVALID_ARGS); + + /** + * @tc.steps: step2. the option is invalid + * @tc.expected: step2. Expect -E_INVALID_ARGS + */ + std::unique_ptr emptyConn = + std::make_unique(nullptr); + ASSERT_NE(emptyConn, nullptr); + SecurityOption option = {S3, SECE}; + EXPECT_EQ(emptyConn->Pragma(PRAGMA_TRIGGER_TO_MIGRATE_DATA, &option), -E_INVALID_CONNECTION); + + /** + * @tc.steps: step3. the size is invalid + * @tc.expected: step3. Expect -E_INVALID_ARGS + */ + int size = 0; + EXPECT_EQ(emptyConn->Pragma(PRAGMA_RESULT_SET_CACHE_MAX_SIZE, &size), -E_INVALID_ARGS); + size = 1; + EXPECT_EQ(emptyConn->Pragma(PRAGMA_RESULT_SET_CACHE_MAX_SIZE, &size), E_OK); + + /** + * @tc.steps: step4. the mode is invalid + * @tc.expected: step4. Expect -E_INVALID_ARGS + */ + ResultSetCacheMode mode = ResultSetCacheMode(2); // 2 is invalid mode + EXPECT_EQ(emptyConn->Pragma(PRAGMA_RESULT_SET_CACHE_MODE, &mode), -E_INVALID_ARGS); + + /** + * @tc.steps: step5. the db is null + * @tc.expected: step5. Expect -E_INVALID_DB + */ + int time = 6000; // 6000 is random + EXPECT_EQ(emptyConn->Pragma(PRAGMA_SET_AUTO_LIFE_CYCLE, &time), -E_INVALID_DB); +} + +/** + * @tc.name: PragmaTest002 + * @tc.desc: Incorrect publishing and unPublishing + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, PragmaTest002, TestSize.Level1) +{ + /** + * @tc.steps: step1. the db is null + * @tc.expected: step1. Expect -E_INVALID_DB + */ + std::unique_ptr emptyConn = + std::make_unique(nullptr); + PragmaPublishInfo info; + EXPECT_EQ(emptyConn->Pragma(PRAGMA_PUBLISH_LOCAL, &info), -E_INVALID_DB); + EXPECT_EQ(emptyConn->Pragma(PRAGMA_UNPUBLISH_SYNC, &info), -E_INVALID_DB); + + /** + * @tc.steps: step2. publish in transaction + * @tc.expected: step2. Expect -E_NOT_SUPPORT + */ + g_store->ReleaseHandle(g_handle); + g_connection->StartTransaction(); + EXPECT_EQ(g_connection->Pragma(PRAGMA_PUBLISH_LOCAL, &info), -E_NOT_SUPPORT); + EXPECT_EQ(g_connection->Pragma(PRAGMA_UNPUBLISH_SYNC, &info), -E_NOT_SUPPORT); + g_connection->RollBack(); + + /** + * @tc.steps: step3. publish in cacheDB + * @tc.expected: step3. Expect -E_EKEYREVOKED + */ + int errCode = E_OK; + SQLiteSingleVerStorageEngine *storageEngine = + static_cast(StorageEngineManager::GetStorageEngine(g_property, errCode)); + ASSERT_EQ(errCode, E_OK); + ASSERT_NE(storageEngine, nullptr); + storageEngine->SetEngineState(EngineState::CACHEDB); + EXPECT_EQ(g_connection->Pragma(PRAGMA_PUBLISH_LOCAL, &info), -E_EKEYREVOKED); + EXPECT_EQ(g_connection->Pragma(PRAGMA_UNPUBLISH_SYNC, &info), -E_EKEYREVOKED); + g_connection->StartTransaction(); + g_connection->Commit(); + storageEngine->Release(); +} + +/** + * @tc.name: PragmaTest003 + * @tc.desc: Failed to call function with empty connection + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, PragmaTest003, TestSize.Level1) +{ + std::unique_ptr emptyConn = + std::make_unique(nullptr); + PragmaEntryDeviceIdentifier identifier = {.key = KEY_1}; + EXPECT_EQ(emptyConn->Pragma(PRAGMA_GET_DEVICE_IDENTIFIER_OF_ENTRY, &identifier), -E_NOT_INIT); + EXPECT_EQ(emptyConn->CheckIntegrity(), -E_NOT_INIT); + + int limit = 0; + EXPECT_EQ(emptyConn->Pragma(PRAGMA_SET_MAX_LOG_LIMIT, &limit), -E_INVALID_DB); + CipherPassword pw; + EXPECT_EQ(emptyConn->Import("/a.b", pw), -E_INVALID_DB); + DatabaseLifeCycleNotifier notifier; + EXPECT_EQ(emptyConn->RegisterLifeCycleCallback(notifier), -E_INVALID_DB); } \ No newline at end of file -- Gitee From 2f74a42a591d5731d83d318e6dcb2469249644b0 Mon Sep 17 00:00:00 2001 From: saikit Date: Wed, 30 Nov 2022 15:13:13 +0800 Subject: [PATCH 008/191] add multi_ver macro Signed-off-by: saikit Change-Id: Ib38e5a508693655c68b654f709bbd1030825f07d --- frameworks/libs/distributeddb/BUILD.gn | 1 + .../include/kv_store_delegate_manager.h | 7 +- .../src/kv_store_delegate_manager.cpp | 17 +- .../storage/include/ikvdb_factory.h | 4 +- .../storage/include/single_ver_kv_entry.h | 1 + .../storage/src/kvdb_manager.cpp | 16 +- frameworks/libs/distributeddb/test/BUILD.gn | 1 + .../test/fuzztest/sync_fuzzer/BUILD.gn | 1 + .../common/distributeddb_tools_unit_test.cpp | 15 +- .../common/distributeddb_tools_unit_test.h | 10 +- ..._interfaces_data_operation_syncdb_test.cpp | 3 +- ...buteddb_interfaces_data_operation_test.cpp | 75 ++++--- ...teddb_interfaces_database_corrupt_test.cpp | 201 +++++++++++++----- ...distributeddb_interfaces_database_test.cpp | 11 +- ...teddb_interfaces_encrypt_database_test.cpp | 54 ++--- ...teddb_interfaces_encrypt_delegate_test.cpp | 53 +++-- ...eddb_interfaces_import_and_export_test.cpp | 56 +++-- ...tributeddb_interfaces_nb_delegate_test.cpp | 27 ++- ...uteddb_interfaces_register_syncdb_test.cpp | 3 +- ...teddb_interfaces_resultset_performance.cpp | 8 +- ...teddb_interfaces_space_management_test.cpp | 23 +- ...ddb_interfaces_transaction_syncdb_test.cpp | 5 +- ...tributeddb_interfaces_transaction_test.cpp | 5 +- ...uteddb_interfaces_transaction_testcase.cpp | 5 +- ...ibuteddb_interfaces_transaction_testcase.h | 5 +- .../distributeddb_multi_ver_vacuum_test.cpp | 3 +- ...tributeddb_storage_commit_storage_test.cpp | 3 +- ...tributeddb_storage_data_operation_test.cpp | 2 + ...ibuteddb_storage_transaction_data_test.cpp | 3 +- ...uteddb_storage_transaction_record_test.cpp | 4 +- .../distributeddb_multi_ver_p2p_sync_test.cpp | 5 +- .../common/syncer/generic_virtual_device.cpp | 7 +- .../common/syncer/kv_virtual_device.cpp | 60 +++--- .../virtual_multi_ver_sync_db_interface.cpp | 3 +- .../virtual_multi_ver_sync_db_interface.h | 5 +- kvstoremock/distributeddb/BUILD.gn | 1 + 36 files changed, 463 insertions(+), 240 deletions(-) diff --git a/frameworks/libs/distributeddb/BUILD.gn b/frameworks/libs/distributeddb/BUILD.gn index 3b8f2f2b394..f756983923e 100644 --- a/frameworks/libs/distributeddb/BUILD.gn +++ b/frameworks/libs/distributeddb/BUILD.gn @@ -44,6 +44,7 @@ config("distrdb_config") { "USING_DB_JSON_EXTRACT_AUTOMATICALLY", "JSONCPP_USE_BUILDER", "OMIT_FLATBUFFER", + "OMIT_MULTI_VER", "RELATIONAL_STORE", "SQLITE_DISTRIBUTE_RELATIONAL", "USE_DFX_ABILITY", diff --git a/frameworks/libs/distributeddb/interfaces/include/kv_store_delegate_manager.h b/frameworks/libs/distributeddb/interfaces/include/kv_store_delegate_manager.h index 70f1cc6ec37..78bc31ff212 100644 --- a/frameworks/libs/distributeddb/interfaces/include/kv_store_delegate_manager.h +++ b/frameworks/libs/distributeddb/interfaces/include/kv_store_delegate_manager.h @@ -25,9 +25,7 @@ #include "auto_launch_export.h" #include "iprocess_communicator.h" #include "iprocess_system_api_adapter.h" -#ifndef OMIT_MULTI_VER #include "kv_store_delegate.h" -#endif #include "kv_store_nb_delegate.h" #include "store_types.h" @@ -45,12 +43,11 @@ public: // Used to set global config of the KvStores, such dataDir, return OK if set config success. DB_API DBStatus SetKvStoreConfig(const KvStoreConfig &kvStoreConfig); -#ifndef OMIT_MULTI_VER // Used to open or create a KvStore. // Return OK and a KvStoreDelegate* if there is no error. else return ERROR and nullptr; DB_API void GetKvStore(const std::string &storeId, const KvStoreDelegate::Option &option, const std::function &callback); -#endif + // Used to open or create a KvStore(Natural store). // Suggest: Not to use encrypted database in S3 SECE access controlled; // Warning: Access controlled prevents access to files so cannot verify passwords, @@ -58,10 +55,8 @@ public: DB_API void GetKvStore(const std::string &storeId, const KvStoreNbDelegate::Option &option, const std::function &callback); -#ifndef OMIT_MULTI_VER // Close a KvStore, return OK if close success. DB_API DBStatus CloseKvStore(KvStoreDelegate *kvStore); -#endif DB_API DBStatus CloseKvStore(KvStoreNbDelegate *kvStore); diff --git a/frameworks/libs/distributeddb/interfaces/src/kv_store_delegate_manager.cpp b/frameworks/libs/distributeddb/interfaces/src/kv_store_delegate_manager.cpp index 311c51c5598..adc8a0eca76 100644 --- a/frameworks/libs/distributeddb/interfaces/src/kv_store_delegate_manager.cpp +++ b/frameworks/libs/distributeddb/interfaces/src/kv_store_delegate_manager.cpp @@ -35,9 +35,7 @@ #include "runtime_context.h" #include "param_check_utils.h" #include "auto_launch.h" -#ifndef OMIT_MULTI_VER #include "kv_store_delegate_impl.h" -#endif namespace DistributedDB { const std::string KvStoreDelegateManager::DEFAULT_PROCESS_APP_ID = "default"; @@ -171,7 +169,6 @@ DBStatus KvStoreDelegateManager::SetKvStoreConfig(const KvStoreConfig &kvStoreCo return OK; } -#ifndef OMIT_MULTI_VER void KvStoreDelegateManager::GetKvStore(const std::string &storeId, const KvStoreDelegate::Option &option, const std::function &callback) { @@ -179,7 +176,7 @@ void KvStoreDelegateManager::GetKvStore(const std::string &storeId, const KvStor LOGE("[KvStoreMgr] Invalid callback for kv store!"); return; } - +#ifndef OMIT_MULTI_VER // Multi version and local database mode not allow the creation of a memory database if (!ParamCheckUtils::CheckStoreParameter(storeId, appId_, userId_) || GetKvStorePath().empty()) { callback(INVALID_ARGS, nullptr); @@ -217,8 +214,11 @@ void KvStoreDelegateManager::GetKvStore(const std::string &storeId, const KvStor return; } callback(OK, kvStore); -} +#else + callback(NOT_SUPPORT, nullptr); + return; #endif +} DBStatus KvStoreDelegateManager::SetObserverNotifier(KvStoreNbDelegate *kvStore, const KvStoreNbDelegate::Option &option) @@ -341,9 +341,10 @@ void KvStoreDelegateManager::GetKvStore(const std::string &storeId, const KvStor callback(OK, kvStore); } -#ifndef OMIT_MULTI_VER + DBStatus KvStoreDelegateManager::CloseKvStore(KvStoreDelegate *kvStore) { +#ifndef OMIT_MULTI_VER if (kvStore == nullptr) { return INVALID_ARGS; } @@ -359,8 +360,10 @@ DBStatus KvStoreDelegateManager::CloseKvStore(KvStoreDelegate *kvStore) delete kvStore; kvStore = nullptr; return OK; -} +#else + return NOT_SUPPORT; #endif +} DBStatus KvStoreDelegateManager::CloseKvStore(KvStoreNbDelegate *kvStore) { diff --git a/frameworks/libs/distributeddb/storage/include/ikvdb_factory.h b/frameworks/libs/distributeddb/storage/include/ikvdb_factory.h index eaf5600bcc1..2bf9940b504 100644 --- a/frameworks/libs/distributeddb/storage/include/ikvdb_factory.h +++ b/frameworks/libs/distributeddb/storage/include/ikvdb_factory.h @@ -29,8 +29,10 @@ namespace DistributedDB { enum KvDBType { LOCAL_KVDB = 0, SINGER_VER_KVDB, +#ifndef OMIT_MULTI_VER MULTI_VER_KVDB, - UNSUPPORT_KVDB_TYPE, +#endif // OMIT_MULTI_VER + UNSUPPORT_KVDB_TYPE = 3, }; class IKvDBFactory { diff --git a/frameworks/libs/distributeddb/storage/include/single_ver_kv_entry.h b/frameworks/libs/distributeddb/storage/include/single_ver_kv_entry.h index 626ad2375f5..c5e02e8c68b 100644 --- a/frameworks/libs/distributeddb/storage/include/single_ver_kv_entry.h +++ b/frameworks/libs/distributeddb/storage/include/single_ver_kv_entry.h @@ -17,6 +17,7 @@ #define SINGLE_VER_KV_ENTRY_H #include +#include "db_types.h" #include "parcel.h" namespace DistributedDB { diff --git a/frameworks/libs/distributeddb/storage/src/kvdb_manager.cpp b/frameworks/libs/distributeddb/storage/src/kvdb_manager.cpp index e153487fe79..74337966543 100644 --- a/frameworks/libs/distributeddb/storage/src/kvdb_manager.cpp +++ b/frameworks/libs/distributeddb/storage/src/kvdb_manager.cpp @@ -33,6 +33,14 @@ std::map KvDBManager::locks_; namespace { DefaultFactory g_defaultFactory; + static const KvDBType g_dbTypeArr[] = { + LOCAL_KVDB, + SINGER_VER_KVDB, +#ifndef OMIT_MULTI_VER + MULTI_VER_KVDB +#endif // OMIT_MULTI_VER + }; + int CreateDataBaseInstance(const KvDBProperties &property, IKvDB *&kvDB) { IKvDBFactory *factory = IKvDBFactory::GetCurrent(); @@ -49,7 +57,11 @@ namespace { } else if (databaseType == KvDBProperties::SINGLE_VER_TYPE) { kvDB = factory->CreateKvDb(SINGER_VER_KVDB, errCode); } else { +#ifndef OMIT_MULTI_VER kvDB = factory->CreateKvDb(MULTI_VER_KVDB, errCode); +#else + return -E_NOT_SUPPORT; +#endif // OMIT_MULTI_VER } return errCode; } @@ -108,7 +120,7 @@ int KvDBManager::ExecuteRemoveDatabase(const KvDBProperties &properties) } errCode = -E_NOT_FOUND; - for (KvDBType kvDbType = LOCAL_KVDB; kvDbType < UNSUPPORT_KVDB_TYPE; kvDbType = (KvDBType)(kvDbType + 1)) { + for (const KvDBType kvDbType : g_dbTypeArr) { int innerErrCode = E_OK; IKvDB *kvdb = factory->CreateKvDb(kvDbType, innerErrCode); if (innerErrCode != E_OK) { @@ -435,7 +447,7 @@ int KvDBManager::CalculateKvStoreSize(const KvDBProperties &properties, uint64_t } uint64_t totalSize = 0; - for (KvDBType kvDbType = LOCAL_KVDB; kvDbType < UNSUPPORT_KVDB_TYPE; kvDbType = (KvDBType)(kvDbType + 1)) { + for (const KvDBType kvDbType : g_dbTypeArr) { int innerErrCode = E_OK; IKvDB *kvDB = factory->CreateKvDb(kvDbType, innerErrCode); if (innerErrCode != E_OK) { diff --git a/frameworks/libs/distributeddb/test/BUILD.gn b/frameworks/libs/distributeddb/test/BUILD.gn index 4545e7244c6..c3db3c40c14 100644 --- a/frameworks/libs/distributeddb/test/BUILD.gn +++ b/frameworks/libs/distributeddb/test/BUILD.gn @@ -57,6 +57,7 @@ config("module_private_config") { "LOW_LEVEL_MEM_DEV", "JSONCPP_USE_BUILDER", "OMIT_FLATBUFFER", + "OMIT_MULTI_VER", "RELATIONAL_STORE", "SQLITE_DISTRIBUTE_RELATIONAL", "USE_DFX_ABILITY", diff --git a/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/BUILD.gn b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/BUILD.gn index e30d87c59c7..76e3ead5d3d 100644 --- a/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/BUILD.gn +++ b/frameworks/libs/distributeddb/test/fuzztest/sync_fuzzer/BUILD.gn @@ -81,6 +81,7 @@ ohos_fuzztest("SyncFuzzTest") { "LOW_LEVEL_MEM_DEV", "JSONCPP_USE_BUILDER", "OMIT_FLATBUFFER", + "OMIT_MULTI_VER", "RELATIONAL_STORE", "SQLITE_DISTRIBUTE_RELATIONAL", ] diff --git a/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp index 88525b61bc5..9d9c96df073 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp @@ -298,6 +298,7 @@ int DistributedDBToolsUnitTest::RemoveTestDbFiles(const std::string &dir) return 0; } +#ifndef OMIT_MULTI_VER void DistributedDBToolsUnitTest::KvStoreDelegateCallback( DBStatus statusSrc, KvStoreDelegate *kvStoreSrc, DBStatus &statusDst, KvStoreDelegate *&kvStoreDst) { @@ -305,18 +306,20 @@ void DistributedDBToolsUnitTest::KvStoreDelegateCallback( kvStoreDst = kvStoreSrc; } -void DistributedDBToolsUnitTest::KvStoreNbDelegateCallback( - DBStatus statusSrc, KvStoreNbDelegate* kvStoreSrc, DBStatus &statusDst, KvStoreNbDelegate *&kvStoreDst) -{ - statusDst = statusSrc; - kvStoreDst = kvStoreSrc; -} void DistributedDBToolsUnitTest::SnapshotDelegateCallback( DBStatus statusSrc, KvStoreSnapshotDelegate* snapshot, DBStatus &statusDst, KvStoreSnapshotDelegate *&snapshotDst) { statusDst = statusSrc; snapshotDst = snapshot; } +#endif + +void DistributedDBToolsUnitTest::KvStoreNbDelegateCallback( + DBStatus statusSrc, KvStoreNbDelegate* kvStoreSrc, DBStatus &statusDst, KvStoreNbDelegate *&kvStoreDst) +{ + statusDst = statusSrc; + kvStoreDst = kvStoreSrc; +} void DistributedDBToolsUnitTest::ValueCallback( DBStatus statusSrc, const Value &valueSrc, DBStatus &statusDst, Value &valueDst) diff --git a/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h b/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h index bc38f9dca7f..c44ccbd77e6 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h +++ b/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h @@ -122,17 +122,19 @@ public: // remove the test db files in the test directory of dir. static int RemoveTestDbFiles(const std::string &dir); +#ifndef OMIT_MULTI_VER // callback function for get a KvStoreDelegate pointer. static void KvStoreDelegateCallback(DistributedDB::DBStatus, DistributedDB::KvStoreDelegate*, DistributedDB::DBStatus &, DistributedDB::KvStoreDelegate *&); - // callback function for get a KvStoreDelegate pointer. - static void KvStoreNbDelegateCallback(DistributedDB::DBStatus, DistributedDB::KvStoreNbDelegate*, - DistributedDB::DBStatus &, DistributedDB::KvStoreNbDelegate *&); - // callback function for get a KvStoreSnapshotDelegate pointer. static void SnapshotDelegateCallback(DistributedDB::DBStatus, DistributedDB::KvStoreSnapshotDelegate*, DistributedDB::DBStatus &, DistributedDB::KvStoreSnapshotDelegate *&); +#endif + + // callback function for get a KvStoreDelegate pointer. + static void KvStoreNbDelegateCallback(DistributedDB::DBStatus, DistributedDB::KvStoreNbDelegate*, + DistributedDB::DBStatus &, DistributedDB::KvStoreNbDelegate *&); // callback function for get the value. static void ValueCallback( diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_syncdb_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_syncdb_test.cpp index 9659896c98f..46eac7dff8e 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_syncdb_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_syncdb_test.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef OMIT_MULTI_VER #include #include #include @@ -1382,3 +1382,4 @@ HWTEST_F(DistributedDBInterfacesDataOperationSyncDBTest, TransactionException001 g_snapshotDelegatePtr->Get(KEY_4, g_valueCallback); EXPECT_EQ(g_valueStatus, NOT_FOUND); } +#endif diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_test.cpp index 36c214cc070..328760930f5 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_data_operation_test.cpp @@ -25,20 +25,19 @@ using namespace std; namespace { string g_testDir; - const bool LOCAL_ONLY = true; const string STORE_ID = STORE_ID_LOCAL; KvStoreDelegateManager g_mgr(APP_ID, USER_ID); KvStoreConfig g_config; // define the g_kvDelegateCallback, used to get some information when open a kv store. DBStatus g_kvDelegateStatusForQuery = INVALID_ARGS; + +#ifndef OMIT_MULTI_VER + const bool LOCAL_ONLY = true; KvStoreDelegate *g_kvDelegatePtrForQuery = nullptr; // the type of g_kvDelegateCallback is function auto g_kvDelegateCallbackForQuery = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1, placeholders::_2, std::ref(g_kvDelegateStatusForQuery), std::ref(g_kvDelegatePtrForQuery)); - KvStoreNbDelegate *g_kvNbDelegatePtrForQuery = nullptr; - auto g_kvNbDelegateCallbackForQuery = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, - placeholders::_1, placeholders::_2, std::ref(g_kvDelegateStatusForQuery), std::ref(g_kvNbDelegatePtrForQuery)); // define the g_kvDelegateCallback, used to get some information when open a kv store. DBStatus g_kvDelegateStatus = INVALID_ARGS; @@ -53,6 +52,11 @@ namespace { // the type of g_snapshotDelegateCallback is function auto g_snapshotDelegateCallback = bind(&DistributedDBToolsUnitTest::SnapshotDelegateCallback, placeholders::_1, placeholders::_2, std::ref(g_snapshotDelegateStatus), std::ref(g_snapshotDelegatePtr)); +#endif // OMIT_MULTI_VER + + KvStoreNbDelegate *g_kvNbDelegatePtrForQuery = nullptr; + auto g_kvNbDelegateCallbackForQuery = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, + placeholders::_1, placeholders::_2, std::ref(g_kvDelegateStatusForQuery), std::ref(g_kvNbDelegatePtrForQuery)); // define the g_valueCallback, used to query a value object data from the kvdb. DBStatus g_valueStatus = INVALID_ARGS; @@ -84,13 +88,40 @@ namespace { "\"field_name10\":\"LONG, DEFAULT 100\"" "}," "\"SCHEMA_INDEXES\":[\"$.field_name1\", \"$.field_name2\"]}"; - +#ifndef OMIT_MULTI_VER void GetSnapshotUnitTest() { g_kvDelegatePtr->GetKvStoreSnapshot(nullptr, g_snapshotDelegateCallback); EXPECT_TRUE(g_snapshotDelegateStatus == OK); ASSERT_TRUE(g_snapshotDelegatePtr != nullptr); } + + void TestSnapshotCreateAndRelease() + { + DBStatus status; + KvStoreSnapshotDelegate *snapshot = nullptr; + KvStoreObserver *observer = nullptr; + auto snapshotDelegateCallback = bind(&DistributedDBToolsUnitTest::SnapshotDelegateCallback, + placeholders::_1, placeholders::_2, std::ref(status), std::ref(snapshot)); + + /** + * @tc.steps: step1. Obtain the snapshot object snapshot through + * the GetKvStoreSnapshot interface of the delegate. + * @tc.expected: step1. Returns a non-empty snapshot. + */ + g_kvDelegatePtr->GetKvStoreSnapshot(observer, snapshotDelegateCallback); + + EXPECT_TRUE(status == OK); + EXPECT_NE(snapshot, nullptr); + + /** + * @tc.steps: step2. Release the obtained snapshot through + * the ReleaseKvStoreSnapshot interface of the delegate. + * @tc.expected: step2. Release successfully. + */ + EXPECT_EQ(g_kvDelegatePtr->ReleaseKvStoreSnapshot(snapshot), OK); + } +#endif // OMIT_MULTI_VER #ifndef OMIT_JSON const int CIRCLE_COUNT = 3; void PutValidEntries1() @@ -271,33 +302,7 @@ namespace { Value value5(validData.begin(), validData.end()); EXPECT_EQ(g_kvNbDelegatePtrForQuery->Put(KEY_5, value5), OK); } -#endif - void TestSnapshotCreateAndRelease() - { - DBStatus status; - KvStoreSnapshotDelegate *snapshot = nullptr; - KvStoreObserver *observer = nullptr; - auto snapshotDelegateCallback = bind(&DistributedDBToolsUnitTest::SnapshotDelegateCallback, - placeholders::_1, placeholders::_2, std::ref(status), std::ref(snapshot)); - /** - * @tc.steps: step1. Obtain the snapshot object snapshot through - * the GetKvStoreSnapshot interface of the delegate. - * @tc.expected: step1. Returns a non-empty snapshot. - */ - g_kvDelegatePtr->GetKvStoreSnapshot(observer, snapshotDelegateCallback); - - EXPECT_TRUE(status == OK); - EXPECT_NE(snapshot, nullptr); - - /** - * @tc.steps: step2. Release the obtained snapshot through - * the ReleaseKvStoreSnapshot interface of the delegate. - * @tc.expected: step2. Release successfully. - */ - EXPECT_EQ(g_kvDelegatePtr->ReleaseKvStoreSnapshot(snapshot), OK); - } -#ifndef OMIT_JSON vector PreDataForQueryByPreFixKey() { vector res; @@ -373,15 +378,18 @@ void DistributedDBInterfacesDataOperationTest::SetUp(void) * Here, we create STORE_ID.db before test, * and it will be closed in TearDown(). */ +#ifndef OMIT_MULTI_VER CipherPassword passwd; KvStoreDelegate::Option option = {true, LOCAL_ONLY, false, CipherType::DEFAULT, passwd}; g_mgr.GetKvStore(STORE_ID, option, g_kvDelegateCallback); EXPECT_TRUE(g_kvDelegateStatus == OK); ASSERT_TRUE(g_kvDelegatePtr != nullptr); +#endif // OMIT_MULTI_VER } void DistributedDBInterfacesDataOperationTest::TearDown(void) { +#ifndef OMIT_MULTI_VER if (g_kvDelegatePtr != nullptr && g_snapshotDelegatePtr != nullptr) { EXPECT_TRUE(g_kvDelegatePtr->ReleaseKvStoreSnapshot(g_snapshotDelegatePtr) == OK); g_snapshotDelegatePtr = nullptr; @@ -391,8 +399,10 @@ void DistributedDBInterfacesDataOperationTest::TearDown(void) EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); g_kvDelegatePtr = nullptr; } +#endif // OMIT_MULTI_VER } +#ifndef OMIT_MULTI_VER /** * @tc.name: Put001 * @tc.desc: Put a data(non-empty key, non-empty value) into an exist distributed db @@ -988,6 +998,7 @@ HWTEST_F(DistributedDBInterfacesDataOperationTest, SetConflictResolutionPolicyFa */ EXPECT_NE(g_kvDelegatePtr->SetConflictResolutionPolicy(CUSTOMER_RESOLUTION, nullptr), OK); } +#endif // OMIT_MULTI_VER #ifndef OMIT_JSON /** * @tc.name: GetEntriesWithQuery001 @@ -2479,4 +2490,4 @@ HWTEST_F(DistributedDBInterfacesDataOperationTest, WriteTimeSort007, TestSize.Le EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtrForQuery), OK); EXPECT_EQ(g_mgr.DeleteKvStore("WriteTimeSort007"), OK); } -#endif // OMIT_JSON \ No newline at end of file +#endif // OMIT_JSON diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_corrupt_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_corrupt_test.cpp index 795d7e661c0..bb28d3b9c36 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_corrupt_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_corrupt_test.cpp @@ -35,12 +35,15 @@ namespace { string g_testDir; KvStoreConfig g_config; +#ifndef OMIT_MULTI_VER DBStatus g_kvDelegateStatus = INVALID_ARGS; - DBStatus g_kvNbDelegateStatus = INVALID_ARGS; KvStoreDelegate *g_kvDelegatePtr = nullptr; - KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr; auto g_kvDelegateCallback = std::bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, std::placeholders::_1, std::placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvDelegatePtr)); +#endif // OMIT_MULTI_VER + + DBStatus g_kvNbDelegateStatus = INVALID_ARGS; + KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr; auto g_kvNbDelegateCallback = std::bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, std::placeholders::_1, std::placeholders::_2, std::ref(g_kvNbDelegateStatus), std::ref(g_kvNbDelegatePtr)); @@ -66,30 +69,30 @@ namespace { return filePath; } - int PutDataIntoDatabase(KvStoreDelegate *kvDelegate, KvStoreNbDelegate *kvNbDelegate) + int PutDataIntoDatabaseSingleVer(KvStoreNbDelegate *kvNbDelegate) { - if (kvDelegate == nullptr && kvNbDelegate == nullptr) { + if (kvNbDelegate == nullptr) { return DBStatus::DB_ERROR; } Key key; Value value; DistributedDBToolsUnitTest::GetRandomKeyValue(key); DistributedDBToolsUnitTest::GetRandomKeyValue(value); - DBStatus status = OK; - if (kvDelegate != nullptr) { - status = kvDelegate->Put(key, value); - if (status != OK) { - return status; - } - } - if (kvNbDelegate != nullptr) { - status = kvNbDelegate->Put(key, value); - if (status != OK) { - return status; - } + return kvNbDelegate->Put(key, value); + } +#ifndef OMIT_MULTI_VER + int PutDataIntoDatabaseMultiVer(KvStoreDelegate *kvDelegate) + { + if (kvDelegate == nullptr) { + return DBStatus::DB_ERROR; } - return status; + Key key; + Value value; + DistributedDBToolsUnitTest::GetRandomKeyValue(key); + DistributedDBToolsUnitTest::GetRandomKeyValue(value); + return kvDelegate->Put(key, value); } +#endif // OMIT_MULTI_VER } class DistributedDBInterfacesDatabaseCorruptTest : public testing::Test { @@ -116,9 +119,11 @@ void DistributedDBInterfacesDatabaseCorruptTest::TearDownTestCase(void) void DistributedDBInterfacesDatabaseCorruptTest::SetUp(void) { +#ifndef OMIT_MULTI_VER DistributedDBToolsUnitTest::PrintTestCaseInfo(); g_kvDelegateStatus = INVALID_ARGS; g_kvDelegatePtr = nullptr; +#endif // OMIT_MULTI_VER } void DistributedDBInterfacesDatabaseCorruptTest::TearDown(void) @@ -126,6 +131,7 @@ void DistributedDBInterfacesDatabaseCorruptTest::TearDown(void) g_mgr.SetKvStoreCorruptionHandler(nullptr); } +#ifndef OMIT_MULTI_VER /** * @tc.name: DatabaseCorruptionHandleTest001 * @tc.desc: Check the corruption detect without setting the corrupt handler. @@ -149,7 +155,7 @@ HWTEST_F(DistributedDBInterfacesDatabaseCorruptTest, DatabaseCorruptionHandleTes g_mgr.GetKvStore("corrupt1", option, g_kvDelegateCallback); ASSERT_TRUE(g_kvDelegatePtr != nullptr); EXPECT_TRUE(g_kvDelegateStatus == OK); - ASSERT_EQ(PutDataIntoDatabase(g_kvDelegatePtr, nullptr), OK); + ASSERT_EQ(PutDataIntoDatabaseMultiVer(g_kvDelegatePtr), OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); g_kvDelegatePtr = nullptr; @@ -168,6 +174,7 @@ HWTEST_F(DistributedDBInterfacesDatabaseCorruptTest, DatabaseCorruptionHandleTes EXPECT_TRUE(g_kvDelegateStatus == INVALID_PASSWD_OR_CORRUPTED_DB); g_mgr.DeleteKvStore("corrupt1"); } +#endif // OMIT_MULTI_VER /** * @tc.name: DatabaseCorruptionHandleTest002 @@ -188,24 +195,30 @@ HWTEST_F(DistributedDBInterfacesDatabaseCorruptTest, DatabaseCorruptionHandleTes DistributedDBToolsUnitTest::GetRandomKeyValue(randomPassword, PASSWD_SIZE); int errCode = passwd.SetValue(randomPassword.data(), randomPassword.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); +#ifndef OMIT_MULTI_VER KvStoreDelegate::Option option = {true, false, false, CipherType::DEFAULT, passwd}; - KvStoreNbDelegate::Option nbOption = {true, false, false, CipherType::DEFAULT, passwd}; - g_mgr.GetKvStore("corrupt2", option, g_kvDelegateCallback); - g_mgr.GetKvStore("corrupt3", nbOption, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvDelegatePtr != nullptr); - ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); - ASSERT_EQ(PutDataIntoDatabase(g_kvDelegatePtr, g_kvNbDelegatePtr), OK); + ASSERT_EQ(PutDataIntoDatabaseMultiVer(g_kvDelegatePtr), OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); - EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); g_kvDelegatePtr = nullptr; +#endif // OMIT_MULTI_VER + + KvStoreNbDelegate::Option nbOption = {true, false, false, CipherType::DEFAULT, passwd}; + g_mgr.GetKvStore("corrupt3", nbOption, g_kvNbDelegateCallback); + ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); + ASSERT_EQ(PutDataIntoDatabaseSingleVer(g_kvNbDelegatePtr), OK); + EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); g_kvNbDelegatePtr = nullptr; /** * @tc.steps: step4. Modify the database file. */ - std::string filePath = GetKvStoreDirectory("corrupt2", DBConstant::DB_TYPE_MULTI_VER); + std::string filePath; +#ifndef OMIT_MULTI_VER + filePath = GetKvStoreDirectory("corrupt2", DBConstant::DB_TYPE_MULTI_VER); DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath); +#endif // OMIT_MULTI_VER filePath = GetKvStoreDirectory("corrupt3", DBConstant::DB_TYPE_SINGLE_VER); // single ver database. DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath); KvStoreCorruptInfo corruptInfo; @@ -217,15 +230,21 @@ HWTEST_F(DistributedDBInterfacesDatabaseCorruptTest, DatabaseCorruptionHandleTes * @tc.steps: step5. Re-obtain the kvStore. * @tc.expected: step5. Returns null kvstore. */ + size_t infoSize = 0; +#ifndef OMIT_MULTI_VER g_mgr.GetKvStore("corrupt2", option, g_kvDelegateCallback); - g_mgr.GetKvStore("corrupt3", nbOption, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvDelegateStatus != OK); + EXPECT_EQ(corruptInfo.IsDataBaseCorrupted(APP_NAME, USER_NAME, "corrupt2"), true); + g_mgr.DeleteKvStore("corrupt2"); + infoSize++; +#endif // OMIT_MULTI_VER + + g_mgr.GetKvStore("corrupt3", nbOption, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvNbDelegateStatus != OK); + infoSize++; std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_CALLBACK_TIME)); - EXPECT_EQ(corruptInfo.GetDatabaseInfoSize(), 2UL); // 2 callback - EXPECT_EQ(corruptInfo.IsDataBaseCorrupted(APP_NAME, USER_NAME, "corrupt2"), true); + EXPECT_EQ(corruptInfo.GetDatabaseInfoSize(), infoSize); // 2 callback EXPECT_EQ(corruptInfo.IsDataBaseCorrupted(APP_NAME, USER_NAME, "corrupt3"), true); - g_mgr.DeleteKvStore("corrupt2"); g_mgr.DeleteKvStore("corrupt3"); } @@ -248,20 +267,25 @@ HWTEST_F(DistributedDBInterfacesDatabaseCorruptTest, DatabaseCorruptionHandleTes DistributedDBToolsUnitTest::GetRandomKeyValue(randomPassword, PASSWD_SIZE); int errCode = passwd.SetValue(randomPassword.data(), randomPassword.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); +#ifndef OMIT_MULTI_VER KvStoreDelegate::Option option = {true, true, false, CipherType::DEFAULT, passwd}; - KvStoreNbDelegate::Option nbOption = {true, false, false, CipherType::DEFAULT, passwd}; - g_mgr.GetKvStore("corrupt4", option, g_kvDelegateCallback); - g_mgr.GetKvStore("corrupt5", nbOption, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvDelegatePtr != nullptr); + ASSERT_EQ(PutDataIntoDatabaseMultiVer(g_kvDelegatePtr), OK); +#endif // OMIT_MULTI_VER + KvStoreNbDelegate::Option nbOption = {true, false, false, CipherType::DEFAULT, passwd}; + g_mgr.GetKvStore("corrupt5", nbOption, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); - ASSERT_EQ(PutDataIntoDatabase(g_kvDelegatePtr, g_kvNbDelegatePtr), OK); + ASSERT_EQ(PutDataIntoDatabaseSingleVer(g_kvNbDelegatePtr), OK); /** * @tc.steps: step4. Modify the database file. */ - std::string filePath = GetKvStoreDirectory("corrupt4", DBConstant::DB_TYPE_LOCAL); // local database. + std::string filePath; +#ifndef OMIT_MULTI_VER + filePath = GetKvStoreDirectory("corrupt4", DBConstant::DB_TYPE_LOCAL); // local database. DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath); +#endif // OMIT_MULTI_VER DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath + "-wal"); filePath = GetKvStoreDirectory("corrupt5", DBConstant::DB_TYPE_SINGLE_VER); // single ver database. DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath); @@ -275,17 +299,23 @@ HWTEST_F(DistributedDBInterfacesDatabaseCorruptTest, DatabaseCorruptionHandleTes * @tc.steps: step5. Put data into the kvStore. * @tc.expected: step5. The corrupt handler is called twice. */ - ASSERT_NE(PutDataIntoDatabase(g_kvDelegatePtr, nullptr), OK); - ASSERT_NE(PutDataIntoDatabase(nullptr, g_kvNbDelegatePtr), OK); + size_t infoSize = 0; +#ifndef OMIT_MULTI_VER + ASSERT_NE(PutDataIntoDatabaseMultiVer(g_kvDelegatePtr), OK); std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_CALLBACK_TIME)); - EXPECT_TRUE(corruptInfo.GetDatabaseInfoSize() >= 2UL); // 2 more callback EXPECT_EQ(corruptInfo.IsDataBaseCorrupted(APP_NAME, USER_NAME, "corrupt4"), true); - EXPECT_EQ(corruptInfo.IsDataBaseCorrupted(APP_NAME, USER_NAME, "corrupt5"), true); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); - EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); g_kvDelegatePtr = nullptr; - g_kvNbDelegatePtr = nullptr; EXPECT_EQ(g_mgr.DeleteKvStore("corrupt4"), OK); + infoSize++; +#endif // OMIT_MULTI_VER + ASSERT_NE(PutDataIntoDatabaseSingleVer(g_kvNbDelegatePtr), OK); + infoSize++; + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_CALLBACK_TIME)); + EXPECT_TRUE(corruptInfo.GetDatabaseInfoSize() >= infoSize); // 2 more callback + EXPECT_EQ(corruptInfo.IsDataBaseCorrupted(APP_NAME, USER_NAME, "corrupt5"), true); + EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); + g_kvNbDelegatePtr = nullptr; EXPECT_EQ(g_mgr.DeleteKvStore("corrupt5"), OK); } @@ -308,20 +338,16 @@ HWTEST_F(DistributedDBInterfacesDatabaseCorruptTest, DatabaseCorruptionHandleTes DistributedDBToolsUnitTest::GetRandomKeyValue(randomPassword, PASSWD_SIZE); int errCode = passwd.SetValue(randomPassword.data(), randomPassword.size()); ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); - KvStoreDelegate::Option option = {true, true, false, CipherType::DEFAULT, passwd}; - KvStoreNbDelegate::Option nbOption = {true, false, false, CipherType::DEFAULT, passwd}; - g_mgr.GetKvStore("corrupt6", option, g_kvDelegateCallback); + KvStoreNbDelegate::Option nbOption = {true, false, false, CipherType::DEFAULT, passwd}; g_mgr.GetKvStore("corrupt7", nbOption, g_kvNbDelegateCallback); - ASSERT_TRUE(g_kvDelegatePtr != nullptr); ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); - ASSERT_EQ(PutDataIntoDatabase(g_kvDelegatePtr, g_kvNbDelegatePtr), OK); + ASSERT_EQ(PutDataIntoDatabaseSingleVer(g_kvNbDelegatePtr), OK); /** * @tc.steps: step4. Modify the database file. */ - std::string filePath = GetKvStoreDirectory("corrupt6", DBConstant::DB_TYPE_LOCAL); // local database. - DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath); + std::string filePath; DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath + "-wal"); filePath = GetKvStoreDirectory("corrupt7", DBConstant::DB_TYPE_SINGLE_VER); // single ver database. DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath); @@ -338,21 +364,80 @@ HWTEST_F(DistributedDBInterfacesDatabaseCorruptTest, DatabaseCorruptionHandleTes * @tc.steps: step5. Re-obtain the kvStore. * @tc.expected: step5. Returns null kvstore. */ - ASSERT_NE(PutDataIntoDatabase(g_kvDelegatePtr, nullptr), OK); - ASSERT_NE(PutDataIntoDatabase(nullptr, g_kvNbDelegatePtr), OK); + size_t infoSize = 0; + ASSERT_NE(PutDataIntoDatabaseSingleVer(g_kvNbDelegatePtr), OK); + infoSize++; std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_CALLBACK_TIME)); EXPECT_EQ(corruptInfo.GetDatabaseInfoSize(), 0UL); // no callback - EXPECT_TRUE(corruptInfoNew.GetDatabaseInfoSize() >= 2UL); // 2 more callback - EXPECT_EQ(corruptInfoNew.IsDataBaseCorrupted(APP_NAME, USER_NAME, "corrupt6"), true); + EXPECT_TRUE(corruptInfoNew.GetDatabaseInfoSize() >= infoSize); // 2 more callback EXPECT_EQ(corruptInfoNew.IsDataBaseCorrupted(APP_NAME, USER_NAME, "corrupt7"), true); - EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); - g_kvDelegatePtr = nullptr; g_kvNbDelegatePtr = nullptr; - EXPECT_EQ(g_mgr.DeleteKvStore("corrupt6"), OK); EXPECT_EQ(g_mgr.DeleteKvStore("corrupt7"), OK); } +#ifndef OMIT_MULTI_VER +/** + * @tc.name: DatabaseCorruptionHandleTest005 + * @tc.desc: Test the DeleteKvStore Interface and check whether the database files can be removed. + * @tc.type: FUNC + * @tc.require: AR000D487C SR000D4878 + * @tc.author: wangbingquan + */ +HWTEST_F(DistributedDBInterfacesDatabaseCorruptTest, DatabaseCorruptionHandleTest005, TestSize.Level1) +{ + /** + * @tc.steps: step1. Get the kvStore. + * @tc.steps: step2. Put data into the store. + * @tc.steps: step3. Close the store. + */ + CipherPassword passwd; + Key randomPassword; + DistributedDBToolsUnitTest::GetRandomKeyValue(randomPassword, PASSWD_SIZE); + int errCode = passwd.SetValue(randomPassword.data(), randomPassword.size()); + ASSERT_EQ(errCode, CipherPassword::ErrorCode::OK); + KvStoreDelegate::Option option = {true, true, false, CipherType::DEFAULT, passwd}; + g_mgr.GetKvStore("corrupt6", option, g_kvDelegateCallback); + ASSERT_TRUE(g_kvDelegatePtr != nullptr); + ASSERT_EQ(PutDataIntoDatabaseMultiVer(g_kvDelegatePtr), OK); + ASSERT_EQ(PutDataIntoDatabaseMultiVer(g_kvDelegatePtr), OK); + + /** + * @tc.steps: step4. Modify the database file. + */ + std::string filePath = GetKvStoreDirectory("corrupt6", DBConstant::DB_TYPE_LOCAL); // local database. + DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath); + DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath + "-wal"); + filePath = GetKvStoreDirectory("corrupt7", DBConstant::DB_TYPE_SINGLE_VER); // single ver database. + DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath); + DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath + "-wal"); + KvStoreCorruptInfo corruptInfo; + KvStoreCorruptInfo corruptInfoNew; + auto notifier = bind(&KvStoreCorruptInfo::CorruptCallBack, &corruptInfo, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3); + g_mgr.SetKvStoreCorruptionHandler(notifier); + auto notifierNew = bind(&KvStoreCorruptInfo::CorruptCallBack, &corruptInfoNew, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3); + g_mgr.SetKvStoreCorruptionHandler(notifierNew); + /** + * @tc.steps: step5. Re-obtain the kvStore. + * @tc.expected: step5. Returns null kvstore. + */ + size_t infoSize = 0; + ASSERT_NE(PutDataIntoDatabaseMultiVer(g_kvDelegatePtr), OK); + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_CALLBACK_TIME)); + EXPECT_EQ(corruptInfoNew.IsDataBaseCorrupted(APP_NAME, USER_NAME, "corrupt6"), true); + EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); + g_kvDelegatePtr = nullptr; + EXPECT_EQ(g_mgr.DeleteKvStore("corrupt6"), OK); + infoSize++; + + std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_CALLBACK_TIME)); + EXPECT_EQ(corruptInfo.GetDatabaseInfoSize(), 0UL); // no callback + EXPECT_TRUE(corruptInfoNew.GetDatabaseInfoSize() >= infoSize); // 2 more callback +} +#endif // OMIT_MULTI_VER + namespace { const uint32_t MODIFY_SIZE = 12; // Modify size is 12 * sizeof(uint32_t); const uint32_t MODIFY_VALUE = 0xF3F3F3F3; // random value, make sure to destroy the page header. @@ -370,7 +455,7 @@ void TestDatabaseIntegrityCheckOption(const std::string &storeId, bool isEncrypt g_mgr.GetKvStore(storeId, nbOption, g_kvNbDelegateCallback); ASSERT_EQ(g_kvNbDelegateStatus, OK); ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); - ASSERT_EQ(PutDataIntoDatabase(nullptr, g_kvNbDelegatePtr), OK); + ASSERT_EQ(PutDataIntoDatabaseSingleVer(g_kvNbDelegatePtr), OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); /** @@ -400,7 +485,7 @@ void TestDatabaseIntegrityCheckOption(const std::string &storeId, bool isEncrypt g_mgr.GetKvStore(storeId, nbOption, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); - ASSERT_EQ(PutDataIntoDatabase(nullptr, g_kvNbDelegatePtr), OK); + ASSERT_EQ(PutDataIntoDatabaseSingleVer(g_kvNbDelegatePtr), OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); /** @@ -470,7 +555,7 @@ HWTEST_F(DistributedDBInterfacesDatabaseCorruptTest, DatabaseIntegrityCheck002, g_mgr.GetKvStore("integrity021", nbOption, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); ASSERT_EQ(g_kvNbDelegatePtr->CheckIntegrity(), OK); - ASSERT_EQ(PutDataIntoDatabase(nullptr, g_kvNbDelegatePtr), OK); + ASSERT_EQ(PutDataIntoDatabaseSingleVer(g_kvNbDelegatePtr), OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath, i * 4096, MODIFY_SIZE, MODIFY_VALUE); // page size 4096 g_mgr.GetKvStore("integrity021", nbOption, g_kvNbDelegateCallback); @@ -493,7 +578,7 @@ HWTEST_F(DistributedDBInterfacesDatabaseCorruptTest, DatabaseIntegrityCheck002, g_mgr.GetKvStore("integrity022", nbOption, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); ASSERT_EQ(g_kvNbDelegatePtr->CheckIntegrity(), OK); - ASSERT_EQ(PutDataIntoDatabase(nullptr, g_kvNbDelegatePtr), OK); + ASSERT_EQ(PutDataIntoDatabaseSingleVer(g_kvNbDelegatePtr), OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); DistributedDBToolsUnitTest::ModifyDatabaseFile(filePath, i * 1024, MODIFY_SIZE, MODIFY_VALUE); // page size 1024 g_mgr.GetKvStore("integrity022", nbOption, g_kvNbDelegateCallback); diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_test.cpp index e2916b7481e..c8a083ca6ea 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_test.cpp @@ -41,12 +41,15 @@ namespace { string g_testDir; KvStoreConfig g_config; - // define the g_kvDelegateCallback, used to get some information when open a kv store. DBStatus g_kvDelegateStatus = INVALID_ARGS; +#ifndef OMIT_MULTI_VER + // define the g_kvDelegateCallback, used to get some information when open a kv store. KvStoreDelegate *g_kvDelegatePtr = nullptr; // the type of g_kvDelegateCallback is function auto g_kvDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1, placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvDelegatePtr)); +#endif // OMIT_MULTI_VER + KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr; auto g_kvNbDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1, placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvNbDelegatePtr)); @@ -334,8 +337,10 @@ void DistributedDBInterfacesDatabaseTest::TearDownTestCase(void) void DistributedDBInterfacesDatabaseTest::SetUp(void) { DistributedDBToolsUnitTest::PrintTestCaseInfo(); +#ifndef OMIT_MULTI_VER g_kvDelegateStatus = INVALID_ARGS; g_kvDelegatePtr = nullptr; +#endif // OMIT_MULTI_VER } void DistributedDBInterfacesDatabaseTest::TearDown(void) @@ -345,6 +350,7 @@ void DistributedDBInterfacesDatabaseTest::TearDown(void) } } +#ifndef OMIT_MULTI_VER /** * @tc.name: GetKvStore001 * @tc.desc: Get kv store through different parameters. @@ -539,6 +545,7 @@ HWTEST_F(DistributedDBInterfacesDatabaseTest, GetKvStore002, TestSize.Level1) EXPECT_TRUE(retStoreId.compare("distributed_getkvstore_002") == 0); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); } +#endif // OMIT_MULTI_VER /** * @tc.name: GetKvStore003 @@ -671,6 +678,7 @@ HWTEST_F(DistributedDBInterfacesDatabaseTest, GetKvStore004, TestSize.Level1) EXPECT_TRUE(g_mgr.DeleteKvStore("distributed_getkvstore_004") == OK); } +#ifndef OMIT_MULTI_VER /** * @tc.name: CloseKvStore001 * @tc.desc: Test the CloseKvStore Interface and check whether the database file can be closed. @@ -792,6 +800,7 @@ HWTEST_F(DistributedDBInterfacesDatabaseTest, DeleteKvStore001, TestSize.Level1) */ EXPECT_TRUE(g_mgr.DeleteKvStore(storeId) == NOT_FOUND); } +#endif // OMIT_MULTI_VER /** * @tc.name: RepeatCloseKvStore001 diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_database_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_database_test.cpp index 46f5f3e3eea..81d6a0316d2 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_database_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_database_test.cpp @@ -68,6 +68,7 @@ void DistributedDBInterfacesEncryptDatabaseTest::TearDown(void) { } +#ifndef OMIT_MULTI_VER void DistributedDBInterfacesEncryptDatabaseTest::CheckRekeyWithMultiKvStore(bool isLocal) { DBStatus status; @@ -343,6 +344,33 @@ HWTEST_F(DistributedDBInterfacesEncryptDatabaseTest, MultiVerRekeyCheck003, Test CheckRekeyWithExistedObserver(false); } +/** + * @tc.name: ExportAndImportCheck001 + * @tc.desc: Test the EXPORT interface + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBInterfacesEncryptDatabaseTest, ExportAndImportCheck001, TestSize.Level1) +{ + DBStatus status; + KvStoreDelegate *kvStore = nullptr; + auto delegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1, + placeholders::_2, std::ref(status), std::ref(kvStore)); + KvStoreDelegate::Option option = {true, true, false}; + g_mgr.GetKvStore(STORE_ID1, option, delegateCallback); + ASSERT_TRUE(kvStore != nullptr); + + string path = g_testDir + "/export.back"; + CipherPassword passwd; + vector passwdBuffer(10, 45); // 10 and 45 as random password. + passwd.SetValue(passwdBuffer.data(), passwdBuffer.size()); + ASSERT_EQ(kvStore->Export(path, passwd), OK); + EXPECT_EQ(g_mgr.CloseKvStore(kvStore), OK); + EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID1), OK); +} +#endif // OMIT_MULTI_VER + /** * @tc.name: SingleVerRekeyCheck001 * @tc.desc: Attempt to rekey while another delegate is existed. @@ -495,30 +523,4 @@ HWTEST_F(DistributedDBInterfacesEncryptDatabaseTest, SingleVerRekeyCheck003, Tes EXPECT_EQ(g_mgr.CloseKvStore(kvStore), OK); EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID2), OK); } - -/** - * @tc.name: ExportAndImportCheck001 - * @tc.desc: Test the EXPORT interface - * @tc.type: FUNC - * @tc.require: - * @tc.author: bty - */ -HWTEST_F(DistributedDBInterfacesEncryptDatabaseTest, ExportAndImportCheck001, TestSize.Level1) -{ - DBStatus status; - KvStoreDelegate *kvStore = nullptr; - auto delegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1, - placeholders::_2, std::ref(status), std::ref(kvStore)); - KvStoreDelegate::Option option = {true, true, false}; - g_mgr.GetKvStore(STORE_ID1, option, delegateCallback); - ASSERT_TRUE(kvStore != nullptr); - - string path = g_testDir + "/export.back"; - CipherPassword passwd; - vector passwdBuffer(10, 45); // 10 and 45 as random password. - passwd.SetValue(passwdBuffer.data(), passwdBuffer.size()); - ASSERT_EQ(kvStore->Export(path, passwd), OK); - EXPECT_EQ(g_mgr.CloseKvStore(kvStore), OK); - EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID1), OK); -} #endif diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_delegate_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_delegate_test.cpp index f2d9b53f256..938c0ff852f 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_delegate_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_encrypt_delegate_test.cpp @@ -41,11 +41,14 @@ namespace { KvStoreConfig g_config; DBStatus g_errCode = INVALID_ARGS; KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr; - KvStoreDelegate *g_kvDelegatePtr = nullptr; - auto g_kvNbDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1, placeholders::_2, std::ref(g_errCode), std::ref(g_kvNbDelegatePtr)); +#ifndef OMIT_MULTI_VER + KvStoreDelegate *g_kvDelegatePtr = nullptr; + DBStatus g_valueStatus = INVALID_ARGS; + Value g_value; + // define the delegate call back auto g_kvDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1, placeholders::_2, std::ref(g_errCode), std::ref(g_kvDelegatePtr)); @@ -56,9 +59,6 @@ namespace { auto g_snapshotDelegateCallback = bind(&DistributedDBToolsUnitTest::SnapshotDelegateCallback, placeholders::_1, placeholders::_2, std::ref(g_snapshotDelegateStatus), std::ref(g_snapshotDelegatePtr)); - DBStatus g_valueStatus = INVALID_ARGS; - Value g_value; - auto g_valueCallback = bind(&DistributedDBToolsUnitTest::ValueCallback, placeholders::_1, placeholders::_2, std::ref(g_valueStatus), std::ref(g_value)); @@ -78,7 +78,7 @@ namespace { } } } - +#endif // OMIT_MULTI_VER void GetNbKvStoreAndCheckFun(const std::string &storeId, const KvStoreNbDelegate::Option &option, const Key &testKey, const Value &testValue) { @@ -133,7 +133,9 @@ void DistributedDBInterfacesEncryptDelegateTest::SetUp(void) DistributedDBToolsUnitTest::PrintTestCaseInfo(); g_errCode = INVALID_ARGS; g_kvNbDelegatePtr = nullptr; +#ifndef OMIT_MULTI_VER g_kvDelegatePtr = nullptr; +#endif // OMIT_MULTI_VER } void DistributedDBInterfacesEncryptDelegateTest::TearDown(void) {} @@ -215,6 +217,7 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, EncryptedDbOperation001, Te g_kvNbDelegatePtr = nullptr; } +#ifndef OMIT_MULTI_VER /** * @tc.name: EncryptedDbOperation002 * @tc.desc: Test the local db encrypted function. @@ -376,6 +379,7 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, EncryptedDbOperation003, Te // finilize logic EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID3), OK); } +#endif // OMIT_MULTI_VER /** * @tc.name: EncryptedDbSwitch001 @@ -657,6 +661,7 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, EncryptedDbSwitch011, TestS g_kvNbDelegatePtr = nullptr; } +#ifndef OMIT_MULTI_VER /** * @tc.name: EncryptedDbSwitch012 * @tc.desc: Test the local db Rekey function from password1 to password2. @@ -947,6 +952,7 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, EncryptedDbSwitch017, TestS EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID3), OK); g_kvDelegatePtr = nullptr; } +#endif // OMIT_MULTI_VER /** * @tc.name: OpenEncryptedDb001 @@ -965,6 +971,7 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, OpenEncryptedDb001, TestSiz g_mgr.GetKvStore(STORE_ID1, option1, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); EXPECT_TRUE(g_errCode == OK); +#ifndef OMIT_MULTI_VER /** * @tc.steps: step2. create multi version encrypted database * @tc.expected: step2. Get result OK. @@ -973,14 +980,16 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, OpenEncryptedDb001, TestSiz g_mgr.GetKvStore(STORE_ID3, option2, g_kvDelegateCallback); ASSERT_TRUE(g_kvDelegatePtr != nullptr); EXPECT_EQ(g_errCode, OK); + + EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); + EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID3), OK); +#endif // OMIT_MULTI_VER /** * @tc.steps: step3. Close db. * @tc.expected: step3. Get result ok. */ EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); - EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID1), OK); - EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID3), OK); } /** @@ -1000,6 +1009,8 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, OpenEncryptedDb002, TestSiz g_mgr.GetKvStore(STORE_ID1, option1, g_kvNbDelegateCallback); EXPECT_TRUE(g_kvNbDelegatePtr == nullptr); EXPECT_EQ(g_errCode, INVALID_ARGS); + +#ifndef OMIT_MULTI_VER /** * @tc.steps: step2. create multi version encrypted database * @tc.expected: step2. Get result INVALID_ARGS. @@ -1008,14 +1019,17 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, OpenEncryptedDb002, TestSiz g_mgr.GetKvStore(STORE_ID3, option2, g_kvDelegateCallback); EXPECT_TRUE(g_kvDelegatePtr == nullptr); EXPECT_EQ(g_errCode, INVALID_ARGS); + + EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), INVALID_ARGS); + EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID3), NOT_FOUND); +#endif // OMIT_MULTI_VER + /** * @tc.steps: step3. Close db. * @tc.expected: step3. Get result ok. */ EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), INVALID_ARGS); - EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), INVALID_ARGS); EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID1), NOT_FOUND); - EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID3), NOT_FOUND); } /** @@ -1033,11 +1047,14 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, OpenEncryptedDb003, TestSiz EXPECT_EQ(g_errCode, OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); +#ifndef OMIT_MULTI_VER KvStoreDelegate::Option option2 = {true, false, true, CipherType::DEFAULT, g_passwd3}; g_mgr.GetKvStore(STORE_ID3, option2, g_kvDelegateCallback); ASSERT_TRUE(g_kvDelegatePtr != nullptr); EXPECT_EQ(g_errCode, OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); +#endif // OMIT_MULTI_VER + /** * @tc.steps: step1. create single version encrypted database * @tc.expected: step1. Get result INVALID_ARGS. @@ -1047,6 +1064,8 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, OpenEncryptedDb003, TestSiz ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); EXPECT_EQ(g_errCode, OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); + +#ifndef OMIT_MULTI_VER /** * @tc.steps: step2. create multi version encrypted database * @tc.expected: step2. Get result INVALID_ARGS. @@ -1056,12 +1075,13 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, OpenEncryptedDb003, TestSiz ASSERT_TRUE(g_kvDelegatePtr != nullptr); EXPECT_EQ(g_errCode, OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); + EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID3), OK); +#endif // OMIT_MULTI_VER /** * @tc.steps: step3. Close db. * @tc.expected: step3. Get result ok. */ EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID1), OK); - EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID3), OK); } /** @@ -1079,11 +1099,14 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, OpenEncryptedDb004, TestSiz EXPECT_EQ(g_errCode, OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); +#ifndef OMIT_MULTI_VER KvStoreDelegate::Option option2 = {true, false, true, CipherType::DEFAULT, g_passwd3}; g_mgr.GetKvStore(STORE_ID3, option2, g_kvDelegateCallback); ASSERT_TRUE(g_kvDelegatePtr != nullptr); EXPECT_EQ(g_errCode, OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); +#endif // OMIT_MULTI_VER + /** * @tc.steps: step1. create single version encrypted database * @tc.expected: step1. Get result INVALID_ARGS. @@ -1093,6 +1116,8 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, OpenEncryptedDb004, TestSiz EXPECT_TRUE(g_kvNbDelegatePtr == nullptr); EXPECT_EQ(g_errCode, INVALID_PASSWD_OR_CORRUPTED_DB); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), INVALID_ARGS); + +#ifndef OMIT_MULTI_VER /** * @tc.steps: step2. create multi version encrypted database * @tc.expected: step2. Get result INVALID_ARGS. @@ -1102,11 +1127,13 @@ HWTEST_F(DistributedDBInterfacesEncryptDelegateTest, OpenEncryptedDb004, TestSiz EXPECT_TRUE(g_kvDelegatePtr == nullptr); EXPECT_EQ(g_errCode, INVALID_PASSWD_OR_CORRUPTED_DB); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), INVALID_ARGS); + EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID3), OK); +#endif // OMIT_MULTI_VER + /** * @tc.steps: step3. Close db. * @tc.expected: step3. Get result ok. */ EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID1), OK); - EXPECT_EQ(g_mgr.DeleteKvStore(STORE_ID3), OK); } -#endif +#endif \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_import_and_export_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_import_and_export_test.cpp index 9d53270f8e2..e8611e2a226 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_import_and_export_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_import_and_export_test.cpp @@ -38,12 +38,18 @@ namespace { // define the g_kvNbDelegateCallback, used to get some information when open a kv store. DBStatus g_kvDelegateStatus = INVALID_ARGS; KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr; - KvStoreDelegate *g_kvDelegatePtr = nullptr; KvStoreNbDelegate *g_kvNbDelegatePtrWithoutPasswd = nullptr; + +#ifndef OMIT_MULTI_VER + KvStoreDelegate *g_kvDelegatePtr = nullptr; KvStoreDelegate *g_kvDelegatePtrWithoutPasswd = nullptr; + // the type of g_kvDelegateCallback is function + auto g_kvDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1, + placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvDelegatePtr)); KvStoreDelegate::Option g_option; - const size_t MAX_PASSWD_SIZE = 128; +#endif // OMIT_MULTI_VER + const size_t MAX_PASSWD_SIZE = 128; // define the g_valueCallback, used to query a value object data from the kvdb. DBStatus g_valueStatus = INVALID_ARGS; Value g_value; @@ -60,10 +66,6 @@ namespace { auto g_kvNbDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1, placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvNbDelegatePtr)); - // the type of g_kvDelegateCallback is function - auto g_kvDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1, - placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvDelegatePtr)); - void RemoveJunkFile(const std::vector &fileList) { for (auto &junkFile : fileList) { @@ -127,7 +129,9 @@ void DistributedDBInterfacesImportAndExportTest::SetUp(void) g_junkFilesList.clear(); g_kvDelegateStatus = INVALID_ARGS; g_kvNbDelegatePtr = nullptr; +#ifndef OMIT_MULTI_VER g_kvDelegatePtr = nullptr; +#endif // OMIT_MULTI_VER } void DistributedDBInterfacesImportAndExportTest::TearDown(void) @@ -160,7 +164,7 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, NormalExport001, TestSize.L */ CipherPassword passwd; EXPECT_EQ(g_kvNbDelegatePtr->Export(singleExportFileName, passwd), OK); - +#ifndef OMIT_MULTI_VER std::string mulitExportFileName = g_exportFileDir + "/mulitNormalExport001.$$"; std::string multiStoreId = "distributed_ExportMulit_001"; g_mgr.GetKvStore(multiStoreId, g_option, g_kvDelegateCallback); @@ -174,12 +178,13 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, NormalExport001, TestSize.L EXPECT_EQ(g_kvDelegatePtr->Export(mulitExportFileName, passwd), OK); // clear resource - g_junkFilesList.push_back(singleExportFileName); g_junkFilesList.push_back(mulitExportFileName); - EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); - EXPECT_EQ(g_mgr.DeleteKvStore(singleStoreId), OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); EXPECT_EQ(g_mgr.DeleteKvStore(multiStoreId), OK); +#endif // OMIT_MULTI_VER + g_junkFilesList.push_back(singleExportFileName); + EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); + EXPECT_EQ(g_mgr.DeleteKvStore(singleStoreId), OK); } /** @@ -243,6 +248,7 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, UndisturbedlSingleExport001 g_junkFilesList.push_back(singleExportFileName); } +#ifndef OMIT_MULTI_VER static void GetSnapshotUnitTest(KvStoreDelegate *&kvDelegatePtr, KvStoreSnapshotDelegate *&snapshotDelegatePtr) { DBStatus snapshotDelegateStatus = INVALID_ARGS; @@ -324,6 +330,7 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, UndisturbedlMultiExport001, EXPECT_EQ(g_mgr.DeleteKvStore(multiStoreId), OK); g_junkFilesList.push_back(mulitExportFileName); } +#endif // OMIT_MULTI_VER /** * @tc.name: ExportParameterCheck001 @@ -393,6 +400,7 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, ExportParameterCheck001, Te g_junkFilesList.push_back(singleExportFileName); } +#ifndef OMIT_MULTI_VER /** * @tc.name: ExportParameterCheck002 * @tc.desc: Check the verification of abnormal interface parameters. @@ -466,6 +474,7 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, ExportParameterCheck002, Te EXPECT_EQ(g_mgr.DeleteKvStore(multiStoreId), OK); g_junkFilesList.push_back(multiExportFileName); } +#endif // OMIT_MULTI_VER /** * @tc.name: NormalImport001 @@ -525,8 +534,9 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, NormalImport001, TestSize.L EXPECT_EQ(g_mgr.DeleteKvStore(singleStoreId), OK); } +#ifndef OMIT_MULTI_VER /** - * @tc.name: NormalImport001 + * @tc.name: NormalImport002 * @tc.desc: Normal import capability for multi version, parameter verification capability * @tc.type: FUNC * @tc.require: AR000D487A @@ -589,6 +599,7 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, NormalImport002, TestSize.L EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); EXPECT_EQ(g_mgr.DeleteKvStore(multiStoreId), OK); } +#endif // OMIT_MULTI_VER /** * @tc.name: ExceptionFileImport001 @@ -642,6 +653,7 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, ExceptionFileImport001, Tes EXPECT_EQ(g_mgr.DeleteKvStore(singleStoreId), OK); } +#ifndef OMIT_MULTI_VER /** * @tc.name: ExceptionFileImport002 * @tc.desc: Normal import capability for multi version, parameter verification capability @@ -732,6 +744,7 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, ExceptionFileImport003, Tes EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); EXPECT_EQ(g_mgr.DeleteKvStore(multiStoreId), OK); } +#endif // OMIT_MULTI_VER /** * @tc.name: ExceptionFileImport004 @@ -753,13 +766,13 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, ExceptionFileImport004, Tes std::string mulitExportFileName = g_exportFileDir + "/mulitExceptionFileImport004.$$"; std::string multiStoreId = "distributed_ExportMulit_004"; - +#ifndef OMIT_MULTI_VER KvStoreDelegate::Option multiOption = {true, false, true, CipherType::DEFAULT, g_passwd1}; g_mgr.GetKvStore(multiStoreId, multiOption, g_kvDelegateCallback); ASSERT_TRUE(g_kvDelegatePtr != nullptr); EXPECT_EQ(g_kvDelegateStatus, OK); EXPECT_EQ(g_kvDelegatePtr->Export(mulitExportFileName, g_passwd2), OK); - +#endif // OMIT_MULTI_VER /** * @tc.steps: step1. Use the diff passwd, try to import database. */ @@ -767,18 +780,19 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, ExceptionFileImport004, Tes EXPECT_EQ(g_kvNbDelegatePtr->Import(singleExportFileName, passwd), INVALID_FILE); EXPECT_EQ(g_kvNbDelegatePtr->Import(singleExportFileName, g_passwd1), INVALID_FILE); EXPECT_EQ(g_kvNbDelegatePtr->Import(singleExportFileName, g_passwd2), OK); - +#ifndef OMIT_MULTI_VER EXPECT_EQ(g_kvDelegatePtr->Import(mulitExportFileName, passwd), INVALID_FILE); EXPECT_EQ(g_kvDelegatePtr->Import(mulitExportFileName, g_passwd1), INVALID_FILE); EXPECT_EQ(g_kvDelegatePtr->Import(mulitExportFileName, g_passwd2), OK); // clear resource - g_junkFilesList.push_back(singleExportFileName); g_junkFilesList.push_back(mulitExportFileName); - EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); - EXPECT_EQ(g_mgr.DeleteKvStore(singleStoreId), OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); EXPECT_EQ(g_mgr.DeleteKvStore(multiStoreId), OK); +#endif // OMIT_MULTI_VER + g_junkFilesList.push_back(singleExportFileName); + EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); + EXPECT_EQ(g_mgr.DeleteKvStore(singleStoreId), OK); } static void TryDbForPasswordIndependence001() @@ -887,6 +901,7 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, PasswordIndependence001, Te EXPECT_EQ(g_mgr.DeleteKvStore(singleStoreIdNoPasswd), OK); } +#ifndef OMIT_MULTI_VER static void TryDbForPasswordIndependence002() { std::string multiStoreIdNoPasswd = "distributed_ExportMulti_007"; @@ -975,6 +990,7 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, PasswordIndependence002, Te EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtrWithoutPasswd), OK); EXPECT_EQ(g_mgr.DeleteKvStore(multiStoreIdNoPasswd), OK); } +#endif // OMIT_MULTI_VER /** * @tc.name: PasswordIndependence002 @@ -1014,6 +1030,7 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, PasswordIndependence003, Te */ EXPECT_EQ(g_kvNbDelegatePtr->Import(singleExportFileName, g_passwd1), OK); +#ifndef OMIT_MULTI_VER /** * @tc.steps: step5. Repeat step 1 - 4. */ @@ -1025,16 +1042,17 @@ HWTEST_F(DistributedDBInterfacesImportAndExportTest, PasswordIndependence003, Te ASSERT_TRUE(g_kvDelegateStatus == OK); EXPECT_EQ(g_kvDelegatePtr->Export(multiExportFileName, g_passwd1), OK); - remove(singleExportFileName.c_str()); EXPECT_EQ(g_kvDelegatePtr->Import(multiExportFileName, g_passwd3), INVALID_FILE); EXPECT_EQ(g_kvDelegatePtr->Import(multiExportFileName, g_passwd1), OK); // clear resource g_junkFilesList.push_back(multiExportFileName); - g_junkFilesList.push_back(singleExportFileName); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); EXPECT_EQ(g_mgr.DeleteKvStore(multiStoreId), OK); +#endif // OMIT_MULTI_VER + g_junkFilesList.push_back(singleExportFileName); + remove(singleExportFileName.c_str()); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); EXPECT_EQ(g_mgr.DeleteKvStore(singleStoreId), OK); } diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_test.cpp index 70e47fbe62c..9e0d295214d 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_test.cpp @@ -48,7 +48,13 @@ namespace { // define the g_kvNbDelegateCallback, used to get some information when open a kv store. DBStatus g_kvDelegateStatus = INVALID_ARGS; KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr; +#ifndef OMIT_MULTI_VER KvStoreDelegate *g_kvDelegatePtr = nullptr; + + // the type of g_kvDelegateCallback is function + auto g_kvDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1, + placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvDelegatePtr)); +#endif // OMIT_MULTI_VER const int OBSERVER_SLEEP_TIME = 100; const int BATCH_PRESET_SIZE_TEST = 10; const int DIVIDE_BATCH_PRESET_SIZE = 5; @@ -74,10 +80,6 @@ namespace { auto g_kvNbDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1, placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvNbDelegatePtr)); - // the type of g_kvDelegateCallback is function - auto g_kvDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1, - placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvDelegatePtr)); - enum LockState { UNLOCKED = 0, LOCKED @@ -238,12 +240,14 @@ void DistributedDBInterfacesNBDelegateTest::SetUp(void) DistributedDBToolsUnitTest::PrintTestCaseInfo(); g_kvDelegateStatus = INVALID_ARGS; g_kvNbDelegatePtr = nullptr; +#ifndef OMIT_MULTI_VER g_kvDelegatePtr = nullptr; +#endif // OMIT_MULTI_VER } void DistributedDBInterfacesNBDelegateTest::TearDown(void) { - if (g_kvDelegatePtr != nullptr) { + if (g_kvNbDelegatePtr != nullptr) { g_mgr.CloseKvStore(g_kvNbDelegatePtr); g_kvNbDelegatePtr = nullptr; } @@ -397,6 +401,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDb001, TestSize.Leve g_mgr.CloseKvStore(kvNbDelegatePtr001); g_mgr.CloseKvStore(kvNbDelegatePtr002); + g_kvNbDelegatePtr = nullptr; } /** @@ -431,6 +436,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDb002, TestSize.Leve delegate1 = nullptr; } +#ifndef OMIT_MULTI_VER /** * @tc.name: CreateMemoryDb003 * @tc.desc: The physical database cannot be created or open, when the MemoryDB has been opened. @@ -460,6 +466,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDb003, TestSize.Leve g_mgr.CloseKvStore(g_kvDelegatePtr); g_kvDelegatePtr = nullptr; } +#endif // OMIT_MULTI_VER /** * @tc.name: OperMemoryDbData001 @@ -519,6 +526,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, OperMemoryDbData001, TestSize.Le EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_2, readValueKey2), OK); EXPECT_EQ(readValueKey2, VALUE_3); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); + g_kvNbDelegatePtr = nullptr; } /** @@ -569,6 +577,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, CloseMemoryDb001, TestSize.Level readValue.clear(); EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_1, readValue), NOT_FOUND); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); + g_kvNbDelegatePtr = nullptr; } /** @@ -1713,6 +1722,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, QueryPreFixKey002, TestSize.Leve EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); EXPECT_TRUE(g_mgr.DeleteKvStore("QueryPreFixKey002") == OK); + g_kvNbDelegatePtr = nullptr; } /** @@ -1939,6 +1949,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, MaxLogSize002, TestSize.Level2) EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); EXPECT_EQ(g_mgr.DeleteKvStore("MaxLogSize002"), OK); + g_kvNbDelegatePtr = nullptr; } /** @@ -1985,6 +1996,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, MaxLogCheckPoint001, TestSize.Le EXPECT_LT(sizeAfterChk, 100 * 1024ULL); // less than 100K EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); EXPECT_EQ(g_mgr.DeleteKvStore("MaxLogCheckPoint001"), OK); + g_kvNbDelegatePtr = nullptr; } /** @@ -2006,6 +2018,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDbWithoutPath, TestS ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); EXPECT_TRUE(g_kvDelegateStatus == OK); EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK); + g_kvNbDelegatePtr = nullptr; } /** @@ -2091,6 +2104,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, BusyTest001, TestSize.Level1) sqlite3_close_v2(db); EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK); EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK); + g_kvNbDelegatePtr = nullptr; } /** @@ -2152,6 +2166,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, GetKeys001, TestSize.Level1) EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); EXPECT_EQ(g_mgr.DeleteKvStore("GetKeys001"), OK); + g_kvNbDelegatePtr = nullptr; } namespace { @@ -2223,6 +2238,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, RemoveDeviceDataTest001, TestSiz EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_4, val), NOT_FOUND); EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK); + g_kvNbDelegatePtr = nullptr; EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK); FreeVirtualDevice(g_deviceB); FreeVirtualDevice(g_deviceC); @@ -2267,6 +2283,7 @@ HWTEST_F(DistributedDBInterfacesNBDelegateTest, TimeChangeWithCloseStoreTest001, ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); EXPECT_EQ(g_kvDelegateStatus, OK); EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK); + g_kvNbDelegatePtr = nullptr; } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // 1000: wait for a while diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_register_syncdb_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_register_syncdb_test.cpp index bb772e09a9f..aca962aff21 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_register_syncdb_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_register_syncdb_test.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef OMIT_MULTI_VER #include #include @@ -1887,3 +1887,4 @@ HWTEST_F(DistributedDBInterfacesRegisterSyncDBTest, SnapshotErr001, TestSize.Lev std::vector entry; EXPECT_EQ(snapshot.GetEntries(key, entry), -E_INVALID_DB); } +#endif // OMIT_MULTI_VER diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_resultset_performance.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_resultset_performance.cpp index 0ded0a669fe..cf01fce891a 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_resultset_performance.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_resultset_performance.cpp @@ -40,7 +40,6 @@ namespace { DBStatus g_kvDelegateStatus = INVALID_ARGS; KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr; - KvStoreDelegate *g_kvDelegatePtr = nullptr; void KvStoreNbDelegateCallback(DBStatus statusSrc, KvStoreNbDelegate* kvStoreSrc, DBStatus* statusDst, KvStoreNbDelegate** kvStoreDst) @@ -101,15 +100,12 @@ void DistributedDBInterfacesNBResultsetPerfTest::SetUp(void) DistributedDBToolsUnitTest::PrintTestCaseInfo(); g_kvDelegateStatus = INVALID_ARGS; g_kvNbDelegatePtr = nullptr; - g_kvDelegatePtr = nullptr; } void DistributedDBInterfacesNBResultsetPerfTest::TearDown(void) { - if (g_kvDelegatePtr != nullptr) { - g_mgr.CloseKvStore(g_kvNbDelegatePtr); - g_kvNbDelegatePtr = nullptr; - } + g_mgr.CloseKvStore(g_kvNbDelegatePtr); + g_kvNbDelegatePtr = nullptr; } /** diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_space_management_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_space_management_test.cpp index 0a837aded51..1d79d1fa599 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_space_management_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_space_management_test.cpp @@ -37,16 +37,18 @@ namespace { // define the g_kvNbDelegateCallback, used to get some information when open a kv store. DBStatus g_kvDelegateStatus = INVALID_ARGS; KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr; - KvStoreDelegate *g_kvDelegatePtr = nullptr; KvStoreNbDelegate::Option g_nbOption; // the type of g_kvNbDelegateCallback is function auto g_kvNbDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1, placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvNbDelegatePtr)); +#ifndef OMIT_MULTI_VER + KvStoreDelegate *g_kvDelegatePtr = nullptr; // the type of g_kvDelegateCallback is function auto g_kvDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1, placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvDelegatePtr)); +#endif // OMIT_MULTI_VER std::string g_storeId; std::string g_identifier; @@ -130,7 +132,9 @@ void DistributedDBInterfacesSpaceManagementTest::SetUp(void) DistributedDBToolsUnitTest::PrintTestCaseInfo(); g_kvDelegateStatus = INVALID_ARGS; g_kvNbDelegatePtr = nullptr; +#ifndef OMIT_MULTI_VER g_kvDelegatePtr = nullptr; +#endif // OMIT_MULTI_VER } void DistributedDBInterfacesSpaceManagementTest::TearDown(void) {} @@ -224,12 +228,13 @@ HWTEST_F(DistributedDBInterfacesSpaceManagementTest, GetKvStoreDiskSize002, Test { g_storeId = "distributed_GetKvStoreDiskSize_002"; GetRealFileUrl(); - +#ifndef OMIT_MULTI_VER KvStoreDelegate::Option option; g_mgr.GetKvStore(g_storeId, option, g_kvDelegateCallback); ASSERT_TRUE(g_kvDelegatePtr != nullptr); EXPECT_TRUE(g_kvDelegateStatus == OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); +#endif // OMIT_MULTI_VER g_mgr.GetKvStore(g_storeId, g_nbOption, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); @@ -252,6 +257,7 @@ HWTEST_F(DistributedDBInterfacesSpaceManagementTest, GetKvStoreDiskSize002, Test EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); +#ifndef OMIT_MULTI_VER /** * @tc.steps: step3/4. Reopen Db and Put some Key Value to change Db size. */ @@ -259,6 +265,7 @@ HWTEST_F(DistributedDBInterfacesSpaceManagementTest, GetKvStoreDiskSize002, Test ASSERT_TRUE(g_kvDelegatePtr != nullptr); EXPECT_TRUE(g_kvDelegateStatus == OK); EXPECT_EQ(g_kvDelegatePtr->Put(key, value), OK); +#endif // OMIT_MULTI_VER /** * @tc.steps: step5/6. Get Db size by GetKvStoreDiskSize. @@ -277,7 +284,9 @@ HWTEST_F(DistributedDBInterfacesSpaceManagementTest, GetKvStoreDiskSize002, Test * @tc.steps: step7. Close and Delete Db. * @tc.expected: step7. Successfully. */ +#ifndef OMIT_MULTI_VER EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); +#endif // OMIT_MULTI_VER EXPECT_EQ(g_mgr.DeleteKvStore(g_storeId), OK); } @@ -324,11 +333,12 @@ HWTEST_F(DistributedDBInterfacesSpaceManagementTest, GetKvStoreDiskSize003, Test ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); EXPECT_TRUE(g_kvDelegateStatus == OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); - +#ifndef OMIT_MULTI_VER KvStoreDelegate::Option option; g_mgr.GetKvStore(g_storeId, option, g_kvDelegateCallback); ASSERT_TRUE(g_kvDelegatePtr != nullptr); EXPECT_TRUE(g_kvDelegateStatus == OK); +#endif // OMIT_MULTI_VER /** * @tc.steps: step1. Use an anomalous length of storeId by GetKvStoreDiskSize to get size. @@ -375,7 +385,9 @@ HWTEST_F(DistributedDBInterfacesSpaceManagementTest, GetKvStoreDiskSize003, Test EXPECT_EQ(dbSizeForCheck, singleAndMultiDbSize); DeleteFile(g_testDir + "/" + g_storeId + "/" + DBConstant::MULTI_SUB_DIR + "/test.txt"); +#ifndef OMIT_MULTI_VER EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); +#endif // OMIT_MULTI_VER EXPECT_EQ(g_mgr.DeleteKvStore(g_storeId), OK); } @@ -452,6 +464,7 @@ HWTEST_F(DistributedDBInterfacesSpaceManagementTest, DeleteDbByStoreId001, TestS ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); EXPECT_TRUE(g_kvDelegateStatus == OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); +#ifndef OMIT_MULTI_VER KvStoreDelegate::Option option; g_mgr.GetKvStore(storeId1, option, g_kvDelegateCallback); ASSERT_TRUE(g_kvDelegatePtr != nullptr); @@ -462,13 +475,14 @@ HWTEST_F(DistributedDBInterfacesSpaceManagementTest, DeleteDbByStoreId001, TestS ASSERT_TRUE(g_kvDelegatePtr != nullptr); EXPECT_TRUE(g_kvDelegateStatus == OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); +#endif // OMIT_MULTI_VER std::string storeId2 = "distributed_DeleteDbByStoreId002"; - g_mgr.GetKvStore(storeId2, nbOption, g_kvNbDelegateCallback); ASSERT_TRUE(g_kvNbDelegatePtr != nullptr); EXPECT_TRUE(g_kvDelegateStatus == OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); +#ifndef OMIT_MULTI_VER option.localOnly = false; g_mgr.GetKvStore(storeId2, option, g_kvDelegateCallback); ASSERT_TRUE(g_kvDelegatePtr != nullptr); @@ -479,6 +493,7 @@ HWTEST_F(DistributedDBInterfacesSpaceManagementTest, DeleteDbByStoreId001, TestS ASSERT_TRUE(g_kvDelegatePtr != nullptr); EXPECT_TRUE(g_kvDelegateStatus == OK); EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); +#endif // OMIT_MULTI_VER uint64_t store1DbSize = 0; EXPECT_EQ(g_mgr.GetKvStoreDiskSize(storeId1, store1DbSize), OK); diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_syncdb_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_syncdb_test.cpp index 1b8779f8e50..87cd87e3239 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_syncdb_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_syncdb_test.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef OMIT_MULTI_VER #include #include "distributeddb_data_generate_unit_test.h" @@ -640,4 +640,5 @@ HWTEST_F(DistributedDBInterfacesTransactionSyncDBTest, RollBack008, TestSize.Lev * @tc.expected: step6. verification is OK . */ DistributedDBInterfacesTransactionTestCase::RollBack008(g_kvDelegatePtr, g_snapshotDelegatePtr); -} \ No newline at end of file +} +#endif // OMIT_MULTI_VER \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_test.cpp index 3dc576de19c..9a2720c7ed0 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_test.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef OMIT_MULTI_VER #include #include "distributeddb_data_generate_unit_test.h" @@ -672,4 +672,5 @@ HWTEST_F(DistributedDBInterfacesTransactionTest, Rollback008, TestSize.Level1) * @tc.expected: step6. verification is OK . */ DistributedDBInterfacesTransactionTestCase::RollBack008(g_kvDelegatePtr, g_snapshotDelegatePtr); -} \ No newline at end of file +} +#endif // OMIT_MULTI_VER \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_testcase.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_testcase.cpp index ff6786cf720..12569a1ad16 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_testcase.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_testcase.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef OMIT_MULTI_VER #include "distributeddb_interfaces_transaction_testcase.h" using namespace testing::ext; @@ -717,4 +717,5 @@ void DistributedDBInterfacesTransactionTestCase::RollBack008(KvStoreDelegate *&k snapshotDelegatePtr->GetEntries(NULL_KEY_1, entryVectorCallback); EXPECT_TRUE(entryVectorStatus == OK); ASSERT_TRUE(matchSizeCallback == matchSize); -} \ No newline at end of file +} +#endif // OMIT_MULTI_VER \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_testcase.h b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_testcase.h index 73181f1a4f9..f21e4fe1256 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_testcase.h +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_transaction_testcase.h @@ -12,10 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef DISTRIBUTEDDB_INTERFACES_TRANSACTION_TESTCASE_H #define DISTRIBUTEDDB_INTERFACES_TRANSACTION_TESTCASE_H +#ifndef OMIT_MULTI_VER #include #include "distributeddb_data_generate_unit_test.h" #include "distributeddb_tools_unit_test.h" @@ -82,4 +82,5 @@ public: static void RollBack008(DistributedDB::KvStoreDelegate *&kvDelegatePtr, DistributedDB::KvStoreSnapshotDelegate *&snapshotDelegatePtr); }; -#endif \ No newline at end of file +#endif +#endif // OMIT_MULTI_VER diff --git a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_multi_ver_vacuum_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_multi_ver_vacuum_test.cpp index 0e0618a83f5..0fa56611e95 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_multi_ver_vacuum_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_multi_ver_vacuum_test.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef OMIT_MULTI_VER #include #include #include @@ -751,3 +751,4 @@ HWTEST_F(DistributedDBMultiVerVacuumTest, MultipleTaskNormalStatusSwitch002, Tes stepFive = CheckVacuumTaskStatus(vacuum, DB_IDENTITY_C, VacuumTaskStatus::FINISH, 1); // only 1 time EXPECT_EQ(stepFive, true); } +#endif // OMIT_MULTI_VER diff --git a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_commit_storage_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_commit_storage_test.cpp index ca62af7ad5b..e998f40f086 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_commit_storage_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_commit_storage_test.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef OMIT_MULTI_VER #include #include "db_errno.h" @@ -836,3 +836,4 @@ HWTEST_F(DistributedDBStorageCommitStorageTest, MultiVerCommitStorage017, TestSi commit = nullptr; } } +#endif // OMIT_MULTI_VER diff --git a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_data_operation_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_data_operation_test.cpp index 99d6d94e580..79a29967291 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_data_operation_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_data_operation_test.cpp @@ -453,6 +453,7 @@ HWTEST_F(DistributedDBStorageDataOperationTest, DeleteBatch001, TestSize.Level1) EXPECT_EQ(entriesRead.size(), 0UL); } +#ifndef OMIT_MULTI_VER static void CheckSplitData(const Value &oriValue, const uint32_t numBlock, std::map &valueDic, Value &savedValue) { @@ -688,6 +689,7 @@ HWTEST_F(DistributedDBStorageDataOperationTest, CutValueIntoBlock002, TestSize.L CheckRecoverData(savedValue, valueDic, value2); EXPECT_EQ(valueDic.size(), 0ul); } +#endif // OMIT_MULTI_VER /** * @tc.name: ShaAlgoEncryptTest001 diff --git a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_data_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_data_test.cpp index ff08d251bb3..c0a0e797f64 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_data_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_data_test.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef OMIT_MULTI_VER #include #include #include @@ -1590,3 +1590,4 @@ HWTEST_F(DistributedDBStorageTransactionDataTest, GetBranchTag001, TestSize.Leve } } } +#endif // OMIT_MULTI_VER \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_record_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_record_test.cpp index 525d897f053..54333d7bd1a 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_record_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_transaction_record_test.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef OMIT_MULTI_VER #include #include "db_constant.h" @@ -1098,4 +1098,4 @@ HWTEST_F(DistributedDBStorageTransactionRecordTest, MultiverStorage025, TestSize EXPECT_EQ(DistributedDBToolsUnitTest::IsKvEntryExist(entry, entriesRead), true); EXPECT_EQ(DistributedDBToolsUnitTest::IsKvEntryExist(entry1, entriesRead), true); } - +#endif // OMIT_MULTI_VER diff --git a/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_multi_ver_p2p_sync_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_multi_ver_p2p_sync_test.cpp index f4cce093ad7..479841dedf1 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_multi_ver_p2p_sync_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_multi_ver_p2p_sync_test.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef OMIT_MULTI_VER #include #include @@ -1646,4 +1646,5 @@ HWTEST_F(DistributedDBMultiVerP2PSyncTest, PermissionCheck002, TestSize.Level2) PermissionCheckCallbackV2 nullCallback; EXPECT_EQ(g_mgr.SetPermissionCheckCallback(nullCallback), OK); } -#endif \ No newline at end of file +#endif +#endif // OMIT_MULTI_VER \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/unittest/common/syncer/generic_virtual_device.cpp b/frameworks/libs/distributeddb/test/unittest/common/syncer/generic_virtual_device.cpp index d0a0bff3ad9..a623568dd0c 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/syncer/generic_virtual_device.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/syncer/generic_virtual_device.cpp @@ -99,8 +99,13 @@ int GenericVirtualDevice::Initialize(VirtualCommunicatorAggregator *comAggregato } else if (storage_->GetInterfaceType() == IKvDBSyncInterface::SYNC_RELATION) { context_ = new (std::nothrow) SingleVerRelationalSyncTaskContext; } else { +#ifndef OMIT_MULTI_VER context_ = new (std::nothrow) MultiVerSyncTaskContext; +#else + return -E_NOT_SUPPORT; +#endif // OMIT_MULTI_VER } + if (context_ == nullptr) { return -E_OUT_OF_MEMORY; } @@ -279,4 +284,4 @@ void GenericVirtualDevice::SetClearRemoteStaleData(bool isStaleData) LOGD("set clear remote stale data mark"); } } -} // DistributedDB \ No newline at end of file +} // DistributedDB diff --git a/frameworks/libs/distributeddb/test/unittest/common/syncer/kv_virtual_device.cpp b/frameworks/libs/distributeddb/test/unittest/common/syncer/kv_virtual_device.cpp index e5aa1368c4e..760b3965d61 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/syncer/kv_virtual_device.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/syncer/kv_virtual_device.cpp @@ -32,12 +32,6 @@ int KvVirtualDevice::GetData(const Key &key, VirtualDataItem &item) return syncAble->GetSyncData(key, item); } -int KvVirtualDevice::GetData(const Key &key, Value &value) -{ - VirtualMultiVerSyncDBInterface *syncInterface = static_cast(storage_); - return syncInterface->GetData(key, value); -} - int KvVirtualDevice::PutData(const Key &key, const Value &value, const Timestamp &time, int flag) { VirtualSingleVerSyncDBInterface *syncAble = static_cast(storage_); @@ -45,53 +39,61 @@ int KvVirtualDevice::PutData(const Key &key, const Value &value, const Timestamp return syncAble->PutData(key, value, time, flag); } -int KvVirtualDevice::PutData(const Key &key, const Value &value) +void KvVirtualDevice::SetSaveDataDelayTime(uint64_t milliDelayTime) { - VirtualMultiVerSyncDBInterface *syncInterface = static_cast(storage_); - return syncInterface->PutData(key, value); + VirtualSingleVerSyncDBInterface *syncInterface = static_cast(storage_); + syncInterface->SetSaveDataDelayTime(milliDelayTime); } -int KvVirtualDevice::DeleteData(const Key &key) +void KvVirtualDevice::DelayGetSyncData(uint64_t milliDelayTime) { - VirtualMultiVerSyncDBInterface *syncInterface = static_cast(storage_); - return syncInterface->DeleteData(key); + VirtualSingleVerSyncDBInterface *syncInterface = static_cast(storage_); + syncInterface->DelayGetSyncData(milliDelayTime); } -int KvVirtualDevice::StartTransaction() +void KvVirtualDevice::SetGetDataErrCode(int whichTime, int errCode, bool isGetDataControl) { - VirtualMultiVerSyncDBInterface *syncInterface = static_cast(storage_); - return syncInterface->StartTransaction(); + VirtualSingleVerSyncDBInterface *syncInterface = static_cast(storage_); + syncInterface->SetGetDataErrCode(whichTime, errCode, isGetDataControl); } -int KvVirtualDevice::Commit() +void KvVirtualDevice::ResetDataControl() +{ + VirtualSingleVerSyncDBInterface *syncInterface = static_cast(storage_); + syncInterface->ResetDataControl(); +} + +#ifndef OMIT_MULTI_VER +int KvVirtualDevice::GetData(const Key &key, Value &value) { VirtualMultiVerSyncDBInterface *syncInterface = static_cast(storage_); - return syncInterface->Commit(); + return syncInterface->GetData(key, value); } -void KvVirtualDevice::SetSaveDataDelayTime(uint64_t milliDelayTime) +int KvVirtualDevice::PutData(const Key &key, const Value &value) { - VirtualSingleVerSyncDBInterface *syncInterface = static_cast(storage_); - syncInterface->SetSaveDataDelayTime(milliDelayTime); + VirtualMultiVerSyncDBInterface *syncInterface = static_cast(storage_); + return syncInterface->PutData(key, value); } -void KvVirtualDevice::DelayGetSyncData(uint64_t milliDelayTime) +int KvVirtualDevice::DeleteData(const Key &key) { - VirtualSingleVerSyncDBInterface *syncInterface = static_cast(storage_); - syncInterface->DelayGetSyncData(milliDelayTime); + VirtualMultiVerSyncDBInterface *syncInterface = static_cast(storage_); + return syncInterface->DeleteData(key); } -void KvVirtualDevice::SetGetDataErrCode(int whichTime, int errCode, bool isGetDataControl) +int KvVirtualDevice::StartTransaction() { - VirtualSingleVerSyncDBInterface *syncInterface = static_cast(storage_); - syncInterface->SetGetDataErrCode(whichTime, errCode, isGetDataControl); + VirtualMultiVerSyncDBInterface *syncInterface = static_cast(storage_); + return syncInterface->StartTransaction(); } -void KvVirtualDevice::ResetDataControl() +int KvVirtualDevice::Commit() { - VirtualSingleVerSyncDBInterface *syncInterface = static_cast(storage_); - syncInterface->ResetDataControl(); + VirtualMultiVerSyncDBInterface *syncInterface = static_cast(storage_); + return syncInterface->Commit(); } +#endif // OMIT_MULTI_VER int KvVirtualDevice::Subscribe(QuerySyncObject query, bool wait, int id) { diff --git a/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.cpp b/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.cpp index fffec2abc0e..f725d7b9c41 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef OMIT_MULTI_VER #include "virtual_multi_ver_sync_db_interface.h" #include "db_common.h" @@ -235,4 +235,5 @@ int VirtualMultiVerSyncDBInterface::DeleteMetaDataByPrefixKey(const Key &keyPref return -E_NOT_SUPPORT; } } // namespace DistributedDB +#endif // OMIT_MULTI_VER diff --git a/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.h b/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.h index e9d985be9ff..fdb921fc606 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.h +++ b/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_multi_ver_sync_db_interface.h @@ -12,10 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #ifndef VIRTUAL_MULTI_VER_SYNC_INTERFACE_H #define VIRTUAL_MULTI_VER_SYNC_INTERFACE_H +#ifndef OMIT_MULTI_VER #include "distributeddb_tools_unit_test.h" #include "multi_ver_natural_store.h" #include "multi_ver_natural_store_connection.h" @@ -101,5 +101,6 @@ private: KvDBProperties properties_; }; } // namespace DistributedDB +#endif // OMIT_MULTI_VER +#endif // VIRTUAL_MULTI_VER_SYNC_INTERFACE -#endif // VIRTUAL_MULTI_VER_SYNC_INTERFACE \ No newline at end of file diff --git a/kvstoremock/distributeddb/BUILD.gn b/kvstoremock/distributeddb/BUILD.gn index 6233c3c5bd7..605f82c9a2b 100644 --- a/kvstoremock/distributeddb/BUILD.gn +++ b/kvstoremock/distributeddb/BUILD.gn @@ -42,6 +42,7 @@ distrdb_defines = [ "USING_DB_JSON_EXTRACT_AUTOMATICALLY", "JSONCPP_USE_BUILDER", "OMIT_FLATBUFFER", + "OMIT_MULTI_VER", "RELATIONAL_STORE", "SQLITE_DISTRIBUTE_RELATIONAL", "SQLITE_ENABLE_DROPTABLE_CALLBACK", -- Gitee From 80dd06ad5e205fc3cd1ca05a23b5f3060b55bf7f Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Fri, 30 Dec 2022 15:59:04 +0800 Subject: [PATCH 009/191] fix error Signed-off-by: zuojiangjiang --- .../distributedKVStore/SingleKvStoreKVCallbackJsTest.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/unittest/distributedKVStore/SingleKvStoreKVCallbackJsTest.js b/test/unittest/distributedKVStore/SingleKvStoreKVCallbackJsTest.js index c2154cf859f..42a8e5013ce 100644 --- a/test/unittest/distributedKVStore/SingleKvStoreKVCallbackJsTest.js +++ b/test/unittest/distributedKVStore/SingleKvStoreKVCallbackJsTest.js @@ -2216,14 +2216,21 @@ describe('SingleKvStoreCallbackTest', function () { it('SingleKvStoreGetResultSetPredicatesCallbackTest', 0, async function (done) { console.log('SingleKvStoreGetResultSetPredicatesCallbackTest'); try { + let resultSet; let predicates = new dataShare.DataSharePredicates(); await kvStore.getResultSet(predicates).then((result) => { console.log('SingleKvStoreGetResultSetPredicatesCallbackTest getResultSet success'); + resultSet = result; expect(true).assertTrue(); }).catch((err) => { console.error('SingleKvStoreGetResultSetPredicatesCallbackTest getResultSet fail ' + err`, error code is ${err.code}, message is ${err.message}`); expect(null).assertFail(); }); + await kvStore.closeResultSet(resultSet).then((err) => { + expect(err == undefined).assertTrue(); + }).catch((err) => { + expect(null).assertFail(); + }); } catch (e) { console.error('SingleKvStoreGetResultSetPredicatesCallbackTest e ' + `, error code is ${e.code}, message is ${e.message}`); expect(null).assertFail(); -- Gitee From bf3b240d45ebd9eed7a58d767947c31626cdc25c Mon Sep 17 00:00:00 2001 From: zwtmichael Date: Tue, 3 Jan 2023 09:43:26 +0800 Subject: [PATCH 010/191] delete unstable testcase Signed-off-by: zwtmichael --- ...distributeddb_single_ver_p2p_sync_test.cpp | 79 ------------------- 1 file changed, 79 deletions(-) diff --git a/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_test.cpp index 41b63825833..386c5171959 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_test.cpp @@ -3332,85 +3332,6 @@ HWTEST_F(DistributedDBSingleVerP2PSyncTest, RebuildSync002, TestSize.Level1) EXPECT_EQ(g_kvDelegatePtr->Get(key2, actualValue), NOT_FOUND); } -/** - * @tc.name: RebuildSync003 - * @tc.desc: test clear history data when receive ack - * @tc.type: FUNC - * @tc.require: - * @tc.author: zhuwentao - */ -HWTEST_F(DistributedDBSingleVerP2PSyncTest, RebuildSync003, TestSize.Level1) -{ - ASSERT_TRUE(g_kvDelegatePtr != nullptr); - /** - * @tc.steps: step1. sync deviceB data to A and check data - * * @tc.expected: step1. interface return ok - */ - Key key1 = {'1'}; - Key key2 = {'2'}; - Key key3 = {'3'}; - Key key4 = {'4'}; - Value value = {'1'}; - EXPECT_EQ(g_deviceB->PutData(key1, value, 1u, 0), E_OK); // 1: timestamp - EXPECT_EQ(g_deviceB->PutData(key2, value, 2u, 0), E_OK); // 2: timestamp - EXPECT_EQ(g_kvDelegatePtr->Put(key3, value), OK); - EXPECT_EQ(g_deviceB->Sync(DistributedDB::SYNC_MODE_PUSH_PULL, true), E_OK); - Value actualValue; - EXPECT_EQ(g_kvDelegatePtr->Get(key1, actualValue), OK); - EXPECT_EQ(actualValue, value); - EXPECT_EQ(g_kvDelegatePtr->Get(key2, actualValue), OK); - EXPECT_EQ(actualValue, value); - VirtualDataItem item; - EXPECT_EQ(g_deviceB->GetData(key3, item), E_OK); - EXPECT_EQ(item.value, value); - /** - * @tc.steps: step2. device B sync to device A,but make it failed - * * @tc.expected: step2. interface return ok - */ - EXPECT_EQ(g_deviceB->PutData(key4, value, 3u, 0), E_OK); // 3: timestamp - g_communicatorAggregator->SetDropMessageTypeByDevice(DEVICE_A, DATA_SYNC_MESSAGE); - EXPECT_EQ(g_deviceB->Sync(DistributedDB::SYNC_MODE_PUSH_ONLY, true), E_OK); - /** - * @tc.steps: step3. device B set delay send time - * * @tc.expected: step3. interface return ok - */ - std::set delayDevice = {DEVICE_B}; - g_communicatorAggregator->SetSendDelayInfo(3000u, DATA_SYNC_MESSAGE, 1u, 0u, delayDevice);// delay 3000ms one time - /** - * @tc.steps: step4. device A rebuilt, device B push data to A and set clear remote data mark into context after 1s - * * @tc.expected: step4. interface return ok - */ - std::thread thread1([]() { - std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // wait 1s - g_deviceB->SetClearRemoteStaleData(true); - if (g_kvDelegatePtr != nullptr) { - g_mgr.CloseKvStore(g_kvDelegatePtr); - g_kvDelegatePtr = nullptr; - } - ASSERT_TRUE(g_mgr.DeleteKvStore(STORE_ID) == OK); - KvStoreNbDelegate::Option option; - g_mgr.GetKvStore(STORE_ID, option, g_kvDelegateCallback); - ASSERT_TRUE(g_kvDelegateStatus == OK); - ASSERT_TRUE(g_kvDelegatePtr != nullptr); - std::map result; - std::vector devices = {g_deviceB->GetDeviceId()}; - g_communicatorAggregator->SetDropMessageTypeByDevice(DEVICE_B, DATA_SYNC_MESSAGE); - ASSERT_TRUE(g_tool.SyncTest(g_kvDelegatePtr, devices, SYNC_MODE_PUSH_ONLY, result) == OK); - }); - /** - * @tc.steps: step5. device B sync to A, make it clear history data and check data - * * @tc.expected: step5. interface return ok - */ - EXPECT_EQ(g_deviceB->Sync(DistributedDB::SYNC_MODE_PUSH_ONLY, true), E_OK); - thread1.join(); - EXPECT_EQ(g_deviceB->GetData(key3, item), -E_NOT_FOUND); - EXPECT_EQ(g_kvDelegatePtr->Get(key1, actualValue), OK); - EXPECT_EQ(actualValue, value); - EXPECT_EQ(g_kvDelegatePtr->Get(key2, actualValue), OK); - EXPECT_EQ(actualValue, value); - g_communicatorAggregator->ResetSendDelayInfo(); -} - /** * @tc.name: GetSyncDataFail001 * @tc.desc: test get sync data failed when sync -- Gitee From b9b597a1a1136c6a77f9d2c03a14b5f69a9fe681 Mon Sep 17 00:00:00 2001 From: zqq Date: Sat, 24 Dec 2022 16:22:07 +0800 Subject: [PATCH 011/191] fix dead lock in timesync Signed-off-by: zqq --- .../distributeddb/syncer/src/time_sync.cpp | 8 ++++- .../libs/distributeddb/syncer/src/time_sync.h | 2 +- .../distributeddb_mock_sync_module_test.cpp | 32 +++++++++++++++++++ .../unittest/common/syncer/mock_time_sync.h | 32 +++++++++++++++++++ 4 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 frameworks/libs/distributeddb/test/unittest/common/syncer/mock_time_sync.h diff --git a/frameworks/libs/distributeddb/syncer/src/time_sync.cpp b/frameworks/libs/distributeddb/syncer/src/time_sync.cpp index e05361feacb..761b06f6cff 100644 --- a/frameworks/libs/distributeddb/syncer/src/time_sync.cpp +++ b/frameworks/libs/distributeddb/syncer/src/time_sync.cpp @@ -185,8 +185,13 @@ void TimeSync::Finalize() // Stop the timer LOGD("[TimeSync] Finalize enter!"); RuntimeContext *runtimeContext = RuntimeContext::GetInstance(); + TimerId timerId; + { + std::unique_lock lock(timeDriverLock_); + timerId = driverTimerId_; + } + runtimeContext->RemoveTimer(timerId, true); std::unique_lock lock(timeDriverLock_); - runtimeContext->RemoveTimer(driverTimerId_, true); timeDriverCond_.wait(lock, [this](){ return this->timeDriverLockCount_ == 0; }); LOGD("[TimeSync] Finalized!"); } @@ -569,6 +574,7 @@ void TimeSync::ResetTimer() void TimeSync::Close() { + Finalize(); { std::lock_guard lock(cvLock_); closed_ = true; diff --git a/frameworks/libs/distributeddb/syncer/src/time_sync.h b/frameworks/libs/distributeddb/syncer/src/time_sync.h index 07f8124f22c..72ddf94215b 100644 --- a/frameworks/libs/distributeddb/syncer/src/time_sync.h +++ b/frameworks/libs/distributeddb/syncer/src/time_sync.h @@ -92,7 +92,7 @@ public: // Used in send msg, as execution is asynchronous, should use this function to handle result. static void CommErrHandlerFunc(int errCode, TimeSync *timeSync); -private: +protected: static const int MAX_RETRY_TIME = 1; static TimeOffset CalculateTimeOffset(const TimeSyncPacket &timeSyncInfo); diff --git a/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp index 3742bcb59b4..0c42e30cb42 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp @@ -33,6 +33,7 @@ #include "mock_single_ver_state_machine.h" #include "mock_sync_engine.h" #include "mock_sync_task_context.h" +#include "mock_time_sync.h" #include "remote_executor_packet.h" #include "single_ver_kv_syncer.h" #include "single_ver_relational_sync_task_context.h" @@ -1514,4 +1515,35 @@ HWTEST_F(DistributedDBMockSyncModuleTest, SyncerCheck001, TestSize.Level1) std::shared_ptr syncer = std::make_shared(); syncer->SetSyncRetry(true); syncer = nullptr; +} + +/** + * @tc.name: TimeSync001 + * @tc.desc: Test syncer call set sync retry before init. + * @tc.type: FUNC + * @tc.require: AR000CCPOM + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBMockSyncModuleTest, TimeSync001, TestSize.Level1) +{ + auto *communicator = new(std::nothrow) MockCommunicator(); + ASSERT_NE(communicator, nullptr); + auto *storage = new(std::nothrow) VirtualSingleVerSyncDBInterface(); + ASSERT_NE(storage, nullptr); + std::shared_ptr metadata = std::make_shared(); + + EXPECT_CALL(*communicator, SendMessage(_, _, _, _)).WillRepeatedly(Return(DB_ERROR)); + const int loopCount = 100; + const int timeDriverMs = 100; + for (int i = 0; i < loopCount; ++i) { + MockTimeSync timeSync; + timeSync.Initialize(communicator, metadata, storage, "DEVICES_A"); + timeSync.ModifyTimer(timeDriverMs); + std::this_thread::sleep_for(std::chrono::milliseconds(timeDriverMs)); + timeSync.Close(); + } + std::this_thread::sleep_for(std::chrono::seconds(1)); + metadata = nullptr; + delete storage; + delete communicator; } \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/unittest/common/syncer/mock_time_sync.h b/frameworks/libs/distributeddb/test/unittest/common/syncer/mock_time_sync.h new file mode 100644 index 00000000000..09f2e7a7d59 --- /dev/null +++ b/frameworks/libs/distributeddb/test/unittest/common/syncer/mock_time_sync.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MOCK_TIME_SYNC_H +#define MOCK_TIME_SYNC_H + +#include +#include "time_sync.h" + +namespace DistributedDB { +class MockTimeSync : public TimeSync { +public: + void ModifyTimer(int milliSeconds) + { + std::lock_guard lock(timeDriverLock_); + RuntimeContext::GetInstance()->ModifyTimer(driverTimerId_, milliSeconds); + } +}; +} +#endif // MOCK_TIME_SYNC_H -- Gitee From eae3fce31d6dcbf1860d8552263e6b01bd1cb38e Mon Sep 17 00:00:00 2001 From: saikit Date: Wed, 4 Jan 2023 16:41:12 +0800 Subject: [PATCH 012/191] fix master warning Signed-off-by: saikit --- .../relational/sqlite_single_relational_storage_engine.h | 2 +- .../distributeddb/syncer/src/single_ver_serialize_manager.cpp | 2 +- .../distributeddb/syncer/src/single_ver_sync_state_machine.h | 2 +- .../distributeddb_interfaces_relational_sync_test.cpp | 3 +-- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.h b/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.h index bb82388dde9..540f499c99b 100644 --- a/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.h +++ b/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.h @@ -55,7 +55,7 @@ private: int UpgradeDistributedTable(const std::string &tableName, bool &schemaChanged); int CreateDistributedTable(const std::string &tableName, bool isUpgraded, const std::string &identity, - RelationalSchemaObject &tmpSchema); + RelationalSchemaObject &schema); int CreateRelationalMetaTable(sqlite3 *db); diff --git a/frameworks/libs/distributeddb/syncer/src/single_ver_serialize_manager.cpp b/frameworks/libs/distributeddb/syncer/src/single_ver_serialize_manager.cpp index 495f7a26c52..f7dbfca0f14 100644 --- a/frameworks/libs/distributeddb/syncer/src/single_ver_serialize_manager.cpp +++ b/frameworks/libs/distributeddb/syncer/src/single_ver_serialize_manager.cpp @@ -486,7 +486,7 @@ int SingleVerSerializeManager::DataPacketSyncerPartDeSerialization(Parcel &parce return -E_LENGTH_ERROR; } parcel.EightByteAlign(); - packLen = Parcel::GetEightByteAlign(packLen); + totPacketLen = Parcel::GetEightByteAlign(totPacketLen); if (parcel.IsError()) { LOGE("[DataSync][DataPacketDeSerialization] deserialize failed! input len=%" PRIu32 ", totPackLen=%" PRIu64, length, totPacketLen); diff --git a/frameworks/libs/distributeddb/syncer/src/single_ver_sync_state_machine.h b/frameworks/libs/distributeddb/syncer/src/single_ver_sync_state_machine.h index 239115160cb..c8ea5878340 100644 --- a/frameworks/libs/distributeddb/syncer/src/single_ver_sync_state_machine.h +++ b/frameworks/libs/distributeddb/syncer/src/single_ver_sync_state_machine.h @@ -72,7 +72,7 @@ public: ~SingleVerSyncStateMachine() override; // Init the SingleVerSyncStateMachine - int Initialize(ISyncTaskContext *context, ISyncInterface *syncInterface, const std::shared_ptr &metadata, + int Initialize(ISyncTaskContext *context, ISyncInterface *syncInterface, const std::shared_ptr &metaData, ICommunicator *communicator) override; // send Message to the StateMachine diff --git a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp index eec431001b2..b66b02ff448 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp @@ -546,7 +546,6 @@ std::string GetKey(VirtualRowData rowData) void CheckSyncData(sqlite3 *db, const std::string &checkSql, const std::vector &resultData) { - int i = 0; std::set keySet; keySet.clear(); for (size_t i = 0; i < resultData.size(); i++) { @@ -555,7 +554,7 @@ void CheckSyncData(sqlite3 *db, const std::string &checkSql, const std::vector Date: Fri, 6 Jan 2023 10:47:13 +0800 Subject: [PATCH 013/191] add ut to increase branch coverage Signed-off-by: saikit --- ...qlite_single_ver_natural_executor_test.cpp | 270 ++++++++++++++++-- 1 file changed, 250 insertions(+), 20 deletions(-) diff --git a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp index eb8023319da..c522c89f853 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp @@ -36,6 +36,10 @@ namespace { SQLiteSingleVerNaturalStoreConnection *g_connection = nullptr; SQLiteSingleVerStorageExecutor *g_handle = nullptr; SQLiteSingleVerStorageExecutor *g_nullHandle = nullptr; + + const char * const ADD_SYNC = "ALTER TABLE sync_data ADD column version INT"; + const char * const INSERT_SQL = "INSERT INTO sync_data VALUES('a', 'b', 1, 2, '', '', 'efdef', 100 , 1);"; + const int SQL_STATE_ERR = -1; } class DistributedDBStorageSQLiteSingleVerNaturalExecutorTest : public testing::Test { @@ -273,6 +277,7 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, InvalidParam006 EXPECT_EQ(g_nullHandle->OpenResultSetForCacheRowIdMode(KEY_1, cache, 0, count), -E_INVALID_DB); Query query = Query::Select(); QueryObject object(query); + EXPECT_EQ(g_nullHandle->OpenResultSet(object, count), -E_INVALID_DB); EXPECT_EQ(g_nullHandle->OpenResultSetForCacheRowIdMode(object, cache, 0, count), -E_INVALID_DB); /** @@ -384,7 +389,7 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, InvalidParam009 /** * @tc.name: InvalidParam010 - * @tc.desc: Get meta key with Invalid condition + * @tc.desc: Fail to call function with Invalid condition * @tc.type: FUNC * @tc.require: * @tc.author: bty @@ -393,15 +398,16 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, InvalidParam010 { vector keys; EXPECT_EQ(g_nullHandle->GetAllMetaKeys(keys), -E_INVALID_DB); - string devName; vector entries; EXPECT_EQ(g_nullHandle->GetAllSyncedEntries(devName, entries), -E_INVALID_DB); + EXPECT_EQ(g_nullHandle->ForceCheckPoint(), -E_INVALID_DB); + EXPECT_EQ(g_nullHandle->CheckIntegrity(), -E_INVALID_DB); } /** * @tc.name: InvalidParam011 - * @tc.desc: + * @tc.desc: Change executor state to operate data * @tc.type: FUNC * @tc.require: * @tc.author: bty @@ -425,18 +431,28 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, InvalidParam011 std::string dbPath = g_testDir + g_databaseName; OpenDbProperties property = {dbPath, false, false}; EXPECT_EQ(SQLiteUtils::OpenDatabase(property, sqlHandle), E_OK); - EXPECT_NE(sqlHandle, nullptr); - auto executor = new (std::nothrow) SQLiteSingleVerStorageExecutor( + ASSERT_NE(sqlHandle, nullptr); + + auto executor = std::make_unique( sqlHandle, false, false, ExecutorState::CACHE_ATTACH_MAIN); - EXPECT_NE(executor, nullptr); + ASSERT_NE(executor, nullptr); /** * @tc.steps: step3. The singleVerNaturalStoreCommitNotifyData is null,delete - * @tc.expected: step3. Expect -1 + * @tc.expected: step3. Expect SQL_STATE_ERR + */ + EXPECT_EQ(executor->DeleteLocalKvData(key, nullptr, value, timestamp), SQL_STATE_ERR); + + /** + * @tc.steps: step4. Update sync_data table and insert a sync data + * @tc.expected: step4. Expect E_OK */ - EXPECT_EQ(executor->DeleteLocalKvData(key, nullptr, value, timestamp), -1); // -1 is covert from sqlite error code + ASSERT_TRUE(SQLiteUtils::ExecuteRawSQL(sqlHandle, ADD_SYNC) == E_OK); + ASSERT_TRUE(SQLiteUtils::ExecuteRawSQL(sqlHandle, INSERT_SQL) == E_OK); + std::vector vec; + uint64_t count = 0u; + EXPECT_EQ(executor->GetMinVersionCacheData(vec, count), E_OK); sqlite3_close_v2(sqlHandle); - delete executor; sqlHandle = nullptr; } @@ -549,6 +565,8 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ConnectionTest0 option.dataType = IOption::SYNC_DATA; EXPECT_EQ(emptyConn->PutBatch(option, entries), -E_INVALID_DB); EXPECT_EQ(emptyConn->DeleteBatch(option, keys), -E_INVALID_DB); + option.dataType = IOption::SYNC_DATA + 1; + EXPECT_EQ(emptyConn->PutBatch(option, entries), -E_NOT_SUPPORT); } /** @@ -562,7 +580,7 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ConnectionTest0 { /** * @tc.steps: step1. Only change the storageEngine to cacheDB - * @tc.expected: step1. Expect -1 + * @tc.expected: step1. Expect SQL_STATE_ERR */ int errCode = E_OK; SQLiteSingleVerStorageEngine *storageEngine = @@ -574,18 +592,18 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ConnectionTest0 std::vector entries; entries.push_back(ENTRY_1); g_store->ReleaseHandle(g_handle); - EXPECT_EQ(g_connection->PutBatch(option, entries), -1); // -1 is sqlite error + EXPECT_EQ(g_connection->PutBatch(option, entries), SQL_STATE_ERR); std::vector keys; keys.push_back(KEY_1); - EXPECT_EQ(g_connection->DeleteBatch(option, keys), -1); + EXPECT_EQ(g_connection->DeleteBatch(option, keys), SQL_STATE_ERR); /** * @tc.steps: step2.Change to LOCAL_DATA option - * @tc.expected: step2. Expect -1 + * @tc.expected: step2. Expect SQL_STATE_ERR */ option.dataType = IOption::LOCAL_DATA; - EXPECT_EQ(g_connection->PutBatch(option, entries), -1); - EXPECT_EQ(g_connection->DeleteBatch(option, keys), -1); + EXPECT_EQ(g_connection->PutBatch(option, entries), SQL_STATE_ERR); + EXPECT_EQ(g_connection->DeleteBatch(option, keys), SQL_STATE_ERR); /** * @tc.steps: step3. Table sync_data adds a column to make the num of cols equal to the cacheDB @@ -594,8 +612,7 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ConnectionTest0 sqlite3 *db; ASSERT_TRUE(sqlite3_open_v2((g_testDir + g_databaseName).c_str(), &db, SQLITE_OPEN_URI | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nullptr) == SQLITE_OK); - string addSync = "alter table sync_data add column version INT"; - ASSERT_TRUE(SQLiteUtils::ExecuteRawSQL(db, addSync) == E_OK); + ASSERT_TRUE(SQLiteUtils::ExecuteRawSQL(db, ADD_SYNC) == E_OK); sqlite3_close_v2(db); option.dataType = IOption::SYNC_DATA; EXPECT_EQ(g_connection->PutBatch(option, entries), E_OK); @@ -623,7 +640,6 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ConnectionTest0 std::unique_ptr emptyConn = std::make_unique(nullptr); EXPECT_EQ(emptyConn->GetResultSet(option, KEY_1, set), -E_INVALID_DB); - emptyConn->ReleaseResultSet(set); /** * @tc.steps: step2. get in transaction @@ -648,6 +664,68 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ConnectionTest0 storageEngine->Release(); } +/** + * @tc.name: ConnectionTest005 + * @tc.desc: Failed to Get entries,value and count + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ConnectionTest005, TestSize.Level1) +{ + /** + * @tc.steps: step1. the db is null + * @tc.expected: step1. Expect -E_INVALID_DB, Get return -E_NOT_INIT + */ + g_store->ReleaseHandle(g_handle); + IOption option; + option.dataType = IOption::SYNC_DATA; + Query query = Query::Select(); + std::unique_ptr emptyConn = + std::make_unique(nullptr); + ASSERT_NE(emptyConn, nullptr); + int count; + EXPECT_EQ(emptyConn->GetCount(option, query, count), -E_INVALID_DB); + std::vector entries; + EXPECT_EQ(emptyConn->GetEntries(option, query, entries), -E_INVALID_DB); + Value value; + EXPECT_EQ(emptyConn->Get(option, KEY_1, value), -E_NOT_INIT); + + /** + * @tc.steps: step2. the dataType is not SYNC_DATA + * @tc.expected: step2. Expect -E_NOT_SUPPORT + */ + option.dataType = IOption::SYNC_DATA + 1; + EXPECT_EQ(emptyConn->GetCount(option, query, count), -E_NOT_SUPPORT); + EXPECT_EQ(emptyConn->GetEntries(option, query, entries), -E_NOT_SUPPORT); + EXPECT_EQ(emptyConn->Get(option, KEY_1, value), -E_NOT_SUPPORT); + + /** + * @tc.steps: step3. get in transaction + * @tc.expected: step3. Expect GetEntries -E_NOT_FOUND, GetCount E_OK + */ + option.dataType = IOption::SYNC_DATA; + g_connection->StartTransaction(); + EXPECT_EQ(g_connection->GetEntries(option, query, entries), -E_NOT_FOUND); + EXPECT_EQ(g_connection->GetCount(option, query, count), E_OK); + g_connection->RollBack(); + + /** + * @tc.steps: step4. change the storageEngine to cacheDB + * @tc.expected: step4. Expect -E_EKEYREVOKED + */ + int errCode = E_OK; + SQLiteSingleVerStorageEngine *storageEngine = + static_cast(StorageEngineManager::GetStorageEngine(g_property, errCode)); + ASSERT_EQ(errCode, E_OK); + ASSERT_NE(storageEngine, nullptr); + storageEngine->SetEngineState(EngineState::CACHEDB); + EXPECT_EQ(g_connection->GetCount(option, query, count), -E_EKEYREVOKED); + EXPECT_EQ(g_connection->GetEntries(option, query, entries), -E_EKEYREVOKED); + EXPECT_EQ(g_connection->Get(option, KEY_1, value), -E_EKEYREVOKED); + storageEngine->Release(); +} + /** * @tc.name: PragmaTest001 * @tc.desc: Calling Pragma incorrectly @@ -759,16 +837,168 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, PragmaTest002, */ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, PragmaTest003, TestSize.Level1) { - std::unique_ptr emptyConn = - std::make_unique(nullptr); + auto emptyConn = std::make_unique(nullptr); PragmaEntryDeviceIdentifier identifier = {.key = KEY_1}; EXPECT_EQ(emptyConn->Pragma(PRAGMA_GET_DEVICE_IDENTIFIER_OF_ENTRY, &identifier), -E_NOT_INIT); + EXPECT_EQ(emptyConn->Pragma(PRAGMA_EXEC_CHECKPOINT, nullptr), -E_NOT_INIT); EXPECT_EQ(emptyConn->CheckIntegrity(), -E_NOT_INIT); int limit = 0; EXPECT_EQ(emptyConn->Pragma(PRAGMA_SET_MAX_LOG_LIMIT, &limit), -E_INVALID_DB); + EXPECT_EQ(emptyConn->Pragma(PRAGMA_RM_DEVICE_DATA, nullptr), -E_INVALID_DB); CipherPassword pw; EXPECT_EQ(emptyConn->Import("/a.b", pw), -E_INVALID_DB); + EXPECT_EQ(emptyConn->Export("/a.b", pw), -E_INVALID_DB); DatabaseLifeCycleNotifier notifier; EXPECT_EQ(emptyConn->RegisterLifeCycleCallback(notifier), -E_INVALID_DB); + + EXPECT_EQ(emptyConn->SetConflictNotifier(0, nullptr), -E_INVALID_ARGS); + EXPECT_EQ(emptyConn->SetConflictNotifier(0, [&](const KvDBCommitNotifyData &data) {}), -E_INVALID_DB); + IKvDBSnapshot *shot; + EXPECT_EQ(emptyConn->GetSnapshot(shot), -E_NOT_SUPPORT); +} + +/** + * @tc.name: ExecutorCache001 + * @tc.desc: Fail to operate data + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ExecutorCache001, TestSize.Level1) +{ + g_handle->SetAttachMetaMode(true); + std::set devices; + EXPECT_EQ(g_handle->GetExistsDevicesFromMeta(devices), SQL_STATE_ERR); + EXPECT_EQ(g_handle->DeleteMetaDataByPrefixKey(KEY_1), SQL_STATE_ERR); + std::vector keys; + EXPECT_EQ(g_handle->DeleteMetaData(keys), SQL_STATE_ERR); + EXPECT_EQ(g_handle->PrepareForSavingCacheData(SingleVerDataType::LOCAL_TYPE), SQL_STATE_ERR); + EXPECT_EQ(g_handle->RemoveDeviceDataInCacheMode("device1", true, 0u), SQL_STATE_ERR); + Timestamp timestamp; + EXPECT_EQ(g_handle->GetMaxTimestampDuringMigrating(timestamp), -E_NOT_INIT); + EXPECT_EQ(g_handle->ResetForSavingCacheData(SingleVerDataType::LOCAL_TYPE), E_OK); +} + +/** + * @tc.name: ExecutorCache002 + * @tc.desc: Fail to call func in each ExecutorState + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ExecutorCache002, TestSize.Level1) +{ + /** + * @tc.steps: step1. In MAINDB + * @tc.expected: step1. Expect not E_OK + */ + NotifyMigrateSyncData syncData; + DataItem dataItem; + std::vector items; + items.push_back(dataItem); + EXPECT_EQ(g_handle->MigrateSyncDataByVersion(0u, syncData, items), -E_INVALID_DB); + uint64_t version; + EXPECT_EQ(g_handle->GetMinVersionCacheData(items, version), -E_INVALID_ARGS); + EXPECT_EQ(g_handle->GetMaxVersionInCacheDb(version), -E_INVALID_ARGS); + EXPECT_EQ(g_handle->MigrateLocalData(), -E_INVALID_ARGS); + + /** + * @tc.steps: step2. Change executor to CACHE_ATTACH_MAIN + * @tc.expected: step2. Expect SQL_STATE_ERR + */ + sqlite3 *sqlHandle = nullptr; + EXPECT_EQ(SQLiteUtils::OpenDatabase({g_testDir + g_databaseName, false, false}, sqlHandle), E_OK); + ASSERT_NE(sqlHandle, nullptr); + auto executor = std::make_unique( + sqlHandle, false, false, ExecutorState::CACHE_ATTACH_MAIN); + ASSERT_NE(executor, nullptr); + EXPECT_EQ(executor->MigrateSyncDataByVersion(0u, syncData, items), SQL_STATE_ERR); + EXPECT_EQ(executor->GetMinVersionCacheData(items, version), SQL_STATE_ERR); + EXPECT_EQ(executor->GetMaxVersionInCacheDb(version), SQL_STATE_ERR); + EXPECT_EQ(executor->MigrateLocalData(), SQL_STATE_ERR); + executor->SetAttachMetaMode(true); + EXPECT_EQ(executor->MigrateSyncDataByVersion(0u, syncData, items), SQL_STATE_ERR); + + /** + * @tc.steps: step3. Change executor to MAIN_ATTACH_CACHE + * @tc.expected: step3. Expect SQL_STATE_ERR + */ + auto executor2 = std::make_unique( + sqlHandle, false, false, ExecutorState::MAIN_ATTACH_CACHE); + ASSERT_NE(executor2, nullptr); + EXPECT_EQ(executor2->MigrateSyncDataByVersion(0u, syncData, items), SQL_STATE_ERR); + EXPECT_EQ(executor2->GetMinVersionCacheData(items, version), SQL_STATE_ERR); + EXPECT_EQ(executor2->GetMaxVersionInCacheDb(version), SQL_STATE_ERR); + EXPECT_EQ(executor2->MigrateLocalData(), SQL_STATE_ERR); + sqlite3_close_v2(sqlHandle); + sqlHandle = nullptr; +} + +/** + * @tc.name: ExecutorCache003 + * @tc.desc: Test different condition to attach db + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ExecutorCache003, TestSize.Level1) +{ + /** + * @tc.steps: step1. Copy empty db, then attach + */ + string cacheDir = g_testDir + "/" + g_identifier + "/" + DBConstant::SINGLE_SUB_DIR + + "/" + DBConstant::CACHEDB_DIR + "/" + DBConstant::SINGLE_VER_CACHE_STORE + ".db"; + EXPECT_EQ(DBCommon::CopyFile(g_testDir + g_databaseName, cacheDir), E_OK); + CipherPassword password; + EXPECT_EQ(g_nullHandle->AttachMainDbAndCacheDb( + CipherType::DEFAULT, password, cacheDir, EngineState::INVALID), -E_INVALID_ARGS); + EXPECT_EQ(g_nullHandle->AttachMainDbAndCacheDb( + CipherType::DEFAULT, password, cacheDir, EngineState::CACHEDB), -E_INVALID_DB); + EXPECT_EQ(g_nullHandle->AttachMainDbAndCacheDb( + CipherType::DEFAULT, password, cacheDir, EngineState::ATTACHING), E_OK); + EXPECT_EQ(g_handle->AttachMainDbAndCacheDb( + CipherType::DEFAULT, password, cacheDir, EngineState::MAINDB), E_OK); + + /** + * @tc.steps: step2. Try migrate data after attaching cache + * @tc.expected: step2. Expect SQL_STATE_ERR + */ + NotifyMigrateSyncData syncData; + DataItem dataItem; + std::vector items; + items.push_back(dataItem); + EXPECT_EQ(g_handle->MigrateSyncDataByVersion(0u, syncData, items), SQL_STATE_ERR); +} + +/** + * @tc.name: ExecutorCache004 + * @tc.desc: Test after attaching cache + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ExecutorCache004, TestSize.Level1) +{ + /** + * @tc.steps: step1. Copy normal db, attach cache + * @tc.expected: step1. Expect E_OK + */ + string cacheDir = g_testDir + "/" + g_identifier + "/" + DBConstant::SINGLE_SUB_DIR + + "/" + DBConstant::CACHEDB_DIR + "/" + DBConstant::SINGLE_VER_CACHE_STORE + ".db"; + EXPECT_EQ(g_handle->ForceCheckPoint(), E_OK); + EXPECT_EQ(DBCommon::CopyFile(g_testDir + g_databaseName, cacheDir), E_OK); + CipherPassword password; + EXPECT_EQ(g_handle->AttachMainDbAndCacheDb( + CipherType::DEFAULT, password, cacheDir, EngineState::MAINDB), E_OK); + + /** + * @tc.steps: step2. Migrate sync data but param incomplete + * @tc.expected: step2. Expect -E_INVALID_ARGS + */ + NotifyMigrateSyncData syncData; + DataItem dataItem; + std::vector items; + items.push_back(dataItem); + EXPECT_EQ(g_handle->MigrateSyncDataByVersion(0u, syncData, items), -E_INVALID_ARGS); } \ No newline at end of file -- Gitee From 8f49276efb9a057591a80ad3e667de4bab81a4b9 Mon Sep 17 00:00:00 2001 From: renjiecui Date: Mon, 9 Jan 2023 11:01:18 +0800 Subject: [PATCH 014/191] =?UTF-8?q?=E4=BF=AE=E6=94=B9JS=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: renjiecui --- BUILD.gn | 3 +- bundle.json | 3 +- .../{ => distributedKVStore}/BUILD.gn | 2 +- .../{ => distributedKVStore}/config.json | 0 .../openharmony_sx.p7b | Bin test/unittest/distributeddata/BUILD.gn | 30 +++++++ test/unittest/distributeddata/config.json | 75 ++++++++++++++++++ .../distributeddata/openharmony_sx.p7b | Bin 0 -> 3509 bytes 8 files changed, 110 insertions(+), 3 deletions(-) rename test/unittest/{ => distributedKVStore}/BUILD.gn (94%) rename test/unittest/{ => distributedKVStore}/config.json (100%) rename test/unittest/{ => distributedKVStore}/openharmony_sx.p7b (100%) create mode 100644 test/unittest/distributeddata/BUILD.gn create mode 100644 test/unittest/distributeddata/config.json create mode 100644 test/unittest/distributeddata/openharmony_sx.p7b diff --git a/BUILD.gn b/BUILD.gn index ffdc42dd56d..afb47d1d240 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -34,6 +34,7 @@ group("unittest") { deps = [] deps += [ "frameworks/innerkitsimpl/kvdb/test:unittest", - "test/unittest:unittest", + "test/unittest/distributedKVStore:unittest", + "test/unittest/distributeddata:unittest", ] } diff --git a/bundle.json b/bundle.json index 7885218b4f2..43dba3d63a7 100644 --- a/bundle.json +++ b/bundle.json @@ -119,7 +119,8 @@ "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/test:distributeddatamgr_fuzztest", "//foundation/distributeddatamgr/kv_store:distributedtest", "//foundation/distributeddatamgr/kv_store:build_native_test", - "//foundation/distributeddatamgr/kv_store/test/unittest:unittest", + "//foundation/distributeddatamgr/kv_store/test/unittest/distributeddata:unittest", + "//foundation/distributeddatamgr/kv_store/test/unittest/distributedKVStore:unittest", "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/test:unittest" ] } diff --git a/test/unittest/BUILD.gn b/test/unittest/distributedKVStore/BUILD.gn similarity index 94% rename from test/unittest/BUILD.gn rename to test/unittest/distributedKVStore/BUILD.gn index bac44b2b515..22c46fcf99f 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/distributedKVStore/BUILD.gn @@ -13,7 +13,7 @@ import("//build/test.gni") -module_output_path = "kv_store/napi" +module_output_path = "kv_store/distributedkvstore" ohos_js_unittest("KvStoreJsTest") { module_out_path = module_output_path diff --git a/test/unittest/config.json b/test/unittest/distributedKVStore/config.json similarity index 100% rename from test/unittest/config.json rename to test/unittest/distributedKVStore/config.json diff --git a/test/unittest/openharmony_sx.p7b b/test/unittest/distributedKVStore/openharmony_sx.p7b similarity index 100% rename from test/unittest/openharmony_sx.p7b rename to test/unittest/distributedKVStore/openharmony_sx.p7b diff --git a/test/unittest/distributeddata/BUILD.gn b/test/unittest/distributeddata/BUILD.gn new file mode 100644 index 00000000000..8401b34440f --- /dev/null +++ b/test/unittest/distributeddata/BUILD.gn @@ -0,0 +1,30 @@ +# 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. + +import("//build/test.gni") + +module_output_path = "kv_store/distributeddata" + +ohos_js_unittest("KvStoreDataJsTest") { + module_out_path = module_output_path + + hap_profile = "./config.json" + + certificate_profile = + "//test/testfwk/developer_test/signature/openharmony_sx.p7b" +} + +group("unittest") { + testonly = true + deps = [ ":KvStoreDataJsTest" ] +} diff --git a/test/unittest/distributeddata/config.json b/test/unittest/distributeddata/config.json new file mode 100644 index 00000000000..c0c57b6b201 --- /dev/null +++ b/test/unittest/distributeddata/config.json @@ -0,0 +1,75 @@ +{ + "app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 4, + "target": 5 + } + }, + "deviceConfig": {}, + "module": { + "package": "com.example.myapplication", + "name": ".MyApplication", + "deviceType": [ + "default", + "tablet", + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "defPermissions": [ + { + "availableScope": [], + "grantMode": "user_grant", + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC", + "reason": "ceshi" + } + ], + "abilities": [ + { + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "name": "com.example.myapplication.MainAbility", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "MyApplication", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } +} diff --git a/test/unittest/distributeddata/openharmony_sx.p7b b/test/unittest/distributeddata/openharmony_sx.p7b new file mode 100644 index 0000000000000000000000000000000000000000..56e8a3d55193b1224bfe64d98465327062a5cd1b GIT binary patch literal 3509 zcmcgvYj6|S8MPj^V~nuDV1onLh=(a4`>rh6l2Zb^(n?z4l`L7ZEn{j{(&}MLyRx+M z%A$ZH8aF_IP^RF9N6gDW10)3!z^*LkmMzR29KZmO{j5ulINyeyGt-)w?US6`mT(Zb9pC721b_BRKIa%2b80cCD|@ zR%H&@r82h(psdd0FyM74i`T(T90v;)Fmzs_9(j_hLulL-VpXO-j#`w} zt1We?6-TgsULL%(hI;0m5v>KT>i^D=1x1x?b)_7$Rp}YKR4&IfW}mGRMCPese?JDd z)KEI`3<}k-4s9f0lWG9L)dJJ#eRl499a1Y>X@M<>+c8jG42f5|hU%|1jv%Z-1;ZA* z&8RY&0+n)?v)-mN$mETnsu0!@5lC8BhB#3*9nzSwYKW}zM~t>;xweMVv$!jy^H{A) zfGT_#uvFQqDTCjQLm|2`Y$r_(u!V*&)~beGapt;m9M!7fN;hJ$dx8#c4W(hMrL;9% zSXf?B9Co1^7lAS6C~WLQn-mD_QlJQos}LE?>f#kO10#aiP)!*V35Gqs8p>ftOd-9K zbyPQ$hLyCzTHz*enANIO4cc;CrsQU;5fiK?V3@5oVG&r*5TMK?4an43xF8U!p-ORQ zsY>lO$*nrb2M}4A)`R$Px6><)x)fBsG87=9s0k|oRR%WTViYDAV|C?WSXxQ?D!c`B z4Hbob8lX^9c74!jWQ>%lLC)%oWj?hHkr^3l)M(Rl%Q$Ezh*J89KB^6Q3TmjnmOu^a z=d=meVFTSb;3E#&pFgMr^EpGvXUGu40f~T*>pF@K`UziO7?8L~f(gglUhLr8DMp?%8*IWj@7gW*;jGBQ7o<(3S`?M57^_x2f9km9&5Zi^-T3&i+8 z1u@>IZ2~@z&leW&@*e@ilV0IG`OIvgK#-UK98fAqNfKCvNf~^V0U8ZP#e-oPse|eP zjRRTnY-&dOplq&%B>d21FeyGH$jBZ%1P21XxMOjjnyZ4r#4M2%0#YD_q})?poh6bf zA!#8r5Q4yuBmqEvKZ(2-kthq&F0YTwHTRo7uz`%E>isD( zd((d1l#$4dcgRjp(t%N%(^<{yk8W&h?YM%hab9xW>)Ca;XH`0ny_*5$lt>&!IGJR>4V1}O%Ks4skpOd3J@Q}HCud_$NZ7T6Pn zcu{xL+IrElO}9k)V~?lPHyyBl-l9%P>ZZm|uG?(q=5O3KH}=EFU)hA(mAJMwupZgD zx9x6c?L$lZ@DbgPx7PecJ97J*qRWSOZhKfe=HaxQmBH@ZpG+`?Y}k_GWbN(k2$&1f z;zG%Y3nvi>xW`Z>@sb89DXS!X>-*z=-kV_Dd#*L_Kx;KS;`Gqn6SxzAlMmQxHV-=e zJ-hq$4V$~F4z1ar*FJ33+2MyvIw!u_JVPF>*|~MRWXpvwXyIh9EsxpA2UFgk@=JQb z-pR@4(K}Y%ZF?K&=QOGR9Y%WtI~q4{x(hZm7}qv+?aI0^v;B;AY)c}iBZAXW?|_ab zl1FC`W%3etZ;%;5@po_FQuta>58a34r7S|D~TP zmi>mgwe-UWC7#+n$BVXHJ(7OBE92^7SGuuRXZ?D4^Egij_T7c+9b?X4?;6RO)v;G- zc27xgtGQ#E0m=H|DJ}|eZ@IUwZd|H T>C)m4YnzjoG^Lb%{_1}LB3Nj% literal 0 HcmV?d00001 -- Gitee From 027d8436c4b70a88cf4fa7162baf42e3b18896f5 Mon Sep 17 00:00:00 2001 From: renjiecui Date: Mon, 9 Jan 2023 11:46:07 +0800 Subject: [PATCH 015/191] =?UTF-8?q?=E4=BF=AE=E6=94=B9JS=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: renjiecui --- .../distributedKVStore/openharmony_sx.p7b | Bin 3509 -> 0 bytes test/unittest/distributeddata/openharmony_sx.p7b | Bin 3509 -> 0 bytes 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 test/unittest/distributedKVStore/openharmony_sx.p7b delete mode 100644 test/unittest/distributeddata/openharmony_sx.p7b diff --git a/test/unittest/distributedKVStore/openharmony_sx.p7b b/test/unittest/distributedKVStore/openharmony_sx.p7b deleted file mode 100644 index 56e8a3d55193b1224bfe64d98465327062a5cd1b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3509 zcmcgvYj6|S8MPj^V~nuDV1onLh=(a4`>rh6l2Zb^(n?z4l`L7ZEn{j{(&}MLyRx+M z%A$ZH8aF_IP^RF9N6gDW10)3!z^*LkmMzR29KZmO{j5ulINyeyGt-)w?US6`mT(Zb9pC721b_BRKIa%2b80cCD|@ zR%H&@r82h(psdd0FyM74i`T(T90v;)Fmzs_9(j_hLulL-VpXO-j#`w} zt1We?6-TgsULL%(hI;0m5v>KT>i^D=1x1x?b)_7$Rp}YKR4&IfW}mGRMCPese?JDd z)KEI`3<}k-4s9f0lWG9L)dJJ#eRl499a1Y>X@M<>+c8jG42f5|hU%|1jv%Z-1;ZA* z&8RY&0+n)?v)-mN$mETnsu0!@5lC8BhB#3*9nzSwYKW}zM~t>;xweMVv$!jy^H{A) zfGT_#uvFQqDTCjQLm|2`Y$r_(u!V*&)~beGapt;m9M!7fN;hJ$dx8#c4W(hMrL;9% zSXf?B9Co1^7lAS6C~WLQn-mD_QlJQos}LE?>f#kO10#aiP)!*V35Gqs8p>ftOd-9K zbyPQ$hLyCzTHz*enANIO4cc;CrsQU;5fiK?V3@5oVG&r*5TMK?4an43xF8U!p-ORQ zsY>lO$*nrb2M}4A)`R$Px6><)x)fBsG87=9s0k|oRR%WTViYDAV|C?WSXxQ?D!c`B z4Hbob8lX^9c74!jWQ>%lLC)%oWj?hHkr^3l)M(Rl%Q$Ezh*J89KB^6Q3TmjnmOu^a z=d=meVFTSb;3E#&pFgMr^EpGvXUGu40f~T*>pF@K`UziO7?8L~f(gglUhLr8DMp?%8*IWj@7gW*;jGBQ7o<(3S`?M57^_x2f9km9&5Zi^-T3&i+8 z1u@>IZ2~@z&leW&@*e@ilV0IG`OIvgK#-UK98fAqNfKCvNf~^V0U8ZP#e-oPse|eP zjRRTnY-&dOplq&%B>d21FeyGH$jBZ%1P21XxMOjjnyZ4r#4M2%0#YD_q})?poh6bf zA!#8r5Q4yuBmqEvKZ(2-kthq&F0YTwHTRo7uz`%E>isD( zd((d1l#$4dcgRjp(t%N%(^<{yk8W&h?YM%hab9xW>)Ca;XH`0ny_*5$lt>&!IGJR>4V1}O%Ks4skpOd3J@Q}HCud_$NZ7T6Pn zcu{xL+IrElO}9k)V~?lPHyyBl-l9%P>ZZm|uG?(q=5O3KH}=EFU)hA(mAJMwupZgD zx9x6c?L$lZ@DbgPx7PecJ97J*qRWSOZhKfe=HaxQmBH@ZpG+`?Y}k_GWbN(k2$&1f z;zG%Y3nvi>xW`Z>@sb89DXS!X>-*z=-kV_Dd#*L_Kx;KS;`Gqn6SxzAlMmQxHV-=e zJ-hq$4V$~F4z1ar*FJ33+2MyvIw!u_JVPF>*|~MRWXpvwXyIh9EsxpA2UFgk@=JQb z-pR@4(K}Y%ZF?K&=QOGR9Y%WtI~q4{x(hZm7}qv+?aI0^v;B;AY)c}iBZAXW?|_ab zl1FC`W%3etZ;%;5@po_FQuta>58a34r7S|D~TP zmi>mgwe-UWC7#+n$BVXHJ(7OBE92^7SGuuRXZ?D4^Egij_T7c+9b?X4?;6RO)v;G- zc27xgtGQ#E0m=H|DJ}|eZ@IUwZd|H T>C)m4YnzjoG^Lb%{_1}LB3Nj% diff --git a/test/unittest/distributeddata/openharmony_sx.p7b b/test/unittest/distributeddata/openharmony_sx.p7b deleted file mode 100644 index 56e8a3d55193b1224bfe64d98465327062a5cd1b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3509 zcmcgvYj6|S8MPj^V~nuDV1onLh=(a4`>rh6l2Zb^(n?z4l`L7ZEn{j{(&}MLyRx+M z%A$ZH8aF_IP^RF9N6gDW10)3!z^*LkmMzR29KZmO{j5ulINyeyGt-)w?US6`mT(Zb9pC721b_BRKIa%2b80cCD|@ zR%H&@r82h(psdd0FyM74i`T(T90v;)Fmzs_9(j_hLulL-VpXO-j#`w} zt1We?6-TgsULL%(hI;0m5v>KT>i^D=1x1x?b)_7$Rp}YKR4&IfW}mGRMCPese?JDd z)KEI`3<}k-4s9f0lWG9L)dJJ#eRl499a1Y>X@M<>+c8jG42f5|hU%|1jv%Z-1;ZA* z&8RY&0+n)?v)-mN$mETnsu0!@5lC8BhB#3*9nzSwYKW}zM~t>;xweMVv$!jy^H{A) zfGT_#uvFQqDTCjQLm|2`Y$r_(u!V*&)~beGapt;m9M!7fN;hJ$dx8#c4W(hMrL;9% zSXf?B9Co1^7lAS6C~WLQn-mD_QlJQos}LE?>f#kO10#aiP)!*V35Gqs8p>ftOd-9K zbyPQ$hLyCzTHz*enANIO4cc;CrsQU;5fiK?V3@5oVG&r*5TMK?4an43xF8U!p-ORQ zsY>lO$*nrb2M}4A)`R$Px6><)x)fBsG87=9s0k|oRR%WTViYDAV|C?WSXxQ?D!c`B z4Hbob8lX^9c74!jWQ>%lLC)%oWj?hHkr^3l)M(Rl%Q$Ezh*J89KB^6Q3TmjnmOu^a z=d=meVFTSb;3E#&pFgMr^EpGvXUGu40f~T*>pF@K`UziO7?8L~f(gglUhLr8DMp?%8*IWj@7gW*;jGBQ7o<(3S`?M57^_x2f9km9&5Zi^-T3&i+8 z1u@>IZ2~@z&leW&@*e@ilV0IG`OIvgK#-UK98fAqNfKCvNf~^V0U8ZP#e-oPse|eP zjRRTnY-&dOplq&%B>d21FeyGH$jBZ%1P21XxMOjjnyZ4r#4M2%0#YD_q})?poh6bf zA!#8r5Q4yuBmqEvKZ(2-kthq&F0YTwHTRo7uz`%E>isD( zd((d1l#$4dcgRjp(t%N%(^<{yk8W&h?YM%hab9xW>)Ca;XH`0ny_*5$lt>&!IGJR>4V1}O%Ks4skpOd3J@Q}HCud_$NZ7T6Pn zcu{xL+IrElO}9k)V~?lPHyyBl-l9%P>ZZm|uG?(q=5O3KH}=EFU)hA(mAJMwupZgD zx9x6c?L$lZ@DbgPx7PecJ97J*qRWSOZhKfe=HaxQmBH@ZpG+`?Y}k_GWbN(k2$&1f z;zG%Y3nvi>xW`Z>@sb89DXS!X>-*z=-kV_Dd#*L_Kx;KS;`Gqn6SxzAlMmQxHV-=e zJ-hq$4V$~F4z1ar*FJ33+2MyvIw!u_JVPF>*|~MRWXpvwXyIh9EsxpA2UFgk@=JQb z-pR@4(K}Y%ZF?K&=QOGR9Y%WtI~q4{x(hZm7}qv+?aI0^v;B;AY)c}iBZAXW?|_ab zl1FC`W%3etZ;%;5@po_FQuta>58a34r7S|D~TP zmi>mgwe-UWC7#+n$BVXHJ(7OBE92^7SGuuRXZ?D4^Egij_T7c+9b?X4?;6RO)v;G- zc27xgtGQ#E0m=H|DJ}|eZ@IUwZd|H T>C)m4YnzjoG^Lb%{_1}LB3Nj% -- Gitee From 86ae70572ef7b2226fdf0fc45712b6549ccd90d4 Mon Sep 17 00:00:00 2001 From: lianhuix Date: Tue, 10 Jan 2023 11:55:14 +0800 Subject: [PATCH 016/191] sync fuzz from monthly Signed-off-by: lianhuix --- .../distributeddb/test/fuzztest/common/fuzzer_data.cpp | 8 ++++++-- .../libs/distributeddb/test/fuzztest/common/fuzzer_data.h | 5 ++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/frameworks/libs/distributeddb/test/fuzztest/common/fuzzer_data.cpp b/frameworks/libs/distributeddb/test/fuzztest/common/fuzzer_data.cpp index f21b4ae63ce..f06718b404a 100644 --- a/frameworks/libs/distributeddb/test/fuzztest/common/fuzzer_data.cpp +++ b/frameworks/libs/distributeddb/test/fuzztest/common/fuzzer_data.cpp @@ -55,8 +55,12 @@ uint64_t FuzzerData::GetUInt64() return *r; } -std::vector FuzzerData::GetSequence(size_t size) +std::vector FuzzerData::GetSequence(size_t size, uint32_t mod) { + if (mod == 0) { + return {}; + } + size = size % mod; if (curr_ + size > data_ + size_) { return {}; } @@ -71,7 +75,7 @@ std::string FuzzerData::GetString(size_t len) return ""; } - std::string res = std::string(curr_, curr_ + len - 1); + std::string res = std::string(curr_, curr_ + len); curr_ += len; return res; } diff --git a/frameworks/libs/distributeddb/test/fuzztest/common/fuzzer_data.h b/frameworks/libs/distributeddb/test/fuzztest/common/fuzzer_data.h index 447ec8cc085..135cabef97f 100644 --- a/frameworks/libs/distributeddb/test/fuzztest/common/fuzzer_data.h +++ b/frameworks/libs/distributeddb/test/fuzztest/common/fuzzer_data.h @@ -22,6 +22,7 @@ #include namespace DistributedDBTest { + class FuzzerData final { public: FuzzerData(const uint8_t *data, size_t size); @@ -30,11 +31,13 @@ public: int GetInt(); uint32_t GetUInt32(); uint64_t GetUInt64(); - std::vector GetSequence(size_t size); + std::vector GetSequence(size_t size, uint32_t mod = MOD); std::string GetString(size_t len); std::vector GetStringVector(size_t size); std::vector GetU16StringVector(size_t size); private: + static const uint32_t MOD = 1024; // MOD length + const uint8_t *data_; const size_t size_; const uint8_t *curr_; -- Gitee From 503fc4eba0c94190c4f477eb75f24fed55873904 Mon Sep 17 00:00:00 2001 From: saikit Date: Tue, 10 Jan 2023 14:39:13 +0800 Subject: [PATCH 017/191] add ut to increase branch coverage Signed-off-by: saikit --- frameworks/libs/distributeddb/test/BUILD.gn | 5 + ...ributeddb_storage_data_connection_test.cpp | 11 +- ...qlite_single_ver_natural_executor_test.cpp | 88 +++++++++- ..._sqlite_single_ver_storage_engine_test.cpp | 160 ++++++++++++++++++ 4 files changed, 248 insertions(+), 16 deletions(-) create mode 100644 frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_storage_engine_test.cpp diff --git a/frameworks/libs/distributeddb/test/BUILD.gn b/frameworks/libs/distributeddb/test/BUILD.gn index c3db3c40c14..c1659816169 100644 --- a/frameworks/libs/distributeddb/test/BUILD.gn +++ b/frameworks/libs/distributeddb/test/BUILD.gn @@ -538,6 +538,10 @@ distributeddb_unittest( sources = [ "unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp" ] } +distributeddb_unittest("DistributedDBStorageSQLiteSingleVerStorageEngineTest") { + sources = [ "unittest/common/storage/distributeddb_storage_sqlite_single_ver_storage_engine_test.cpp" ] +} + distributeddb_unittest("DistributedDBStorageMemorySingleVerNaturalStoreTest") { sources = [ "unittest/common/storage/distributeddb_storage_memory_single_ver_naturall_store_test.cpp", @@ -832,6 +836,7 @@ group("unittest") { ":DistributedDBStorageResultAndJsonOptimizeTest", ":DistributedDBStorageSQLiteSingleVerNaturalExecutorTest", ":DistributedDBStorageSQLiteSingleVerNaturalStoreTest", + ":DistributedDBStorageSQLiteSingleVerStorageEngineTest", ":DistributedDBStorageSingleVerUpgradeTest", ":DistributedDBStorageTransactionDataTest", ":DistributedDBStorageTransactionRecordTest", diff --git a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_data_connection_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_data_connection_test.cpp index 43ae774b560..500db15c820 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_data_connection_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_data_connection_test.cpp @@ -69,10 +69,6 @@ namespace { g_invalidDb = nullptr; } } - - void TestFunc(const KvDBCommitNotifyData &data) - { - } } class DistributedDBStorageDataConnectionTest : public testing::Test { @@ -437,11 +433,12 @@ HWTEST_F(DistributedDBStorageDataConnectionTest, ConnectionTest008, TestSize.Lev int result; Key key; key.push_back('a'); - KvDBObserverHandle* handle = g_connection->RegisterObserver( + KvDBObserverAction func = [&](const KvDBCommitNotifyData &data) {}; + KvDBObserverHandle *handle = g_connection->RegisterObserver( static_cast(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_LOCAL_PUT_EVENT), key, - TestFunc, result); + func, result); EXPECT_EQ(result, E_OK); - EXPECT_NE(handle, nullptr); + ASSERT_NE(handle, nullptr); EXPECT_EQ(g_connection->Rekey(passwd), -E_BUSY); EXPECT_EQ(g_connection->Import(filePath, passwd), -E_BUSY); g_connection->UnRegisterObserver(handle); diff --git a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp index c522c89f853..afdd441c425 100644 --- a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp +++ b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_executor_test.cpp @@ -38,6 +38,7 @@ namespace { SQLiteSingleVerStorageExecutor *g_nullHandle = nullptr; const char * const ADD_SYNC = "ALTER TABLE sync_data ADD column version INT"; + const char * const ADD_LOCAL = "ALTER TABLE local_data ADD column flag INT"; const char * const INSERT_SQL = "INSERT INTO sync_data VALUES('a', 'b', 1, 2, '', '', 'efdef', 100 , 1);"; const int SQL_STATE_ERR = -1; } @@ -59,7 +60,7 @@ void DistributedDBStorageSQLiteSingleVerNaturalExecutorTest::SetUpTestCase(void) g_identifier = DBCommon::TransferStringToHex(identifier); g_databaseName = "/" + g_identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::MAINDB_DIR + "/" + - DBConstant::SINGLE_VER_DATA_STORE + ".db"; + DBConstant::SINGLE_VER_DATA_STORE + DBConstant::SQLITE_DB_EXTENSION; g_property.SetStringProp(KvDBProperties::DATA_DIR, g_testDir); g_property.SetStringProp(KvDBProperties::STORE_ID, "TestGeneralNBExecutor"); g_property.SetStringProp(KvDBProperties::IDENTIFIER_DIR, g_identifier); @@ -450,8 +451,10 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, InvalidParam011 ASSERT_TRUE(SQLiteUtils::ExecuteRawSQL(sqlHandle, ADD_SYNC) == E_OK); ASSERT_TRUE(SQLiteUtils::ExecuteRawSQL(sqlHandle, INSERT_SQL) == E_OK); std::vector vec; - uint64_t count = 0u; - EXPECT_EQ(executor->GetMinVersionCacheData(vec, count), E_OK); + uint64_t version = 0u; + EXPECT_EQ(executor->GetMinVersionCacheData(vec, version), E_OK); + EXPECT_EQ(executor->GetMaxVersionInCacheDb(version), E_OK); + EXPECT_EQ(executor->RemoveDeviceDataInCacheMode("device1", true, 0u), E_OK); sqlite3_close_v2(sqlHandle); sqlHandle = nullptr; } @@ -853,7 +856,8 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, PragmaTest003, EXPECT_EQ(emptyConn->RegisterLifeCycleCallback(notifier), -E_INVALID_DB); EXPECT_EQ(emptyConn->SetConflictNotifier(0, nullptr), -E_INVALID_ARGS); - EXPECT_EQ(emptyConn->SetConflictNotifier(0, [&](const KvDBCommitNotifyData &data) {}), -E_INVALID_DB); + KvDBConflictAction func = [&](const KvDBCommitNotifyData &data) {}; + EXPECT_EQ(emptyConn->SetConflictNotifier(0, func), -E_INVALID_DB); IKvDBSnapshot *shot; EXPECT_EQ(emptyConn->GetSnapshot(shot), -E_NOT_SUPPORT); } @@ -922,11 +926,13 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ExecutorCache00 /** * @tc.steps: step3. Change executor to MAIN_ATTACH_CACHE - * @tc.expected: step3. Expect SQL_STATE_ERR */ auto executor2 = std::make_unique( sqlHandle, false, false, ExecutorState::MAIN_ATTACH_CACHE); ASSERT_NE(executor2, nullptr); + items.clear(); + EXPECT_EQ(executor2->MigrateSyncDataByVersion(0u, syncData, items), -E_INVALID_ARGS); + items.push_back(dataItem); EXPECT_EQ(executor2->MigrateSyncDataByVersion(0u, syncData, items), SQL_STATE_ERR); EXPECT_EQ(executor2->GetMinVersionCacheData(items, version), SQL_STATE_ERR); EXPECT_EQ(executor2->GetMaxVersionInCacheDb(version), SQL_STATE_ERR); @@ -948,7 +954,7 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ExecutorCache00 * @tc.steps: step1. Copy empty db, then attach */ string cacheDir = g_testDir + "/" + g_identifier + "/" + DBConstant::SINGLE_SUB_DIR + - "/" + DBConstant::CACHEDB_DIR + "/" + DBConstant::SINGLE_VER_CACHE_STORE + ".db"; + "/" + DBConstant::CACHEDB_DIR + "/" + DBConstant::SINGLE_VER_CACHE_STORE + DBConstant::SQLITE_DB_EXTENSION; EXPECT_EQ(DBCommon::CopyFile(g_testDir + g_databaseName, cacheDir), E_OK); CipherPassword password; EXPECT_EQ(g_nullHandle->AttachMainDbAndCacheDb( @@ -973,7 +979,7 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ExecutorCache00 /** * @tc.name: ExecutorCache004 - * @tc.desc: Test after attaching cache + * @tc.desc: Test migrate after attaching * @tc.type: FUNC * @tc.require: * @tc.author: bty @@ -985,7 +991,7 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ExecutorCache00 * @tc.expected: step1. Expect E_OK */ string cacheDir = g_testDir + "/" + g_identifier + "/" + DBConstant::SINGLE_SUB_DIR + - "/" + DBConstant::CACHEDB_DIR + "/" + DBConstant::SINGLE_VER_CACHE_STORE + ".db"; + "/" + DBConstant::CACHEDB_DIR + "/" + DBConstant::SINGLE_VER_CACHE_STORE + DBConstant::SQLITE_DB_EXTENSION; EXPECT_EQ(g_handle->ForceCheckPoint(), E_OK); EXPECT_EQ(DBCommon::CopyFile(g_testDir + g_databaseName, cacheDir), E_OK); CipherPassword password; @@ -994,11 +1000,75 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ExecutorCache00 /** * @tc.steps: step2. Migrate sync data but param incomplete - * @tc.expected: step2. Expect -E_INVALID_ARGS */ NotifyMigrateSyncData syncData; DataItem dataItem; std::vector items; items.push_back(dataItem); EXPECT_EQ(g_handle->MigrateSyncDataByVersion(0u, syncData, items), -E_INVALID_ARGS); + Timestamp timestamp; + EXPECT_EQ(g_handle->GetMaxTimestampDuringMigrating(timestamp), E_OK); + items.front().neglect = true; + EXPECT_EQ(g_handle->MigrateSyncDataByVersion(0u, syncData, items), SQL_STATE_ERR); + items.front().neglect = false; + items.front().flag = DataItem::REMOVE_DEVICE_DATA_FLAG; + EXPECT_EQ(g_handle->MigrateSyncDataByVersion(0u, syncData, items), -E_INVALID_ARGS); + items.front().key = {'r', 'e', 'm', 'o', 'v', 'e'}; + EXPECT_EQ(g_handle->MigrateSyncDataByVersion(0u, syncData, items), SQL_STATE_ERR); + items.front().flag = DataItem::REMOVE_DEVICE_DATA_NOTIFY_FLAG; + EXPECT_EQ(g_handle->MigrateSyncDataByVersion(0u, syncData, items), SQL_STATE_ERR); + items.front().flag = DataItem::REMOTE_DEVICE_DATA_MISS_QUERY; + EXPECT_EQ(g_handle->MigrateSyncDataByVersion(0u, syncData, items), -E_INVALID_DB); + string selectSync = "SELECT * FROM sync_data"; + Value value; + value.assign(selectSync.begin(), selectSync.end()); + items.front().value = value; + items.front().flag = DataItem::REMOVE_DEVICE_DATA_NOTIFY_FLAG; + EXPECT_EQ(g_handle->MigrateSyncDataByVersion(0u, syncData, items), SQL_STATE_ERR); + EXPECT_EQ(g_handle->MigrateLocalData(), E_OK); + + /** + * @tc.steps: step3. Attach maindb + */ + EXPECT_EQ(g_handle->AttachMainDbAndCacheDb( + CipherType::DEFAULT, password, cacheDir, EngineState::CACHEDB), E_OK); + EXPECT_EQ(g_handle->MigrateLocalData(), E_OK); + EXPECT_EQ(g_handle->MigrateSyncDataByVersion(0u, syncData, items), -E_BUSY); +} + +/** + * @tc.name: ExecutorCache005 + * @tc.desc: Alter table then save data in cache mode + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalExecutorTest, ExecutorCache005, TestSize.Level1) +{ + g_store->ReleaseHandle(g_handle); + sqlite3 *db = nullptr; + ASSERT_TRUE(sqlite3_open_v2((g_testDir + g_databaseName).c_str(), + &db, SQLITE_OPEN_URI | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nullptr) == SQLITE_OK); + ASSERT_TRUE(SQLiteUtils::ExecuteRawSQL(db, ADD_LOCAL) == E_OK); + ASSERT_TRUE(SQLiteUtils::ExecuteRawSQL(db, ADD_SYNC) == E_OK); + auto executor = std::make_unique(db, false, false); + ASSERT_NE(executor, nullptr); + LocalDataItem item; + EXPECT_EQ(executor->PutLocalDataToCacheDB(item), -E_INVALID_ARGS); + item.hashKey = KEY_1; + EXPECT_EQ(executor->PutLocalDataToCacheDB(item), -E_INVALID_ARGS); + item.flag = DataItem::DELETE_FLAG; + EXPECT_EQ(executor->PutLocalDataToCacheDB(item), E_OK); + Query query = Query::Select(); + QueryObject object(query); + DataItem dataItem; + dataItem.flag = DataItem::REMOTE_DEVICE_DATA_MISS_QUERY; + DeviceInfo info; + Timestamp maxTime; + EXPECT_EQ(executor->SaveSyncDataItemInCacheMode(dataItem, info, maxTime, 0, object), -E_INVALID_ARGS); + dataItem.key = KEY_1; + EXPECT_EQ(executor->SaveSyncDataItemInCacheMode(dataItem, info, maxTime, 0, object), E_OK); + dataItem.flag = DataItem::DELETE_FLAG; + EXPECT_EQ(executor->SaveSyncDataItemInCacheMode(dataItem, info, maxTime, 0, object), E_OK); + sqlite3_close_v2(db); } \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_storage_engine_test.cpp b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_storage_engine_test.cpp new file mode 100644 index 00000000000..a54ef8c01ac --- /dev/null +++ b/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_storage_engine_test.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (c) 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 + * + * 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 "db_common.h" +#include "distributeddb_storage_single_ver_natural_store_testcase.h" +#include "storage_engine_manager.h" + +using namespace testing::ext; +using namespace DistributedDB; +using namespace DistributedDBUnitTest; +using namespace std; + +namespace { + string g_testDir; + string g_databaseName; + string g_identifier; + string g_cacheDir; + KvDBProperties g_property; + + SQLiteSingleVerNaturalStore *g_store = nullptr; + SQLiteSingleVerNaturalStoreConnection *g_connection = nullptr; + + const char * const ADD_SYNC = "ALTER TABLE sync_data ADD column version INT"; + const char * const INSERT_SQL = "INSERT INTO sync_data VALUES('a', 'b', 1, 2, '', '', 'efdef', 100 , 1);"; + const int SQL_STATE_ERR = -1; + + void CopyCacheDb() + { + EXPECT_EQ(DBCommon::CopyFile(g_testDir + g_databaseName, g_cacheDir), E_OK); + EXPECT_EQ(DBCommon::CopyFile(g_testDir + g_databaseName + "-wal", g_cacheDir + "-wal"), E_OK); + } + + void GetStorageEngine(SQLiteSingleVerStorageEngine *&storageEngine) + { + int errCode; + storageEngine = + static_cast(StorageEngineManager::GetStorageEngine(g_property, errCode)); + EXPECT_EQ(errCode, E_OK); + } +} + +class DistributedDBStorageSQLiteSingleVerStorageEngineTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DistributedDBStorageSQLiteSingleVerStorageEngineTest::SetUpTestCase(void) +{ + DistributedDBToolsUnitTest::TestDirInit(g_testDir); + LOGI("DistributedDBStorageSQLiteSingleVerStorageEngineTest dir is %s", g_testDir.c_str()); + std::string oriIdentifier = APP_ID + "-" + USER_ID + "-" + "TestGeneralNBStorageEngine"; + std::string identifier = DBCommon::TransferHashString(oriIdentifier); + g_identifier = DBCommon::TransferStringToHex(identifier); + + g_databaseName = "/" + g_identifier + "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::MAINDB_DIR + "/" + + DBConstant::SINGLE_VER_DATA_STORE + DBConstant::SQLITE_DB_EXTENSION; + g_property.SetStringProp(KvDBProperties::DATA_DIR, g_testDir); + g_property.SetStringProp(KvDBProperties::STORE_ID, "TestGeneralNBStorageEngine"); + g_property.SetStringProp(KvDBProperties::IDENTIFIER_DIR, g_identifier); + g_property.SetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::SINGLE_VER_TYPE); + g_cacheDir = g_testDir + "/" + g_identifier + "/" + DBConstant::SINGLE_SUB_DIR + + "/" + DBConstant::CACHEDB_DIR + "/" + DBConstant::SINGLE_VER_CACHE_STORE + DBConstant::SQLITE_DB_EXTENSION; +} + +void DistributedDBStorageSQLiteSingleVerStorageEngineTest::TearDownTestCase(void) +{ + DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir + "/" + g_identifier + "/" + DBConstant::SINGLE_SUB_DIR); +} + +void DistributedDBStorageSQLiteSingleVerStorageEngineTest::SetUp(void) +{ + DistributedDBToolsUnitTest::PrintTestCaseInfo(); + DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir + "/" + g_identifier + "/" + DBConstant::SINGLE_SUB_DIR); + g_store = new (std::nothrow) SQLiteSingleVerNaturalStore; + ASSERT_NE(g_store, nullptr); + ASSERT_EQ(g_store->Open(g_property), E_OK); + + int erroCode = E_OK; + g_connection = static_cast(g_store->GetDBConnection(erroCode)); + ASSERT_NE(g_connection, nullptr); + g_store->DecObjRef(g_store); + EXPECT_EQ(erroCode, E_OK); +} + +void DistributedDBStorageSQLiteSingleVerStorageEngineTest::TearDown(void) +{ + if (g_connection != nullptr) { + g_connection->Close(); + g_connection = nullptr; + } + g_store = nullptr; +} + +/** + * @tc.name: DataTest001 + * @tc.desc: Change engine state, execute migrate + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerStorageEngineTest, DataTest001, TestSize.Level1) +{ + SQLiteSingleVerStorageEngine *storageEngine = nullptr; + GetStorageEngine(storageEngine); + ASSERT_NE(storageEngine, nullptr); + CopyCacheDb(); + + storageEngine->SetEngineState(EngineState::ENGINE_BUSY); + EXPECT_EQ(storageEngine->ExecuteMigrate(), -E_BUSY); + storageEngine->SetEngineState(EngineState::ATTACHING); + EXPECT_EQ(storageEngine->ExecuteMigrate(), -E_NOT_SUPPORT); + storageEngine->SetEngineState(EngineState::MAINDB); + EXPECT_EQ(storageEngine->ExecuteMigrate(), SQL_STATE_ERR); + storageEngine->SetEngineState(EngineState::CACHEDB); + EXPECT_EQ(storageEngine->ExecuteMigrate(), SQL_STATE_ERR); + storageEngine->Release(); + storageEngine = nullptr; +} + +/** + * @tc.name: DataTest002 + * @tc.desc: Alter table, Change engine state, execute migrate + * @tc.type: FUNC + * @tc.require: + * @tc.author: bty + */ +HWTEST_F(DistributedDBStorageSQLiteSingleVerStorageEngineTest, DataTest002, TestSize.Level1) +{ + sqlite3 *db; + ASSERT_TRUE(sqlite3_open_v2((g_testDir + g_databaseName).c_str(), + &db, SQLITE_OPEN_URI | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nullptr) == SQLITE_OK); + ASSERT_TRUE(SQLiteUtils::ExecuteRawSQL(db, ADD_SYNC) == E_OK); + ASSERT_TRUE(SQLiteUtils::ExecuteRawSQL(db, INSERT_SQL) == E_OK); + sqlite3_close_v2(db); + CopyCacheDb(); + SQLiteSingleVerStorageEngine *storageEngine = nullptr; + GetStorageEngine(storageEngine); + ASSERT_NE(storageEngine, nullptr); + storageEngine->SetEngineState(EngineState::CACHEDB); + EXPECT_EQ(storageEngine->ExecuteMigrate(), -E_BUSY); + storageEngine->Release(); + storageEngine = nullptr; +} \ No newline at end of file -- Gitee From 158688b1b60fa38c70e17ebf709b78dd6ff35c82 Mon Sep 17 00:00:00 2001 From: ylq121 Date: Tue, 10 Jan 2023 20:35:47 +0800 Subject: [PATCH 018/191] kv-TDD Signed-off-by: ylq121 --- .../kvdb/test/auto_sync_timer_test.cpp | 139 +++++++++++++++++- 1 file changed, 133 insertions(+), 6 deletions(-) diff --git a/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp b/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp index 75468660142..1e8d53bb971 100644 --- a/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp +++ b/frameworks/innerkitsimpl/kvdb/test/auto_sync_timer_test.cpp @@ -129,7 +129,7 @@ void AutoSyncTimerTest::TearDown(void) /** * @tc.name: SingleWrite -* @tc.desc: get the store id of the kv store +* @tc.desc: single write * @tc.type: FUNC * @tc.require: I4XVQQ * @tc.author: Yang Qing @@ -151,13 +151,13 @@ HWTEST_F(AutoSyncTimerTest, SingleWrite, TestSize.Level0) } /** -* @tc.name: MultiWrite -* @tc.desc: get the store id of the kv store +* @tc.name: MultiWriteBelowDelayTime +* @tc.desc: write every 40 milliseconds * @tc.type: FUNC * @tc.require: I4XVQQ * @tc.author: Yang Qing */ -HWTEST_F(AutoSyncTimerTest, MultiWrite, TestSize.Level1) +HWTEST_F(AutoSyncTimerTest, MultiWriteBelowDelayTime, TestSize.Level1) { auto *instance = KVDBServiceMock::GetInstance(); ASSERT_NE(instance, nullptr); @@ -169,7 +169,7 @@ HWTEST_F(AutoSyncTimerTest, MultiWrite, TestSize.Level1) std::thread thread([&finished] { while (!finished.load()) { AutoSyncTimer::GetInstance().DoAutoSync("ut_test", { { "ut_test_store" } }); - usleep(40); + std::this_thread::sleep_for(std::chrono::milliseconds(40)); } }); EXPECT_EQ(static_cast(instance->GetCallCount(1)), 1); @@ -182,6 +182,68 @@ HWTEST_F(AutoSyncTimerTest, MultiWrite, TestSize.Level1) ASSERT_EQ(it->second.count("ut_test_store"), 1); } +/** +* @tc.name: MultiWriteOverDelayTime +* @tc.desc: write every 150 milliseconds +* @tc.type: FUNC +* @tc.require: I4XVQQ +* @tc.author: Yang Qing + */ +HWTEST_F(AutoSyncTimerTest, MultiWriteOverDelayTime, TestSize.Level1) +{ + auto *instance = KVDBServiceMock::GetInstance(); + ASSERT_NE(instance, nullptr); + instance->ResetToZero(); + instance->startTime = time_point_cast(system_clock::now()).time_since_epoch().count(); + instance->endTime = 0; + instance->values_.clear(); + std::atomic_bool finished = false; + std::thread thread([&finished] { + while (!finished.load()) { + AutoSyncTimer::GetInstance().DoAutoSync("ut_test", { { "ut_test_store" } }); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + } + }); + EXPECT_EQ(static_cast(instance->GetCallCount(1)), 1); + ASSERT_LT(instance->endTime - instance->startTime, 100); + finished.store(true); + thread.join(); + auto it = instance->values_.find("ut_test"); + ASSERT_NE(it, instance->values_.end()); + ASSERT_EQ(it->second.count("ut_test_store"), 1); +} + +/** +* @tc.name: MultiWriteOverForceTime +* @tc.desc: write every 400 milliseconds +* @tc.type: FUNC +* @tc.require: I4XVQQ +* @tc.author: Yang Qing + */ +HWTEST_F(AutoSyncTimerTest, MultiWriteOverForceTime, TestSize.Level1) +{ + auto *instance = KVDBServiceMock::GetInstance(); + ASSERT_NE(instance, nullptr); + instance->ResetToZero(); + instance->startTime = time_point_cast(system_clock::now()).time_since_epoch().count(); + instance->endTime = 0; + instance->values_.clear(); + std::atomic_bool finished = false; + std::thread thread([&finished] { + while (!finished.load()) { + AutoSyncTimer::GetInstance().DoAutoSync("ut_test", { { "ut_test_store" } }); + std::this_thread::sleep_for(std::chrono::milliseconds(400)); + } + }); + EXPECT_EQ(static_cast(instance->GetCallCount(1)), 1); + ASSERT_LT(instance->endTime - instance->startTime, 100); + finished.store(true); + thread.join(); + auto it = instance->values_.find("ut_test"); + ASSERT_NE(it, instance->values_.end()); + ASSERT_EQ(it->second.count("ut_test_store"), 1); +} + /** * @tc.name: SingleWriteOvertenKVStores * @tc.desc: single write over ten kv stores @@ -281,4 +343,69 @@ HWTEST_F(AutoSyncTimerTest, MultiWriteOvertenKVStores, TestSize.Level1) ASSERT_EQ(it->second.count("ut_test_store9"), 1); ASSERT_EQ(it->second.count("ut_test_store10"), 1); } -} \ No newline at end of file + +/** +* @tc.name: DoubleWrite +* @tc.desc: double wirte +* @tc.type: FUNC +* @tc.require: I4XVQQ +* @tc.author: YangQing + */ +HWTEST_F(AutoSyncTimerTest, DoubleWrite, TestSize.Level1) +{ + auto *instance = KVDBServiceMock::GetInstance(); + ASSERT_NE(instance, nullptr); + instance->ResetToZero(); + instance->startTime = time_point_cast(system_clock::now()).time_since_epoch().count(); + instance->endTime = 0; + instance->values_.clear(); + AutoSyncTimer::GetInstance().DoAutoSync("ut_test", { + { "ut_test_store0" }, + { "ut_test_store1" }, + { "ut_test_store2" }, + { "ut_test_store3" }, + { "ut_test_store4" }, + { "ut_test_store5" }, + { "ut_test_store6" }, + { "ut_test_store7" }, + { "ut_test_store8" }, + { "ut_test_store9" }, + { "ut_test_store10" }, + }); + AutoSyncTimer::GetInstance().DoAutoSync("ut_test", { + { "ut_test_store-0" }, + { "ut_test_store-1" }, + { "ut_test_store-2" }, + { "ut_test_store-3" }, + { "ut_test_store-4" }, + { "ut_test_store-5" }, + { "ut_test_store-6" }, + { "ut_test_store-7" }, + { "ut_test_store-8" }, + }); + EXPECT_EQ(static_cast(instance->GetCallCount(1)), 1); + ASSERT_LT(instance->endTime - instance->startTime, 100); + EXPECT_EQ(static_cast(instance->GetCallCount(20)), 20); + auto it = instance->values_.find("ut_test"); + ASSERT_EQ(it->second.count("ut_test_store0"), 1); + ASSERT_EQ(it->second.count("ut_test_store1"), 1); + ASSERT_EQ(it->second.count("ut_test_store2"), 1); + ASSERT_EQ(it->second.count("ut_test_store3"), 1); + ASSERT_EQ(it->second.count("ut_test_store4"), 1); + ASSERT_EQ(it->second.count("ut_test_store5"), 1); + ASSERT_EQ(it->second.count("ut_test_store6"), 1); + ASSERT_EQ(it->second.count("ut_test_store7"), 1); + ASSERT_EQ(it->second.count("ut_test_store8"), 1); + ASSERT_EQ(it->second.count("ut_test_store9"), 1); + ASSERT_EQ(it->second.count("ut_test_store10"), 1); + ASSERT_EQ(it->second.count("ut_test_store-0"), 1); + ASSERT_EQ(it->second.count("ut_test_store-1"), 1); + ASSERT_EQ(it->second.count("ut_test_store-2"), 1); + ASSERT_EQ(it->second.count("ut_test_store-3"), 1); + ASSERT_EQ(it->second.count("ut_test_store-4"), 1); + ASSERT_EQ(it->second.count("ut_test_store-5"), 1); + ASSERT_EQ(it->second.count("ut_test_store-6"), 1); + ASSERT_EQ(it->second.count("ut_test_store-7"), 1); + ASSERT_EQ(it->second.count("ut_test_store-8"), 1); +} +} // namespace OHOS::Test \ No newline at end of file -- Gitee From 96d4a14ea66a2a7ae68bc17c73ccccd28864aed7 Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Tue, 10 Jan 2023 22:33:41 +0800 Subject: [PATCH 019/191] fix devManager Signed-off-by: zuojiangjiang --- .../src/distributed_kv_data_manager.cpp | 8 +- .../innerkitsimpl/kvdb/include/dev_manager.h | 23 ++-- .../innerkitsimpl/kvdb/include/kvdb_service.h | 4 + .../kvdb/include/kvdb_service_client.h | 2 + .../innerkitsimpl/kvdb/src/dev_manager.cpp | 127 ++++++++---------- .../kvdb/src/device_convertor.cpp | 2 +- .../innerkitsimpl/kvdb/src/kv_types_util.cpp | 4 +- .../kvdb/src/kvdb_service_client.cpp | 22 +++ .../kvdb/test/dev_manager_test.cpp | 58 +++++--- .../kvdb/test/single_store_impl_test.cpp | 2 +- .../innerkits/distributeddata/include/types.h | 1 + 11 files changed, 137 insertions(+), 116 deletions(-) diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/distributed_kv_data_manager.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/distributed_kv_data_manager.cpp index 8a4db228cdf..3ec10f16c22 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/distributed_kv_data_manager.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/distributed_kv_data_manager.cpp @@ -169,11 +169,11 @@ void DistributedKvDataManager::UnRegisterKvStoreServiceDeathRecipient( Status DistributedKvDataManager::GetLocalDevice(DeviceInfo &localDevice) { auto dvInfo = DevManager::GetInstance().GetLocalDevice(); - if (dvInfo.networkId.empty()) { + if (dvInfo.deviceId.empty()) { ZLOGE("deviceId empty!"); return Status::ERROR; } - localDevice.deviceId = dvInfo.networkId; + localDevice.deviceId = dvInfo.deviceId; localDevice.deviceName = dvInfo.deviceName; localDevice.deviceType = dvInfo.deviceType; return Status::SUCCESS; @@ -183,11 +183,11 @@ Status DistributedKvDataManager::GetDeviceList(std::vector &deviceIn { auto dvInfos = DevManager::GetInstance().GetRemoteDevices(); for (const auto &info : dvInfos) { - if (info.networkId.empty()) { + if (info.deviceId.empty()) { ZLOGW("deviceId empty!"); continue; } - DeviceInfo devInfo = { info.networkId, info.deviceName, info.deviceType }; + DeviceInfo devInfo = { info.deviceId, info.deviceUuid, info.deviceName, info.deviceType }; deviceInfoList.emplace_back(devInfo); } ZLOGI("strategy is:%{public}d", strategy); diff --git a/frameworks/innerkitsimpl/kvdb/include/dev_manager.h b/frameworks/innerkitsimpl/kvdb/include/dev_manager.h index c6e18d9cdb9..cf074664b57 100644 --- a/frameworks/innerkitsimpl/kvdb/include/dev_manager.h +++ b/frameworks/innerkitsimpl/kvdb/include/dev_manager.h @@ -22,18 +22,11 @@ namespace OHOS::DistributedKv { class DevManager { public: static constexpr size_t MAX_ID_LEN = 64; - struct DetailInfo { - std::string uuid; - std::string udid; - std::string networkId; - std::string deviceName; - std::string deviceType; - }; static DevManager &GetInstance(); - std::string ToUUID(const std::string &networkId) const; - std::string ToNetworkId(const std::string &uuid) const; - const DetailInfo &GetLocalDevice(); - std::vector GetRemoteDevices() const; + std::string ToUUID(const std::string &networkId); + std::string ToNetworkId(const std::string &uuid); + const DeviceInfo &GetLocalDevice(); + std::vector GetRemoteDevices() const; class Observer { public: Observer() = default; @@ -55,14 +48,16 @@ private: void OnChanged(const std::string &networkId); void OnReady(const std::string &networkId); void RegisterDevCallback(); + void UpdateBucket(); + DeviceInfo GetDvInfoFromBucket(const std::string &id); int32_t Init(); std::function Retry(); const std::string PKG_NAME; - const DetailInfo invalidDetail_ {}; - DetailInfo localInfo_ {}; + const DeviceInfo invalidDetail_ {}; + DeviceInfo localInfo_ {}; mutable std::mutex mutex_ {}; - mutable LRUBucket deviceInfos_ {64}; + mutable LRUBucket deviceInfos_ {64}; ConcurrentMap observers_; }; } // namespace OHOS::DistributedKv diff --git a/frameworks/innerkitsimpl/kvdb/include/kvdb_service.h b/frameworks/innerkitsimpl/kvdb/include/kvdb_service.h index 3332366ec47..1d4d802908c 100644 --- a/frameworks/innerkitsimpl/kvdb/include/kvdb_service.h +++ b/frameworks/innerkitsimpl/kvdb/include/kvdb_service.h @@ -59,6 +59,8 @@ public: virtual Status Unsubscribe(const AppId &appId, const StoreId &storeId, sptr observer) = 0; virtual Status GetBackupPassword( const AppId &appId, const StoreId &storeId, std::vector &password) = 0; + virtual Status GetLocalDevice(DeviceInfo &dvInfo) = 0; + virtual Status GetRemoteDevices(std::vector &dvInfos) = 0; protected: enum TransId : int32_t { @@ -80,6 +82,8 @@ protected: TRANS_SUB, TRANS_UNSUB, TRANS_GET_PASSWORD, + TRANS_GET_LOCAL_DEVICE, + TRANS_GET_REMOTE_DEVICE, TRANS_BUTT, }; }; diff --git a/frameworks/innerkitsimpl/kvdb/include/kvdb_service_client.h b/frameworks/innerkitsimpl/kvdb/include/kvdb_service_client.h index 94adb555619..0af825057d2 100644 --- a/frameworks/innerkitsimpl/kvdb/include/kvdb_service_client.h +++ b/frameworks/innerkitsimpl/kvdb/include/kvdb_service_client.h @@ -48,6 +48,8 @@ public: Status Subscribe(const AppId &appId, const StoreId &storeId, sptr observer) override; Status Unsubscribe(const AppId &appId, const StoreId &storeId, sptr observer) override; Status GetBackupPassword(const AppId &appId, const StoreId &storeId, std::vector &password) override; + Status GetLocalDevice(DeviceInfo &dvInfo) override; + Status GetRemoteDevices(std::vector &dvInfos) override; sptr GetSyncAgent(const AppId &appId); protected: diff --git a/frameworks/innerkitsimpl/kvdb/src/dev_manager.cpp b/frameworks/innerkitsimpl/kvdb/src/dev_manager.cpp index 0beb71ff4fb..7ea0caf0d9e 100644 --- a/frameworks/innerkitsimpl/kvdb/src/dev_manager.cpp +++ b/frameworks/innerkitsimpl/kvdb/src/dev_manager.cpp @@ -19,6 +19,7 @@ #include "device_manager.h" #include "device_manager_callback.h" #include "dm_device_info.h" +#include "kvdb_service_client.h" #include "log_print.h" #include "store_util.h" #include "task_executor.h" @@ -118,97 +119,79 @@ DevManager &DevManager::GetInstance() return instance; } -std::string DevManager::ToUUID(const std::string &networkId) const +std::string DevManager::ToUUID(const std::string &networkId) { - DetailInfo deviceInfo; - if (deviceInfos_.Get(networkId, deviceInfo)) { - return deviceInfo.uuid; - } + return GetDvInfoFromBucket(networkId).deviceUuid; +} - std::string uuid; - std::string udid; - auto &deviceManager = DeviceManager::GetInstance(); - deviceManager.GetUuidByNetworkId(PKG_NAME, networkId, uuid); - deviceManager.GetUdidByNetworkId(PKG_NAME, networkId, udid); - if (uuid.empty() || udid.empty() || networkId.empty()) { - return ""; +std::string DevManager::ToNetworkId(const std::string &uuid) +{ + return GetDvInfoFromBucket(uuid).deviceId; +} + +DeviceInfo DevManager::GetDvInfoFromBucket(const std::string &id) +{ + DeviceInfo dvInfo; + if (!deviceInfos_.Get(id, dvInfo)) { + UpdateBucket(); + deviceInfos_.Get(id, dvInfo); } - deviceInfo = { uuid, std::move(udid), networkId, "", "" }; - deviceInfos_.Set(networkId, deviceInfo); - deviceInfos_.Set(uuid, deviceInfo); - return uuid; + if (dvInfo.deviceUuid.empty()) { + ZLOGE("id:%{public}s", StoreUtil::Anonymous(id).c_str()); + } + return dvInfo; } -std::string DevManager::ToNetworkId(const std::string &uuid) const +void DevManager::UpdateBucket() { - DetailInfo deviceInfo; - if (deviceInfos_.Get(uuid, deviceInfo)) { - return deviceInfo.networkId; + auto dvInfos = GetRemoteDevices(); + if (dvInfos.empty()) { + ZLOGD("no remote device"); } - auto infos = GetRemoteDevices(); - for (auto &info : infos) { - if (info.uuid == uuid) { - deviceInfos_.Set(info.uuid, info); - deviceInfos_.Set(info.networkId, info); - return info.networkId; + dvInfos.emplace_back(GetLocalDevice()); + for (const auto &info : dvInfos) { + if (info.deviceId.empty() || info.deviceUuid.empty()) { + continue; } + deviceInfos_.Set(info.deviceId, info); + deviceInfos_.Set(info.deviceUuid, info); } - - std::lock_guard lockGuard(mutex_); - return (localInfo_.uuid == uuid) ? localInfo_.networkId : ""; } -const DevManager::DetailInfo &DevManager::GetLocalDevice() +const DeviceInfo &DevManager::GetLocalDevice() { std::lock_guard lockGuard(mutex_); - if (!localInfo_.uuid.empty()) { + if (!localInfo_.deviceUuid.empty()) { return localInfo_; } - - DmDeviceInfo info; - auto &deviceManager = DeviceManager::GetInstance(); - int32_t ret = deviceManager.GetLocalDeviceInfo(PKG_NAME, info); - if (ret != DM_OK) { - ZLOGE("GetLocalNodeDeviceInfo error"); - return invalidDetail_; + auto service = KVDBServiceClient::GetInstance(); + if (service == nullptr) { + ZLOGE("service unavailable"); + return {}; } - std::string networkId = std::string(info.networkId); - std::string uuid; - deviceManager.GetUuidByNetworkId(PKG_NAME, networkId, uuid); - std::string udid; - deviceManager.GetUdidByNetworkId(PKG_NAME, networkId, udid); - if (uuid.empty() || udid.empty() || networkId.empty()) { - return invalidDetail_; + auto status = service->GetLocalDevice(localInfo_); + if (status != SUCCESS) { + return {}; } - ZLOGI("[LocalDevice] id:%{public}s, name:%{public}s, type:%{public}d", StoreUtil::Anonymous(uuid).c_str(), - info.deviceName, info.deviceTypeId); - localInfo_ = { std::move(uuid), std::move(udid), std::move(networkId), std::string(info.deviceName), - std::string(info.deviceName) }; + ZLOGI("[LocalDevice] id:%{public}s, name:%{public}s, type:%{public}s", + StoreUtil::Anonymous(localInfo_.deviceUuid).c_str(), + localInfo_.deviceName.c_str(), localInfo_.deviceType.c_str()); return localInfo_; } -std::vector DevManager::GetRemoteDevices() const +std::vector DevManager::GetRemoteDevices() const { - std::vector devices; - std::vector dmDeviceInfos{}; - auto &deviceManager = DeviceManager::GetInstance(); - int32_t ret = deviceManager.GetTrustedDeviceList(PKG_NAME, "", dmDeviceInfos); - if (ret != DM_OK) { - ZLOGE("GetTrustedDeviceList error"); - return devices; + std::vector dvInfos; + auto service = KVDBServiceClient::GetInstance(); + if (service == nullptr) { + ZLOGE("service unavailable"); + return {}; } - - for (const auto &dmDeviceInfo : dmDeviceInfos) { - std::string networkId = dmDeviceInfo.networkId; - std::string uuid; - std::string udid; - deviceManager.GetUuidByNetworkId(PKG_NAME, networkId, uuid); - deviceManager.GetUdidByNetworkId(PKG_NAME, networkId, udid); - DetailInfo deviceInfo = { std::move(uuid), std::move(udid), std::move(networkId), - std::string(dmDeviceInfo.deviceName), std::to_string(dmDeviceInfo.deviceTypeId) }; - devices.push_back(std::move(deviceInfo)); + auto status = service->GetRemoteDevices(dvInfos); + if (status != SUCCESS || dvInfos.empty()) { + ZLOGD("no remote device"); } - return devices; + return dvInfos; } void DevManager::Online(const std::string &networkId) @@ -219,10 +202,10 @@ void DevManager::Online(const std::string &networkId) void DevManager::Offline(const std::string &networkId) { - DetailInfo deviceInfo; - if (deviceInfos_.Get(networkId, deviceInfo)) { - deviceInfos_.Delete(networkId); - deviceInfos_.Delete(deviceInfo.uuid); + DeviceInfo dvInfo; + if (deviceInfos_.Get(networkId, dvInfo)) { + deviceInfos_.Delete(dvInfo.deviceId); + deviceInfos_.Delete(dvInfo.deviceUuid); } ZLOGI("%{public}s observers:%{public}zu", StoreUtil::Anonymous(networkId).c_str(), observers_.Size()); observers_.ForEach([&networkId](const auto &key, auto &value) { diff --git a/frameworks/innerkitsimpl/kvdb/src/device_convertor.cpp b/frameworks/innerkitsimpl/kvdb/src/device_convertor.cpp index 27897cacfa4..a79f3339648 100644 --- a/frameworks/innerkitsimpl/kvdb/src/device_convertor.cpp +++ b/frameworks/innerkitsimpl/kvdb/src/device_convertor.cpp @@ -27,7 +27,7 @@ std::vector DeviceConvertor::ToLocalDBKey(const Key &key) const std::vector DeviceConvertor::ToLocal(const Key &in, bool withLen) const { - auto uuid = DevManager::GetInstance().GetLocalDevice().uuid; + auto uuid = DevManager::GetInstance().GetLocalDevice().deviceUuid; if (uuid.empty()) { return {}; } diff --git a/frameworks/innerkitsimpl/kvdb/src/kv_types_util.cpp b/frameworks/innerkitsimpl/kvdb/src/kv_types_util.cpp index efd5b76a8aa..a445b9f7229 100644 --- a/frameworks/innerkitsimpl/kvdb/src/kv_types_util.cpp +++ b/frameworks/innerkitsimpl/kvdb/src/kv_types_util.cpp @@ -71,13 +71,13 @@ bool Unmarshalling(Entry &output, MessageParcel &data) template<> bool Marshalling(const DeviceInfo &entry, MessageParcel &data) { - return ITypesUtil::Marshal(data, entry.deviceId, entry.deviceName, entry.deviceType); + return ITypesUtil::Marshal(data, entry.deviceId, entry.deviceUuid, entry.deviceName, entry.deviceType); } template<> bool Unmarshalling(DeviceInfo &output, MessageParcel &data) { - return ITypesUtil::Unmarshal(data, output.deviceId, output.deviceName, output.deviceType); + return ITypesUtil::Unmarshal(data, output.deviceId, output.deviceUuid, output.deviceName, output.deviceType); } template<> diff --git a/frameworks/innerkitsimpl/kvdb/src/kvdb_service_client.cpp b/frameworks/innerkitsimpl/kvdb/src/kvdb_service_client.cpp index 3464c910de2..535e4b9d8f7 100644 --- a/frameworks/innerkitsimpl/kvdb/src/kvdb_service_client.cpp +++ b/frameworks/innerkitsimpl/kvdb/src/kvdb_service_client.cpp @@ -290,6 +290,28 @@ Status KVDBServiceClient::GetBackupPassword( return static_cast(status); } +Status KVDBServiceClient::GetLocalDevice(DeviceInfo &dvInfo) +{ + MessageParcel reply; + int32_t status = IPC_SEND(TRANS_GET_LOCAL_DEVICE, reply, AppId(), StoreId()); + if (status != SUCCESS) { + ZLOGE("status:0x%{public}x", status); + } + ITypesUtil::Unmarshal(reply, dvInfo); + return static_cast(status); +} + +Status KVDBServiceClient::GetRemoteDevices(std::vector &dvInfos) +{ + MessageParcel reply; + int32_t status = IPC_SEND(TRANS_GET_REMOTE_DEVICE, reply, AppId(), StoreId()); + if (status != SUCCESS) { + ZLOGE("status:0x%{public}x", status); + } + ITypesUtil::Unmarshal(reply, dvInfos); + return static_cast(status); +} + sptr KVDBServiceClient::GetSyncAgent(const AppId &appId) { std::lock_guard lockGuard(agentMtx_); diff --git a/frameworks/innerkitsimpl/kvdb/test/dev_manager_test.cpp b/frameworks/innerkitsimpl/kvdb/test/dev_manager_test.cpp index b143860233b..6a102c4d99a 100644 --- a/frameworks/innerkitsimpl/kvdb/test/dev_manager_test.cpp +++ b/frameworks/innerkitsimpl/kvdb/test/dev_manager_test.cpp @@ -44,52 +44,66 @@ void DevManagerTest::TearDown(void) {} /** -* @tc.name: GetLocalDevice001 +* @tc.name: GetLocalDevice * @tc.desc: Get local device's infomation * @tc.type: FUNC * @tc.require: * @tc.author: taoyuxin */ -HWTEST_F(DevManagerTest, GetLocalDevice001, TestSize.Level1) +HWTEST_F(DevManagerTest, GetLocalDevice, TestSize.Level1) { - ZLOGI("GetLocalDevice001 begin."); - DevManager &devManager = OHOS::DistributedKv::DevManager::GetInstance(); - DevManager::DetailInfo devInfo = devManager.GetLocalDevice(); - - EXPECT_NE(devInfo.networkId, ""); - EXPECT_NE(devInfo.uuid, ""); - EXPECT_NE(devInfo.udid, ""); + ZLOGI("GetLocalDevice begin."); + auto dvInfo = DevManager::GetInstance().GetLocalDevice(); + EXPECT_NE(dvInfo.deviceId, ""); + EXPECT_NE(dvInfo.deviceUuid, ""); } /** -* @tc.name: ToUUID001 +* @tc.name: ToUUID * @tc.desc: Get uuid from networkId * @tc.type: FUNC * @tc.require: * @tc.author: taoyuxin */ -HWTEST_F(DevManagerTest, ToUUID001, TestSize.Level1) +HWTEST_F(DevManagerTest, ToUUID, TestSize.Level1) { - ZLOGI("ToUUID001 begin."); - DevManager &devManager = OHOS::DistributedKv::DevManager::GetInstance(); - DevManager::DetailInfo devInfo = devManager.GetLocalDevice(); - EXPECT_NE(devInfo.networkId, ""); - std::string uuid = devManager.ToUUID(devInfo.networkId); + ZLOGI("ToUUID begin."); + auto &DevMgr = DevManager::GetInstance(); + auto dvInfo = DevMgr.GetLocalDevice(); + EXPECT_NE(dvInfo.deviceId, ""); + auto uuid = DevMgr.ToUUID(dvInfo.deviceId); EXPECT_NE(uuid, ""); - EXPECT_EQ(uuid, devInfo.uuid); + EXPECT_EQ(uuid, dvInfo.deviceUuid); +} + +/** +* @tc.name: ToNetworkId +* @tc.desc: Get networkId from uuid +* @tc.type: FUNC +* @tc.require: +* @tc.author: zuojiangjiang +*/ +HWTEST_F(DevManagerTest, ToNetworkId, TestSize.Level1) +{ + auto &DevMgr = DevManager::GetInstance(); + auto dvInfo = DevMgr.GetLocalDevice(); + EXPECT_NE(dvInfo.deviceUuid, ""); + auto networkId = DevMgr.ToNetworkId(dvInfo.deviceUuid); + EXPECT_NE(networkId, ""); + EXPECT_EQ(networkId, dvInfo.deviceId); } /** -* @tc.name: GetRemoteDevices001 +* @tc.name: GetRemoteDevices * @tc.desc: Get remote devices * @tc.type: FUNC * @tc.require: * @tc.author: taoyuxin */ -HWTEST_F(DevManagerTest, GetRemoteDevices001, TestSize.Level1) +HWTEST_F(DevManagerTest, GetRemoteDevices, TestSize.Level1) { - ZLOGI("GetRemoteDevices001 begin."); + ZLOGI("GetRemoteDevices begin."); DevManager &devManager = OHOS::DistributedKv::DevManager::GetInstance(); - vector devInfo = devManager.GetRemoteDevices(); - EXPECT_EQ(devInfo.size(), 0); + auto dvInfos = devManager.GetRemoteDevices(); + EXPECT_EQ(dvInfos.size(), 0); } diff --git a/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp b/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp index b669a2a2ad3..664463334fe 100644 --- a/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp +++ b/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp @@ -826,7 +826,7 @@ HWTEST_F(SingleStoreImplTest, RemoveDeviceData, TestSize.Level0) status = store->GetCount({}, count); ASSERT_EQ(status, SUCCESS); ASSERT_EQ(count, 10); - status = store->RemoveDeviceData(DevManager::GetInstance().GetLocalDevice().networkId); + status = store->RemoveDeviceData(DevManager::GetInstance().GetLocalDevice().deviceId); ASSERT_EQ(status, SUCCESS); status = store->GetCount({}, count); ASSERT_EQ(status, SUCCESS); diff --git a/interfaces/innerkits/distributeddata/include/types.h b/interfaces/innerkits/distributeddata/include/types.h index a3bf298c3e3..3555247131a 100644 --- a/interfaces/innerkits/distributeddata/include/types.h +++ b/interfaces/innerkits/distributeddata/include/types.h @@ -197,6 +197,7 @@ enum class DeviceChangeType { struct DeviceInfo { std::string deviceId; + std::string deviceUuid; std::string deviceName; std::string deviceType; }; -- Gitee From 1db4f1405bab027bd231d42c18f672529e5250d3 Mon Sep 17 00:00:00 2001 From: htt1997 Date: Wed, 11 Jan 2023 09:51:59 +0800 Subject: [PATCH 020/191] bug fix Signed-off-by: htt1997 --- .../distributeddatafwk/src/kvstore_service_death_notifier.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_service_death_notifier.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_service_death_notifier.cpp index 8c10c7878d9..86fee360cc3 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_service_death_notifier.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_service_death_notifier.cpp @@ -62,7 +62,7 @@ sptr KvStoreServiceDeathNotifier::GetDistributedKvDataServi } auto remote = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); - kvDataServiceProxy_ = iface_cast(remote); + kvDataServiceProxy_ = new (std::nothrow) KvStoreDataServiceProxy(remote); if (kvDataServiceProxy_ == nullptr) { ZLOGE("initialize proxy failed."); return nullptr; -- Gitee From 04814902109f910cee4b9b5a2079e3990836d508 Mon Sep 17 00:00:00 2001 From: lianhuixxx Date: Thu, 22 Dec 2022 15:42:24 +0800 Subject: [PATCH 021/191] Move MST from datamgr_service Signed-off-by: lianhuixxx Change-Id: I66a03dacfe7a0f9e8afa4a321c0d51d5d033c79b --- BUILD.gn | 1 + .../distributeddb/test/moduletest/BUILD.gn | 708 +++++ .../include/auto_launch_callback.h | 53 + .../distributeddb/include/delegate_callback.h | 49 + .../include/delegate_kv_mgr_callback.h | 43 + .../include/distributed_rdb_tools.h | 104 + .../include/distributed_test_sysinfo.h | 113 + .../include/distributed_test_tools.h | 436 +++ .../include/distributeddb_constant.h | 133 + .../include/distributeddb_data_generator.h | 567 ++++ .../include/distributeddb_log_print.h | 33 + .../include/distributeddb_nb_test_tools.h | 356 +++ .../include/distributeddb_schema_test_tools.h | 311 +++ .../include/kv_store_observer_impl.h | 86 + .../include/kv_store_snapshot_callback.h | 42 + .../src/auto_launch_callback.cpp | 72 + .../distributeddb/src/delegate_callback.cpp | 36 + .../src/delegate_kv_mgr_callback.cpp | 31 + .../src/distributed_rdb_tools.cpp | 247 ++ .../src/distributed_test_sysinfo.cpp | 302 ++ .../src/distributed_test_tools.cpp | 1993 +++++++++++++ .../src/distributeddb_constant.cpp | 35 + .../src/distributeddb_data_generator.cpp | 637 +++++ .../src/distributeddb_nb_test_tools.cpp | 739 +++++ .../src/distributeddb_schema_test_tools.cpp | 354 +++ .../src/kv_store_observer_impl.cpp | 221 ++ .../src/kv_store_snapshot_callback.cpp | 36 + .../distributed_crud_transaction_tools.h | 64 + .../distributeddb_nb_cursor_testcase.h | 55 + .../include/process_communicator_test_stub.h | 96 + .../distributed_crud_transaction_tools.cpp | 274 ++ .../src/distributed_rdb_exception_test.cpp | 352 +++ .../src/distributeddb_kv_backup_test.cpp | 1226 ++++++++ .../src/distributeddb_kv_batch_crud_test.cpp | 1085 ++++++++ ...distributeddb_kv_concurrency_crud_test.cpp | 323 +++ .../src/distributeddb_kv_create_test.cpp | 1979 +++++++++++++ .../src/distributeddb_kv_crud_test.cpp | 720 +++++ .../distributeddb_kv_observer_snap_test.cpp | 1587 +++++++++++ .../src/distributeddb_kv_observer_test.cpp | 1683 +++++++++++ .../src/distributeddb_kv_realdel_test.cpp | 374 +++ ...distributeddb_kv_transaction_perf_test.cpp | 339 +++ .../src/distributeddb_kv_transaction_test.cpp | 1997 +++++++++++++ .../src/distributeddb_nb_autolaunch_test.cpp | 775 ++++++ .../src/distributeddb_nb_backup_test.cpp | 1517 ++++++++++ .../src/distributeddb_nb_batch_crud_test.cpp | 2472 +++++++++++++++++ .../src/distributeddb_nb_create_test.cpp | 1969 +++++++++++++ .../src/distributeddb_nb_crud_power_test.cpp | 157 ++ .../src/distributeddb_nb_crud_test.cpp | 1877 +++++++++++++ .../src/distributeddb_nb_cursor_test.cpp | 790 ++++++ .../src/distributeddb_nb_cursor_testcase.cpp | 2027 ++++++++++++++ .../src/distributeddb_nb_db_damage_test.cpp | 251 ++ ...teddb_nb_enable_sync_by_closed_db_test.cpp | 762 +++++ ...distributeddb_nb_local_batch_crud_test.cpp | 1035 +++++++ .../src/distributeddb_nb_observer_test.cpp | 2222 +++++++++++++++ ...buteddb_nb_predicate_query_expand_test.cpp | 1188 ++++++++ .../distributeddb_nb_predicate_query_test.cpp | 1956 +++++++++++++ .../src/distributeddb_nb_schema_test.cpp | 2396 ++++++++++++++++ .../distributeddb_nb_schema_upgrade_test.cpp | 1383 +++++++++ 58 files changed, 42669 insertions(+) create mode 100644 frameworks/libs/distributeddb/test/moduletest/BUILD.gn create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/auto_launch_callback.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/delegate_callback.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/delegate_kv_mgr_callback.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_rdb_tools.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_test_sysinfo.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_test_tools.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_constant.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_data_generator.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_log_print.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_nb_test_tools.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_schema_test_tools.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/kv_store_observer_impl.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/kv_store_snapshot_callback.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/auto_launch_callback.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/delegate_callback.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/delegate_kv_mgr_callback.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/distributed_rdb_tools.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/distributed_test_sysinfo.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/distributed_test_tools.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/distributeddb_constant.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/distributeddb_data_generator.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/distributeddb_nb_test_tools.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/distributeddb_schema_test_tools.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/kv_store_observer_impl.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/common/distributeddb/src/kv_store_snapshot_callback.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/include/distributed_crud_transaction_tools.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/include/distributeddb_nb_cursor_testcase.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/include/process_communicator_test_stub.h create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributed_crud_transaction_tools.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributed_rdb_exception_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_kv_backup_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_kv_batch_crud_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_kv_concurrency_crud_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_kv_create_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_kv_crud_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_kv_observer_snap_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_kv_observer_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_kv_realdel_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_kv_transaction_perf_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_kv_transaction_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_autolaunch_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_backup_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_batch_crud_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_create_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_crud_power_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_crud_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_cursor_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_cursor_testcase.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_db_damage_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_enable_sync_by_closed_db_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_local_batch_crud_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_observer_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_predicate_query_expand_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_predicate_query_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_schema_test.cpp create mode 100644 frameworks/libs/distributeddb/test/moduletest/src/distributeddb_nb_schema_upgrade_test.cpp diff --git a/BUILD.gn b/BUILD.gn index ffdc42dd56d..831ae84a914 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -25,6 +25,7 @@ group("build_native_test") { deps = [ "frameworks/innerkitsimpl/distributeddatafwk/test:unittest", "frameworks/libs/distributeddb/test:unittest", + "frameworks/libs/distributeddb/test/moduletest:moduletest", ] } diff --git a/frameworks/libs/distributeddb/test/moduletest/BUILD.gn b/frameworks/libs/distributeddb/test/moduletest/BUILD.gn new file mode 100644 index 00000000000..0095263f882 --- /dev/null +++ b/frameworks/libs/distributeddb/test/moduletest/BUILD.gn @@ -0,0 +1,708 @@ +# 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. +import("//build/test.gni") + +module_output_path = "kv_store/distributeddb" + +mul_sources = [ + "common/distributeddb/src/auto_launch_callback.cpp", + "common/distributeddb/src/delegate_callback.cpp", + "common/distributeddb/src/delegate_kv_mgr_callback.cpp", + "common/distributeddb/src/distributed_test_tools.cpp", + "common/distributeddb/src/kv_store_observer_impl.cpp", + "common/distributeddb/src/kv_store_snapshot_callback.cpp", +] + +############################################################################### +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/interfaces/include", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/storage/include", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/storage/src", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/storage/src/multiver", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/storage/src/sqlite", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/common/include", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/include", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/interfaces/src", + + # "../adapter/include/communicator", + "//developtools/liblog", + "common/distributeddb/include", + "include", + "//commonlibrary/c_utils/base/include", + "//third_party/sqlite/include", + "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include", + "//third_party/openssl/include/", + ] + + defines = [ + "_LARGEFILE64_SOURCE", + "_FILE_OFFSET_BITS=64", + "SQLITE_HAS_CODEC", + "USE_SQLITE_SYMBOLS", + "USING_HILOG_LOGGER", + "TESTCASES_USING_GTEST_EXT", + "OMIT_JSON", + "LOW_LEVEL_MEM_DEV", + "RELEASE_MODE_V2", + "RELEASE_MODE_V3", + ] + ldflags = [ "-Wl,--exclude-libs,ALL" ] +} + +##############################moduletest########################################## +ohos_moduletest("DistributeddbKvTransactionTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributed_test_sysinfo.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "src/distributed_crud_transaction_tools.cpp", + "src/distributeddb_kv_transaction_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbKvTransactionPerfTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributed_test_sysinfo.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "src/distributed_crud_transaction_tools.cpp", + "src/distributeddb_kv_transaction_perf_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} +ohos_moduletest("DistributeddbKvConcurrencyCrudTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributed_test_sysinfo.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "src/distributeddb_kv_concurrency_crud_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} +ohos_moduletest("DistributeddbKvBatchCrudTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributed_test_sysinfo.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "src/distributeddb_kv_batch_crud_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} +ohos_moduletest("DistributeddbKvCreateTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributed_test_sysinfo.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "src/distributeddb_kv_create_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} +ohos_moduletest("DistributeddbKvCrudTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributed_test_sysinfo.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "src/distributeddb_kv_crud_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} +ohos_moduletest("DistributeddbKvObserverTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributed_test_sysinfo.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "src/distributeddb_kv_observer_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} +ohos_moduletest("DistributeddbKvObserverSnapTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributed_test_sysinfo.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "src/distributeddb_kv_observer_snap_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbKvBackupTest") { + module_out_path = module_output_path + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "src/distributeddb_kv_backup_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbKvRealdelTest") { + module_out_path = module_output_path + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "src/distributeddb_kv_realdel_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbCreateTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "src/distributeddb_nb_create_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} +ohos_moduletest("DistributeddbNbCrudTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "src/distributeddb_nb_crud_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} +ohos_moduletest("DistributeddbNbObserverTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "src/distributeddb_nb_observer_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbCursorTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "src/distributeddb_nb_cursor_test.cpp", + "src/distributeddb_nb_cursor_testcase.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbBackupTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "src/distributeddb_nb_backup_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbBatchCrudTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "src/distributeddb_nb_batch_crud_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbLocalBatchCrudTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "src/distributeddb_nb_local_batch_crud_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbSchemaDbTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "src/distributeddb_nb_schema_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbPredicateQueryTest") { + module_out_path = module_output_path + + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "src/distributeddb_nb_predicate_query_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbPredicateQueryExpandTest") { + module_out_path = module_output_path + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "common/distributeddb/src/distributeddb_schema_test_tools.cpp", + "src/distributeddb_nb_predicate_query_expand_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbAutolaunchTest") { + module_out_path = module_output_path + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "common/distributeddb/src/distributeddb_schema_test_tools.cpp", + "src/distributeddb_nb_autolaunch_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributedbNbDbDamageTest") { + module_out_path = module_output_path + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "common/distributeddb/src/distributeddb_schema_test_tools.cpp", + "src/distributeddb_nb_db_damage_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbCrudPowerTest") { + module_out_path = module_output_path + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "common/distributeddb/src/distributeddb_schema_test_tools.cpp", + "src/distributeddb_nb_crud_power_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbSchemaTest") { + module_out_path = module_output_path + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "common/distributeddb/src/distributeddb_schema_test_tools.cpp", + "src/distributeddb_nb_schema_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +ohos_moduletest("DistributeddbNbSchemaUpgradeTest") { + module_out_path = module_output_path + sources = [ + "common/distributeddb/src/distributeddb_constant.cpp", + "common/distributeddb/src/distributeddb_data_generator.cpp", + "common/distributeddb/src/distributeddb_nb_test_tools.cpp", + "common/distributeddb/src/distributeddb_schema_test_tools.cpp", + "src/distributeddb_nb_schema_upgrade_test.cpp", + ] + sources += mul_sources + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//third_party/googletest:gtest_main", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "datamgr_service" +} + +############################################################################### +group("moduletest") { + testonly = true + deps = [ + "//third_party/googletest:gmock", + "//third_party/googletest:gtest_main", + "//third_party/sqlite:sqlite", + ] + + deps += [ + ":DistributedbNbDbDamageTest", + ":DistributeddbKvBackupTest", + ":DistributeddbKvBatchCrudTest", + ":DistributeddbKvConcurrencyCrudTest", + ":DistributeddbKvCreateTest", + ":DistributeddbKvCrudTest", + ":DistributeddbKvObserverSnapTest", + ":DistributeddbKvObserverTest", + ":DistributeddbKvRealdelTest", + ":DistributeddbKvTransactionPerfTest", + ":DistributeddbKvTransactionTest", + ":DistributeddbNbAutolaunchTest", + ":DistributeddbNbBackupTest", + ":DistributeddbNbBatchCrudTest", + ":DistributeddbNbCreateTest", + ":DistributeddbNbCrudPowerTest", + ":DistributeddbNbCrudTest", + ":DistributeddbNbCursorTest", + ":DistributeddbNbLocalBatchCrudTest", + ":DistributeddbNbObserverTest", + ":DistributeddbNbPredicateQueryExpandTest", + ":DistributeddbNbPredicateQueryTest", + ":DistributeddbNbSchemaTest", + ":DistributeddbNbSchemaUpgradeTest", + ] +} diff --git a/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/auto_launch_callback.h b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/auto_launch_callback.h new file mode 100644 index 00000000000..17e1f409e8e --- /dev/null +++ b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/auto_launch_callback.h @@ -0,0 +1,53 @@ +/* + * 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. + */ +#ifndef AUTO_LAUNCH_CALLBACK_H +#define AUTO_LAUNCH_CALLBACK_H + +#include +#include "auto_launch_export.h" +#include "types_export.h" + +#ifdef RELEASE_MODE_V2 +class AutoLaunchCallback { +public: + AutoLaunchCallback() {} + ~AutoLaunchCallback() {} + + // Delete the copy and assign constructors + AutoLaunchCallback(const AutoLaunchCallback &callback) = delete; + AutoLaunchCallback &operator=(const AutoLaunchCallback &callback) = delete; + AutoLaunchCallback(AutoLaunchCallback &&callback) = delete; + AutoLaunchCallback &operator=(AutoLaunchCallback &&callback) = delete; + + void AutoLaunchNotifier(const std::string &userId, const std::string &appId, const std::string &storeId, + DistributedDB::AutoLaunchStatus status); + int GetStatus(); + void Clear(); +#ifdef RELEASE_MODE_V3 + bool AutoLaunchRequestNotifier(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m); + void AddHashIdentity(const std::string &hashIdentity); + void ClearHashIdentities(); + void SetAutoLaunchParam(DistributedDB::AutoLaunchParam &autoLaunchParam); +#endif + +private: + int realStatus_ = 0; + std::vector hashIdentities_; +#ifdef RELEASE_MODE_V3 + DistributedDB::AutoLaunchParam autoLaunchParam_; +#endif +}; +#endif // end of RELEASE_MODE_V2 +#endif // AUTO_LAUNCH_CALLBACK_H \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/delegate_callback.h b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/delegate_callback.h new file mode 100644 index 00000000000..a6a045fc999 --- /dev/null +++ b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/delegate_callback.h @@ -0,0 +1,49 @@ +/* + * 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. + */ +#ifndef DELEGATE_CALLBACK_H +#define DELEGATE_CALLBACK_H +#include "kv_store_snapshot_delegate.h" +#include "types_export.h" + +// DelegateCallback conclude the Callback implements of function< void(DBStatus, KvStoreSnapshotDelegate*)> +class DelegateCallback { +public: + DelegateCallback() {} + ~DelegateCallback() {} + + // Delete the copy and assign constructors + DelegateCallback(const DelegateCallback &callback) = delete; + DelegateCallback& operator=(const DelegateCallback &callback) = delete; + DelegateCallback(DelegateCallback &&callback) = delete; + DelegateCallback& operator=(DelegateCallback &&callback) = delete; + + void Callback(DistributedDB::DBStatus status, DistributedDB::KvStoreSnapshotDelegate *kvStoreSnapshotDelegate); + void CallbackKv(DistributedDB::DBStatus status, const DistributedDB::Value &value); + + DistributedDB::DBStatus GetStatus(); + const DistributedDB::Value &GetValue(); + + const DistributedDB::KvStoreSnapshotDelegate *GetKvStoreSnapshot() + { + return kvStoreSnapshotDelegate_; + } + +private: + DistributedDB::DBStatus status_ = DistributedDB::DBStatus::INVALID_ARGS; + DistributedDB::Value value_ = {}; + DistributedDB::KvStoreSnapshotDelegate *kvStoreSnapshotDelegate_ = nullptr; +}; + +#endif // DELEGATE_CALLBACK_H \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/delegate_kv_mgr_callback.h b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/delegate_kv_mgr_callback.h new file mode 100644 index 00000000000..35b08709373 --- /dev/null +++ b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/delegate_kv_mgr_callback.h @@ -0,0 +1,43 @@ +/* + * 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. + */ +#ifndef DELEGATE_KV_MGR_CALLBACK_H +#define DELEGATE_KV_MGR_CALLBACK_H + +#include "kv_store_delegate.h" + +// DelegateKvMgrCallback conclude the Callback implements of function< void(DBStatus, KvStoreDelegate*)> +class DelegateKvMgrCallback { +public: + DelegateKvMgrCallback() {} + ~DelegateKvMgrCallback() {} + + // Delete the copy and assign constructors + DelegateKvMgrCallback(const DelegateKvMgrCallback &callback) = delete; + DelegateKvMgrCallback& operator=(const DelegateKvMgrCallback &callback) = delete; + DelegateKvMgrCallback(DelegateKvMgrCallback &&callback) = delete; + DelegateKvMgrCallback& operator=(DelegateKvMgrCallback &&callback) = delete; + + void Callback(DistributedDB::DBStatus status, DistributedDB::KvStoreDelegate *kvStoreDelegate); + + DistributedDB::DBStatus GetStatus(); + + const DistributedDB::KvStoreDelegate *GetKvStore(); + +private: + DistributedDB::DBStatus status_ = DistributedDB::DBStatus::INVALID_ARGS; + DistributedDB::KvStoreDelegate *kvStoreDelegate_ = nullptr; +}; + +#endif // DELEGATE_KV_MGR_CALLBACK_H \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_rdb_tools.h b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_rdb_tools.h new file mode 100644 index 00000000000..95b15b9d39e --- /dev/null +++ b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_rdb_tools.h @@ -0,0 +1,104 @@ +/* + * 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. + */ +#ifndef DISTRIBUTED_RDB_MODULE_TEST_TOOLS_H +#define DISTRIBUTED_RDB_MODULE_TEST_TOOLS_H +#include +#include + +#include "relational_store_delegate.h" +#include "relational_store_manager.h" +#include "distributed_test_sysinfo.h" +#include "distributeddb_data_generator.h" +#include "log_print.h" +#ifdef TESTCASES_USING_GTEST +#define HWTEST_F(test_case_name, test_name, level) TEST_F(test_case_name, test_name) +#endif + +struct RdbParameters { + std::string path; + std::string storeId; + std::string appId; + std::string userId; + RdbParameters(str::string pathStr, std::string storeIdStr, std::string appIdStr, std::string userIdStr) + : pathStr(pathStr), storeId(storeIdStr), appId(appIdStr), userId(userIdStr) + { + } +}; + +const static std::string TAG = "DistributedRdbTools"; + +const static std::string NORMAL_PATH = "/data/test/"; +const static std::string NON_EXISTENT_PATH = "/data/test/nonExistent_rdb/"; +const static std::string UNREADABLE_PATH = "/data/test/unreadable_rdb/"; +const static std::string UNWRITABLE_PATH = "/data/test/unwritable_rdb/"; + +const static std::string NULL_STOREID = {}; +const static std::string ILLEGAL_STOREID = "rdb_$%#@~%"; +const static std::string MODE_STOREID = "rdb_mode"; +const static std::string FULL_STOREID = "rdb_full"; +const static std::string SUPER_STOREID = "rdb_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + +const static std::string NON_EXISTENT_TABLE = "non_table"; +const static std::string KEYWORD_START_TABLE = "naturalbase_rdb_a"; + +const static std::string NORMAL_TABLE = "NORMAL_RDB"; +const static std::string CONSTRAINT_TABLE = "CONSTRAINT_RDB"; + +const static RdbParameters g_rdbParameter1(NORMAL_PATH, DistributedDBDataGenerator::STORE_ID_1, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); + +const static RdbParameters g_rdbParameter2(NORMAL_PATH, DistributedDBDataGenerator::STORE_ID, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); + +const static RdbParameters g_rdbParameter3(NORMAL_PATH, ILLEGAL_STOREID, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); + +const static RdbParameters g_rdbParameter4(NORMAL_PATH, MODE_STOREID, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); + +const static RdbParameters g_rdbParameter5(NORMAL_PATH, SUPER_STOREID, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); + +const static RdbParameters g_rdbParameter6(NON_EXISTENT_PATH, DistributedDBDataGenerator::STORE_ID_1, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); + +const static RdbParameters g_rdbParameter7(UNREADABLE_PATH, DistributedDBDataGenerator::STORE_ID_1, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); + +const static RdbParameters g_rdbParameter8(UNWRITABLE_PATH, DistributedDBDataGenerator::STORE_ID_1, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); + +const static RdbParameters g_rdbParameter9(NORMAL_PATH, FULL_STOREID, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); + +class DistributedRdbTools final { +public: + DistributedRdbTools() {} + ~DistributedRdbTools() {} + // Relational Database OpenStore And CreateDistributeTable + static DistributedDB::DBStatus GetOpenStoreStatus(const RelatetionalStoreManager *&manager, + RelatetionalStoreDelegate *&delegate, const RdbParameters ¶m); + static DistributedDB::DBStatus GetCreateDistributedTableStatus(const RelatetionalStoreDelegate *&delegate, + const std::string &tableName); + static bool CloseStore(const DistributedDB::RelatetionalStoreDelegate *&delegate); + + static bool InitSqlite3Store(sqlite3 *&db, const RdbParameters ¶m); + static bool InitTableDataAndTrigger(const sqlite3 *&db) ; + static bool AlterTableAttributes(const sqlite3 *&db); + static bool Sqlite3ExecOpration(const sqlite3 *&db, cont char *&sql_name); + static void CloseSqlite3Store(sqlite3 *&db); +} +#endif // DISTRIBUTED_RDB_MODULE_TEST_TOOLS_H \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_test_sysinfo.h b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_test_sysinfo.h new file mode 100644 index 00000000000..417e9979fea --- /dev/null +++ b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_test_sysinfo.h @@ -0,0 +1,113 @@ +/* + * 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. + */ +#ifndef DISTRIBUTED_TEST_SYSINFO_H +#define DISTRIBUTED_TEST_SYSINFO_H + +#include +#include "distributeddb_log_print.h" +#if defined(RUNNING_ON_LINUX) +#include +#elif defined RUNNING_ON_WIN +#endif + +const uint64_t SYSTEM_INFO_BUFFER_SIZE = 20; +const uint64_t PROC_BUFFER_LENGTH = 4096; +const uint64_t DEFAULT_INTEVAL = 250000; +const uint64_t DEFAULT_COUNT = 5; + +#if defined(RUNNING_ON_LINUX) +const std::string SYS_MEM_FILE = "/proc/meminfo"; +const std::string SYS_CPU_FILE = "/proc/stat"; +const std::string POWER_FOLLOW_FILE = "/sys/class/power_supply/Battery/current_now"; +const std::string VOLTAGE_FILE = "/sys/class/power_supply/Battery/voltage_now"; +const std::string FILE_READ_PERMISSION = "r"; + +// struct of mem occupy +struct MemOccupy { + char memTotalName_[SYSTEM_INFO_BUFFER_SIZE]; + uint64_t memTotal_; + char memFreeName_[SYSTEM_INFO_BUFFER_SIZE]; + uint64_t memFree_; + char buffersName_[SYSTEM_INFO_BUFFER_SIZE]; + uint64_t buffers_; + char cachedName_[SYSTEM_INFO_BUFFER_SIZE]; + uint64_t cached_; + char swapCachedName_[SYSTEM_INFO_BUFFER_SIZE]; + uint64_t swapCached_; +}; + +// struct of cpu occupy +struct CpuOccupy { + char name_[SYSTEM_INFO_BUFFER_SIZE]; + uint64_t user_; + uint64_t nice_; + uint64_t system_; + uint64_t idle_; + uint64_t iowait_; + uint64_t irq_; + uint64_t softirq_; +}; +#elif defined RUNNING_ON_WIN +#endif + +enum SeqNo { + FIRST = 1, + SECOND +}; + +// this class get system info, such as system or cpu storage and power at the moment +class DistributedTestSysInfo final { +public: + + DistributedTestSysInfo(); + ~DistributedTestSysInfo() {} + + // Delete the copy and assign constructors + DistributedTestSysInfo(const DistributedTestSysInfo &distributeTestSysInfo) = delete; + DistributedTestSysInfo& operator=(const DistributedTestSysInfo &distributeTestSysInfo) = delete; + DistributedTestSysInfo(DistributedTestSysInfo &&distributeTestSysInfo) = delete; + DistributedTestSysInfo& operator=(DistributedTestSysInfo &&distributeTestSysInfo) = delete; + + // read memory information from system file + void GetSysMemOccpy(SeqNo seqNo); + // read cpu information from system file sleep microSeconds between first and second read. + void GetSysCpuUsage(SeqNo seqNo, uint64_t microSeconds); + // read value from specific file + float ReadSysValFromFile(const std::string &filePath); + // read value from specific file and take the average within totalCount + float GetSysMeanCurrentVal(const std::string &filePath, int totalCount, uint64_t microSeconds); + // read power from specific file + void GetSysCurrentPower(SeqNo seqNo, int totalCount, uint64_t microSeconds); + + uint64_t GetFirstMemFree() const; + uint64_t GetSecondMemFree() const; + float GetFirstCpuUsage() const; + float GetSecondCpuUsage() const; + float GetFirstPower() const; + float GetSecondPower() const; + + void SaveSecondToFirst(); + +private: +#if defined(RUNNING_ON_LINUX) + MemOccupy memStatFirst_, memStatSecond_; + CpuOccupy cpuStatFirst_, cpuStatSecond_; +#elif defined RUNNING_ON_WIN +#endif + float cpuStatFirstUsage_, cpuStatSecondUsage_; + float powerStatFirst_, powerStatSecond_; + float val_; +}; +#endif // DISTRIBUTED_TEST_SYSINFO_H \ No newline at end of file diff --git a/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_test_tools.h b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_test_tools.h new file mode 100644 index 00000000000..6e1e512d949 --- /dev/null +++ b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributed_test_tools.h @@ -0,0 +1,436 @@ +/* + * 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. + */ +#ifndef DISTRIBUTED_DB_MODULE_TEST_TOOLS_H +#define DISTRIBUTED_DB_MODULE_TEST_TOOLS_H +#include +#include + +#include "kv_store_delegate.h" +#include "kv_store_delegate_manager.h" +#include "kv_store_observer_impl.h" +#include "distributed_test_sysinfo.h" +#include "distributeddb_data_generator.h" +#include "log_print.h" +#ifdef RUN_MST_ON_TRUNCK // only need it in WAGNER env if run MST +#define HWTEST_F(test_case_name, test_name, level) TEST_F(test_case_name, test_name) +#endif +#define ULL(x) (static_cast(x)) +const int MAX_DIR_LENGTH = 4096; // the max length of directory +const int BUF_LEN = 8192; +const static std::string TAG = "DistributedTestTools"; // for log +const int AUTHORITY = 0755; +const int E_OK = 0; +const int E_ERROR = -1; +const std::string DIRECTOR = "/data/test/getstub/"; // default work dir. +static std::condition_variable g_conditionKvVar; + +struct KvDBParameters { + std::string storeId; + std::string appId; + std::string userId; + KvDBParameters(std::string storeIdStr, std::string appIdStr, std::string userIdStr) + : storeId(storeIdStr), appId(appIdStr), userId(userIdStr) + { + } +}; + +struct KvOption { + bool createIfNecessary = true; + bool localOnly = false; + bool isEncryptedDb = false; // whether need encrypt + DistributedDB::CipherType cipher = DistributedDB::CipherType::DEFAULT; // cipher type + std::vector passwd; // cipher password + KvOption(bool createIfNecessary1, bool isLocalOnly, + bool isEncryptedDb1, DistributedDB::CipherType cipher1, std::vector passwd1) + : createIfNecessary(createIfNecessary1), + localOnly(isLocalOnly), + isEncryptedDb(isEncryptedDb1), + cipher(cipher1), passwd(passwd1) + { + } + KvOption() + {} +}; + +struct EncrypteAttribute { + bool isEncryptedDb = false; + std::vector passwd; +}; + +const static KvDBParameters g_kvdbParameter1(DistributedDBDataGenerator::STORE_ID_1, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); +const static KvDBParameters g_kvdbParameter2(DistributedDBDataGenerator::STORE_ID_2, + DistributedDBDataGenerator::APP_ID_2, DistributedDBDataGenerator::USER_ID_2); +const static KvDBParameters g_kvdbParameter3(DistributedDBDataGenerator::STORE_ID_3, + DistributedDBDataGenerator::APP_ID_3, DistributedDBDataGenerator::USER_ID_3); +const static KvDBParameters g_kvdbParameter4(DistributedDBDataGenerator::STORE_ID_4, + DistributedDBDataGenerator::APP_ID_4, DistributedDBDataGenerator::USER_ID_4); +const static KvDBParameters g_kvdbParameter5(DistributedDBDataGenerator::STORE_ID_5, + DistributedDBDataGenerator::APP_ID_5, DistributedDBDataGenerator::USER_ID_5); +const static KvDBParameters g_kvdbParameter6(DistributedDBDataGenerator::STORE_ID_6, + DistributedDBDataGenerator::APP_ID_6, DistributedDBDataGenerator::USER_ID_6); +const static KvDBParameters g_kvdbParameter1_1_2(DistributedDBDataGenerator::STORE_ID_1, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_2); +const static KvDBParameters g_kvdbParameter1_2_1(DistributedDBDataGenerator::STORE_ID_1, + DistributedDBDataGenerator::APP_ID_2, DistributedDBDataGenerator::USER_ID_1); +const static KvDBParameters g_kvdbParameter1_2_2(DistributedDBDataGenerator::STORE_ID_1, + DistributedDBDataGenerator::APP_ID_2, DistributedDBDataGenerator::USER_ID_2); +const static KvDBParameters g_kvdbParameter2_1_1(DistributedDBDataGenerator::STORE_ID_2, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); +const static KvDBParameters g_kvdbParameter2_1_2(DistributedDBDataGenerator::STORE_ID_2, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_2); +const static KvDBParameters KVDB_PARAMETER_PERFORM(DistributedDBDataGenerator::STORE_ID_PERFORM, + DistributedDBDataGenerator::APP_ID_PERFORM, DistributedDBDataGenerator::USER_ID_PERFORM); +const static KvOption g_createKvDiskUnencrypted(true, false, false, DistributedDB::CipherType::DEFAULT, + DistributedDBDataGenerator::NULL_PASSWD_VECTOR); +const static KvOption g_createKvDiskEncrypted(true, false, true, DistributedDB::CipherType::DEFAULT, + DistributedDBDataGenerator::PASSWD_VECTOR_1); +const static KvOption g_createLocalDiskUnencrypted(true, true, false, DistributedDB::CipherType::DEFAULT, + DistributedDBDataGenerator::NULL_PASSWD_VECTOR); +const static KvOption g_createLocalDiskEncrypted(true, true, true, DistributedDB::CipherType::DEFAULT, + DistributedDBDataGenerator::PASSWD_VECTOR_1); +static KvOption g_kvOption = g_createKvDiskEncrypted; +bool CompareVector(const std::vector& first, const std::vector& second); +bool CompareEntriesVector(std::vector& retVec, + std::vector& expectVec); +void PutUniqueKey(std::vector& entryVec, + const DistributedDB::Key &putKey, const DistributedDB::Value &putValue); +int Uint8VecToString(std::vector& vec, std::string& str); +int GetIntValue(DistributedDB::Value &value); +int RemoveDir(const std::string &directory); +int SetDir(const std::string &directory, const int authRight = AUTHORITY); +void CopyFile(const std::string &srcFile, const std::string &destFile); +void CopyDir(const std::string &srcDir, const std::string &destDir, const int authRight = AUTHORITY); +void CheckFileNumber(const std::string &filePath, int &fileCount); +DistributedDB::Value GetValueWithInt(int val); +std::vector GenRanKeyVal(int putGetTimes, int keyLength, int valueLength, char val); +std::vector GetKeysFromEntries(std::vector entries, bool random); +bool GetRandBool(); +bool PutEntries(DistributedDB::KvStoreNbDelegate *&delegate, std::vector &entries); + +using SysTime = std::chrono::time_point; +using SysDurTime = std::chrono::duration; + +struct PerformanceData { + int putGetTimes; + int keyLength; + int valueLength; + bool putBatch; + bool getBatch; + bool useClear; + bool getSysInfo; + bool isLocal; + double openDuration; + double putDuration; + double readPutDuration; + double updateDuration; + double readUpdateDuration; + double deleteDuration; + double closeDuration; + PerformanceData(int putGetTimes, int keyLength, int valueLength, + bool putBatch, bool getBatch, bool useClear, bool getSysInfo, bool isLocal) + : putGetTimes(putGetTimes), keyLength(keyLength), valueLength(valueLength), + putBatch(putBatch), getBatch(getBatch), useClear(useClear), + getSysInfo(getSysInfo), isLocal(isLocal), + openDuration(0.0), putDuration(0.0), readPutDuration(0.0), updateDuration(0.0), + readUpdateDuration(0.0), deleteDuration(0.0), closeDuration(0.0) + { + } +}; + +struct Duration { + double putDuration = 0.0; + double readDuration = 0.0; + double updateDuration = 0.0; + double deleteDuration = 0.0; + Duration() = default; + void Clear() + { + putDuration = readDuration = updateDuration = deleteDuration = 0.0; + } +}; + +struct BackupDuration { + double exportDuration = 0.0; + double importDuration = 0.0; + BackupDuration() = default; + BackupDuration(double exportDur, double importDur) + { + exportDuration = exportDur; + importDuration = importDur; + } + BackupDuration operator+(const BackupDuration &backupDur) const + { + return BackupDuration(exportDuration + backupDur.exportDuration, importDuration + backupDur.importDuration); + } + void Clear() + { + exportDuration = importDuration = 0; + } +}; + +enum KvDbType { + ENCRYED = 0, + UNENCRYED = 1 +}; + +enum OperRecordNum { + SINGLE = 1, + SMALL_BATCH = 100, + BATCH = 128, +}; + +enum class OperType { + PUT, + PUT_LOCAL, + UPDATE, + UPDATE_LOCAL, + DELETE, + DELETE_LOCAL +}; + +struct KvPerfData { + KvDbType kvDbType; + int testCnt; + OperRecordNum operRecordNum; + int keyLength; + int valueLength; + bool isPresetRecords; + int presetRecordsCnt; + std::vector allCrudDur; + KvPerfData(KvDbType kvDbType, int testCnt, OperRecordNum operRecordNum, int keyLength, int valueLength, + bool isPresetRecords, int presetRecordsCnt) + : kvDbType(kvDbType), testCnt(testCnt), operRecordNum(operRecordNum), + keyLength(keyLength), valueLength(valueLength), + isPresetRecords(isPresetRecords), presetRecordsCnt(presetRecordsCnt) + { + } +}; + +struct RekeyTypesDur { + double nullPasswdToPasswd1 = 0.0; + double passwd1ToPasswd1 = 0.0; + double passwd1ToPasswd2 = 0.0; + double passwd2ToNullPasswd = 0.0; + RekeyTypesDur() = default; + RekeyTypesDur(double nullPasswdToPasswd1, double passwd1ToPasswd1, + double passwd1ToPasswd2, double passwd2ToNullPasswd) + : nullPasswdToPasswd1(nullPasswdToPasswd1), passwd1ToPasswd1(passwd1ToPasswd1), + passwd1ToPasswd2(passwd1ToPasswd2), passwd2ToNullPasswd(passwd2ToNullPasswd) + { + } + RekeyTypesDur operator+(const RekeyTypesDur &rekeyTypesDur) const + { + return RekeyTypesDur(nullPasswdToPasswd1 + rekeyTypesDur.nullPasswdToPasswd1, + passwd1ToPasswd1 + rekeyTypesDur.passwd1ToPasswd1, + passwd1ToPasswd2 + rekeyTypesDur.passwd1ToPasswd2, + passwd2ToNullPasswd + rekeyTypesDur.passwd2ToNullPasswd); + } +}; + +struct KvRekeyPerfData { + int testCnt; + int presetRecordsCnt; + int keyLength; + int valueLength; + std::vector allRekeyDur; + KvRekeyPerfData(int testCnt, int presetRecordsCnt, int keyLength, int valueLength) + : testCnt(testCnt), presetRecordsCnt(presetRecordsCnt), keyLength(keyLength), valueLength(valueLength) + { + } +}; + +struct KvBackupPerfData { + KvDbType kvDbType; + int testCnt; + int presetRecordsCnt; + int keyLength; + int valueLength; + std::vector allBackupDur; + KvBackupPerfData(KvDbType kvDbType, int testCnt, int presetRecordsCnt, int keyLength, int valueLength) + : kvDbType(kvDbType), testCnt(testCnt), presetRecordsCnt(presetRecordsCnt), + keyLength(keyLength), valueLength(valueLength) + { + } +}; + +struct PerImageGallery { + uint64_t putDuration = 0; + uint64_t readDuration = 0; + void Clear() + { + putDuration = 0; + readDuration = 0; + } +}; +struct NbGalleryPerfData { + int testCnt; + unsigned int keyLength; + unsigned int valueLength; + bool isLocal; + bool isPresetRecords; + int presetRecordsCnt; + std::vector allCrudDur; + NbGalleryPerfData(int testCnt, int keyLength, int valueLength, + bool isLocal, bool isPresetRecords, int presetRecordsCnt) + : testCnt(testCnt), keyLength(keyLength), valueLength(valueLength), + isLocal(isLocal), isPresetRecords(isPresetRecords), presetRecordsCnt(presetRecordsCnt) + { + } +}; +struct NbLocalPerfData { + int testCnt; + unsigned int keyLength; + unsigned int valueLength; + bool isLocal; + bool isPresetRecords; + int presetRecordsCnt; + std::vector allCrudDur; + NbLocalPerfData(int testCnt, int keyLength, int valueLength, + bool isLocal, bool isPresetRecords, int presetRecordsCnt) + : testCnt(testCnt), keyLength(keyLength), valueLength(valueLength), + isLocal(isLocal), isPresetRecords(isPresetRecords), presetRecordsCnt(presetRecordsCnt) + { + } +}; + +struct QueryDur { + double getEntriesDuration = 0.0; + double getResultSetDuration = 0.0; + QueryDur() = default; + void Clear() + { + getEntriesDuration = getResultSetDuration = 0; + } +}; +struct NbSchemaCRUDPerfData { + int testCnt; + OperRecordNum operRecordNum; + unsigned int keyLength; + unsigned int valueLength; + bool isLocal; + bool isPresetRecords; + unsigned int presetRecordsCnt; + bool isQueryNeeded; + bool isIndexSchema; + std::vector allCrudDur; + std::vector allQueryDur; + NbSchemaCRUDPerfData(int testCnt, OperRecordNum operRecordNum, int keyLength, int valueLength, + bool isLocal, bool isPresetRecords, int presetRecordsCnt, int isQueryNeeded, int isIndexSchema) + : testCnt(testCnt), operRecordNum(operRecordNum), keyLength(keyLength), valueLength(valueLength), + isLocal(isLocal), isPresetRecords(isPresetRecords), presetRecordsCnt(presetRecordsCnt), + isQueryNeeded(isQueryNeeded), isIndexSchema(isIndexSchema) + { + } +}; + +// default kvStoreDelegateManager's config. +const DistributedDB::KvStoreConfig KV_CONFIG = { + .dataDir = DIRECTOR +}; + +class DistributedTestTools final { +public: + DistributedTestTools() {} + ~DistributedTestTools() {} + + // Delete the copy and assign constructors + DistributedTestTools(const DistributedTestTools &distributeDBTools) = delete; + DistributedTestTools& operator=(const DistributedTestTools &distributeDBTools) = delete; + DistributedTestTools(DistributedTestTools &&distributeDBTools) = delete; + DistributedTestTools& operator=(DistributedTestTools &&distributeDBTools) = delete; + + // this static method is to compare if the two Value has the same data. + static bool IsValueEquals(const DistributedDB::Value &v1, const DistributedDB::Value &v2); + static DistributedDB::KvStoreDelegate::Option TransferKvOptionType(const KvOption &optionParam); + static DistributedDB::KvStoreDelegate* GetDelegateSuccess(DistributedDB::KvStoreDelegateManager *&outManager, + const KvDBParameters ¶m, const KvOption &optionParam); + static DistributedDB::KvStoreDelegate* GetDelegateStatus(DistributedDB::KvStoreDelegateManager *&outManager, + DistributedDB::DBStatus &status, const KvDBParameters ¶m, const KvOption &optionParam); + + static DistributedDB::DBStatus GetDelegateNotGood( + DistributedDB::KvStoreDelegateManager *&outManager, DistributedDB::KvStoreDelegate *&outDelegate, + const std::string &storeId, const std::string &appId, const std::string &userId, const KvOption &optionParam); + + static DistributedDB::DBStatus Put(DistributedDB::KvStoreDelegate &kvStoreDelegate, + const DistributedDB::Key &key, const DistributedDB::Value &value); + + static DistributedDB::DBStatus PutBatch(DistributedDB::KvStoreDelegate &kvStoreDelegate, + const std::vector &entries); + + static DistributedDB::DBStatus Delete(DistributedDB::KvStoreDelegate &kvStoreDelegate, + const DistributedDB::Key &key); + + static DistributedDB::DBStatus DeleteBatch(DistributedDB::KvStoreDelegate &kvStoreDelegate, + const std::vector &keys); + + static DistributedDB::DBStatus Clear(DistributedDB::KvStoreDelegate &kvStoreDelegate); + + static DistributedDB::KvStoreSnapshotDelegate *GetKvStoreSnapshot(DistributedDB::KvStoreDelegate &kvStoreDelegate); + static DistributedDB::Value Get(DistributedDB::KvStoreDelegate &kvStoreDelegate, const DistributedDB::Key &key); + static DistributedDB::Value Get(DistributedDB::KvStoreSnapshotDelegate &kvStoreSnapshotDelegate, + const DistributedDB::Key &key); + + static std::vector GetEntries( + DistributedDB::KvStoreSnapshotDelegate &kvStoreSnapshotDelegate, const DistributedDB::Key &key); + static std::vector GetEntries(DistributedDB::KvStoreDelegate &kvStoreDelegate, + const DistributedDB::Key &keyPrefix); + + static DistributedDB::KvStoreSnapshotDelegate *RegisterSnapObserver(DistributedDB::KvStoreDelegate *delegate, + DistributedDB::KvStoreObserver *observer); + static DistributedDB::DBStatus RegisterObserver(DistributedDB::KvStoreDelegate *delegate, + DistributedDB::KvStoreObserver *observer); + static DistributedDB::DBStatus UnRegisterObserver(DistributedDB::KvStoreDelegate *delegate, + DistributedDB::KvStoreObserver *observer); + static bool CalculateOpenPerformance(PerformanceData &performanceData); + static bool CalculateInsertPerformance(PerformanceData &performanceData); + static bool CalculateGetPutPerformance(PerformanceData &performanceData); + static bool CalculateUpdatePerformance(PerformanceData &performanceData); + static bool CalculateGetUpdatePerformance(PerformanceData &performanceData); + static bool CalculateUseClearPerformance(PerformanceData &performanceData); + static bool CalculateTransactionPerformance(PerformanceData &performanceData); + static bool CloseAndRelease(DistributedDB::KvStoreDelegateManager *&manager, + DistributedDB::KvStoreDelegate *&delegate); + static bool CloseAndRelease(DistributedDB::KvStoreDelegateManager *&manager, + DistributedDB::KvStoreNbDelegate *&delegate); + static bool VerifyDbRecordCnt(DistributedDB::KvStoreNbDelegate *&delegate, unsigned int recordCnt, + bool isLocal = false); + static bool VerifyRecordsInDb(DistributedDB::KvStoreNbDelegate *&delegate, + std::vector &entriesExpected, + const std::vector &keyPrefix = DistributedDBDataGenerator::KEY_EMPTY, bool isLocal = false); + static bool GetRecordCntByKey(const std::string &dbName, + const std::string &strSql, std::vector &sqlParam, KvOption &option, int &count); + static bool QuerySpecifiedData(const std::string &dbName, const std::string &strSql, + EncrypteAttribute &attribute, int &count); + static bool RepeatCheckAsyncResult(const std::function &inPred, int repeatLimit, + uint32_t repeatInterval); + static bool CompareKey(const DistributedDB::Entry &entry1, const DistributedDB::Entry &entry2); + static void CopyFile(const std::string &srcFile, const std::string &destFile); +}; + +std::string TransferStringToHashHexString(const std::string &origStr); + +int RemoveDatabaseDirectory(const std::string &directory); + +bool VerifyObserverResult(const KvStoreObserverImpl &pObserver, + int changedTimes, ListType type, const std::list &lst, + uint32_t timeout = DistributedDBDataGenerator::DistributedDBConstant::THIRTY_MINUTES); +bool VerifyObserverResult(const KvStoreObserverImpl &pObserver, + int changedTimes, ListType type, const std::vector &vec, + uint32_t timeout = DistributedDBDataGenerator::DistributedDBConstant::THIRTY_MINUTES); +bool VerifyObserverForSchema(const KvStoreObserverImpl &pObserver, + int changedTimes, ListType type, const std::vector &expectEntry, + uint32_t timeout = DistributedDBDataGenerator::DistributedDBConstant::THIRTY_MINUTES); +#endif // DISTRIBUTED_DB_MODULE_TEST_TOOLS_H diff --git a/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_constant.h b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_constant.h new file mode 100644 index 00000000000..4f50a04dc4d --- /dev/null +++ b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_constant.h @@ -0,0 +1,133 @@ +/* + * 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. + */ + +#ifndef DISTRIBUTEDDB_CONSTANT_DEFINE_H +#define DISTRIBUTEDDB_CONSTANT_DEFINE_H + +#include +#include "store_types.h" + +namespace DistributedDBDataGenerator { +const int TEST_ID_1 = 1; +const int TEST_ID_2 = 2; +const int TEST_ID_3 = 3; +const int TEST_ID_4 = 4; +const int TEST_ID_5 = 5; +const int TEST_ID_6 = 6; +const int TEST_ID_7 = 7; +const int TEST_ID_8 = 8; +const int TEST_ID_9 = 9; +const int TEST_ID_10 = 10; +const int TEST_ID_11 = 11; +const int TEST_ID_12 = 12; +const int TEST_ID_13 = 13; +const int TEST_ID_14 = 14; +const int TEST_ID_15 = 15; +const int TEST_ID_16 = 16; +const int TEST_ID_17 = 17; +const int TEST_ID_18 = 18; +const int TEST_ID_19 = 19; +const int TEST_ID_20 = 20; +const int TEST_ID_21 = 21; +const int TEST_ID_22 = 22; +const int TEST_ID_23 = 23; +const int TEST_ID_24 = 24; +const int TEST_ID_25 = 25; +const int TEST_ID_26 = 26; +const int TEST_ID_27 = 27; +const int TEST_ID_28 = 28; +const int TEST_ID_29 = 29; +const int TEST_ID_30 = 30; +const int TEST_ID_31 = 31; +const int TEST_ID_32 = 32; +const int TEST_ID_33 = 33; +const int TEST_ID_34 = 34; +const int TEST_ID_35 = 35; +const int TEST_ID_36 = 36; +const int TEST_ID_37 = 37; +const int TEST_ID_38 = 38; +const int TEST_ID_39 = 39; +const int TEST_ID_40 = 40; +const int TEST_ID_41 = 41; +const int TEST_ID_42 = 42; +const int TEST_ID_43 = 43; +const int TEST_ID_44 = 44; +const int TEST_ID_45 = 45; +const int TEST_ID_46 = 46; +const int TEST_ID_47 = 47; +const int TEST_ID_48 = 48; +const int TEST_ID_49 = 49; +const int TEST_ID_50 = 50; +const int TEST_ID_51 = 51; +const int TEST_ID_52 = 52; + +class DistributedDBConstant { +public: + static const std::string NB_DIRECTOR; // default work dir. + static const std::string NB_DATABASE_NAME; + static const std::string NORMAL_COMMON_SCHEMA; + static const std::string COMPATIBLE_FOR_NORMAL_COMMON_SCHEMA; + static const std::string UNCOMPATIBLE_FOR_NORMAL_COMMON_SCHEMA; + // default kvStoreDelegateManager's config. + static const DistributedDB::KvStoreConfig CONFIG; + static const std::string DB_FILE_DOCUMENT; + static constexpr int UNLOCK_ACCESS = 0; + static constexpr int LOCKED_ACCESS = 1; + static constexpr uint32_t THIRTY_MINUTES = 1800; + static constexpr uint32_t WAIT_UNTIL_CALLBACK_COME = 0; + +// ************************ SYNC PACKET ************************************ + static constexpr int ZERO_PACKET = 0; + static constexpr int ONE_PACKET = 1; + static constexpr int TWO_PACKETS = 2; + static constexpr int THREE_PACKETS = 3; + static constexpr int FOUR_PACKETS = 4; + static constexpr int EIGHT_PACKETS = 8; + static constexpr int FIRST_PACKET = 1; + static constexpr int THIRD_PACKET = 3; + static constexpr int FIFTH_PACKET = 5; + static constexpr int EIGHTH_PACKET = 8; + static constexpr uint32_t THROW_PACKET_CNT_LEN = 168; // the length of data packet is greater than 168 + // the length of registering subscriber packet is greater than 111 + static constexpr uint32_t REGISTER_SUBSCRIBER_PACKET_LEN = 111; + +// ************************ MILLISECOND ************************************ + static const unsigned int THREE_S_TO_MS = 3000; + static const unsigned int FIVE_S_TO_MS = 5000; + static const unsigned int EIGHT_S_TO_MS = 8000; + static const unsigned int NINE_S_TO_MS = 9000; + static const unsigned int TEN_S_TO_MS = 10000; + static const unsigned int SIXTY_S_TO_MS = 60000; + +// ************************ compression ratio ************************** + static const unsigned int COMPRESSION_RATIO_ZERO = 0; + static const unsigned int COMPRESSION_RATIO_TEN = 10; + static const unsigned int COMPRESSION_RATIO_TWENTY = 20; + static const unsigned int COMPRESSION_RATIO_THIRTY = 30; + static const unsigned int COMPRESSION_RATIO_FORTY = 40; + static const unsigned int COMPRESSION_RATIO_FIFTY = 50; + static const unsigned int COMPRESSION_RATIO_SIXTY = 60; + static const unsigned int COMPRESSION_RATIO_SEVENTY = 70; + static const unsigned int COMPRESSION_RATIO_EIGHTY = 80; + static const unsigned int COMPRESSION_RATIO_NINETY = 90; + static const unsigned int COMPRESSION_RATIO_ONE_HUNDRED = 100; + static const unsigned int COMPRESSION_RATIO_ONE_HUNDRED_AND_ONE = 101; + +// ************************ record number ************************** + static const unsigned int THIRTY_THOUSAND_RECORDS = 30000; +}; +} // namespace DistributedDBDataGenerator + +#endif // DISTRIBUTEDDB_CONSTANT_DEFINE_H diff --git a/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_data_generator.h b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_data_generator.h new file mode 100644 index 00000000000..4603d80bbbe --- /dev/null +++ b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_data_generator.h @@ -0,0 +1,567 @@ +/* + * 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. + */ +#ifndef DISTRIBUTED_DB_MODULE_TEST_TYPES_H +#define DISTRIBUTED_DB_MODULE_TEST_TYPES_H + +#include +#include +#include +#include "kv_store_delegate.h" +#include "kv_store_delegate_manager.h" +#include "distributed_test_sysinfo.h" +#include "distributeddb_log_print.h" +#include "distributeddb_constant.h" + +struct EntrySize { + unsigned int keySize = 0; + unsigned int valSize = 0; + void Set(unsigned int keySizeInput, unsigned int valSizeInput) + { + this->keySize = keySizeInput; + this->valSize = valSizeInput; + } +}; + +enum DBType { + UNENCRYPTED_DISK_DB = 0, + ENCRYPTED_DISK_DB, + MEMORY_DB +}; + +struct TimeSamp { + std::vector startTime; + std::vector endTime; + TimeSamp() + { + } +}; + +struct ImagePerSamp { + std::vector firstStep; + std::vector secondStep; + ImagePerSamp() + { + } +}; + +struct PerTimeLength { + std::vector entriesDuration; + std::vector cursorDuration; + std::vector moveNextDuration; + std::vector entryDurationForward; + std::vector movePreviousDuration; + std::vector entryDurationBackup; +}; + +struct Schema { + std::vector version; + std::vector mode; + std::vector define; + std::vector index; +}; +struct LongDefine { + int recordNum; + int recordSize; + char prefix; +}; + +struct NumberSize { + EntrySize entrySize; + int recordsNumber; + bool isRoundBack = false; + NumberSize() : recordsNumber(0) + { + } +}; + +enum class RandType { + ALPHA_NUM, + ALPHA_NUM_UNDERLINE, + SPECIAL, +}; + +// ************************ number class ********************************** +const unsigned int OBSERVER_NUM = 8; +const int BUFFER_COUNT = 5; +const unsigned int NB_OBSERVER_NUM = 4; +const unsigned int NB_OPERATION_NUM = 100; +const unsigned int NB_PREDATA_NUM = 50; +const unsigned int RECORDS_SMALL_CNT = 2; +const unsigned int NO_RECORD = 0; +const unsigned int THREE_RECORDS = 3; +const unsigned int THREE_PERF_DATA = 3; +const unsigned int BATCH_RECORDS = 128; +const static int ONE_RECORD = 1; +const static int TWO_RECORDS = 2; +const static int FOUR_RECORDS = 4; +const static int FIVE_RECORDS = 5; +const static int SIX_RECORDS = 6; +const static int EIGHT_RECORDS = 8; +const static int NINE_RECORDS = 9; +const static int TEN_RECORDS = 10; +const static int SIXTEEN_RECORDS = 16; +const static int TWENTY_RECORDS = 20; +const static int THIRTY_RECORDS = 30; +const static int THIRTYTWO_RECORDS = 32; +const static int FORTY_RECORDS = 40; +const static int FIFTY_RECORDS = 50; +const static int SIXTY_RECORDS = 60; +const static int EIGHTY_RECORDS = 80; +const static int ONE_HUNDRED_RECORDS = 100; +const static int TWO_HUNDREDS_RECORDS = 200; +const static int FIVE_HUNDREDS_RECORDS = 500; +const static int SIX_HUNDREDS_RECORDS = 600; +const static int ONE_THOUSAND_RECORDS = 1000; +const static int TWO_THOUSANDS_RECORDS = 2000; +const static int TWO_FIVE_ZERO_ZERO_RECORDS = 2500; +const static int TWO_FIVE_SIX_ZERO_RECORDS = 2560; +const static int FIVE_THOUSANDS_RECORDS = 5000; +const static int TEN_THOUSAND_RECORDS = 10000; +const static int FIFTEEN_THOUSAND_RECORDS = 15000; +const static int TWENTY_THOUSAND_RECORDS = 20000; +const static int THIRTY_THOUSAND_RECORDS = 30000; +const static int FIFTY_THOUSAND_RECORDS = 50000; +const static int HUNDRED_THOUSAND_RECORDS = 100000; +const static int FOUR_HUNDRED_THOUSAND_RECORDS = 400000; +const static int FIVE_HUNDRED_THOUSAND_RECORDS = 500000; +const static int TWO_FIVE_SIX_RECORDS = 256; +const static int FIRST_RECORD = 1; +const static int SECOND_RECORD = 2; +const static int DATAS_ACCOUNT = 300; +const static int DATA_LEN = 13; +const static int NINE_CNT = 9; +const static int TEN_CNT = 10; +const static unsigned int TWO_DEVICES = 2; +const static unsigned int FOUR_DEVICES = 4; +const static int THIRD_FUNC = 3; +const static int FOURTH_FUNC = 4; +const static int FIFTH_FUNC = 5; +const static int THREE_DBS = 3; +const static int EIGHT_DBS = 8; +const static int TEN_DBS = 10; +const static int ELEVEN_DBS = 11; +const static int TWELVE_DBS = 12; +const static int FIRST_DB = 1; +const static int FIFTH_DB = 5; +const static int TENTH_DB = 10; +const static int ELEVENTH_DB = 11; +const static int TWELFTH_DB = 12; + +// ************************ loop times class ************************** +const unsigned int MOD_NUM = 2; +const unsigned int BIG_MOD_NUM = 3; + +const unsigned int ID_CNT_START = 0; +const unsigned int ID_MIN_CNT = 2; +const unsigned int ID_MEDIUM_CNT = 3; +const unsigned int ID_MAX_CNT = 16; +const unsigned int STORE_CNT = 4; +const unsigned int DIR_CNT_START = 0; +const unsigned int DIR_MAX_CNT = 14; +const static int MANYTINES = 3; +const static int ONE_TIME = 1; +const static int TWO_TIMES = 2; +const static int FIVE_TIMES = 5; +const static int TEN_TIMES = 10; +const static int FIFTY_TIMES = 50; +const static int HUNDRED_TIMES = 100; + +// ************************ time class ************************** +const unsigned int UNIQUE_SECOND = 1; +const unsigned int TWO_SECONDS = 2; +const unsigned int THREE_SECONDS = 3; +const unsigned int FOUR_SECONDS = 4; +const unsigned int FIVE_SECONDS = 5; +const unsigned int SIX_SECONDS = 6; +const unsigned int TEN_SECONDS = 10; +const unsigned int FIFTEEN_SECONDS = 15; +const unsigned int TWENTY_SECONDS = 20; +const unsigned int THIRTY_SECONDS = 30; +const unsigned int FORTY_SECONDS = 40; +const unsigned int SIXTY_SECONDS = 60; +const unsigned int ONE_HUNDRED_SECONDS = 100; +const unsigned int TWO_HUNDREDS_SECONDS = 200; +const unsigned int THREE_HUNDREDS_SECONDS = 300; +const unsigned int FOUR_HUNDREDS_SECONDS = 400; +const unsigned int FIVE_HUNDREDS_SECONDS = 500; +const unsigned int SIX_HUNDREDS_SECONDS = 600; +const unsigned int SEVEN_HUNDREDS_SECONDS = 700; +const unsigned int EIGHT_HUNDREDS_SECONDS = 800; +const unsigned int TEN_HUNDREDS_SECONDS = 1000; +const unsigned int ONE_FIVE_ZERO_ZERO_SECONDS = 1500; +const unsigned int SIXTEEN_HUNDREDS_SECONDS = 1600; +const unsigned int EIGHTEEN_HUNDREDS_SECONDS = 1800; +const unsigned int TWENTY_HUNDREDS_SECONDS = 2000; +const unsigned int THREE_THOUSANDS_SECONDS = 3000; +const unsigned int THREE_SIX_ZERO_ZERO_SECONDS = 3600; +const unsigned int EIGHT_THOUSANDS_SECONDS = 8000; +const unsigned int TEN_THOUSANDS_SECONDS = 10000; +const unsigned int WAIT_FOR_LONG_TIME = 15000; +const unsigned int WAIT_FOR_FIFTY_MS = 50000; +const unsigned int WAIT_FOR_LAST_SYNC = 500000; +const unsigned int WAIT_FOR_TWO_HUNDREDS_MS = 200000; +const int FIFTY_MILI_SECONDS = 50; +const int HUNDRED_MILLI_SECONDS = 100; +const static int MILLSECONDS_PER_SECOND = 1000; + +// ************************ length of key class ************************** +const static int KEY_SIX_BYTE = 6; +const static int KEY_EIGHT_BYTE = 8; +const static int KEY_THIRTYTWO_BYTE = 32; +const static int KEY_SIXTYFOUR_BYTE = 64; +const static int KEY_TWO_FIVE_SIX_BYTE = 256; +const static int KEY_ONE_K_BYTE = 1024; +const static int KEY_ONE_HUNDRED_BYTE = 100; + +// ************************ length of value class ************************** +const unsigned int SMALL_VALUE_SIZE = 2; +const unsigned int ONE_K_LONG_STRING = 1024; // 1K +const unsigned int TWO_K_LONG_STRING = 2048; // 2K +const unsigned int TWO_POINT_FOUR_LONG = 2400; // 2.4K +const unsigned int THREE_K_LONG_STRING = 3072; // 3K +const unsigned int FOUR_K_LONG_STRING = 4096; // 4K +const unsigned int ONE_M_LONG_STRING = 1048576; // 1M +const unsigned int TWO_M_LONG_STRING = 2097152; // 2M +const unsigned int FOUR_M_LONG_STRING = 4194304; // 4M +const unsigned int TEN_M_LONG_STRING = 10485760; // 10M +const static int VALUE_SIX_BYTE = 6; +const static int VALUE_ONE_HUNDRED_BYTE = 100; +const static int VALUE_FIVE_HUNDRED_BYTE = 500; +const static int VALUE_ONE_K_BYTE = 1024; +const static int VALUE_HUNDRED_K_BYTE = 102400; +const static int VALUE_TWENTY_K_BYTE = 20480; +const static int VALUE_TWO_POINT_FOUR_K_BYTE = 2458; +const static int PASSWD_BYTE = 129; + +// ************************ bool class ************************************* +const bool IS_LOCAL_ONLY = true; +const bool IS_NOT_LOCAL_ONLY = false; +const bool IS_NEED_CREATE = true; +const bool IS_NOT_NEED_CREATE = false; + +// ************************ range verify class ***************************** +const static int CHANGED_ZERO_TIME = 0; +const static int CHANGED_ONE_TIME = 1; +const static int CHANGED_TWO_TIMES = 2; +const static int CHANGED_THREE_TIMES = 3; +const static int CHANGED_ONE_HUNDRED_TIMES = 100; +const static int CHANGED_TWO_HUNDRED_TIMES = 200; +const static int CHANGED_TWO_FIVE_SIX_TIMES = 256; +const static int CHANGED_ONE_THOUSAND_TIMES = 1000; +const static int CHANGED_TEN_THOUSAND_TIMES = 10000; +const unsigned int RECORDS_NUM_START = 1; +const unsigned int RECORDS_NUM_END = 128; +const unsigned int DEFAULT_START = 1; +const unsigned int DEFAULT_ANOTHER_START = 11; +const unsigned int OBSERVER_CNT_START = 0; +const unsigned int OBSERVER_CNT_END = 8; +const unsigned int NB_OBSERVER_CNT_START = 0; +const unsigned int NB_OBSERVER_CNT_END = 4; +const unsigned int NB_OPERATION_CNT_START = 0; +const unsigned int NB_OPERATION_CNT_END = 5; + +const int LOCAL_OPER_CNT = 2; +const int NATIVE_OPER_CNT = 6; +const static int OPER_CNT_START = 0; +const static int OPER_CNT_END = 10; +const static int MODE_RAND_MIN = 0; +const static int MODE_RAND_MAX = 2; + +// ************************ USED FOR THREAD ******************************** +const unsigned int SINGLE_THREAD_NUM = 2; +const unsigned int CHAR_SPAN_MIN = 0; +const unsigned int CHAR_SPAN_MAX = 255; + +// ************************ USED FOR INDEX ********************************* +const int INDEX_ZEROTH = 0; +const int INDEX_FIRST = 1; +const int INDEX_SECOND = 2; +const int INDEX_THIRD = 3; +const int INDEX_FORTH = 4; +const int INDEX_FIFTH = 5; +const int INDEX_SIXTH = 6; +const int INDEX_SEVENTH = 7; +const int INDEX_EIGHTTH = 8; +const int INDEX_NINTH = 9; +const int INDEX_TENTH = 10; +const int INDEX_NINE_NINE_NINTH = 999; +const int INDEX_FIVE_THOUSANDS = 5000; +const int INDEX_TEN_THOUSANDS = 10000; +const int INDEX_FIFTEEN_THOUSANDS = 15000; + +// ************************ OTHER CLASS ************************************ +const int TABLE_MAX = 60; + +const static int ENCRYPT_COUNT = 100; + +const static int EVEN_NUMBER = 2; + +const int VALUE_FIVE_HUNDRED = 500; +const int VALUE_SUM = VALUE_FIVE_HUNDRED + VALUE_FIVE_HUNDRED; +const int VALUE_CHANGE1_FIRST = 400; +const int VALUE_CHANGE1_SECOND = VALUE_SUM - VALUE_CHANGE1_FIRST; +const int VALUE_CHANGE2_FIRST = 700; +const int VALUE_CHANGE2_SECOND = VALUE_SUM - VALUE_CHANGE2_FIRST; + +const static std::string MULTIDB = "/multi_ver/value_storage.db"; +const static std::string KVMULTIDB = "/multi_ver/multi_ver_data.db"; +const static std::string SYNC_MULTI_VER_QUERY_SQL = "select count(*) from version_data;"; +const static std::string DATABASE_INFOR_FILE = "/single_ver/main/gen_natural_store.db"; +const static std::string SYNC_VALUE_SLICE_QUERY_SQL = "select count(*) from data;"; +const static std::string QUERY_SQL = "select count(*) from version_data where key = ?;"; +const static std::string MULTI_KEY_QUERY_SQL = "select count(*) from version_data where key = ? or key = ?;"; + +typedef std::chrono::time_point microClock_type; + +// place some const values for testcases in namespace. +namespace DistributedDBDataGenerator { +const std::string STORE_ID = ""; +const std::string STORE_ID_1 = "STORE_ID_1"; +const std::string STORE_ID_2 = "STORE_ID_2"; +const std::string STORE_ID_3 = "STORE_ID_3"; +const std::string STORE_ID_4 = "STORE_ID_4"; +const std::string STORE_ID_5 = "STORE_ID_5"; +const std::string STORE_ID_6 = "STORE_ID_6"; +const std::string STORE_ID_7 = "STORE_ID_7"; +const std::string STORE_ID_8 = "STORE_ID_8"; +const std::string STORE_ID_9 = "STORE_ID_9"; +const std::string STORE_ID_10 = "STORE_ID_10"; +const std::string JSON_SCHEMA_STORE_ID_11 = "JSON_SCHEMA_STORE_ID_11"; +const std::string STORE_ID_PERFORM = "STORE_ID_PERFORM"; +const static std::string STORE_ID_SYNC_1 = "SYNC1"; +const static std::string STORE_ID_SYNC_2 = "SYNC2"; +const static std::string STORE_ID_SYNC_3 = "SYNC3"; +const static std::string STORE_ID_SYNC_4 = "SYNC4"; +const static std::string STORE_ID_SYNC_5 = "SYNC5"; +const static std::string STORE_ID_SYNC_6 = "SYNC6"; +const static std::string STORE_ID_SYNC_7 = "SYNC7"; +const static std::string STORE_ID_SYNC_8 = "SYNC8"; +const static std::string STORE_ID_SYNC_9 = "SYNC9"; +const static std::string STORE_ID_SYNC_10 = "SYNC10"; + +const std::string APP_ID = "APP_ID"; +const std::string APP_ID_1 = "APP_ID_1"; +const std::string APP_ID_2 = "APP_ID_2"; +const std::string APP_ID_3 = "APP_ID_3"; +const std::string APP_ID_4 = "APP_ID_4"; +const std::string APP_ID_5 = "APP_ID_5"; +const std::string APP_ID_6 = "APP_ID_6"; +const std::string APP_ID_PERFORM = "APP_ID_PERFORM"; +const std::string APP_ID_NB_1 = "APP_ID_NB_1"; +const std::string APP_ID_NB_2 = "APP_ID_NB_2"; +const std::string APP_ID_LOCAL_1 = "APP_ID_LOCAL_1"; + +const std::string USER_ID = "USER_ID"; +const std::string USER_ID_1 = "USER_ID_1"; +const std::string USER_ID_2 = "USER_ID_2"; +const std::string USER_ID_3 = "USER_ID_3"; +const std::string USER_ID_4 = "USER_ID_4"; +const std::string USER_ID_5 = "USER_ID_5"; +const std::string USER_ID_6 = "USER_ID_6"; +const std::string USER_ID_PERFORM = "USER_ID_PERFORM"; + +const std::vector K1_HASH_KEY = { 0xA2, 0xAB, 0x19, 0x59, 0xC1, 0xC3, 0xBF, 0xA2, 0x95, 0xB0, 0xFC, 0x90, + 0x19, 0x93, 0x78, 0x27, 0x2D, 0xB7, 0x6B, 0x45}; +const std::vector K2_HASH_KEY = { 0xBF, 0xEB, 0x73, 0x4D, 0x2E, 0xB5, 0xD0, 0x91, 0x51, 0x45, 0xC1, 0x86, + 0x12, 0x48, 0x75, 0x7D, 0x4F, 0xD3, 0x2B, 0xC2 }; +const std::vector K3_HASH_KEY = { 0xB5, 0x32, 0xA5, 0x44, 0x0D, 0xD8, 0x42, 0x2D, 0x9D, 0x5F, 0x8D, 0x99, + 0x9B, 0x31, 0x06, 0x87, 0xD4, 0xA2, 0xFE, 0xD9 }; +const std::vector K4_HASH_KEY = { 0x5E, 0xF8, 0x76, 0x6D, 0xE9, 0x35, 0x32, 0x44, 0x24, 0xB5, 0x63, 0xAA, + 0x3E, 0xB0, 0xC7, 0x46, 0x6B, 0x29, 0x3C, 0x94 }; +const std::vector NULL_HASH_KEY = {}; +const DistributedDB::Key KEY_1 = { 'k', '1' }; +const DistributedDB::Key KEY_2 = { 'k', '2' }; +const DistributedDB::Key KEY_3 = { 'k', '3' }; +const DistributedDB::Key KEY_4 = { 'k', '4' }; +const DistributedDB::Key KEY_5 = { 'k', '5' }; +const DistributedDB::Key KEY_6 = { 'k', '6' }; +const DistributedDB::Key KEY_7 = { 'k', '7' }; +const DistributedDB::Key KEY_8 = { 'k', '8' }; +const DistributedDB::Key KEY_9 = { 'k', '9' }; +const DistributedDB::Key KEY_10 = { 'k', '1', '0' }; +const DistributedDB::Key KEY_6_BYTE = { 'k', 'k', 'k', 'k', 'k', '1' }; +const DistributedDB::Key KEY_A_1 = { 'a', 'b', 'c' }; +const DistributedDB::Key KEY_A_2 = { 'a', 'b', 'c', 'd', 'a', 's', 'd' }; +const DistributedDB::Key KEY_A_3 = { 'a', 'b', 'c', 'd', 's' }; +const DistributedDB::Key KEY_BIG_1 = { 'b', 'i', 'g', '1' }; + +const std::vector NULL_K1 = {}; +const DistributedDB::Key KEY_EMPTY = { }; +const DistributedDB::Key KEY_K = { 'k' }; +const DistributedDB::Key KEY_A = { 'a' }; +const DistributedDB::Key KEY_E = { 'k', 'e' }; +const DistributedDB::Key OK_KEY_1 = { 'o', 'k' }; + +const DistributedDB::Value VALUE_1 = { 'v', '1' }; +const DistributedDB::Value VALUE_2 = { 'v', '2' }; +const DistributedDB::Value VALUE_3 = { 'v', '3' }; +const DistributedDB::Value VALUE_4 = { 'v', '4' }; +const DistributedDB::Value VALUE_5 = { 'v', '5' }; +const DistributedDB::Value VALUE_6 = { 'v', '6' }; +const DistributedDB::Value VALUE_7 = { 'v', '7' }; +const DistributedDB::Value VALUE_8 = { 'v', '8' }; +const DistributedDB::Value VALUE_9 = { 'v', '9' }; +const DistributedDB::Value VALUE_10 = { 'v', '1', '0' }; +const DistributedDB::Value VALUE_A_1 = { 'a', '1' }; +const DistributedDB::Value VALUE_A_2 = { 'a', '2' }; +const DistributedDB::Value VALUE_A_3 = { 'a', '3' }; +const DistributedDB::Value VALUE_EMPTY = { }; +const DistributedDB::Value OK_VALUE_1 = { 'o', 'k' }; + +const std::vector IMAGE_KEY_PRE = {'a', 'l', 'b', 'u', 'm', '_'}; +const std::vector IMAGE_FILE_KEY_PRE = {'f', 'i', 'l', 'e', '_'}; +const std::string IMAGE_VALUE_PRE = {"\"_id\":23,\"local_media_id\":0," \ + "\"_data\":\"/storage/emulated/0/Pictures/.Gallery2/recycle/GF6DA7BR\"," \ + "\"_size\":427460,\"date_added\":1518606965,\"date_modified\":1519460678," \ + "\"mime_type\":\"image/jpeg\",\"title\":\"MagazinePic-05-2.3.001-bigpicture_05_4\"," \ + "\"description\":\"\",\"_display_name\":\"MagazinePic-05-2.3.001-bigpicture_05_4.jpg\"," \ + "\"orientation\":0,\"latitude\":0,\"longitude\":0,\"datetaken\":1514792938000," \ + "\"bucket_id\":771419238,\"bucket_display_name\":\"MagazineUnlock\",\"duration\":0," \ + "\"resolution\":\"1440x2560\",\"media_type\":1,\"storage_id\":65537,\"width\":1440," \ + "\"height\":2560,\"is_hdr\":0,\"is_hw_privacy\":0,\"hw_voice_offset\":0,\"is_hw_favorite\":0," \ + "\"hw_image_refocus\":0,\"is_hw_burst\":0,\"hw_rectify_offset\":0,\"contenturi\":\"\"," \ + "\"hash\":\"e46cf1bb4773421fbded2e2583fe7130\",\"special_file_list\":0,\"special_file_type\":0," \ + "\"special_file_offset\":0,\"relative_bucket_id\":1793967153,\"albumId\":\"default-album-3\",\"fileType\":1," \ + "\"fileId\":0,\"videoThumbId\":0,\"thumbId\":0,\"lcdThumbId\":0,\"thumbType\":3,\"localThumbPath\":\"\"," \ + "\"localBigThumbPath\":\"\",\"expand\":\"\",\"showDateToken\":1514792938000,\"visit_time\":0," \ + "\"last_update_time\":1519461225861,\"source\":\"\",\"geo_code\":0,\"location_key\":104473884060," \ + "\"story_id\":0,\"story_cluster_state\":\"todo\",\"search_data_status\":0,\"category_id\":-2," \ + "\"portrait_id\":0,\"portrait_cluster_state\":\"todo\",\"dirty\":0,\"recycleFlag\":2," \ + "\"recycledTime\":1519550100614,\"sourcePath\":\"/storage/emulated/0/MagazineUnlock/MagazinePic\"," \ + "\"sourceFileName\":\"MagazinePic-05-2.3.001-bigpict\",\"garbage\":0,\"uniqueId\":0,\"localKey\":\"\"," \ + "\"picture_score\":99,\"cam_perception\":\"\",\"cam_exif_flag\":1,\"sync_status\":0," \ + "\"album_name\":\".MagazineUnlock\",\"ocr_status\":0"}; + +const DistributedDB::Key KEY_SEARCH_0 = KEY_A; +const DistributedDB::Key KEY_SEARCH = { 'a', 'b' }; +const DistributedDB::Key KEY_SEARCH_2 = { 'a', 'b', 'c', 'd', 'e' }; +const std::vector K_SEARCH_3 = { 'b', 'i', 'g'}; +const DistributedDB::Key KEY_SEARCH_3 = { 'b', 'i', 'g'}; +const DistributedDB::Key KEY_SEARCH_4 = { 'k' }; +const std::vector K_SEARCH_5 = { 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k' }; +const DistributedDB::Key KEY_SEARCH_6 = { 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', '6' }; +const DistributedDB::Key PERFORMANCEKEY = { 'p', 'e', 'r' }; +const DistributedDB::Key KEY_CONS_1 = { 'c', 'o', 'n', 's', '1' }; +const DistributedDB::Key KEY_CONS_2 = { 'c', 'o', 'n', 's', '2' }; +const DistributedDB::Key KEY_BATCH_CONS_1 = { 'r', 'e', 's', 'u', 'l', 't', '1' }; +const DistributedDB::Key KEY_BATCH_CONS_2 = { 'r', 'e', 's', 'u', 'l', 't', '2' }; +const DistributedDB::Key KEY_BATCH_CONS_3 = { 'r', 'e', 's', 'u', 'l', 't', '3' }; +const std::vector KEYS_1 = { KEY_1, KEY_2 }; +const DistributedDB::Entry ENTRY_1 = { .key = KEY_1, .value = VALUE_1 }; +const DistributedDB::Entry ENTRY_2 = { .key = KEY_2, .value = VALUE_2 }; +const DistributedDB::Entry ENTRY_3 = { .key = KEY_3, .value = VALUE_3 }; +const DistributedDB::Entry ENTRY_4 = { .key = KEY_4, .value = VALUE_4 }; +const DistributedDB::Entry ENTRY_5 = { .key = KEY_5, .value = VALUE_5 }; +const DistributedDB::Entry ENTRY_6 = { .key = KEY_6, .value = VALUE_6 }; +const DistributedDB::Entry ENTRY_7 = { .key = KEY_7, .value = VALUE_7 }; +const DistributedDB::Entry ENTRY_8 = { .key = KEY_8, .value = VALUE_8 }; +const DistributedDB::Entry ENTRY_9 = { .key = KEY_9, .value = VALUE_9 }; +const DistributedDB::Entry ENTRY_10 = { .key = KEY_10, .value = VALUE_10 }; +const DistributedDB::Entry ENTRY_1_2 = { .key = KEY_1, .value = VALUE_2 }; +const DistributedDB::Entry ENTRY_2_3 = { .key = KEY_2, .value = VALUE_3 }; +const DistributedDB::Entry ENTRY_3_1 = { .key = KEY_3, .value = VALUE_1 }; +const DistributedDB::Entry ENTRY_4_5 = { .key = KEY_4, .value = VALUE_5 }; +const DistributedDB::Entry ENTRY_5_6 = { .key = KEY_5, .value = VALUE_6 }; +const DistributedDB::Entry ENTRY_2_1 = { .key = KEY_2, .value = VALUE_1 }; +const DistributedDB::Entry ENTRY_1_3 = { .key = KEY_1, .value = VALUE_3 }; +const DistributedDB::Entry ENTRY_2_4 = { .key = KEY_2, .value = VALUE_4 }; +const DistributedDB::Entry ENTRY_1_4 = { .key = KEY_1, .value = VALUE_4 }; +const DistributedDB::Entry ENTRY_3_4 = { .key = KEY_3, .value = VALUE_4 }; +const DistributedDB::Entry ENTRY_1_NULL = { .key = KEY_1, .value = VALUE_EMPTY }; +const DistributedDB::Entry ENTRY_2_NULL = { .key = KEY_2, .value = VALUE_EMPTY }; +const DistributedDB::Entry ENTRY_3_NULL = { .key = KEY_3, .value = VALUE_EMPTY }; +const DistributedDB::Entry ENTRY_NULL_1 = { .key = KEY_EMPTY, .value = VALUE_2 }; +const DistributedDB::Entry ENTRY_NULL_2 = { .key = KEY_EMPTY, .value = VALUE_3 }; +const DistributedDB::Entry ENTRY_NULL_3 = { .key = KEY_EMPTY, .value = VALUE_1 }; +const DistributedDB::Entry ENTRY_NULL = { .key = KEY_EMPTY, .value = VALUE_EMPTY }; +const DistributedDB::Entry ENTRY_A_1 = { .key = KEY_A_1, .value = VALUE_A_1 }; +const DistributedDB::Entry ENTRY_A_2 = { .key = KEY_A_2, .value = VALUE_A_2 }; +const DistributedDB::Entry ENTRY_A_3 = { .key = KEY_A_3, .value = VALUE_A_3 }; +const DistributedDB::Entry ENTRY_A_1_2 = { .key = KEY_A_1, .value = VALUE_A_2 }; +const DistributedDB::Entry ENTRY_A_2_3 = { .key = KEY_A_2, .value = VALUE_A_3 }; +const DistributedDB::Entry ENTRY_A_3_1 = { .key = KEY_A_3, .value = VALUE_A_1 }; + +const DistributedDB::CipherPassword NULL_PASSWD; +const std::vector NULL_PASSWD_VECTOR = {}; +const std::vector PASSWD_VECTOR_1 = {'P', 'a', 's', 's', 'w', 'o', 'r', 'd', '@', '1', '2', '3'}; +const std::vector PASSWD_VECTOR_2 = {'P', 'a', 's', 's', 'w', 'o', 'r', 'd', '@', 'c', 'o', 'm'}; +const std::vector FILE_PASSWD_VECTOR_1 = {'F', 'i', 'l', 'e', 'p', 'a', 's', 's', 'w', 'd', '1'}; +const std::vector FILE_PASSWD_VECTOR_2 = {'F', 'i', 'l', 'e', 'p', 'a', 's', 's', 'w', 'd', '2'}; + +void GenerateRecord(unsigned int keyNo, DistributedDB::Entry &entry, std::vector keyPrifix = { 'k' }); + +void GenerateCharSet(std::vector &charSet); + +void GenerateAlphaNumUnderlineCharSet(std::vector &charSet); + +void GenerateSpecialCharSet(std::vector &charSet); + +void GenerateFixedLenRandString(unsigned int neededLen, RandType randType, std::string &genString); + +void GenerateRandRecord(DistributedDB::Entry &entry, EntrySize &entrySize, unsigned int keyNo); + +void GenerateRecords(unsigned int recordNum, unsigned int start, + std::vector &allKeys, std::vector &entriesBatch, + std::vector keyPrifix = { 'k' }); +void GenerateMaxBigRecord(unsigned int keyNo, DistributedDB::Entry &entry, + const std::vector &keyPrefix, unsigned int num); +bool GenerateMaxBigRecords(unsigned int recordNum, unsigned int start, + std::vector &allKeys, std::vector &entriesBatch); + +void GenerateTenThousandRecords(unsigned int recordNum, unsigned int start, + std::vector &allKeys, std::vector &entriesBatch); + +void GenerateNormalAsciiRecords(DistributedDB::Entry &entry); + +void GenerateFullAsciiRecords(DistributedDB::Entry &entry); + +void GenerateBiggistKeyRecords(DistributedDB::Entry &entry); + +DistributedDB::Entry GenerateFixedLenKVRecord(unsigned int serialNo, + unsigned int keyLen, uint8_t keyFilledChr, unsigned int valueLen, uint8_t valueFilledChr); + +void GenerateFixedRecords(std::vector &entries, std::vector &allKeys, + int recordNum, unsigned int keySize, unsigned int valSize); + +void GenerateOneRecordForImage(int entryNo, const EntrySize &entrySize, + const std::vector &keyPrefix, const std::vector &val, DistributedDB::Entry &entry); +void GenerateRecordsForImage(std::vector &entries, EntrySize &entrySize, + int num, std::vector keyPrefix = {'k'}, std::vector val = {'v'}); + +void GenerateAppointPrefixAndSizeRecord(int recordNo, const EntrySize &entrySize, + const std::vector &keyPrefix, const std::vector &valPrefix, DistributedDB::Entry &entry); +void GenerateAppointPrefixAndSizeRecords(std::vector &entries, const EntrySize &entrySize, + int num, const std::vector &keyPrefix = {'k'}, const std::vector &valPrefix = {'v'}); +void GenerateAppointPrefixAndSizeRecords(std::vector &entries, int startpoint, + const NumberSize param, const std::vector &keyPrefix = {'k'}, + const std::vector &valPrefix = {'v'}); + +int GetRandInt(const int randMin, const int randMax); + +void GenerateFixedLenRandRecords(std::vector &entries, std::vector &allKeys, + int recordNum, unsigned int keySize, unsigned int valSize); +std::vector GenerateFixedLenRandRecords(std::vector &allKeys, + int recordNum, const EntrySize &entrySize, const std::vector &keyPrefix = {'k'}, + const std::vector &valPrefix = {'v'}); + +const std::string GetDbType(const int type); +void GenerateRandomRecords(std::vector &entries, EntrySize &entrySize, int num); +void GetLongSchemaDefine(LongDefine ¶m, std::string &longDefine); +const std::string SpliceToSchema(const std::string &version, const std::string &mode, + const std::string &define, const std::string &index = "", const std::string &skipSize = ""); +std::vector GetValidSchema(Schema &validSchema, bool hasIndex); +std::map> GetInvalidSchema(Schema &invalidSchema, Schema &validSchema, bool hasIndex); +} // DistributedDBDataGenerator +#endif // DISTRIBUTED_DB_MODULE_TEST_TYPES_H diff --git a/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_log_print.h b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_log_print.h new file mode 100644 index 00000000000..7f8a56d2a25 --- /dev/null +++ b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_log_print.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef DISTRIBUTED_DB_LOG_PRINT_H +#define DISTRIBUTED_DB_LOG_PRINT_H + +#if defined _WIN32 + #ifndef RUNNING_ON_WIN + #define RUNNING_ON_WIN + #endif +#else + #ifndef RUNNING_ON_LINUX + #define RUNNING_ON_LINUX + #endif +#endif + +#include "hilog/log.h" + +static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, 0xD001630, "DistributedDB[TEST]" }; +#define MST_LOG(fmt, ...) \ + OHOS::HiviewDFX::HiLog::Info(LOG_LABEL, "%s: " fmt, __FUNCTION__, ##__VA_ARGS__) +#endif diff --git a/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_nb_test_tools.h b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_nb_test_tools.h new file mode 100644 index 00000000000..b75b70866c8 --- /dev/null +++ b/frameworks/libs/distributeddb/test/moduletest/common/distributeddb/include/distributeddb_nb_test_tools.h @@ -0,0 +1,356 @@ +/* + * 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. + */ +#ifndef DISTRIBUTEDDB_NB_TEST_TOOLS_H +#define DISTRIBUTEDDB_NB_TEST_TOOLS_H + +#include "kv_store_delegate.h" +#include "kv_store_delegate_manager.h" +#include "kv_store_nb_delegate.h" +#include "kv_store_observer.h" +#ifdef RELEASE_MODE_V2 +#include "query.h" +#endif +#include "distributeddb_data_generator.h" +#include "distributed_test_tools.h" + +struct DBParameters { + std::string storeId; + std::string appId; + std::string userId; + DBParameters(std::string storeIdStr, std::string appIdStr, std::string userIdStr) + : storeId(storeIdStr), appId(appIdStr), userId(userIdStr) + { + } +}; + +struct Option { + bool createIfNecessary = true; + bool isMemoryDb = false; // true represents using a memory database + bool isEncryptedDb = false; // whether need encrypt + DistributedDB::CipherType cipher = DistributedDB::CipherType::DEFAULT; // cipher type + std::vector passwd; // cipher password +#ifdef RELEASE_MODE_V2 + std::string schema; + bool createDirByStoreIdOnly = false; +#endif // endif of RELEASE_MODE_V2 +#ifdef RELEASE_MODE_V3 + DistributedDB::SecurityOption secOption; + DistributedDB::KvStoreObserver *observer = nullptr; + DistributedDB::Key key; + unsigned int mode = 0; + int conflictType = 0; + DistributedDB::KvStoreNbConflictNotifier notifier = nullptr; + int conflictResolvePolicy = DistributedDB::LAST_WIN; + bool isNeedIntegrityCheck = false; + bool isNeedRmCorruptedDb = false; + bool isNeedCompressOnSync = false; + uint8_t compressionRate = 100; // default compression rate 100%, that means not compressing +#endif // end of RELEASE_MODE_V3 + Option(bool createIfNecessary, bool isMemoryDb, bool isEncryptedDb, DistributedDB::CipherType cipher, + std::vector passwd) + : createIfNecessary(createIfNecessary), isMemoryDb(isMemoryDb), isEncryptedDb(isEncryptedDb), + cipher(cipher), passwd(passwd) + { + } +#ifdef RELEASE_MODE_V3 + Option(bool createIfNecessary, bool isMemoryDb, bool isEncryptedDb, const DistributedDB::CipherType &cipher, + const std::vector &passwd, const DistributedDB::SecurityOption &secOption, + DistributedDB::KvStoreObserver *observer, const DistributedDB::KvStoreNbConflictNotifier ¬ifier) + : createIfNecessary(createIfNecessary), isMemoryDb(isMemoryDb), isEncryptedDb(isEncryptedDb), + cipher(cipher), passwd(passwd), secOption(secOption), observer(observer), notifier(notifier) + { + } +#endif // endif of RELEASE_MODE_V3 + Option() + {} +}; + +struct ConflictData { + DistributedDB::KvStoreNbConflictType type; + DistributedDB::Key key; + DistributedDB::Value oldValue; + DistributedDB::Value newValue; + bool oldIsDeleted = false; + bool newIsDeleted = false; + bool oldIsNative = false; + bool newIsNative = false; +}; + +enum EntryType { + INSERT_LOCAL = 0, + INSERT_NATIVE = 1, + DELETE_LOCAL = 2, + DELETE_NATIVE = 3, + UPDATE_LOCAL = 4, + UPDATE_NATIVE = 5 +}; + +enum class ReadOrWriteTag { + READ = 0, + WRITE = 1, + DELETE = 2, + REGISTER = 3 +}; + +const static DBParameters g_dbParameter1(DistributedDBDataGenerator::STORE_ID_1, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); +const static DBParameters g_dbParameter2(DistributedDBDataGenerator::STORE_ID_2, + DistributedDBDataGenerator::APP_ID_2, DistributedDBDataGenerator::USER_ID_2); +const static DBParameters g_dbParameter3(DistributedDBDataGenerator::STORE_ID_3, + DistributedDBDataGenerator::APP_ID_3, DistributedDBDataGenerator::USER_ID_3); +const static DBParameters g_dbParameter4(DistributedDBDataGenerator::STORE_ID_4, + DistributedDBDataGenerator::APP_ID_4, DistributedDBDataGenerator::USER_ID_4); +const static DBParameters g_dbParameter5(DistributedDBDataGenerator::STORE_ID_5, + DistributedDBDataGenerator::APP_ID_5, DistributedDBDataGenerator::USER_ID_5); +const static DBParameters g_dbParameter6(DistributedDBDataGenerator::STORE_ID_6, + DistributedDBDataGenerator::APP_ID_6, DistributedDBDataGenerator::USER_ID_6); +const static DBParameters g_dbParameter2_1(DistributedDBDataGenerator::STORE_ID_2, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); +const static DBParameters DB_PARAMETER_0_1(DistributedDBDataGenerator::STORE_ID, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_1); +const static DBParameters g_dbParameter1_2_1(DistributedDBDataGenerator::STORE_ID_1, + DistributedDBDataGenerator::APP_ID_2, DistributedDBDataGenerator::USER_ID_1); +const static DBParameters g_dbParameter2_1_2(DistributedDBDataGenerator::STORE_ID_2, + DistributedDBDataGenerator::APP_ID_1, DistributedDBDataGenerator::USER_ID_2); +const static DBParameters g_dbParameter3_2_1(DistributedDBDataGenerator::STORE_ID_3, + DistributedDBDataGenerator::APP_ID_2, DistributedDBDataGenerator::USER_ID_1); +const static DBParameters g_dbParameter4_2_2(DistributedDBDataGenerator::STORE_ID_4, + DistributedDBDataGenerator::APP_ID_2, DistributedDBDataGenerator::USER_ID_2); +const static Option g_createDiskUnencrypted(true, false, false, DistributedDB::CipherType::DEFAULT, + DistributedDBDataGenerator::NULL_PASSWD_VECTOR); +const static Option g_createDiskEncrypted(true, false, true, DistributedDB::CipherType::DEFAULT, + DistributedDBDataGenerator::PASSWD_VECTOR_1); +const static Option g_ncreateDiskUnencrypted(false, false, false, DistributedDB::CipherType::DEFAULT, + DistributedDBDataGenerator::NULL_PASSWD_VECTOR); +const static Option g_ncreateDiskEncrypted(false, false, true, DistributedDB::CipherType::DEFAULT, + DistributedDBDataGenerator::PASSWD_VECTOR_1); +const static Option g_createMemUnencrypted(true, true, false, DistributedDB::CipherType::DEFAULT, + DistributedDBDataGenerator::NULL_PASSWD_VECTOR); +static Option g_option = g_createDiskUnencrypted; +const std::vector