diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index a76fddfde304eb5067aa7e0e386707e83fcbdf79..648f36643af9043975f033adb2689131176c165a 100755 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -7,4 +7,57 @@ * **FUZZ**:Pass/Fail/NA * **ACTS**:Pass/Fail/NA * **DCTS**:Pass/Fail/NA -* **DST**:Pass/Fail/NA \ No newline at end of file +* **DST**:Pass/Fail/NA + +### 稳定性排查: +- [ ] 【规则】禁止在锁内向其他进程发送IPC(进程间通信); +- [ ] 【规则】禁止将捕获**栈变量引用**的lambda函数**异步到其他线程执行**; +- [ ] 【规则】禁止传递this指针至其他模块或线程(特别是eventhandler任务); +- [ ] 【规则】禁止存储string的c_str()方法获取到的指针; +- [ ] 【规则】成员变量进行赋值或创建需要排查并发; +- [ ] 【规则】谨慎在未经拷贝的情况下使用外部传入的string、C字符串; +- [ ] 【规则】map\vector\list\set等stl模板类使用时需要排查并发; +- [ ] 【规则】谨慎考虑加锁范围,尽可能的小范围加锁; +- [ ] 【规则】在IPC通信中谨慎使用同步通信方式; +- [ ] 【规则】禁止将外部传入的裸指针在内部直接构造智能指针; +- [ ] 【规则】禁止多个独立创建的智能指针管理同一地址; +- [ ] 【规则】禁止在析构函数中抛异步任务; +- [ ] 【规则】禁止js对象在非js线程(例如在IPC线程)创建、使用或销毁; +- [ ] 【规则】禁止在对外接口中未经判空直接使用外部传入的指针; +- [ ] 【规则】监听回调要确保,回调触发和取消注册并发时无生命周期问题; +- [ ] 【规则】遍历容器进行删除或插入时注意迭代器失效问题; + +### 日志打印排查: +- [ ] 【规则】禁止打印内存地址,如:%p; +- [ ] 【规则】禁止打印密钥、文件路径、数据库名称、udidhash、设备名称、账号id等敏感信息; +- [ ] 【规则】禁止不作匿名化直接打印udid/networkid/uuid/ip/mac等敏感信息; +- [ ] 【规则】非必要不要在循环内打印日志,防止日志超限; + +### 安全编码自检: +- [ ] 【内存管理】内存申请前必须对内存大小进行合法性校验; +- [ ] 【内存管理】内存申请后必须判空,判断内存申请是否成功; +- [ ] 【内存管理】分配和释放内存(or fd等资源)的函数需要成对出现; +- [ ] 【内存管理】申请内存后异常退出前需要及时进行内存释放; +- [ ] 【内存管理】禁止使用realloc、alloca函数; +- [ ] 【内存管理】strdup使用需要注意内存释放; +- [ ] 【内存管理】正则表达式构造后需释放资源,regcomp/regexec与regfree必须成对使用; +- [ ] 【内存管理】realpath使用时如果resolved_path为NULL需要注意内存释放; +- [ ] 【外部输入校验】外部传入的路径要做规范化校验,对路径中的.、..、../等特殊字符严格校验; +- [ ] 【外部输入校验】按TLV格式解析时需校验解析长度值是否小于等于缓冲区实际值,并校验是否符合业务数据范围; +- [ ] 【外部输入校验】解析数据后拷贝时需校验源buffer实际缓冲区大小,避免越界读写; +- [ ] 【外部输入校验】使用外部输入作为循环变量时,需要校验循环变量上限是否合理,防止出现超大循环; +- [ ] 【外部输入校验】禁止直接使用外部输入作为数组下标,防止出现内存越界; +- [ ] 【敏感信息】堆、栈中保存密钥、口令(包括加密后的变量)变量使用完后必须显式覆盖或清空; +- [ ] 【加密算法】禁止使用私有加密算法或不安全加密算法; +- [ ] 【变量初始化】指针变量、表示资源描述符的变量、bool变量必须赋初值; +- [ ] 【指针】IPC流程中ReadCString、ReadRawData、readParcelable等结果必须判空; +- [ ] 【整数运算】整数之间运算时必须严格检查,确保不会出现溢出、反转、除0; +- [ ] 【整数运算】禁止对有符号整数进行位操作符运算; +- [ ] 【循环变量】循环次数如果受外部数据控制,需要检验其合法性; +- [ ] 【循环变量】循环变量和中止条件的数据类型定义保持一致; +- [ ] 【安全函数】安全函数必须检查返回值,并进行正确处理; +- [ ] 【安全函数】安全函数目标缓冲区入参大小与目标缓冲区实际大小必须一致; +- [ ] 【安全函数】禁止封装或者自定义安全函数; +- [ ] 【常见问题】修改单个函数时,如果涉及新增异常返回分支,必须排查是否需要释放锁、内存、fd等资源; +- [ ] 【常见问题】函数返回值需与函数签名相同,参数定义需在同一范畴(不能定义bool,返回int32_t),或同一枚举类型; +- [ ] 【常见问题】格式化打印类型需匹配,例如:int32_t %d; uint32_t %u; long %ld; unsigned long %lu; long long PRId64;
unsigned long long PRIu64; diff --git a/bundle.json b/bundle.json index b1a8472dba866d162bf31c03216e699c14086ab1..e80707c82fe8af9d23e8d659598542202d669afc 100644 --- a/bundle.json +++ b/bundle.json @@ -81,6 +81,7 @@ "napi", "netmanager_base", "os_account", + "qos_manager", "relational_store", "resource_management", "safwk", diff --git a/cfi_blocklist.txt b/cfi_blocklist.txt new file mode 100644 index 0000000000000000000000000000000000000000..89d302fdc73f6ae208a1956ed722e5016e548e3e --- /dev/null +++ b/cfi_blocklist.txt @@ -0,0 +1,16 @@ +# Copyright (C) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[cfi] +src:*third_party/googletest/googlemock/include/gmock/* +src:*third_party/googletest/googletest/include/gtest/* \ No newline at end of file diff --git a/datamgr_service.gni b/datamgr_service.gni index da3e7a494d5e4474f2f5e30387cab6d3a8465cfd..7b327ccea5c69ef499da3dbd5991d35f004b2ed9 100644 --- a/datamgr_service.gni +++ b/datamgr_service.gni @@ -38,6 +38,8 @@ udmf_path = "//foundation/distributeddatamgr/udmf" dataobject_path = "//foundation/distributeddatamgr/data_object" +datamgr_service_path = "//foundation/distributeddatamgr/datamgr_service" + declare_args() { datamgr_service_power = true if (!defined(global_parts_info.power_manager_native_powermgr_client) || diff --git a/services/distributeddataservice/adapter/account/test/BUILD.gn b/services/distributeddataservice/adapter/account/test/BUILD.gn index 9986137426b1f9c53b81c2b29cbc4caa239409db..39c09ee550b4fef1467c7acf6d978b25fc53b72d 100755 --- a/services/distributeddataservice/adapter/account/test/BUILD.gn +++ b/services/distributeddataservice/adapter/account/test/BUILD.gn @@ -12,7 +12,7 @@ # limitations under the License. import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### ohos_unittest("AccountDelegateTest") { diff --git a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp index b9b0078f6d5f718b9d66135bb3c7ea8d28d5c678..817824732148815ffdf85897b8b23e59a58eb449 100644 --- a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp +++ b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp @@ -263,8 +263,9 @@ void DeviceManagerAdapter::OnChanged(const DmDeviceInfo &info) ZLOGE("get device info fail"); return; } - ZLOGI("[OnChanged] uuid:%{public}s, name:%{public}s, type:%{public}d", - KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType); + ZLOGI("[OnChanged] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d osType:%{public}d", + KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, + static_cast(dvInfo.authForm), dvInfo.osType); } void DeviceManagerAdapter::OnReady(const DmDeviceInfo &info) @@ -275,8 +276,9 @@ void DeviceManagerAdapter::OnReady(const DmDeviceInfo &info) return; } readyDevices_.InsertOrAssign(dvInfo.uuid, std::make_pair(DeviceState::DEVICE_ONREADY, dvInfo)); - ZLOGI("[OnReady] uuid:%{public}s, name:%{public}s, type:%{public}d", - KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType); + ZLOGI("[OnReady] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d, osType:%{public}d", + KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, + static_cast(dvInfo.authForm), dvInfo.osType); auto task = [this, dvInfo]() { observers_.ForEachCopies([&dvInfo](const auto &key, auto &value) { if (value != nullptr) { @@ -326,6 +328,11 @@ void DeviceManagerAdapter::SaveDeviceInfo(const DeviceInfo &dvInfo, const Device deviceInfos_.Set(dvInfo.uuid, dvInfo); deviceInfos_.Set(dvInfo.udid, dvInfo); readyDevices_.InsertOrAssign(dvInfo.uuid, std::make_pair(DeviceState::DEVICE_ONLINE, dvInfo)); + if (dvInfo.osType != OH_OS_TYPE) { + otherDeviceInfos_.Set(dvInfo.networkId, dvInfo); + otherDeviceInfos_.Set(dvInfo.uuid, dvInfo); + otherDeviceInfos_.Set(dvInfo.udid, dvInfo); + } break; } case DeviceChangeType::DEVICE_OFFLINE: { @@ -333,6 +340,11 @@ void DeviceManagerAdapter::SaveDeviceInfo(const DeviceInfo &dvInfo, const Device deviceInfos_.Delete(dvInfo.uuid); deviceInfos_.Delete(dvInfo.udid); readyDevices_.Erase(dvInfo.uuid); + if (dvInfo.osType != OH_OS_TYPE) { + otherDeviceInfos_.Delete(dvInfo.networkId); + otherDeviceInfos_.Delete(dvInfo.uuid); + otherDeviceInfos_.Delete(dvInfo.udid); + } break; } default: { @@ -409,7 +421,7 @@ bool DeviceManagerAdapter::IsOHOSType(const std::string &id) int32_t DeviceManagerAdapter::GetAuthType(const std::string &id) { DeviceInfo dvInfo; - if (!deviceInfos_.Get(id, dvInfo)) { + if (!otherDeviceInfos_.Get(id, dvInfo) && !deviceInfos_.Get(id, dvInfo)) { InitDeviceInfo(); deviceInfos_.Get(id, dvInfo); } diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp index 81b9f74e4cf492bf50fd8eb15cdeade7abb8343c..f4df6deecc68bd90d9e58361b9bff9fd9c29ab2b 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp @@ -207,7 +207,8 @@ std::shared_ptr SoftBusAdapter::GetConnect(const PipeInfo &pipeIn uint32_t qosType) { std::shared_ptr conn; - connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType](const auto &key, + std::string networkId = DmAdapter::GetInstance().ToNetworkID(deviceId.deviceId); + connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType, &networkId](const auto &key, std::vector> &connects) -> bool { for (auto &connect : connects) { if (connect == nullptr) { @@ -218,7 +219,7 @@ std::shared_ptr SoftBusAdapter::GetConnect(const PipeInfo &pipeIn return true; } } - auto connect = std::make_shared(pipeInfo, deviceId, qosType); + auto connect = std::make_shared(pipeInfo, deviceId, networkId, qosType); connects.emplace_back(connect); conn = connect; return true; @@ -354,23 +355,24 @@ std::string SoftBusAdapter::DelConnect(int32_t socket, bool isForce) if (!isForce && DmAdapter::GetInstance().IsOHOSType(deviceId)) { return false; } + std::string networkId; for (auto iter = connects.begin(); iter != connects.end();) { if (*iter != nullptr && **iter == socket) { name += deviceId; name += " "; + networkId = (*iter)->GetNetworkId(); iter = connects.erase(iter); } else { iter++; } } - if (connects.empty()) { - closedConnect.insert(deviceId); + if (connects.empty() && !networkId.empty()) { + closedConnect.insert(std::move(networkId)); return true; } return false; }); - for (const auto &deviceId : closedConnect) { - auto networkId = DmAdapter::GetInstance().GetDeviceInfo(deviceId).networkId; + for (const auto &networkId : closedConnect) { ConnectManager::GetInstance()->OnSessionClose(networkId); } return name; diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp index f4451869fc0dd6eb479961ce84b27b9aaed1e225..23c8c79167f5735c46c620a3d592cda106bede2b 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp @@ -28,8 +28,8 @@ namespace OHOS::AppDistributedKv { using namespace OHOS::DistributedKv; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; using Context = DistributedData::CommunicatorContext; -SoftBusClient::SoftBusClient(const PipeInfo& pipeInfo, const DeviceId& deviceId, uint32_t type) - : type_(type), pipe_(pipeInfo), device_(deviceId) +SoftBusClient::SoftBusClient(const PipeInfo& pipeInfo, const DeviceId& deviceId, const std::string& networkId, + uint32_t type) : type_(type), pipe_(pipeInfo), device_(deviceId), networkId_(networkId) { mtu_ = DEFAULT_MTU_SIZE; } @@ -125,8 +125,7 @@ int32_t SoftBusClient::CreateSocket() const SocketInfo socketInfo; std::string peerName = pipe_.pipeId; socketInfo.peerName = const_cast(peerName.c_str()); - std::string networkId = DmAdapter::GetInstance().ToNetworkID(device_.deviceId); - socketInfo.peerNetworkId = const_cast(networkId.c_str()); + socketInfo.peerNetworkId = const_cast(networkId_.c_str()); std::string clientName = pipe_.pipeId; socketInfo.name = const_cast(clientName.c_str()); std::string pkgName = "ohos.distributeddata"; @@ -177,7 +176,7 @@ int32_t SoftBusClient::Open(int32_t socket, uint32_t type, const ISocketListener UpdateBindInfo(socket, mtu, status, async); ZLOGI("open %{public}s, session:%{public}s success, socket:%{public}d", KvStoreUtils::ToBeAnonymous(device_.deviceId).c_str(), pipe_.pipeId.c_str(), socket_); - ConnectManager::GetInstance()->OnSessionOpen(DmAdapter::GetInstance().GetDeviceInfo(device_.deviceId).networkId); + ConnectManager::GetInstance()->OnSessionOpen(networkId_); return status; } @@ -256,4 +255,9 @@ Status SoftBusClient::ReuseConnect(const ISocketListener *listener) int32_t status = Open(socket, QOS_REUSE, listener, false); return status == SOFTBUS_OK ? Status::SUCCESS : Status::NETWORK_ERROR; } + +const std::string& SoftBusClient::GetNetworkId() const +{ + return networkId_; +} } // namespace OHOS::AppDistributedKv \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.h b/services/distributeddataservice/adapter/communicator/src/softbus_client.h index 67709bf9007d755123e27b8bfc25033dae199c50..a0196c94f3203f1475bb84c3c5c111e4dbc6ee31 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.h +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.h @@ -33,7 +33,8 @@ public: QOS_REUSE, QOS_BUTT }; - SoftBusClient(const PipeInfo &pipeInfo, const DeviceId &deviceId, uint32_t type = QOS_HML); + SoftBusClient(const PipeInfo &pipeInfo, const DeviceId &deviceId, const std::string& networkId, + uint32_t type = QOS_HML); ~SoftBusClient(); using Time = std::chrono::steady_clock::time_point; @@ -51,6 +52,7 @@ public: void UpdateExpireTime(bool async = true); int32_t GetSoftBusError(); Status ReuseConnect(const ISocketListener *listener); + const std::string& GetNetworkId() const; private: int32_t Open(int32_t socket, uint32_t type, const ISocketListener *listener, bool async = true); @@ -95,6 +97,7 @@ private: int32_t socket_ = INVALID_SOCKET_ID; int32_t bindState_ = -1; int32_t softBusError_ = 0; + const std::string networkId_; }; } // namespace OHOS::AppDistributedKv diff --git a/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/BUILD.gn index cf89c446402bb35ba4990b5aeeb1aa178e8026db..5e5a3489d5438eaa917185bec97fa6ec43cf30bd 100755 --- a/services/distributeddataservice/adapter/communicator/test/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/BUILD.gn @@ -188,11 +188,31 @@ ohos_unittest("ProcessCommunicatorImplTest") { ohos_unittest("SoftbusAdapterStandardTest") { module_out_path = module_output_path - sources = [ "unittest/softbus_adapter_standard_test.cpp" ] + sources = [ + "../src/app_pipe_handler.cpp", + "../src/app_pipe_handler.h", + "../src/app_pipe_mgr.cpp", + "../src/app_pipe_mgr.h", + "../src/ark_communication_provider.cpp", + "../src/communication_provider.cpp", + "../src/communication_provider_impl.cpp", + "../src/communicator_context.cpp", + "../src/data_buffer.cpp", + "../src/device_manager_adapter.cpp", + "../src/process_communicator_impl.cpp", + "../src/softbus_adapter.h", + "../src/softbus_client.cpp", + "../src/softbus_client.h", + "unittest/softbus_adapter_standard_test.cpp", + ] + include_dirs = [ "${data_service_path}/adapter/include/communicator", "${data_service_path}/framework/include/dfx", "../src", + "../../include/communicator", + "../../include/utils", + "${data_service_path}/framework/include/utils", ] external_deps = [ "access_token:libaccesstoken_sdk", @@ -203,14 +223,19 @@ ohos_unittest("SoftbusAdapterStandardTest") { "dsoftbus:softbus_client", "hilog:libhilog", "ipc:ipc_core", + "json:nlohmann_json_static", + "kv_store:datamgr_common", "kv_store:distributeddata_inner", + "kv_store:distributeddb", ] cflags = [ "-Dprivate=public", "-Dprotected=public", ] deps = [ - "${data_service_path}/adapter/communicator:distributeddata_communicator", + "${data_service_path}/adapter/utils:distributeddata_utils", + "${data_service_path}/framework:distributeddatasvcfwk", + "../../dfx:distributeddata_dfx", ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp index 8999b2ea1ba94968594463d6553ae9c38e788cb2..f5c4cc30cc37bfaf066e57ce6dbbd0408689a40a 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp @@ -22,6 +22,8 @@ #include "communication_provider.h" #include "device_manager_adapter_mock.h" #include "process_communicator_impl.h" +#include "softbus_adapter.h" +#include "softbus_error_code.h" using namespace testing; using namespace testing::ext; @@ -31,12 +33,13 @@ using OnDeviceChange = DistributedDB::OnDeviceChange; using OnDataReceive = DistributedDB::OnDataReceive; using OnSendAble = DistributedDB::OnSendAble; using DeviceInfos = DistributedDB::DeviceInfos; -using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo; +using DeviceInfoo = OHOS::AppDistributedKv::DeviceInfo; using UserInfo = DistributedDB::UserInfo; namespace OHOS::AppDistributedKv { class MockCommunicationProvider : public CommunicationProvider { public: + ~MockCommunicationProvider() = default; static MockCommunicationProvider& Init() { static MockCommunicationProvider instance; @@ -79,7 +82,7 @@ public: static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); - void TearDown() {} + void TearDown(); ProcessCommunicatorImpl* communicator_; MockCommunicationProvider* mockProvider; @@ -114,6 +117,11 @@ void ProcessCommunicatorImplTest::SetUp(void) mockProvider = &MockCommunicationProvider::Init(); } +void ProcessCommunicatorImplTest::TearDown(void) +{ + mockProvider = nullptr; +} + void ProcessCommunicatorImplTest::SetUpTestCase(void) { deviceManagerAdapterMock = std::make_shared(); @@ -123,6 +131,7 @@ void ProcessCommunicatorImplTest::SetUpTestCase(void) void ProcessCommunicatorImplTest::TearDownTestCase() { deviceManagerAdapterMock = nullptr; + BDeviceManagerAdapter::deviceManagerAdapter = nullptr; } /** @@ -285,9 +294,9 @@ HWTEST_F(ProcessCommunicatorImplTest, GetRemoteOnlineDeviceInfosList, TestSize.L auto remoteDevInfos = communicator_->GetRemoteOnlineDeviceInfosList(); EXPECT_EQ(remoteDevInfos.empty(), true); - DeviceInfo deviceInfo; + DeviceInfoo deviceInfo; deviceInfo.uuid = "GetRemoteOnlineDeviceInfosList"; - std::vector devInfos; + std::vector devInfos; devInfos.push_back(deviceInfo); EXPECT_CALL(*deviceManagerAdapterMock, GetRemoteDevices()).WillRepeatedly(Return(devInfos)); remoteDevInfos = communicator_->GetRemoteOnlineDeviceInfosList(); @@ -304,7 +313,7 @@ HWTEST_F(ProcessCommunicatorImplTest, GetRemoteOnlineDeviceInfosList, TestSize.L HWTEST_F(ProcessCommunicatorImplTest, OnMessage, TestSize.Level0) { ASSERT_NE(communicator_, nullptr); - DeviceInfo deviceInfo; + DeviceInfoo deviceInfo; deviceInfo.uuid = "OnMessageTest"; uint8_t data[] = {0x10, 0x20, 0x30, 0x40, 0x50}; uint8_t *ptr = data; @@ -329,7 +338,7 @@ HWTEST_F(ProcessCommunicatorImplTest, OnMessage, TestSize.Level0) HWTEST_F(ProcessCommunicatorImplTest, OnDeviceChanged, TestSize.Level0) { ASSERT_NE(communicator_, nullptr); - DeviceInfo deviceInfo; + DeviceInfoo deviceInfo; deviceInfo.uuid = "cloudDeviceUuid"; EXPECT_NO_FATAL_FAILURE(communicator_->OnDeviceChanged(deviceInfo, DeviceChangeType::DEVICE_ONREADY)); EXPECT_NO_FATAL_FAILURE(communicator_->OnDeviceChanged(deviceInfo, DeviceChangeType::DEVICE_OFFLINE)); @@ -351,7 +360,7 @@ HWTEST_F(ProcessCommunicatorImplTest, OnDeviceChanged, TestSize.Level0) HWTEST_F(ProcessCommunicatorImplTest, OnSessionReady, TestSize.Level0) { ASSERT_NE(communicator_, nullptr); - DeviceInfo deviceInfo; + DeviceInfoo deviceInfo; deviceInfo.uuid = "OnSessionReadyTest"; communicator_->sessionListener_ = nullptr; EXPECT_NO_FATAL_FAILURE(communicator_->OnSessionReady(deviceInfo, 1)); @@ -448,4 +457,50 @@ HWTEST_F(ProcessCommunicatorImplTest, GetDataUserInfo, TestSize.Level0) userInfos.push_back(user3); status = communicator_->GetDataUserInfo(ptr, totalLen, label, userInfos); EXPECT_EQ(status, DistributedDB::OK); +} + +/** +* @tc.name: ReuseConnect01 +* @tc.desc: reuse connect +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin + */ +HWTEST_F(ProcessCommunicatorImplTest, ReuseConnect01, TestSize.Level0) +{ + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); + PipeInfo pipe; + pipe.pipeId = "appId"; + pipe.userId = "groupId"; + DeviceId device = {"DeviceId"}; + auto status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device); + EXPECT_EQ(status, Status::NOT_SUPPORT); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(testing::_)).WillOnce(testing::Return(true)) + .WillRepeatedly(testing::Return(true)); + status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device); + EXPECT_EQ(status, Status::NETWORK_ERROR); +} + +/** +* @tc.name: CloseSession +* @tc.desc: close session +* @tc.type: FUNC +* @tc.author: nhj +*/ +HWTEST_F(ProcessCommunicatorImplTest, CloseSession, TestSize.Level1) +{ + std::string networkId = "networkId"; + auto flag = SoftBusAdapter::GetInstance(); + ASSERT_NE(flag, nullptr); + std::string uuid = "CloseSessionTest"; + EXPECT_CALL(*deviceManagerAdapterMock, GetUuidByNetworkId(testing::_)).WillOnce(testing::Return(uuid)) + .WillRepeatedly(testing::Return(uuid)); + std::shared_ptr conn = nullptr; + std::vector> clients; + clients.emplace_back(conn); + auto result = SoftBusAdapter::GetInstance()->connects_.Insert(uuid, clients); + EXPECT_EQ(result, true); + auto status = SoftBusAdapter::GetInstance()->CloseSession(networkId); + SoftBusAdapter::GetInstance()->connects_.Clear(); + EXPECT_EQ(status, true); } \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp index b4b4e92b347d0fce0a8f3b042970b066882d2896..842b4777781ad6790ac9be831e7dd4e66cb5d72a 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp @@ -12,14 +12,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#define LOG_TAG "SoftbusAdapterStandardTest" - #include "app_device_change_listener.h" #include #include "gtest/gtest.h" #include -#include "log_print.h" #include "softbus_adapter.h" +#include "softbus_adapter_standard.cpp" +#include "softbus_error_code.h" #include "types.h" #include #include @@ -27,6 +26,7 @@ namespace OHOS::Test { using namespace testing::ext; using namespace OHOS::AppDistributedKv; +using namespace OHOS::DistributedData; using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo; class AppDataChangeListenerImpl : public AppDataChangeListener { struct ServerSocketInfo { @@ -41,9 +41,7 @@ class AppDataChangeListenerImpl : public AppDataChangeListener { void AppDataChangeListenerImpl::OnMessage(const OHOS::AppDistributedKv::DeviceInfo &info, const uint8_t *ptr, const int size, const struct PipeInfo &id) const -{ - ZLOGI("data %{public}s %s", info.deviceName.c_str(), ptr); -} +{} class SoftbusAdapterStandardTest : public testing::Test { public: @@ -65,6 +63,7 @@ protected: */ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange, TestSize.Level0) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(nullptr, {}); EXPECT_EQ(status, Status::INVALID_ARGUMENT); } @@ -78,12 +77,16 @@ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange, TestSize.Level0) */ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange01, TestSize.Level0) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo appId; appId.pipeId = "appId"; appId.userId = "groupId"; const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId); EXPECT_EQ(status, Status::SUCCESS); + status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId); + delete dataListener; + EXPECT_EQ(status, Status::ERROR); } /** @@ -95,11 +98,13 @@ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange01, TestSize.Level0) */ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange02, TestSize.Level0) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo appId; appId.pipeId = ""; appId.userId = "groupId"; const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId); + delete dataListener; EXPECT_EQ(status, Status::SUCCESS); } @@ -111,7 +116,6 @@ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange02, TestSize.Level0) */ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange03, TestSize.Level1) { - ZLOGI("begin."); PipeInfo appId; appId.pipeId = "appId06"; appId.userId = "groupId06"; @@ -139,6 +143,9 @@ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange, TestSize.Level0) const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); auto status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId); EXPECT_EQ(status, Status::SUCCESS); + status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId); + delete dataListener; + EXPECT_EQ(status, Status::ERROR); } /** @@ -150,14 +157,35 @@ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange, TestSize.Level0) */ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange01, TestSize.Level0) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo appId; appId.pipeId = ""; appId.userId = "groupId"; const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); auto status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId); + delete dataListener; EXPECT_EQ(status, Status::SUCCESS); } +/** +* @tc.name: GetExpireTime +* @tc.desc: GetExpireTime Test +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin + */ +HWTEST_F(SoftbusAdapterStandardTest, GetExpireTime, TestSize.Level0) +{ + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); + PipeInfo appId; + appId.pipeId = "appId"; + appId.userId = "groupId"; + DeviceId id = {"DeviceId"}; + std::shared_ptr conn = std::make_shared( + appId, id, "", SoftBusClient::QoSType::QOS_HML); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->GetExpireTime(conn)); +} + /** * @tc.name: SendData * @tc.desc: parse sent data @@ -166,6 +194,7 @@ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange01, TestSize.Level0) */ HWTEST_F(SoftbusAdapterStandardTest, SendData, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); PipeInfo id; id.pipeId = "appId"; @@ -209,6 +238,189 @@ HWTEST_F(SoftbusAdapterStandardTest, SendData01, TestSize.Level1) delete dataListener; } +/** +* @tc.name: StartCloseSessionTask +* @tc.desc: StartCloseSessionTask tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, StartCloseSessionTask, TestSize.Level1) +{ + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); + std::shared_ptr conn = nullptr; + std::vector> clients; + clients.emplace_back(conn); + auto status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId01", clients); + EXPECT_EQ(status, true); + SoftBusAdapter::GetInstance()->connects_.Clear(); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->StartCloseSessionTask("deviceId02")); +} + +/** +* @tc.name: OnClientShutdown +* @tc.desc: DelConnect tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, OnClientShutdown, TestSize.Level1) +{ + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); + PipeInfo appId; + appId.pipeId = "appId"; + appId.userId = "groupId"; + DeviceId id = {"DeviceId"}; + std::shared_ptr conn1 = std::make_shared( + appId, id, "", SoftBusClient::QoSType::QOS_HML); + std::shared_ptr conn2 = nullptr; + std::vector> clients; + clients.emplace_back(conn1); + clients.emplace_back(conn2); + auto status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId01", clients); + EXPECT_EQ(status, true); + status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId02", {}); + EXPECT_EQ(status, true); + auto name = SoftBusAdapter::GetInstance()->OnClientShutdown(-1, true); + EXPECT_EQ(name, "deviceId01 "); + name = SoftBusAdapter::GetInstance()->OnClientShutdown(-1, false); + EXPECT_EQ(name, ""); + name = SoftBusAdapter::GetInstance()->OnClientShutdown(1, true); + SoftBusAdapter::GetInstance()->connects_.Clear(); + EXPECT_EQ(name, ""); +} + +/** +* @tc.name: NotifyDataListeners +* @tc.desc: NotifyDataListeners tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, NotifyDataListeners, TestSize.Level1) +{ + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); + PipeInfo appId; + appId.pipeId = "appId"; + appId.userId = "groupId"; + std::string content = "Helloworlds"; + const uint8_t *t = reinterpret_cast(content.c_str()); + SoftBusAdapter::GetInstance()->dataChangeListeners_.Clear(); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->NotifyDataListeners(t, 1, "deviceId", appId)); + const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); + SoftBusAdapter::GetInstance()->dataChangeListeners_.Insert(appId.pipeId, dataListener); + delete dataListener; + SoftBusAdapter::GetInstance()->dataChangeListeners_.Clear(); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->NotifyDataListeners(t, 1, "deviceId", appId)); +} + +/** +* @tc.name: ListenBroadcastMsg +* @tc.desc: ListenBroadcastMsg tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, ListenBroadcastMsg, TestSize.Level1) +{ + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); + SoftBusAdapter::GetInstance()->onBroadcast_= nullptr; + PipeInfo appId; + appId.pipeId = "appId"; + appId.userId = "groupId"; + auto result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, nullptr); + EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_INVALID_PARAM); + + auto listener = [](const std::string &message, const LevelInfo &info) {}; + result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, listener); + EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_INVALID_PARAM); + result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, listener); + EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_ALREADY_EXISTED); +} + +/** +* @tc.name: OnBroadcast +* @tc.desc: OnBroadcast tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, OnBroadcast, TestSize.Level1) +{ + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); + DeviceId id = {"DeviceId"}; + LevelInfo level; + level.dynamic = 1; + level.statics = 1; + level.switches = 1; + level.switchesLen = 1; + EXPECT_NE(SoftBusAdapter::GetInstance()->onBroadcast_, nullptr); + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(id, level)); + SoftBusAdapter::GetInstance()->onBroadcast_ = nullptr; + EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(id, level)); +} + +/** +* @tc.name: OnClientSocketChanged +* @tc.desc: OnClientSocketChanged tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, OnClientSocketChanged, TestSize.Level1) +{ + QosTV qosTv; + qosTv.qos = QosType::QOS_TYPE_MIN_BW; + qosTv.value = 1; + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 1)); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 0)); + qosTv.qos = QosType::QOS_TYPE_MAX_WAIT_TIMEOUT; + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 0)); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, nullptr, 0)); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_NOT_SATISFIED, nullptr, 0)); +} + +/** +* @tc.name: OnServerBytesReceived +* @tc.desc: OnServerBytesReceived tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, OnServerBytesReceived, TestSize.Level1) +{ + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); + PeerSocketInfo info; + info.name = strdup(""); + info.networkId = strdup("peertest01"); + info.pkgName = strdup("ohos.kv.test"); + info.dataType = TransDataType::DATA_TYPE_MESSAGE; + AppDistributedKv::SoftBusAdapter::ServerSocketInfo serinfo; + auto result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, serinfo); + EXPECT_EQ(result, false); + char str[] = "Hello"; + const void* data = static_cast(str); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(1, data, 10)); + SoftBusAdapter::GetInstance()->OnBind(1, info); + result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, serinfo); + EXPECT_EQ(result, true); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(1, data, 10)); + info.name = strdup("name"); + SoftBusAdapter::GetInstance()->OnBind(2, info); + result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(2, serinfo); + EXPECT_EQ(result, true); + EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(2, data, 10)); +} + +/** +* @tc.name: GetPipeId +* @tc.desc: GetPipeId tests +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(SoftbusAdapterStandardTest, GetPipeId, TestSize.Level1) +{ + std::string names = "GetPipeId"; + auto name = AppDataListenerWrap::GetPipeId(names); + EXPECT_EQ(name, names); + names = "test01_GetPipeId"; + name = AppDataListenerWrap::GetPipeId(names); + EXPECT_EQ(name, "test01"); +} + /** * @tc.name: GetMtuSize * @tc.desc: get size @@ -217,6 +429,7 @@ HWTEST_F(SoftbusAdapterStandardTest, SendData01, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, GetMtuSize, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); PipeInfo id; id.pipeId = "appId"; @@ -238,6 +451,7 @@ HWTEST_F(SoftbusAdapterStandardTest, GetMtuSize, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, GetTimeout, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); PipeInfo id; id.pipeId = "appId01"; @@ -258,6 +472,7 @@ HWTEST_F(SoftbusAdapterStandardTest, GetTimeout, TestSize.Level1) */ HWTEST_F(SoftbusAdapterStandardTest, IsSameStartedOnPeer, TestSize.Level1) { + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); PipeInfo id; id.pipeId = "appId01"; id.userId = "groupId01"; @@ -289,6 +504,23 @@ HWTEST_F(SoftbusAdapterStandardTest, ReuseConnect, TestSize.Level1) delete dataListener; } +/** +* @tc.name: ReuseConnect01 +* @tc.desc: reuse connect +* @tc.type: FUNC +* @tc.author: wangbin +*/ +HWTEST_F(SoftbusAdapterStandardTest, ReuseConnect01, TestSize.Level1) +{ + ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); + PipeInfo pipe; + pipe.pipeId = "appId"; + pipe.userId = "groupId"; + DeviceId device = {"DeviceId"}; + auto status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device); + EXPECT_EQ(status, Status::NOT_SUPPORT); +} + /** * @tc.name: GetConnect * @tc.desc: get connect @@ -416,6 +648,6 @@ HWTEST_F(SoftbusAdapterStandardTest, GetPeerSocketInfo01, TestSize.Level1) auto flag = SoftBusAdapter::GetInstance(); ASSERT_NE(flag, nullptr); auto status = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, info); - EXPECT_EQ(status, false); + EXPECT_EQ(status, true); } } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp index 3ba198442597f4c79adeaf845e4b802a0910dff3..3f1d713deb0fc7b2b05b72ae2cde2ac687dd6375 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp @@ -46,7 +46,7 @@ void SoftbusClientTest::SetUpTestCase(void) pipeInfo.pipeId = "pipeId"; pipeInfo.userId = "userId"; DeviceId id = {"DeviceId"}; - client = std::make_shared(pipeInfo, id); + client = std::make_shared(pipeInfo, id, ""); } void SoftbusClientTest::TearDownTestCase(void) diff --git a/services/distributeddataservice/adapter/dfx/test/BUILD.gn b/services/distributeddataservice/adapter/dfx/test/BUILD.gn index 78a3fa45b61c20bd967c6e9e912f88d87d399501..67f11fddb9b0cbfe3ecc0de756c135f609152872 100755 --- a/services/distributeddataservice/adapter/dfx/test/BUILD.gn +++ b/services/distributeddataservice/adapter/dfx/test/BUILD.gn @@ -36,6 +36,7 @@ ohos_unittest("DistributeddataDfxMSTTest") { external_deps = [ "c_utils:utils", "datamgr_service:distributeddatasvcfwk", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", @@ -43,11 +44,7 @@ ohos_unittest("DistributeddataDfxMSTTest") { "openssl:libcrypto_shared", ] ldflags = [ "-Wl,--exclude-libs,ALL" ] - deps = [ - "${data_service_path}/adapter/dfx:distributeddata_dfx", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", - ] + deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx" ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } @@ -77,6 +74,7 @@ ohos_unittest("DistributeddataDfxUTTest") { external_deps = [ "c_utils:utils", "datamgr_service:distributeddatasvcfwk", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", @@ -87,8 +85,6 @@ ohos_unittest("DistributeddataDfxUTTest") { deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx", "${data_service_path}/adapter/utils:distributeddata_utils", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } diff --git a/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h b/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h index a50783ae1d148c07b41d3a1286ddf56959fdef71..53135966b3566c5e059880aa4ceb1c7ca0283e84 100644 --- a/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h +++ b/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h @@ -103,6 +103,7 @@ private: const DmDeviceInfo cloudDmInfo; ConcurrentMap observers_ {}; LRUBucket deviceInfos_ {64}; + LRUBucket otherDeviceInfos_ {64}; static constexpr size_t TIME_TASK_CAPACITY = 50; static constexpr int32_t SYNC_TIMEOUT = 60 * 1000; // ms static constexpr int32_t OH_OS_TYPE = 10; diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp index 0372dc5b6d436b84d32075d9d81f714c7ceadcc2..192c32cb6b64126a102e150449a1f5de3457d68b 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp +++ b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp @@ -40,6 +40,10 @@ NetworkDelegate::NetworkType NetworkDelegateDefaultImpl::GetNetworkType(bool ret return NetworkType::NONE; } +void NetworkDelegateDefaultImpl::BindExecutor(std::shared_ptr executors) +{ +} + bool NetworkDelegateDefaultImpl::Init() { static NetworkDelegateDefaultImpl delegate; diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h index db00f8d752eef652288de9391e65764ac8d9588a..b3ddd1a17d745adba678be83928e4d038a2a49ff 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h +++ b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h @@ -25,7 +25,7 @@ public: bool IsNetworkAvailable() override; void RegOnNetworkChange() override; NetworkType GetNetworkType(bool retrieve = false) override; - + void BindExecutor(std::shared_ptr executors) override; private: NetworkDelegateDefaultImpl(); ~NetworkDelegateDefaultImpl(); diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp index 9389f8dcfbb4d6653f245cf95d52a37935523722..5f6d25db0d70b67be96e8117ea9c8e762fcdb5fb 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp +++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp @@ -114,22 +114,42 @@ NetworkDelegateNormalImpl::~NetworkDelegateNormalImpl() void NetworkDelegateNormalImpl::RegOnNetworkChange() { - static std::atomic_bool flag = false; - if (flag.exchange(true)) { - ZLOGW("run only one"); - return; + if (executors_ != nullptr) { + executors_->Execute(GetTask(0)); } - sptr observer = new (std::nothrow) NetConnCallbackObserver(*this); - if (observer == nullptr) { - ZLOGE("new operator error.observer is nullptr"); - flag.store(false); - return; - } - auto nRet = NetConnClient::GetInstance().RegisterNetConnCallback(observer); - if (nRet != NETMANAGER_SUCCESS) { +} + +void NetworkDelegateNormalImpl::BindExecutor(std::shared_ptr executors) +{ + executors_ = std::move(executors); +} + +ExecutorPool::Task NetworkDelegateNormalImpl::GetTask(uint32_t retry) +{ + return [this, retry] { + static std::atomic_bool flag = false; + if (flag.exchange(true)) { + ZLOGW("run only one"); + return; + } + sptr observer = new (std::nothrow) NetConnCallbackObserver(*this); + if (observer == nullptr) { + ZLOGE("new operator error.observer is nullptr"); + flag.store(false); + return; + } + auto nRet = NetConnClient::GetInstance().RegisterNetConnCallback(observer); + if (nRet == NETMANAGER_SUCCESS) { + return; + } ZLOGE("RegisterNetConnCallback failed, ret = %{public}d", nRet); flag.store(false); - } + if (retry + 1 >= MAX_RETRY_TIME) { + ZLOGE("fail to register subscriber!"); + return; + } + executors_->Schedule(std::chrono::seconds(RETRY_WAIT_TIME_S), GetTask(retry + 1)); + }; } bool NetworkDelegateNormalImpl::IsNetworkAvailable() diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h index c403f8497f46b36df8062e7d7248b5488a28bdea..f4c62051d58b81a257489e62355093e6907bba24 100644 --- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h +++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h @@ -30,6 +30,7 @@ public: bool IsNetworkAvailable() override; NetworkType GetNetworkType(bool retrieve = false) override; void RegOnNetworkChange() override; + void BindExecutor(std::shared_ptr executors) override; friend class NetConnCallbackObserver; private: NetworkDelegateNormalImpl(); @@ -43,11 +44,15 @@ private: std::chrono::steady_clock::now().time_since_epoch()) .count(); } + ExecutorPool::Task GetTask(uint32_t retry); static constexpr int32_t EFFECTIVE_DURATION = 30 * 1000; // ms static constexpr int32_t NET_LOST_DURATION = 10 * 1000; // ms + static constexpr int32_t MAX_RETRY_TIME = 3; + static constexpr int32_t RETRY_WAIT_TIME_S = 1; NetworkType defaultNetwork_ = NONE; uint64_t expireTime_ = 0; uint64_t netLostTime_ = 0; + std::shared_ptr executors_; }; } // namespace OHOS::DistributedData #endif // OHOS_DISTRIBUTED_DATA_NETWORK_NORMAL_DELEGATE_IMPL_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/network/test/BUILD.gn b/services/distributeddataservice/adapter/network/test/BUILD.gn index 6c030e7689fc89ffb8c2e675c75af1daca97463e..c1b564cc83c05748a2cc5ba119f7fc735a486009 100755 --- a/services/distributeddataservice/adapter/network/test/BUILD.gn +++ b/services/distributeddataservice/adapter/network/test/BUILD.gn @@ -12,7 +12,7 @@ # limitations under the License. import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### ohos_unittest("NetworkDelegateTest") { @@ -47,12 +47,52 @@ ohos_unittest("NetworkDelegateTest") { defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } +ohos_unittest("NetworkDelegateNormalImplTest") { + module_out_path = module_output_path + + sources = [ + "${data_service_path}/framework/network/network_delegate.cpp", + "network_delegate_normal_impl_test.cpp", + ] + include_dirs = [ + "${data_service_path}/adapter/include/communicator", + "${data_service_path}/framework/include/network", + "${data_service_path}/adapter/include/utils", + "${data_service_path}/framework/include", + "${data_service_path}/adapter/network/src", + "${data_service_path}/adapter/include", + ] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + deps = [ + "${data_service_path}/adapter/communicator:distributeddata_communicator", + ] + + external_deps = [ + "c_utils:utils", + "device_manager:devicemanagersdk", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:datamgr_common", + "netmanager_base:net_conn_manager_if", + ] + defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] +} + ############################################################################### group("unittest") { testonly = true deps = [] - deps += [ ":NetworkDelegateTest" ] + deps += [ + ":NetworkDelegateNormalImplTest", + ":NetworkDelegateTest", + ] } ############################################################################### diff --git a/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..64c63947582916e8168bc65bc6e1443e46f6683b --- /dev/null +++ b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp @@ -0,0 +1,217 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "network_delegate.h" +#include "network_delegate_normal_impl.h" +#include "network_delegate_normal_impl.cpp" +#include +#include + +using namespace testing::ext; +using namespace std; +using namespace OHOS::DistributedData; +using namespace OHOS::NetManagerStandard; +using DmDeviceInfo = OHOS::DistributedHardware::DmDeviceInfo; +namespace OHOS::Test { +namespace DistributedDataTest { +class NetworkDelegateNormalImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void NetworkDelegateNormalImplTest::SetUpTestCase(void) +{ +} + +void NetworkDelegateNormalImplTest::TearDownTestCase() +{ +} + +void NetworkDelegateNormalImplTest::SetUp() +{ +} + +void NetworkDelegateNormalImplTest::TearDown() +{ +} + +/** +* @tc.name: GetNetworkType001 +* @tc.desc: GetNetworkType testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(NetworkDelegateNormalImplTest, GetNetworkType001, TestSize.Level1) +{ + NetworkDelegateNormalImpl delegate; + bool retrieve = false; + EXPECT_NO_FATAL_FAILURE(delegate.RegOnNetworkChange()); + NetworkDelegate::NetworkType status = delegate.GetNetworkType(retrieve); + EXPECT_EQ(status, NetworkDelegate::NetworkType::NONE); +} + +/** +* @tc.name: GetNetworkType002 +* @tc.desc: GetNetworkType testing normal branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(NetworkDelegateNormalImplTest, GetNetworkType002, TestSize.Level1) +{ + NetworkDelegateNormalImpl delegate; + bool retrieve = true; + EXPECT_NO_FATAL_FAILURE(delegate.RegOnNetworkChange()); + NetworkDelegate::NetworkType status = delegate.GetNetworkType(retrieve); + EXPECT_EQ(status, NetworkDelegate::NetworkType::NONE); +} + +/** +* @tc.name: IsNetworkAvailable +* @tc.desc: IsNetworkAvailable testing different branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(NetworkDelegateNormalImplTest, IsNetworkAvailable, TestSize.Level1) +{ + NetworkDelegateNormalImpl delegate; + bool ret = delegate.IsNetworkAvailable(); // false false + EXPECT_FALSE(ret); + + DmDeviceInfo& info = const_cast(delegate.cloudDmInfo_); + std::fill(info.networkId, info.networkId + sizeof(info.networkId), '\0'); + NetworkDelegateNormalImpl::NetworkType netWorkType = NetworkDelegate::NetworkType::NONE; + NetworkDelegateNormalImpl::NetworkType status = delegate.SetNet(netWorkType); + EXPECT_EQ(status, NetworkDelegate::NONE); + ret = delegate.IsNetworkAvailable(); // false true + EXPECT_FALSE(ret); + + netWorkType = NetworkDelegate::NetworkType::WIFI; + status = delegate.SetNet(netWorkType); + EXPECT_EQ(status, NetworkDelegate::WIFI); + ret = delegate.IsNetworkAvailable(); // true true + EXPECT_TRUE(ret); + + netWorkType = NetworkDelegate::NetworkType::NONE; + status = delegate.SetNet(netWorkType); + EXPECT_EQ(status, NetworkDelegate::NONE); + ret = delegate.IsNetworkAvailable(); // false true + EXPECT_FALSE(ret); + + netWorkType = NetworkDelegate::NetworkType::WIFI; + status = delegate.SetNet(netWorkType); + EXPECT_EQ(status, NetworkDelegate::WIFI); + ret = delegate.IsNetworkAvailable(); // false true + EXPECT_TRUE(ret); +} + +/** +* @tc.name: NetCapabilitiesChange001 +* @tc.desc: NetCapabilitiesChange testing different branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange001, TestSize.Level1) +{ + NetworkDelegateNormalImpl delegate; + sptr observer = new (std::nothrow) NetConnCallbackObserver(delegate); + sptr netHandle = nullptr; + sptr netAllCap = nullptr; + int32_t status = observer->NetCapabilitiesChange(netHandle, netAllCap); + EXPECT_EQ(status, 0); + + netHandle = new (std::nothrow) NetHandle(); + status = observer->NetCapabilitiesChange(netHandle, netAllCap); + EXPECT_EQ(status, 0); + + netHandle = nullptr; + netAllCap = new (std::nothrow) NetAllCapabilities(); + status = observer->NetCapabilitiesChange(netHandle, netAllCap); + EXPECT_EQ(status, 0); +} + +/** +* @tc.name: NetCapabilitiesChange002 +* @tc.desc: NetCapabilitiesChange testing different branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange002, TestSize.Level1) +{ + NetworkDelegateNormalImpl delegate; + DmDeviceInfo& info = const_cast(delegate.cloudDmInfo_); + std::fill(info.networkId, info.networkId + sizeof(info.networkId), '\0'); + sptr observer = new (std::nothrow) NetConnCallbackObserver(delegate); + sptr netHandle = new (std::nothrow) NetHandle(); + sptr netAllCap = new (std::nothrow) NetAllCapabilities(); + EXPECT_FALSE(netAllCap->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED)); + EXPECT_FALSE(!netAllCap->bearerTypes_.empty()); + int32_t status = observer->NetCapabilitiesChange(netHandle, netAllCap); + EXPECT_EQ(status, 0); + + netAllCap->netCaps_.insert(NetManagerStandard::NET_CAPABILITY_VALIDATED); + EXPECT_TRUE(netAllCap->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED)); + EXPECT_FALSE(!netAllCap->bearerTypes_.empty()); + status = observer->NetCapabilitiesChange(netHandle, netAllCap); + EXPECT_EQ(status, 0); + + sptr netAllCaps = new (std::nothrow) NetAllCapabilities(); + netAllCaps->bearerTypes_.insert(NetManagerStandard::BEARER_WIFI); + EXPECT_FALSE(netAllCaps->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED)); + EXPECT_TRUE(!netAllCaps->bearerTypes_.empty()); + status = observer->NetCapabilitiesChange(netHandle, netAllCaps); + EXPECT_EQ(status, 0); + + netAllCaps->netCaps_.insert(NetManagerStandard::NET_CAPABILITY_VALIDATED); + EXPECT_TRUE(netAllCaps->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED)); + EXPECT_TRUE(!netAllCaps->bearerTypes_.empty()); + status = observer->NetCapabilitiesChange(netHandle, netAllCaps); + EXPECT_EQ(status, 0); +} + +/** +* @tc.name: Convert +* @tc.desc: Convert testing different branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(NetworkDelegateNormalImplTest, Convert, TestSize.Level1) +{ + NetManagerStandard::NetBearType bearType = NetManagerStandard::BEARER_WIFI; + NetworkDelegateNormalImpl::NetworkType status = Convert(bearType); + EXPECT_EQ(status, NetworkDelegate::WIFI); + + bearType = NetManagerStandard::BEARER_CELLULAR; + status = Convert(bearType); + EXPECT_EQ(status, NetworkDelegate::CELLULAR); + + bearType = NetManagerStandard::BEARER_ETHERNET; + status = Convert(bearType); + EXPECT_EQ(status, NetworkDelegate::ETHERNET); + + bearType = NetManagerStandard::BEARER_VPN; + status = Convert(bearType); + EXPECT_EQ(status, NetworkDelegate::OTHER); +} +} // namespace DistributedDataTest +} // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/adapter/screenlock/test/BUILD.gn b/services/distributeddataservice/adapter/screenlock/test/BUILD.gn index 8a1c3084cbfabe1634c0ecdf7ac96ab91539936c..f1f16b53b97aa91b48e36de832466a7d197a9a9c 100755 --- a/services/distributeddataservice/adapter/screenlock/test/BUILD.gn +++ b/services/distributeddataservice/adapter/screenlock/test/BUILD.gn @@ -12,7 +12,7 @@ # limitations under the License. import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### ohos_unittest("ScreenLockTest") { diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index 084cbb75e4cceddd76db9d286434490604f41fe3..45849945d3d997f0c16d3f4abb0ed3df0738ccc9 100644 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -38,7 +38,6 @@ ohos_sa_profile("distributeddata_profile") { config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "${kv_store_common_path}", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", "${data_service_path}/adapter/include/account", @@ -125,6 +124,7 @@ ohos_shared_library("distributeddataservice") { configs = [ ":module_private_config" ] deps = [ + "${data_service_path}/adapter/network:distributeddata_network", "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/app/src/checker:distributeddata_checker", "${data_service_path}/app/src/installer:distributeddata_installer", @@ -168,4 +168,4 @@ ohos_shared_library("distributeddataservice") { subsystem_name = "distributeddatamgr" part_name = "datamgr_service" defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] -} +} \ No newline at end of file diff --git a/services/distributeddataservice/app/src/checker/bundle_checker.cpp b/services/distributeddataservice/app/src/checker/bundle_checker.cpp index 674e09d5909e7d186dc098af80444a3263476676..b14a5fedda3aa72af2431e96abdc3d82dfa78404 100644 --- a/services/distributeddataservice/app/src/checker/bundle_checker.cpp +++ b/services/distributeddataservice/app/src/checker/bundle_checker.cpp @@ -114,7 +114,6 @@ bool BundleChecker::IsValid(const CheckerManager::StoreInfo &info) if (AccessTokenKit::GetHapTokenInfo(info.tokenId, tokenInfo) != RET_SUCCESS) { return false; } - return tokenInfo.bundleName == info.bundleName; } diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp old mode 100755 new mode 100644 index 8d732f7d034b8bd451a203b3422d3b05c5882abc..03cae1122ddd7012c4200e037e77725b93842f09 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -50,6 +50,7 @@ #include "mem_mgr_proxy.h" #include "metadata/appid_meta_data.h" #include "metadata/meta_data_manager.h" +#include "network/network_delegate.h" #include "permission_validator.h" #include "permit_delegate.h" #include "process_communicator_impl.h" @@ -298,6 +299,7 @@ void KvStoreDataService::OnStart() AccountDelegate::GetInstance()->RegisterHashFunc(Crypto::Sha256); DmAdapter::GetInstance().Init(executors_); AutoCache::GetInstance().Bind(executors_); + NetworkDelegate::GetInstance()->BindExecutor(executors_); static constexpr int32_t RETRY_TIMES = 50; static constexpr int32_t RETRY_INTERVAL = 500 * 1000; // unit is ms for (BlockInteger retry(RETRY_INTERVAL); retry < RETRY_TIMES; ++retry) { @@ -319,6 +321,9 @@ void KvStoreDataService::OnStart() } AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); AddSystemAbilityListener(MEMORY_MANAGER_SA_ID); + AddSystemAbilityListener(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID); + AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN); + AddSystemAbilityListener(CONCURRENT_TASK_SERVICE_ID); RegisterStoreInfo(); Handler handlerStoreInfo = std::bind(&KvStoreDataService::DumpStoreInfo, this, std::placeholders::_1, std::placeholders::_2); @@ -346,6 +351,7 @@ void KvStoreDataService::LoadConfigs() Bootstrap::GetInstance().LoadBackup(executors_); Bootstrap::GetInstance().LoadCloud(); Bootstrap::GetInstance().LoadAppIdMappings(); + Bootstrap::GetInstance().LoadDeviceSyncAppWhiteLists(); } void KvStoreDataService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) @@ -353,12 +359,15 @@ void KvStoreDataService::OnAddSystemAbility(int32_t systemAbilityId, const std:: ZLOGI("add system abilityid:%{public}d", systemAbilityId); (void)deviceId; if (systemAbilityId == COMMON_EVENT_SERVICE_ID) { - AccountDelegate::GetInstance()->SubscribeAccountEvent(); Installer::GetInstance().Init(this, executors_); ScreenManager::GetInstance()->SubscribeScreenEvent(); + } else if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { + AccountDelegate::GetInstance()->SubscribeAccountEvent(); } else if (systemAbilityId == MEMORY_MANAGER_SA_ID) { Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), 1, 1, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); + } else if (systemAbilityId == COMM_NET_CONN_MANAGER_SYS_ABILITY_ID) { + NetworkDelegate::GetInstance()->RegOnNetworkChange(); } return; } @@ -367,10 +376,12 @@ void KvStoreDataService::OnRemoveSystemAbility(int32_t systemAbilityId, const st { ZLOGI("remove system abilityid:%{public}d", systemAbilityId); (void)deviceId; + if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { + AccountDelegate::GetInstance()->UnsubscribeAccountEvent(); + } if (systemAbilityId != COMMON_EVENT_SERVICE_ID) { return; } - AccountDelegate::GetInstance()->UnsubscribeAccountEvent(); ScreenManager::GetInstance()->UnsubscribeScreenEvent(); Installer::GetInstance().UnsubscribeEvent(); } diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index f7e315cabb42bfa37b7d29cdf9f3c47e0a8c01c2..304048400b9b514950dff97ca1dd3a33f37ff93e 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -33,8 +33,16 @@ #include "kv_radar_reporter.h" #include "log_print.h" #include "matrix_event.h" +#include "metadata/auto_launch_meta_data.h" +#include "metadata/capability_meta_data.h" +#include "metadata/device_meta_data.h" #include "metadata/meta_data_manager.h" +#include "metadata/matrix_meta_data.h" +#include "metadata/strategy_meta_data.h" #include "metadata/store_meta_data_local.h" +#include "metadata/strategy_meta_data.h" +#include "metadata/switches_meta_data.h" +#include "metadata/user_meta_data.h" #include "metadata/version_meta_data.h" #include "runtime_config.h" #include "safe_block_queue.h" @@ -46,6 +54,7 @@ #include "utils/crypto.h" #include "utils/ref_count.h" #include "utils/converter.h" +#include "utils/constant.h" namespace OHOS { namespace DistributedKv { @@ -134,9 +143,10 @@ void KvStoreMetaManager::InitMetaData() ZLOGI("get meta failed."); return; } + + CheckMetaDeviceId(); auto uid = getuid(); auto tokenId = IPCSkeleton::GetCallingTokenID(); - const std::string accountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); auto userId = AccountDelegate::GetInstance()->GetUserByToken(tokenId); StoreMetaData data; data.appId = label_; @@ -153,7 +163,7 @@ void KvStoreMetaManager::InitMetaData() data.dataType = DataType::TYPE_DYNAMICAL; data.schema = ""; data.storeId = Bootstrap::GetInstance().GetMetaDBName(); - data.account = accountId; + data.account = AccountDelegate::GetInstance()->GetCurrentAccountId(); data.uid = static_cast(uid); data.version = META_STORE_VERSION; data.securityLevel = SecurityLevel::S1; @@ -554,5 +564,118 @@ AppDistributedKv::ChangeLevelType KvStoreMetaManager::DBInfoDeviceChangeListener { return AppDistributedKv::ChangeLevelType::MIN; } + +void KvStoreMetaManager::CheckMetaDeviceId() +{ + DeviceMetaData deviceMeta; + auto localUuid = DmAdapter::GetInstance().GetLocalDevice().uuid; + if (localUuid.empty()) { + ZLOGW("get uuid failed"); + return; + } + if (!MetaDataManager::GetInstance().LoadMeta(deviceMeta.GetKey(), deviceMeta, true)) { + deviceMeta.newUuid = localUuid; + MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true); + return; + } + if (deviceMeta.newUuid != localUuid) { + UpdateStoreMetaData(localUuid, deviceMeta.newUuid); + UpdateMetaDatas(localUuid, deviceMeta.newUuid); + deviceMeta.oldUuid = deviceMeta.newUuid; + deviceMeta.newUuid = localUuid; + MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true); + ZLOGI("meta changed! curruuid:%{public}s, olduuid:%{public}s", Anonymous::Change(deviceMeta.newUuid).c_str(), + Anonymous::Change(deviceMeta.oldUuid).c_str()); + } +} + +void KvStoreMetaManager::UpdateStoreMetaData(const std::string &newUuid, const std::string &oldUuid) +{ + std::vector storeMetas; + MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ oldUuid }), storeMetas, true); + for (auto &storeMeta : storeMetas) { + auto oldMeta = storeMeta; + storeMeta.isNeedUpdateDeviceId = true; + storeMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), storeMeta, true); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey(), true); + + StoreMetaData syncStoreMeta; + if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetKey(), syncStoreMeta)) { + syncStoreMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), syncStoreMeta); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); + } + + StrategyMeta strategyMeta; + if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetStrategyKey(), strategyMeta)) { + strategyMeta.devId = newUuid; + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetStrategyKey(), strategyMeta); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetStrategyKey()); + } + + StoreMetaDataLocal metaDataLocal; + if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetKeyLocal(), metaDataLocal, true)) { + MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKeyLocal(), metaDataLocal, true); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKeyLocal(), true); + } + + AutoLaunchMetaData autoLaunchMetaData; + bool isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, true); + if (!isExist) { + oldMeta.storeId = ""; + isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, true); + } + if (isExist) { + MetaDataManager::GetInstance().DelMeta(oldMeta.GetAutoLaunchKey(), true); + oldMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, true); + } + if (storeMeta.isEncrypt) { + MetaDataManager::GetInstance().DelMeta(storeMeta.GetSecretKey(), true); + MetaDataManager::GetInstance().DelMeta(storeMeta.GetCloneSecretKey(), true); + } + } +} + +void KvStoreMetaManager::UpdateMetaDatas(const std::string &newUuid, const std::string &oldUuid) +{ + MatrixMetaData matrixMeta; + if (MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUuid }), matrixMeta, true)) { + MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ oldUuid }), true); + matrixMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({ newUuid }), matrixMeta, true); + } + + if (MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUuid }), matrixMeta)) { + MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ oldUuid })); + matrixMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({ newUuid }), matrixMeta); + } + + SwitchesMetaData switchesMetaData; + if (MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({ oldUuid }), + switchesMetaData, true)) { + MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({ oldUuid }), true); + switchesMetaData.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({ newUuid }), + switchesMetaData, true); + } + + UserMetaData userMeta; + if (MetaDataManager::GetInstance().LoadMeta(UserMetaRow::GetKeyFor(oldUuid), userMeta)) { + MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor(oldUuid)); + userMeta.deviceId = newUuid; + MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor(newUuid), userMeta); + } + + CapMetaData capMetaData; + auto capKey = CapMetaRow::GetKeyFor(oldUuid); + if (MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), capMetaData)) { + auto newCapKey = CapMetaRow::GetKeyFor(newUuid); + MetaDataManager::GetInstance().DelMeta(std::string(capKey.begin(), capKey.end())); + MetaDataManager::GetInstance().SaveMeta(std::string(newCapKey.begin(), newCapKey.end()), capMetaData); + } +} } // namespace DistributedKv } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index 87bcc7162d8ad9f84f9ac437a5cbd233ca119677..f7b28e1cd2a2a29dbccdb8d170800c051ba829c2 100644 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -95,6 +95,12 @@ private: ExecutorPool::Task GetTask(uint32_t retry); DistributedDB::KvStoreNbDelegate::Option InitDBOption(); + + void CheckMetaDeviceId(); + + void UpdateStoreMetaData(const std::string &newUuid, const std::string &oldUuid); + + void UpdateMetaDatas(const std::string &newUuid, const std::string &oldUuid); static ExecutorPool::Task GetBackupTask( TaskQueue queue, std::shared_ptr executors, const NbDelegate store); diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp index f52cde722d9237a3e8c28bf215cee5d9ca0bdb2e..40d0403a46da7c34c55a1d748319d066ce14be69 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp @@ -113,7 +113,8 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize return DistributedDB::DB_ERROR; } size_t expectSize = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair) - + session_.targetUserIds.size() * sizeof(int) + sizeof(SessionAppId) + session_.appId.size(); + + session_.targetUserIds.size() * sizeof(int) + sizeof(SessionAppId) + session_.appId.size() + + sizeof(SessionStoreId) + session_.storeId.size(); // align message uint width headSize = GET_ALIGNED_SIZE(expectSize, ALIGN_WIDTH); @@ -194,16 +195,27 @@ bool RouteHeadHandlerImpl::PackDataBody(uint8_t *data, uint32_t totalLen) ptr += (sizeof(SessionUserPair) + session_.targetUserIds.size() * sizeof(int)); SessionAppId *appPair = reinterpret_cast(ptr); + uint32_t appIdSize = session_.appId.size(); + appPair->len = HostToNet(appIdSize); + uint8_t *end = data + totalLen; ptr += sizeof(SessionAppId); + ret = memcpy_s(appPair->appId, end - ptr, session_.appId.c_str(), appIdSize); + if (ret != 0) { + ZLOGE("memcpy for app id failed, ret is %{public}d, leftSize is %{public}u, appIdSize is %{public}u", + ret, static_cast(end - ptr), appIdSize); + return false; + } + ptr += appIdSize; - uint8_t *end = data + totalLen; - uint32_t appIdSize = session_.appId.size(); - ret = memcpy_s(appPair->appId, end - ptr, session_.appId.data(), appIdSize); + SessionStoreId *storePair = reinterpret_cast(ptr); + uint32_t storeIdSize = session_.storeId.size(); + ret = memcpy_s(storePair->storeId, end - ptr, session_.storeId.data(), storeIdSize); if (ret != 0) { - ZLOGE("strcpy for app id failed, error:%{public}d", errno); + ZLOGE("memcpy for store id failed, ret is %{public}d, leftSize is %{public}u, storeIdSize is %{public}u", + ret, static_cast(end - ptr), storeIdSize); return false; } - appPair->len = HostToNet(appIdSize); + storePair->len = HostToNet(storeIdSize); return true; } @@ -222,6 +234,9 @@ bool RouteHeadHandlerImpl::ParseHeadDataLen(const uint8_t *data, uint32_t totalL std::string RouteHeadHandlerImpl::ParseStoreId(const std::string &deviceId, const std::string &label) { + if (!session_.storeId.empty()) { + return session_.storeId; + } std::vector metaData; auto prefix = StoreMetaData::GetPrefix({ deviceId }); if (!MetaDataManager::GetInstance().LoadMeta(prefix, metaData)) { @@ -255,7 +270,7 @@ bool RouteHeadHandlerImpl::ParseHeadDataUser(const uint8_t *data, uint32_t total metaData.deviceId = session_.targetDeviceId; metaData.user = DEFAULT_USERID; metaData.bundleName = session_.appId; - metaData.storeId = storeId; + metaData.storeId = std::move(storeId); if (!MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData)) { int foregroundUserId = 0; AccountDelegate::GetInstance()->QueryForegroundUserId(foregroundUserId); @@ -369,6 +384,28 @@ bool RouteHeadHandlerImpl::UnPackDataBody(const uint8_t *data, uint32_t totalLen return false; } session_.appId.append(appId->appId, appIdLen); + leftSize -= (sizeof(SessionAppId) + appIdLen); + if (leftSize > 0) { + ptr += (sizeof(SessionAppId) + appIdLen); + return UnPackStoreId(ptr, leftSize); + } + return true; +} + +bool RouteHeadHandlerImpl::UnPackStoreId(const uint8_t *data, uint32_t leftSize) +{ + if (leftSize < sizeof(SessionStoreId)) { + ZLOGE("failed to parse store id, leftSize:%{public}d.", leftSize); + return false; + } + const uint8_t *ptr = data; + const SessionStoreId *storeId = reinterpret_cast(ptr); + auto storeIdLen = NetToHost(storeId->len); + if (leftSize - sizeof(SessionStoreId) < storeIdLen) { + ZLOGE("failed to parse store id, storeIdLen:%{public}d, leftSize:%{public}d.", storeIdLen, leftSize); + return false; + } + session_.storeId = std::string(storeId->storeId, storeIdLen); return true; } } // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h index f23360dd7341b4a6430c6d6a30099122b5c0ffc0..11583b7b1d4c712c8129b23f60f7d29dffa456a9 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h @@ -53,6 +53,11 @@ struct SessionAppId { uint32_t len; char appId[0]; }; + +struct SessionStoreId { + uint32_t len; + char storeId[0]; +}; #pragma pack() class RouteHeadHandlerImpl : public DistributedData::RouteHeadHandler { @@ -74,6 +79,7 @@ private: bool UnPackDataHead(const uint8_t *data, uint32_t totalLen, RouteHead &routeHead); bool UnPackDataBody(const uint8_t *data, uint32_t totalLen); std::string ParseStoreId(const std::string &deviceId, const std::string &label); + bool UnPackStoreId(const uint8_t *data, uint32_t leftSize); std::string userId_; std::string appId_; diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.cpp b/services/distributeddataservice/app/src/session_manager/session_manager.cpp index e13e43579f07d20b031ee1df5dd331fb0346b4b3..1ef5c834ab26b19bc412b6335aa028cf9890edcd 100644 --- a/services/distributeddataservice/app/src/session_manager/session_manager.cpp +++ b/services/distributeddataservice/app/src/session_manager/session_manager.cpp @@ -44,6 +44,7 @@ Session SessionManager::GetSession(const SessionPoint &local, const std::string ZLOGD("begin. peer device:%{public}s", Anonymous::Change(targetDeviceId).c_str()); Session session; session.appId = local.appId; + session.storeId = local.storeId; session.sourceUserId = local.userId; session.sourceDeviceId = local.deviceId; session.targetDeviceId = targetDeviceId; @@ -64,6 +65,8 @@ Session SessionManager::GetSession(const SessionPoint &local, const std::string aclParams.accCallee.userId = user.id; auto [isPermitted, isSameAccount] = AuthDelegate::GetInstance()->CheckAccess(local.userId, user.id, targetDeviceId, aclParams); + ZLOGD("targetDeviceId:%{public}s, user.id:%{public}d, isPermitted:%{public}d, isSameAccount: %{public}d", + Anonymous::Change(targetDeviceId).c_str(), user.id, isPermitted, isSameAccount); if (isPermitted) { auto it = std::find(session.targetUserIds.begin(), session.targetUserIds.end(), user.id); if (it == session.targetUserIds.end() && isSameAccount) { @@ -145,6 +148,8 @@ bool SessionManager::CheckSession(const SessionPoint &local, const SessionPoint } auto [isPermitted, isSameAccount] = AuthDelegate::GetInstance()->CheckAccess(local.userId, peer.userId, peer.deviceId, aclParams); + ZLOGD("peer.deviceId:%{public}s, peer.userId:%{public}d, isPermitted:%{public}d, isSameAccount: %{public}d", + Anonymous::Change(peer.deviceId).c_str(), peer.userId, isPermitted, isSameAccount); if (isPermitted && local.userId != UserDelegate::SYSTEM_USER) { isPermitted = Account::GetInstance()->IsUserForeground(local.userId); } @@ -159,6 +164,7 @@ bool Session::Marshal(json &node) const ret = SetValue(node[GET_NAME(sourceUserId)], sourceUserId) && ret; ret = SetValue(node[GET_NAME(targetUserIds)], targetUserIds) && ret; ret = SetValue(node[GET_NAME(appId)], appId) && ret; + ret = SetValue(node[GET_NAME(storeId)], storeId) && ret; return ret; } @@ -170,6 +176,7 @@ bool Session::Unmarshal(const json &node) ret = GetValue(node, GET_NAME(sourceUserId), sourceUserId) && ret; ret = GetValue(node, GET_NAME(targetUserIds), targetUserIds) && ret; ret = GetValue(node, GET_NAME(appId), appId) && ret; + ret = GetValue(node, GET_NAME(storeId), storeId) && ret; return ret; } } // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.h b/services/distributeddataservice/app/src/session_manager/session_manager.h index ca83970bc6494277011ba7bdf0aa3f67f341404d..c72c1bef195f8b24c351fae585b0e6e4754c97a8 100644 --- a/services/distributeddataservice/app/src/session_manager/session_manager.h +++ b/services/distributeddataservice/app/src/session_manager/session_manager.h @@ -39,6 +39,7 @@ public: uint32_t sourceUserId; std::vector targetUserIds; std::string appId; + std::string storeId; bool Marshal(json &node) const override; bool Unmarshal(const json &node) override; inline bool IsValid() diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index 628a466b83cb1fc3ecc9b20f1e43ae12d2a1c2f7..4feefbd64ad7a21b508e3258e22f111e78696e40 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -13,18 +13,14 @@ import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddataservice" +module_output_path = "datamgr_service/datamgr_service/distributeddataservice" ############################################################################### config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", - "${kv_store_path}/frameworks/common", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/src", - "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", - "${kv_store_path}/interfaces/innerkits/distributeddata/include", "${data_service_path}/adapter/include/permission", "${data_service_path}/adapter/include/account", "${data_service_path}/adapter/include", @@ -41,9 +37,7 @@ config("module_private_config") { "${data_service_path}/app/src", "${data_service_path}/app/src/session_manager", "${data_service_path}/service/kvdb", - "${device_manager_path}/interfaces/inner_kits/native_cpp/include", - "//commonlibrary/c_utils/base/include", - "//utils/system/safwk/native/include", + "${data_service_path}/service/test/mock", "../include", "../src", "../src/security", @@ -52,7 +46,6 @@ config("module_private_config") { "../../service/backup/include", "../../../../interfaces/innerkits/distributeddata", "../../service/dumper/include", - "//third_party/json/single_include", "${data_service_path}/adapter/include/communicator", ] @@ -109,7 +102,9 @@ ohos_unittest("KvStoreDataServiceTest") { "common_event_service:cesfwk_innerkits", "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", + "device_manager:devicemanagersdk", "file_api:securitylabel", + "googletest:gtest_main", "hicollie:libhicollie", "hilog:libhilog", "hisysevent:libhisysevent", @@ -117,6 +112,7 @@ ohos_unittest("KvStoreDataServiceTest") { "hitrace:libhitracechain", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "kv_store:distributeddb", "memmgr:memmgrclient", "safwk:system_ability_fwk", @@ -133,7 +129,6 @@ ohos_unittest("KvStoreDataServiceTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] part_name = "datamgr_service" } @@ -153,6 +148,7 @@ ohos_unittest("SessionManagerTest") { cfi = true cfi_cross_dso = true debug = false + blocklist = "${datamgr_service_path}/cfi_blocklist.txt" } cflags_cc = [ "-DUT_TEST" ] @@ -165,10 +161,17 @@ ohos_unittest("SessionManagerTest") { "c_utils:utils", "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", + "device_manager:devicemanagersdk", "file_api:securitylabel", + "googletest:gmock", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", + "json:nlohmann_json_static", + "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", + "kv_store:distributeddb", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] @@ -183,12 +186,9 @@ ohos_unittest("SessionManagerTest") { deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/app/src/checker:distributeddata_checker", - "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", + "${data_service_path}/service/test/mock:distributeddata_mock_static", ] part_name = "datamgr_service" @@ -233,13 +233,16 @@ ohos_unittest("KvStoreDataServiceClearTest") { "c_utils:utils", "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", + "device_manager:devicemanagersdk", "file_api:securitylabel", + "googletest:gtest_main", "hicollie:libhicollie", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", "hitrace:libhitracechain", "ipc:ipc_core", + "json:nlohmann_json_static", "kv_store:distributeddata_inner", "kv_store:distributeddata_mgr", "kv_store:distributeddb", @@ -261,7 +264,6 @@ ohos_unittest("KvStoreDataServiceClearTest") { "${data_service_path}/app/src/installer:distributeddata_installer", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] part_name = "datamgr_service" @@ -298,6 +300,7 @@ ohos_unittest("FeatureStubImplTest") { "c_utils:utils", "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", + "device_manager:devicemanagersdk", "file_api:securitylabel", "googletest:gtest_main", "hilog:libhilog", @@ -346,14 +349,5 @@ group("unittest") { ############################################################################### group("moduletest") { testonly = true - deps = [ - "//third_party/googletest:gmock", - "//third_party/googletest:gtest_main", - "//third_party/sqlite:sqlite", - ] - - deps += [ - #":DistributedDataAccountEventModuleTest", - ] } ############################################################################### diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index 8031dc6c64107682bd434dfcaadd6fa5064d5933..e009b52ad7ba4d4f7c0f678354eb313d01ae9fac 100644 --- a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -13,10 +13,18 @@ * limitations under the License. */ +#include "session_manager/session_manager.h" + +#include + #include "accesstoken_kit.h" +#include "account_delegate_mock.h" +#include "auth_delegate_mock.h" #include "bootstrap.h" #include "device_manager_adapter.h" -#include "kvstore_meta_manager.h" +#include "device_manager_adapter_mock.h" +#include "gtest/gtest.h" +#include "meta_data_manager_mock.h" #include "metadata/meta_data_manager.h" #include "metadata/store_meta_data.h" #include "nativetoken_kit.h" @@ -24,18 +32,25 @@ #include "session_manager/upgrade_manager.h" #include "token_setproc.h" #include "user_delegate.h" -#include "gtest/gtest.h" +#include "user_delegate_mock.h" +#include "utils/endian_converter.h" namespace { +using namespace testing; using namespace testing::ext; using namespace OHOS::DistributedKv; using namespace OHOS::DistributedData; +using namespace DistributedDB; using namespace OHOS; using namespace OHOS::Security::AccessToken; +using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo; +using UserInfo = DistributedDB::UserInfo; constexpr const char *PEER_DEVICE_ID = "PEER_DEVICE_ID"; constexpr int PEER_USER_ID1 = 101; constexpr int PEER_USER_ID2 = 100; +constexpr int32_t USER_MAXID = 4; constexpr int METADATA_UID = 2000000; +static constexpr int32_t OH_OS_TYPE = 10; void GrantPermissionNative() { @@ -55,20 +70,48 @@ void GrantPermissionNative() uint64_t tokenId = GetAccessTokenId(&infoInstance); SetSelfTokenID(tokenId); AccessTokenKit::ReloadNativeTokenInfo(); - delete []perms; + delete[] perms; } class SessionManagerTest : public testing::Test { public: + void CreateUserStatus(std::vector &users) + { + for (int32_t i = 0; i < USER_MAXID; i++) { + UserStatus stat; + stat.id = i; + users.push_back(stat); + } + } + void CreateStoreMetaData(std::vector &datas, SessionPoint local) + { + StoreMetaData data; + data.appId = local.appId; + data.storeId = local.storeId; + data.bundleName = "com.test.session"; + StoreMetaData data1; + data1.appId = local.appId; + data1.storeId = "local.storeId"; + data1.bundleName = "com.test.session1"; + StoreMetaData data2; + data2.appId = "local.appId"; + data2.storeId = local.storeId; + data2.bundleName = "com.test.session2"; + StoreMetaData data3; + data3.appId = "local.appId"; + data3.storeId = "local.storeId"; + data3.bundleName = "com.test.session3"; + datas.push_back(data); + datas.push_back(data1); + datas.push_back(data2); + datas.push_back(data3); + } static void SetUpTestCase() { auto executors = std::make_shared(12, 5); Bootstrap::GetInstance().LoadComponents(); Bootstrap::GetInstance().LoadDirectory(); Bootstrap::GetInstance().LoadCheckers(); - KvStoreMetaManager::GetInstance().BindExecutor(executors); - KvStoreMetaManager::GetInstance().InitMetaParameter(); - KvStoreMetaManager::GetInstance().InitMetaListener(); DeviceManagerAdapter::GetInstance().Init(executors); // init peer device @@ -102,6 +145,14 @@ public: metaData.storeType = 1; MetaDataManager::GetInstance().SaveMeta(metaData.GetKey(), metaData); GrantPermissionNative(); + deviceManagerAdapterMock = std::make_shared(); + BDeviceManagerAdapter::deviceManagerAdapter = deviceManagerAdapterMock; + metaDataManagerMock = std::make_shared(); + BMetaDataManager::metaDataManager = metaDataManagerMock; + metaDataMock = std::make_shared>(); + BMetaData::metaDataManager = metaDataMock; + userDelegateMock = std::make_shared(); + BUserDelegate::userDelegate = userDelegateMock; } static void TearDownTestCase() { @@ -119,22 +170,149 @@ public: metaData.uid = METADATA_UID; metaData.storeType = 1; MetaDataManager::GetInstance().DelMeta(metaData.GetKey()); + deviceManagerAdapterMock = nullptr; + BDeviceManagerAdapter::deviceManagerAdapter = nullptr; + metaDataManagerMock = nullptr; + BMetaDataManager::metaDataManager = nullptr; + metaDataMock = nullptr; + BMetaData::metaDataManager = nullptr; + userDelegateMock = nullptr; + BUserDelegate::userDelegate = nullptr; } void SetUp() { + ConstructValidData(); } void TearDown() { } + void ConstructValidData() + { + const std::string storeId = "test_store"; + InitializeBuffer(); + ConstructRouteHead(storeId); + ConstructSessionDevicePair(); + ConstructSessionUserPair(); + ConstructSessionAppId(); + ConstructSessionStoreId(storeId); + + const size_t validlLen = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair) + + sizeof(uint32_t) * 1 + sizeof(SessionAppId) + APP_STR_LEN + sizeof(SessionStoreId) + + storeId.size(); + validTotalLen = validlLen; + } + + static inline std::shared_ptr deviceManagerAdapterMock = nullptr; + static inline std::shared_ptr metaDataManagerMock = nullptr; + static inline std::shared_ptr> metaDataMock = nullptr; + static inline std::shared_ptr userDelegateMock = nullptr; + +private: + void InitializeBuffer() + { + memset_s(dataBuffer, BUFFER_SIZE, 0, BUFFER_SIZE); + ptr = dataBuffer; + remaining = BUFFER_SIZE; + } + + void ConstructRouteHead(const std::string &storeId) + { + RouteHead head{}; + head.magic = HostToNet(RouteHead::MAGIC_NUMBER); + head.version = HostToNet(RouteHead::VERSION); + head.dataLen = HostToNet(sizeof(SessionDevicePair) + sizeof(SessionUserPair) + sizeof(uint32_t) * 1 + + sizeof(SessionAppId) + APP_STR_LEN + sizeof(SessionStoreId) + storeId.size()); + head.checkSum = 0; + + errno_t err = memcpy_s(ptr, remaining, &head, sizeof(RouteHead)); + ASSERT_EQ(err, 0) << "Failed to copy RouteHead"; + ptr += sizeof(RouteHead); + remaining -= sizeof(RouteHead); + } + + void ConstructSessionDevicePair() + { + SessionDevicePair devPair{}; + constexpr size_t DEV_ID_SIZE = sizeof(devPair.sourceId); + + errno_t err = memset_s(devPair.sourceId, DEV_ID_SIZE, 'A', DEV_ID_SIZE - 1); + ASSERT_EQ(err, 0) << "Failed to init sourceId"; + devPair.sourceId[DEV_ID_SIZE - 1] = '\0'; + + err = memset_s(devPair.targetId, DEV_ID_SIZE, 'B', DEV_ID_SIZE - 1); + ASSERT_EQ(err, 0) << "Failed to init targetId"; + devPair.targetId[DEV_ID_SIZE - 1] = '\0'; + + err = memcpy_s(ptr, remaining, &devPair, sizeof(SessionDevicePair)); + ASSERT_EQ(err, 0) << "Failed to copy SessionDevicePair"; + ptr += sizeof(SessionDevicePair); + remaining -= sizeof(SessionDevicePair); + } + + void ConstructSessionUserPair() + { + SessionUserPair userPair{}; + userPair.sourceUserId = HostToNet(100U); + userPair.targetUserCount = HostToNet(1U); + + errno_t err = memcpy_s(ptr, remaining, &userPair, sizeof(SessionUserPair)); + ASSERT_EQ(err, 0) << "Failed to copy SessionUserPair"; + ptr += sizeof(SessionUserPair); + remaining -= sizeof(SessionUserPair); + + uint32_t targetUser = HostToNet(200U); + err = memcpy_s(ptr, remaining, &targetUser, sizeof(uint32_t)); + ASSERT_EQ(err, 0) << "Failed to copy targetUser"; + ptr += sizeof(uint32_t); + remaining -= sizeof(uint32_t); + } + + void ConstructSessionAppId() + { + SessionAppId appId{}; + const char *appStr = "test"; + appId.len = HostToNet(static_cast(APP_STR_LEN)); + + errno_t err = memcpy_s(ptr, remaining, &appId, sizeof(SessionAppId)); + ASSERT_EQ(err, 0) << "Failed to copy SessionAppId"; + ptr += sizeof(SessionAppId); + remaining -= sizeof(SessionAppId); + + err = memcpy_s(ptr, remaining, appStr, APP_STR_LEN); + ASSERT_EQ(err, 0) << "Failed to copy appId data"; + ptr += APP_STR_LEN; + remaining -= APP_STR_LEN; + } + void ConstructSessionStoreId(const std::string &storeId) + { + SessionStoreId storeIdHeader{}; + storeIdHeader.len = HostToNet(static_cast(storeId.size())); + + errno_t err = memcpy_s(ptr, remaining, &storeIdHeader, sizeof(SessionStoreId)); + ASSERT_EQ(err, 0) << "Failed to copy storeId length"; + ptr += sizeof(SessionStoreId); + remaining -= sizeof(SessionStoreId); + + err = memcpy_s(ptr, remaining, storeId.c_str(), storeId.size()); + ASSERT_EQ(err, 0) << "Failed to copy storeId data"; + ptr += storeId.size(); + remaining -= storeId.size(); + } + size_t validTotalLen; + uint8_t dataBuffer[1024]; + static constexpr size_t APP_STR_LEN = 4; + uint8_t *ptr = dataBuffer; + size_t remaining = BUFFER_SIZE; + static constexpr size_t BUFFER_SIZE = sizeof(dataBuffer); }; /** -* @tc.name: PackAndUnPack01 -* @tc.desc: test get db dir -* @tc.type: FUNC -* @tc.require: -* @tc.author: illybyy -*/ + * @tc.name: PackAndUnPack01 + * @tc.desc: test get db dir + * @tc.type: FUNC + * @tc.require: + * @tc.author: illybyy + */ HWTEST_F(SessionManagerTest, PackAndUnPack01, TestSize.Level2) { const DistributedDB::ExtendInfo info = { @@ -152,9 +330,317 @@ HWTEST_F(SessionManagerTest, PackAndUnPack01, TestSize.Level2) auto recvHandler = RouteHeadHandlerImpl::Create({}); ASSERT_NE(recvHandler, nullptr); uint32_t parseSize = 1; + auto res = recvHandler->ParseHeadDataLen(nullptr, routeHeadSize, parseSize); + EXPECT_EQ(res, false); recvHandler->ParseHeadDataLen(data.get(), routeHeadSize, parseSize); EXPECT_EQ(routeHeadSize, parseSize); recvHandler->ParseHeadDataUser(data.get(), routeHeadSize, "", users); ASSERT_EQ(users.size(), 0); } +/** + * @tc.name: GetHeadDataSize_Test1 + * @tc.desc: test appId equal processLabel. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, GetHeadDataSize_Test1, TestSize.Level1) +{ + ExtendInfo info; + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t headSize = 0; + routeHeadHandlerImpl.appId_ = Bootstrap::GetInstance().GetProcessLabel(); + auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize); + EXPECT_EQ(status, DistributedDB::OK); + EXPECT_EQ(headSize, 0); +} +/** + * @tc.name: GetHeadDataSize_Test2 + * @tc.desc: test appId not equal processLabel. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, GetHeadDataSize_Test2, TestSize.Level1) +{ + ExtendInfo info; + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t headSize = 0; + routeHeadHandlerImpl.appId_ = "otherAppId"; + auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize); + EXPECT_EQ(status, DistributedDB::OK); + EXPECT_EQ(headSize, 0); +} +/** + * @tc.name: GetHeadDataSize_Test3 + * @tc.desc: test devInfo.osType equal OH_OS_TYPE, appId not equal processLabel. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, GetHeadDataSize_Test3, TestSize.Level1) +{ + DeviceInfo deviceInfo; + deviceInfo.osType = OH_OS_TYPE; + EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo)); + ExtendInfo info; + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t headSize = 0; + routeHeadHandlerImpl.appId_ = "otherAppId"; + auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize); + EXPECT_EQ(status, DistributedDB::DB_ERROR); + EXPECT_EQ(headSize, 0); +} +/** + * @tc.name: GetHeadDataSize_Test4 + * @tc.desc: test GetHeadDataSize + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, GetHeadDataSize_Test4, TestSize.Level1) +{ + DeviceInfo deviceInfo; + deviceInfo.osType = OH_OS_TYPE; + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo)); + + const DistributedDB::ExtendInfo info = { + .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID + }; + auto sendHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(sendHandler, nullptr); + + CapMetaData capMetaData; + capMetaData.version = CapMetaData::CURRENT_VERSION; + EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) + .WillRepeatedly(DoAll(SetArgReferee<1>(capMetaData), Return(true))); + std::vector userStatus; + UserStatus userStat1; + UserStatus userStat2; + UserStatus userStat3; + userStat1.id = 1; + userStat2.id = 2; + userStat3.id = 3; + userStatus.push_back(userStat1); + userStatus.push_back(userStat2); + userStatus.push_back(userStat3); + EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillRepeatedly(Return(userStatus)); + + uint32_t headSize = 0; + auto status = sendHandler->GetHeadDataSize(headSize); + EXPECT_EQ(status, DistributedDB::OK); + EXPECT_EQ(headSize, 0); + + uint32_t routeHeadSize = 10; + std::unique_ptr data = std::make_unique(routeHeadSize); + status = sendHandler->FillHeadData(data.get(), routeHeadSize, routeHeadSize); + EXPECT_EQ(status, DistributedDB::DB_ERROR); +} +/** + * @tc.name: ParseHeadDataUserTest001 + * @tc.desc: test parse null data. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, ParseHeadDataUserTest001, TestSize.Level1) +{ + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true)); + const DistributedDB::ExtendInfo info = { + .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID + }; + auto sendHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(sendHandler, nullptr); + + uint32_t totalLen = 10; + std::string label = "testLabel"; + std::vector userInfos; + + bool result = sendHandler->ParseHeadDataUser(nullptr, totalLen, label, userInfos); + + EXPECT_FALSE(result); + EXPECT_EQ(userInfos.size(), 0); +} +/** + * @tc.name: ParseHeadDataUserTest002 + * @tc.desc: test totalLen < sizeof(RouteHead). + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, ParseHeadDataUserTest002, TestSize.Level1) +{ + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true)); + const DistributedDB::ExtendInfo info = { + .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID + }; + auto sendHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(sendHandler, nullptr); + + uint8_t data[10] = { 0 }; + std::string label = "testLabel"; + std::vector userInfos; + + bool result = sendHandler->ParseHeadDataUser(data, sizeof(RouteHead) - 1, label, userInfos); + + EXPECT_FALSE(result); + EXPECT_EQ(userInfos.size(), 0); +} + +/** + * @tc.name: ParseHeadDataUserTest003 + * @tc.desc: test totalLen < sizeof(RouteHead). + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, ParseHeadDataUserTest003, TestSize.Level1) +{ + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true)); + const DistributedDB::ExtendInfo info = { + .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID + }; + auto sendHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(sendHandler, nullptr); + + uint8_t data[10] = { 0 }; + std::string label = "testLabel"; + std::vector userInfos; + + RouteHead head = { 0 }; + head.version = RouteHead::VERSION; + head.dataLen = static_cast(sizeof(data) - sizeof(RouteHead)); + + bool result = sendHandler->ParseHeadDataUser(data, sizeof(RouteHead), label, userInfos); + + EXPECT_FALSE(result); + EXPECT_EQ(userInfos.size(), 0); +} + +/** + * @tc.name: UnPackData_InvalidMagic + * @tc.desc: test invalid magic. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, UnPackData_InvalidMagic, TestSize.Level1) +{ + RouteHead *head = reinterpret_cast(dataBuffer); + head->magic = 0xFFFF; + ExtendInfo info; + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t unpackedSize; + EXPECT_FALSE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize)); +} + +/** + * @tc.name: UnPackData_VersionMismatch + * @tc.desc: test version mismatch. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, UnPackData_VersionMismatch, TestSize.Level1) +{ + RouteHead *head = reinterpret_cast(dataBuffer); + head->version = 0x00; + ExtendInfo info; + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t unpackedSize; + EXPECT_FALSE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize)); +} + +/** + * @tc.name: UnPackData_ValidData + * @tc.desc: test valid data. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, UnPackData_ValidData, TestSize.Level1) +{ + ExtendInfo info; + RouteHeadHandlerImpl routeHeadHandlerImpl(info); + uint32_t unpackedSize; + EXPECT_TRUE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize)); + EXPECT_EQ(unpackedSize, validTotalLen); +} + +/** + * @tc.name: ShouldAddSystemUserWhenLocalUserIdIsSystem + * @tc.desc: test GetSession. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, ShouldAddSystemUserWhenLocalUserIdIsSystem, TestSize.Level1) +{ + SessionPoint local; + local.userId = UserDelegate::SYSTEM_USER; + local.appId = "test_app"; + local.deviceId = "local_device"; + local.storeId = "test_store"; + + std::vector users; + CreateUserStatus(users); + EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillOnce(Return(users)); + EXPECT_CALL(AuthHandlerMock::GetInstance(), CheckAccess(_, _, _, _)) + .WillOnce(Return(std::pair(true, true))) + .WillOnce(Return(std::pair(true, false))) + .WillOnce(Return(std::pair(false, true))) + .WillOnce(Return(std::pair(false, false))); + std::vector datas; + CreateStoreMetaData(datas, local); + EXPECT_CALL(*metaDataMock, LoadMeta(_, _, _)).WillRepeatedly(DoAll(SetArgReferee<1>(datas), Return(true))); + + Session session = SessionManager::GetInstance().GetSession(local, "target_device"); + ASSERT_EQ(2, session.targetUserIds.size()); + EXPECT_EQ(UserDelegate::SYSTEM_USER, session.targetUserIds[0]); +} + +/** + * @tc.name: ShouldReturnEarlyWhenGetSendAuthParamsFails + * @tc.desc: test GetSession. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, ShouldReturnEarlyWhenGetSendAuthParamsFails, TestSize.Level1) +{ + SessionPoint local; + local.userId = 100; + local.appId = "test_app"; + local.deviceId = "local_device"; + EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillOnce(Return(std::vector{})); + std::vector datas; + EXPECT_CALL(*metaDataMock, LoadMeta(_, _, _)).WillRepeatedly(Return(false)); + + Session session = SessionManager::GetInstance().GetSession(local, "target_device"); + + EXPECT_TRUE(session.targetUserIds.empty()); +} + +/** + * @tc.name: CheckSession + * @tc.desc: test CheckSession. + * @tc.type: FUNC + * @tc.author: guochao + */ +HWTEST_F(SessionManagerTest, CheckSession, TestSize.Level1) +{ + SessionPoint localSys; + localSys.userId = UserDelegate::SYSTEM_USER; + localSys.appId = "test_app"; + localSys.deviceId = "local_device"; + localSys.storeId = "test_store"; + SessionPoint localNormal; + localNormal.userId = 100; + localNormal.appId = "test_app"; + localNormal.deviceId = "local_device"; + localNormal.storeId = "test_store"; + std::vector datas; + CreateStoreMetaData(datas, localSys); + EXPECT_CALL(*metaDataMock, LoadMeta(_, _, _)) + .WillOnce(DoAll(SetArgReferee<1>(datas), Return(false))) + .WillRepeatedly(DoAll(SetArgReferee<1>(datas), Return(true))); + EXPECT_CALL(AuthHandlerMock::GetInstance(), CheckAccess(_, _, _, _)) + .WillOnce(Return(std::pair(false, true))) + .WillOnce(Return(std::pair(true, false))); + bool result = SessionManager::GetInstance().CheckSession(localSys, localNormal); + EXPECT_FALSE(result); + result = SessionManager::GetInstance().CheckSession(localSys, localNormal); + EXPECT_FALSE(result); + result = SessionManager::GetInstance().CheckSession(localNormal, localSys); + EXPECT_TRUE(result); +} } // namespace \ No newline at end of file diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index f85d7b550348928f82494508b66ddc537bca4d41..a99bba56a8357c480ade0ff429361df15181ce3b 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -76,6 +76,7 @@ ohos_shared_library("distributeddatasvcfwk") { "cloud/sync_event.cpp", "cloud/sync_strategy.cpp", "communication/connect_manager.cpp", + "device_sync_app/device_sync_app_manager.cpp", "dfx/reporter.cpp", "directory/directory_manager.cpp", "dump/dump_manager.cpp", @@ -88,9 +89,11 @@ ohos_shared_library("distributeddatasvcfwk") { "metadata/capability_meta_data.cpp", "metadata/capability_range.cpp", "metadata/corrupted_meta_data.cpp", + "metadata/device_meta_data.cpp", "metadata/matrix_meta_data.cpp", "metadata/meta_data.cpp", "metadata/meta_data_manager.cpp", + "metadata/object_user_meta_data.cpp", "metadata/secret_key_meta_data.cpp", "metadata/store_debug_info.cpp", "metadata/store_meta_data.cpp", diff --git a/services/distributeddataservice/framework/cloud/cloud_db.cpp b/services/distributeddataservice/framework/cloud/cloud_db.cpp index 863475888ff457cd9be3f5886f66524197822fc5..3d916243ee02ca5b969453b05c26e6279643a478 100644 --- a/services/distributeddataservice/framework/cloud/cloud_db.cpp +++ b/services/distributeddataservice/framework/cloud/cloud_db.cpp @@ -40,14 +40,14 @@ int32_t CloudDB::BatchDelete(const std::string &table, VBuckets &extends) return E_NOT_SUPPORT; } -std::shared_ptr CloudDB::Query(const std::string &table, const VBucket &extend) +std::pair> CloudDB::Query(const std::string &table, const VBucket &extend) { - return nullptr; + return { E_NOT_SUPPORT, nullptr }; } -std::shared_ptr CloudDB::Query(GenQuery &query, const VBucket &extend) +std::pair> CloudDB::Query(GenQuery &query, const VBucket &extend) { - return nullptr; + return { E_NOT_SUPPORT, nullptr }; } int32_t CloudDB::PreSharing(const std::string &table, VBuckets &extend) diff --git a/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp b/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e20ee46ef181dd261371ee36788e70cd6f83cc79 --- /dev/null +++ b/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define LOG_TAG "DeviceSyncAppManager" +#include "device_sync_app/device_sync_app_manager.h" + +namespace OHOS::DistributedData { +DeviceSyncAppManager::DeviceSyncAppManager() +{ +} + +DeviceSyncAppManager &DeviceSyncAppManager::GetInstance() +{ + static DeviceSyncAppManager instance; + return instance; +} + +void DeviceSyncAppManager::Initialize(const std::vector &lists) +{ + for (const auto &list : lists) { + whiteLists_.push_back(list); + } +} + +bool DeviceSyncAppManager::Check(const WhiteList &whiteList) +{ + for (const auto &info : whiteLists_) { + if (info.appId == whiteList.appId && (info.bundleName == whiteList.bundleName) && + (info.version == whiteList.version)) { + return true; + } + } + return false; +} + +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/cloud/cloud_db.h b/services/distributeddataservice/framework/include/cloud/cloud_db.h index fcf7cfca5ca9daad3767417064e393b02a466ef2..58933563237ba73b5b47333cf274534de12f1819 100644 --- a/services/distributeddataservice/framework/include/cloud/cloud_db.h +++ b/services/distributeddataservice/framework/include/cloud/cloud_db.h @@ -40,9 +40,9 @@ public: virtual int32_t BatchDelete(const std::string &table, VBuckets &extends); - virtual std::shared_ptr Query(const std::string &table, const VBucket &extend); + virtual std::pair> Query(const std::string &table, const VBucket &extend); - virtual std::shared_ptr Query(GenQuery &query, const VBucket &extend); + virtual std::pair> Query(GenQuery &query, const VBucket &extend); virtual int32_t PreSharing(const std::string &table, VBuckets &extend); diff --git a/services/distributeddataservice/framework/include/cloud/schema_meta.h b/services/distributeddataservice/framework/include/cloud/schema_meta.h index bc74d210b11676ad6a4835461066605d599ca8d8..33dc0cb41946842ab8e357ee76d2baa23fde2325 100644 --- a/services/distributeddataservice/framework/include/cloud/schema_meta.h +++ b/services/distributeddataservice/framework/include/cloud/schema_meta.h @@ -73,7 +73,8 @@ public: static constexpr const char *SHARING_RESOURCE = "#_sharing_resource"; static constexpr const char *HASH_KEY = "#_hash_key"; - static constexpr uint32_t CURRENT_VERSION = 0x10000; + static constexpr uint32_t CURRENT_VERSION = 0x10001; + static constexpr uint32_t CLEAN_WATER_VERSION = 0x10001; static inline uint32_t GetLowVersion(uint32_t metaVersion = CURRENT_VERSION) { return metaVersion & 0xFFFF; @@ -104,4 +105,4 @@ enum AutoSyncType { }; } // namespace OHOS::DistributedData -#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CLOUD_SCHEMA_META_H +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CLOUD_SCHEMA_META_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/device_sync_app/device_sync_app_manager.h b/services/distributeddataservice/framework/include/device_sync_app/device_sync_app_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..664883bce41c938e7644226cef7392cd7daf0a88 --- /dev/null +++ b/services/distributeddataservice/framework/include/device_sync_app/device_sync_app_manager.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_DEVICE_SYNC_APP_MANAGER_H +#define DISTRIBUTEDDATAMGR_DEVICE_SYNC_APP_MANAGER_H + +#include +#include +#include "visibility.h" +namespace OHOS::DistributedData { +class DeviceSyncAppManager { +public: + struct WhiteList { + std::string appId; + std::string bundleName; + uint32_t version; + }; + API_EXPORT static DeviceSyncAppManager &GetInstance(); + API_EXPORT void Initialize(const std::vector &lists); + API_EXPORT bool Check(const WhiteList &whiteList); + +private: + DeviceSyncAppManager(); + std::vector whiteLists_; +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_DEVICE_SYNC_APP_MANAGER_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/metadata/device_meta_data.h b/services/distributeddataservice/framework/include/metadata/device_meta_data.h new file mode 100644 index 0000000000000000000000000000000000000000..7df8c5564c90f2f750cf90cdd569522bf1dc1d7a --- /dev/null +++ b/services/distributeddataservice/framework/include/metadata/device_meta_data.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICE_META_DATA_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICE_META_DATA_H +#include + +#include "serializable/serializable.h" +namespace OHOS::DistributedData { +class API_EXPORT DeviceMetaData final : public Serializable { +public: + API_EXPORT DeviceMetaData(); + API_EXPORT ~DeviceMetaData(); + API_EXPORT bool Marshal(json &node) const override; + API_EXPORT bool Unmarshal(const json &node) override; + API_EXPORT std::string GetKey() const; + + std::string newUuid = ""; + std::string oldUuid = ""; +}; +} // namespace OHOS::DistributedData +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICE_META_DATA_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h b/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h new file mode 100644 index 0000000000000000000000000000000000000000..cd2dd38e44135a2569b93ff5821c623d3c014e77 --- /dev/null +++ b/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDDATAMGR_OBJECT_USER_META_DATA_H +#define DISTRIBUTEDDATAMGR_OBJECT_USER_META_DATA_H + +#include "serializable/serializable.h" +namespace OHOS::DistributedData { +class API_EXPORT ObjectUserMetaData final : public Serializable { +public: + std::string userId; + + API_EXPORT bool Marshal(json &node) const override; + API_EXPORT bool Unmarshal(const json &node) override; + API_EXPORT ObjectUserMetaData(); + + API_EXPORT static std::string GetKey(); + +private: + static constexpr const char *KEY_PREFIX = "ObjectUserMetaData"; +}; +} // namespace OHOS::DistributedData +#endif // DISTRIBUTEDDATAMGR_OBJECT_USER_META_DATA_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/metadata/store_meta_data.h b/services/distributeddataservice/framework/include/metadata/store_meta_data.h index e0a614e2d2d47f94119198b21e8972b2e97b807c..2d17763414843203eae334f12a38925ddfec2c59 100644 --- a/services/distributeddataservice/framework/include/metadata/store_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/store_meta_data.h @@ -60,6 +60,7 @@ struct API_EXPORT StoreMetaData final : public Serializable { std::string account = ""; int32_t authType = 0; bool asyncDownloadAsset = false; + bool isNeedUpdateDeviceId = false; enum StoreType { STORE_KV_BEGIN = 0, diff --git a/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h index a3cb9275bc3378a707afaf9081242386cb5728fd..25feaeded8b904f311a80118c83042a6e25f622f 100644 --- a/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h @@ -29,6 +29,7 @@ struct API_EXPORT StrategyMeta final : public Serializable { API_EXPORT StrategyMeta(const std::string &devId, const std::string &userId, const std::string &bundleName, const std::string &storeId); + API_EXPORT StrategyMeta() {}; API_EXPORT ~StrategyMeta() {}; API_EXPORT bool Marshal(json &node) const override; API_EXPORT bool Unmarshal(const json &node) override; diff --git a/services/distributeddataservice/framework/include/network/network_delegate.h b/services/distributeddataservice/framework/include/network/network_delegate.h index ae7e9f94aba2dcff0a84aa721585ddb65e6ce35e..38763f58d68e1cff6b7d90c66b64709af52481b0 100644 --- a/services/distributeddataservice/framework/include/network/network_delegate.h +++ b/services/distributeddataservice/framework/include/network/network_delegate.h @@ -19,7 +19,8 @@ #include #include -#include "types.h" +#include "executor_pool.h" +#include "visibility.h" namespace OHOS { namespace DistributedData { @@ -37,6 +38,7 @@ public: API_EXPORT static bool RegisterNetworkInstance(NetworkDelegate *instance); virtual bool IsNetworkAvailable() = 0; virtual void RegOnNetworkChange() = 0; + virtual void BindExecutor(std::shared_ptr executors) = 0; virtual NetworkType GetNetworkType(bool retrieve = false) = 0; private: diff --git a/services/distributeddataservice/framework/include/store/general_store.h b/services/distributeddataservice/framework/include/store/general_store.h index 3789ae685a618496b1f3a170369ea882c40bdf80..dc109463a23646ff36efa977381f77d7c0694f63 100644 --- a/services/distributeddataservice/framework/include/store/general_store.h +++ b/services/distributeddataservice/framework/include/store/general_store.h @@ -61,6 +61,7 @@ public: CLOUD_DATA, CLOUD_INFO, LOCAL_DATA, + CLEAN_WATER, CLEAN_MODE_BUTT }; @@ -197,6 +198,11 @@ public: virtual std::pair LockCloudDB() = 0; virtual int32_t UnLockCloudDB() = 0; + + virtual int32_t UpdateDBStatus() + { + return 0; + } }; } // namespace OHOS::DistributedData #endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_STORE_GENERAL_STORE_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/store/general_value.h b/services/distributeddataservice/framework/include/store/general_value.h index e1f9b3a18a43b90e8756dfb92b7794276d4e437f..888c9f7c151ab147b1cb9dce1d3080f6875ce9a3 100644 --- a/services/distributeddataservice/framework/include/store/general_value.h +++ b/services/distributeddataservice/framework/include/store/general_value.h @@ -115,6 +115,7 @@ struct ReportParam { std::string prepareTraceId; SyncStage syncStage = SyncStage::PREPARE; int32_t errCode = 0; + std::string message = ""; }; using Assets = std::vector; diff --git a/services/distributeddataservice/framework/metadata/device_meta_data.cpp b/services/distributeddataservice/framework/metadata/device_meta_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c16c6400f140d94755c3ad0fe9497408e94a9a08 --- /dev/null +++ b/services/distributeddataservice/framework/metadata/device_meta_data.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "metadata/device_meta_data.h" + +namespace OHOS { +namespace DistributedData { +static constexpr const char *KEY_PREFIX = "DeviceMeta"; +bool DeviceMetaData::Marshal(json &node) const +{ + SetValue(node[GET_NAME(newUuid)], newUuid); + SetValue(node[GET_NAME(oldUuid)], oldUuid); + return true; +} + +bool DeviceMetaData::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(newUuid), newUuid); + GetValue(node, GET_NAME(oldUuid), oldUuid); + return true; +} + +DeviceMetaData::DeviceMetaData() +{ +} + +DeviceMetaData::~DeviceMetaData() +{ +} + +std::string DeviceMetaData::GetKey() const +{ + return KEY_PREFIX; +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp b/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5d5d9e073ae8cd22c4799b1ca85bd8eeabf340f --- /dev/null +++ b/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "metadata/object_user_meta_data.h" + +namespace OHOS::DistributedData { +ObjectUserMetaData::ObjectUserMetaData() +{ +} +bool ObjectUserMetaData::Marshal(json &node) const +{ + return SetValue(node[GET_NAME(userId)], userId); +} + +bool ObjectUserMetaData::Unmarshal(const json &node) +{ + return GetValue(node, GET_NAME(userId), userId); +} + +std::string ObjectUserMetaData::GetKey() +{ + return KEY_PREFIX; +} +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/metadata/store_meta_data.cpp b/services/distributeddataservice/framework/metadata/store_meta_data.cpp index f3d16332619aaf4be82aec62858b71b11dde7a1b..61d6785804a0bcdcc9553cbf4f829d08fd4d5031 100644 --- a/services/distributeddataservice/framework/metadata/store_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/store_meta_data.cpp @@ -57,6 +57,7 @@ bool StoreMetaData::Marshal(json &node) const SetValue(node[GET_NAME(enableCloud)], enableCloud); SetValue(node[GET_NAME(cloudAutoSync)], cloudAutoSync); SetValue(node[GET_NAME(asyncDownloadAsset)], asyncDownloadAsset); + SetValue(node[GET_NAME(isNeedUpdateDeviceId)], isNeedUpdateDeviceId); // compatible with the versions which lower than VERSION_TAG_0000 SetValue(node[GET_NAME(kvStoreType)], storeType); SetValue(node[GET_NAME(deviceAccountID)], user); @@ -98,6 +99,7 @@ bool StoreMetaData::Unmarshal(const json &node) GetValue(node, GET_NAME(enableCloud), enableCloud); GetValue(node, GET_NAME(cloudAutoSync), cloudAutoSync); GetValue(node, GET_NAME(asyncDownloadAsset), asyncDownloadAsset); + GetValue(node, GET_NAME(isNeedUpdateDeviceId), isNeedUpdateDeviceId); // compatible with the older versions if (version < FIELD_CHANGED_TAG) { GetValue(node, GET_NAME(kvStoreType), storeType); @@ -138,7 +140,8 @@ bool StoreMetaData::operator==(const StoreMetaData &metaData) const Constant::NotEqual(isNeedCompress, metaData.isNeedCompress) || Constant::NotEqual(enableCloud, metaData.enableCloud) || Constant::NotEqual(cloudAutoSync, metaData.cloudAutoSync) || - Constant::NotEqual(isManualClean, metaData.isManualClean)) { + Constant::NotEqual(isManualClean, metaData.isManualClean) || + Constant::NotEqual(isNeedUpdateDeviceId, metaData.isNeedUpdateDeviceId)) { return false; } return (version == metaData.version && storeType == metaData.storeType && dataType == metaData.dataType && diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn index 619dc289a82912a2501af701e19cd29e29fa7b7b..4417c7c7a3a08a8a1290cb40426b9b65309162ad 100644 --- a/services/distributeddataservice/framework/test/BUILD.gn +++ b/services/distributeddataservice/framework/test/BUILD.gn @@ -14,37 +14,26 @@ import("//build/ohos_var.gni") import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "${device_manager_path}/interfaces/inner_kits/native_cpp/include", - "../include/", - "../../service/bootstrap/include/", - "../../service/common/", - "../../service/rdb/", - "../../../../../relational_store/interfaces/inner_api/rdb/include", - "../../../../../relational_store/interfaces/inner_api/common_type/include", - "${kv_store_distributeddb_path}/interfaces/include", - "${kv_store_distributeddb_path}/include", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", - "${kv_store_common_path}", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/src", - "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", - "${kv_store_path}/interfaces/innerkits/distributeddata/include", + "${data_service_path}/service/bootstrap/include/", + "${data_service_path}/service/common/", + "${data_service_path}/service/rdb/", "${data_service_path}/adapter/include", "${data_service_path}/framework/include", "${data_service_path}/service/config/include", "${data_service_path}/app/src", "${data_service_path}/adapter/include/account", + "${data_service_path}/adapter/include/communicator", "${data_service_path}/app/src/security", "${data_service_path}/service/crypto/include", "${data_service_path}/service/matrix/include", - "//third_party/json/single_include", + "${data_service_path}/service/kvdb", ] cflags = [ "-Werror" ] ldflags = [ "-Wl,--whole-archive" ] @@ -61,17 +50,17 @@ ohos_unittest("CheckerManagerTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", ] deps = [ "${data_service_path}/app/src/checker:distributeddata_checker", - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", ] } @@ -83,15 +72,13 @@ ohos_unittest("EventCenterTest") { external_deps = [ "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", ] - deps = [ - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", - ] + deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] } ohos_unittest("SerializableTest") { @@ -105,16 +92,14 @@ ohos_unittest("SerializableTest") { "ability_base:base", "ability_base:want", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", ] - deps = [ - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", - ] + deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] } ohos_unittest("ServiceUtilsTest") { @@ -133,14 +118,13 @@ ohos_unittest("ServiceUtilsTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "json:nlohmann_json_static", ] - deps = [ - "${data_service_path}/framework:distributeddatasvcfwk", - "//third_party/googletest:gtest_main", - ] + deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] } ohos_unittest("StoreTest") { @@ -170,6 +154,7 @@ ohos_unittest("StoreTest") { "access_token:libnativetoken", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -183,7 +168,6 @@ ohos_unittest("StoreTest") { "${data_service_path}/service:distributeddatasvc", "${data_service_path}/service/common:distributeddata_common", "${data_service_path}/service/test/mock:distributeddata_mock_static", - "//third_party/googletest:gtest_main", ] } @@ -213,6 +197,11 @@ ohos_unittest("CloudInfoTest") { sources = [ "cloud_test.cpp" ] configs = [ ":module_private_config" ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] + + external_deps = [ + "json:nlohmann_json_static", + "kv_store:datamgr_common", + ] } ohos_unittest("EventTest") { @@ -227,6 +216,7 @@ ohos_unittest("GeneralStoreTest") { sources = [ "general_store_test.cpp" ] configs = [ ":module_private_config" ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] + external_deps = [ "kv_store:datamgr_common" ] } ohos_unittest("SubscriptionTest") { @@ -234,16 +224,18 @@ ohos_unittest("SubscriptionTest") { sources = [ "subscription_test.cpp" ] configs = [ ":module_private_config" ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] + external_deps = [ + "json:nlohmann_json_static", + "kv_store:datamgr_common", + ] } ohos_unittest("FeatureTest") { module_out_path = module_output_path sources = [ "feature_test.cpp" ] configs = [ ":module_private_config" ] - deps = [ - "${data_service_path}/framework:distributeddatasvcfwk", - "${kv_store_path}/interfaces/innerkits/distributeddata:distributeddata_inner", - ] + deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] + external_deps = [ "kv_store:distributeddata_inner" ] } ohos_unittest("MetaDataManagerTest") { @@ -255,14 +247,15 @@ ohos_unittest("MetaDataManagerTest") { external_deps = [ "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "json:nlohmann_json_static", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] } @@ -271,6 +264,7 @@ ohos_unittest("StoreMetaDataLocalTest") { sources = [ "store_meta_data_local_test.cpp" ] configs = [ ":module_private_config" ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] + external_deps = [ "json:nlohmann_json_static" ] } ohos_unittest("ConstantTest") { @@ -301,49 +295,29 @@ ohos_unittest("ServiceMetaDataTest") { debug = false } - configs = [ ":module_private_config" ] - - include_dirs = [ - "${device_manager_path}/interfaces/inner_kits/native_cpp/include", - "../include/", - "../../service/bootstrap/include/", - "../../service/common/", - "../../service/rdb/", - "../../../../../relational_store/interfaces/inner_api/rdb/include", - "../../../../../relational_store/interfaces/inner_api/common_type/include", - "${kv_store_distributeddb_path}/interfaces/include", - "${kv_store_distributeddb_path}/include", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", - "${kv_store_common_path}", - "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/src", - "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", - "${kv_store_path}/interfaces/innerkits/distributeddata/include", - "${data_service_path}/adapter/include", - "${data_service_path}/framework/include", - "${data_service_path}/service/config/include", - "${data_service_path}/app/src", - "${data_service_path}/adapter/include/account", - "${data_service_path}/app/src/security", - "${data_service_path}/service/crypto/include", - "${data_service_path}/service/matrix/include", - "${data_service_path}/service/kvdb", - "//third_party/json/single_include", - "${data_service_path}/adapter/include/communicator", + cflags = [ + "-Dprivate=public", + "-Dprotected=public", ] + configs = [ ":module_private_config" ] + external_deps = [ "c_utils:utils", "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", + "device_manager:devicemanagersdk", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", "hitrace:libhitracechain", "ipc:ipc_core", + "json:nlohmann_json_static", "kv_store:distributeddata_inner", "kv_store:distributeddata_mgr", "kv_store:distributeddb", + "openssl:libcrypto_shared", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] @@ -355,11 +329,6 @@ ohos_unittest("ServiceMetaDataTest") { "${data_service_path}/app/src/checker:distributeddata_checker", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/kvdb:distributeddata_kvdb", - "${kv_store_distributeddb_path}:distributeddb", - "${kv_store_path}/interfaces/innerkits/distributeddata:distributeddata_inner", - "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", ] } diff --git a/services/distributeddataservice/framework/test/cloud_test.cpp b/services/distributeddataservice/framework/test/cloud_test.cpp index 1940f95fc3bf7f00f54b53f6d4c7e89d7f94f507..5179ef0176e1ec1d57250cbd3ce39694cbc6680e 100644 --- a/services/distributeddataservice/framework/test/cloud_test.cpp +++ b/services/distributeddataservice/framework/test/cloud_test.cpp @@ -502,9 +502,9 @@ HWTEST_F(ServicesCloudDBTest, CloudDB, TestSize.Level0) EXPECT_EQ(result1, GeneralError::E_NOT_SUPPORT); auto result2 = cloudDB.Query(table, extend); - EXPECT_EQ(result2, nullptr); + EXPECT_EQ(result2.second, nullptr); result2 = cloudDB.Query(query, extend); - EXPECT_EQ(result2, nullptr); + EXPECT_EQ(result2.second, nullptr); auto result3 = cloudDB.AliveTime(); EXPECT_EQ(result3, -1); diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp index 6bc7f9186660c6249d080330c6055b655892cef2..58359051ec6464c24a2a9c25a60d52f552f63bca 100644 --- a/services/distributeddataservice/framework/test/meta_data_test.cpp +++ b/services/distributeddataservice/framework/test/meta_data_test.cpp @@ -15,6 +15,9 @@ #include "bootstrap.h" #include "kvstore_meta_manager.h" + +#include "metadata/appid_meta_data.h" +#include "metadata/auto_launch_meta_data.h" #include "metadata/appid_meta_data.h" #include "metadata/capability_meta_data.h" #include "metadata/capability_range.h" @@ -22,11 +25,14 @@ #include "metadata/matrix_meta_data.h" #include "metadata/meta_data.h" #include "metadata/meta_data_manager.h" +#include "metadata/object_user_meta_data.h" #include "metadata/secret_key_meta_data.h" #include "metadata/store_meta_data.h" #include "metadata/store_meta_data_local.h" #include "metadata/strategy_meta_data.h" +#include "metadata/switches_meta_data.h" #include "metadata/user_meta_data.h" +#include "metadata/device_meta_data.h" #include "utils/constant.h" #include "gtest/gtest.h" #include @@ -794,4 +800,212 @@ HWTEST_F(ServiceMetaDataTest, MatrixMetaData, TestSize.Level1) std::string key = matrixMetaData3.GetConsistentKey(); EXPECT_EQ(key, "MatrixMeta###DEVICE_ID###Consistent"); } + +/** + * @tc.name: DeviceMetaData + * @tc.desc: test DeviceMetaData function + * @tc.type: FUNC + * @tc.require: + * @tc.author: yl + */ +HWTEST_F(ServiceMetaDataTest, DeviceMetaData, TestSize.Level1) +{ + DeviceMetaData metaData; + std::string newUuid = "newuuid"; + std::string oldUuid = "olduuid"; + metaData.newUuid = newUuid; + metaData.oldUuid = oldUuid; + Serializable::json node1; + metaData.Marshal(node1); + EXPECT_EQ(node1["newUuid"], newUuid); + EXPECT_EQ(node1["oldUuid"], oldUuid); + + DeviceMetaData newMetaData; + newMetaData.Unmarshal(node1); + EXPECT_EQ(newMetaData.newUuid, newUuid); + EXPECT_EQ(newMetaData.oldUuid, oldUuid); +} + +/** +* @tc.name: InitMeta +* @tc.desc: test Init TestMeta +* @tc.type: FUNC +* @tc.require: +* @tc.author: yl +*/ +HWTEST_F(ServiceMetaDataTest, InitTestMeta, TestSize.Level1) +{ + StoreMetaData oldMeta; + oldMeta.deviceId = "mockOldUuid"; + oldMeta.user = "200"; + oldMeta.bundleName = "test_appid_001"; + oldMeta.storeId = "test_storeid_001"; + oldMeta.isEncrypt = true; + bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta, true); + EXPECT_TRUE(isSuccess); + StoreMetaDataLocal metaDataLocal; + isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKeyLocal(), metaDataLocal, true); + EXPECT_TRUE(isSuccess); + SwitchesMetaData switchesMetaData; + isSuccess = MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({"mockOldUuid"}), + switchesMetaData, true); + EXPECT_TRUE(isSuccess); + AutoLaunchMetaData autoLaunchMetaData; + MetaDataManager::GetInstance().SaveMeta(AutoLaunchMetaData::GetPrefix({ oldMeta.deviceId, oldMeta.user, + "default", oldMeta.bundleName, "" }), autoLaunchMetaData, true); + EXPECT_TRUE(isSuccess); + MatrixMetaData matrixMeta0; + isSuccess = MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({"mockOldUuid"}), matrixMeta0, true); + EXPECT_TRUE(isSuccess); + + isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta); + EXPECT_TRUE(isSuccess); + MatrixMetaData matrixMeta; + isSuccess = MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({"mockOldUuid"}), matrixMeta); + EXPECT_TRUE(isSuccess); + UserMetaData userMeta; + isSuccess = MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor("mockOldUuid"), userMeta); + EXPECT_TRUE(isSuccess); + CapMetaData capMetaData; + auto capKey = CapMetaRow::GetKeyFor("mockOldUuid"); + isSuccess = MetaDataManager::GetInstance().SaveMeta(std::string(capKey.begin(), capKey.end()), capMetaData); + EXPECT_TRUE(isSuccess); + StrategyMeta strategyMeta; + isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetStrategyKey(), strategyMeta); + EXPECT_TRUE(isSuccess); +} + +/** +* @tc.name: UpdateStoreMetaData +* @tc.desc: test UpdateStoreMetaData function +* @tc.type: FUNC +* @tc.require: +* @tc.author: yl +*/ +HWTEST_F(ServiceMetaDataTest, UpdateStoreMetaData, TestSize.Level1) +{ + std::string mockNewUuid = "mockNewUuid"; + std::string mockOldUuid = "mockOldUuid"; + StoreMetaData newMeta; + newMeta.deviceId = "mockNewUuid"; + newMeta.user = "200"; + newMeta.bundleName = "test_appid_001"; + newMeta.storeId = "test_storeid_001"; + KvStoreMetaManager::GetInstance().UpdateStoreMetaData(mockNewUuid, mockOldUuid); + bool isSuccess = MetaDataManager::GetInstance().LoadMeta(newMeta.GetKey(), newMeta, true); + EXPECT_TRUE(isSuccess); + EXPECT_TRUE(newMeta.isNeedUpdateDeviceId); + isSuccess = MetaDataManager::GetInstance().LoadMeta(newMeta.GetKey(), newMeta); + EXPECT_TRUE(isSuccess); + AutoLaunchMetaData autoLaunchMetaData; + isSuccess = MetaDataManager::GetInstance().LoadMeta(AutoLaunchMetaData::GetPrefix({ newMeta.deviceId, newMeta.user, + "default", newMeta.bundleName, "" }), autoLaunchMetaData, true); + EXPECT_TRUE(isSuccess); + StrategyMeta strategyMeta; + isSuccess = MetaDataManager::GetInstance().LoadMeta(newMeta.GetStrategyKey(), strategyMeta); + EXPECT_TRUE(isSuccess); +} + +/** +* @tc.name: UpdateMetaDatas +* @tc.desc: test UpdateMetaDatas function +* @tc.type: FUNC +* @tc.require: +* @tc.author: yl +*/ +HWTEST_F(ServiceMetaDataTest, UpdateMetaDatas, TestSize.Level1) +{ + std::string mockNewUuid = "mockNewUuid"; + std::string mockOldUuid = "mockOldUuid"; + StoreMetaData newMeta; + newMeta.deviceId = "mockNewUuid"; + newMeta.user = "200"; + newMeta.bundleName = "test_appid_001"; + newMeta.storeId = "test_storeid_001"; + KvStoreMetaManager::GetInstance().UpdateMetaDatas(mockNewUuid, mockOldUuid); + MatrixMetaData matrixMeta; + bool isSuccess = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }), + matrixMeta, true); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }), matrixMeta); + EXPECT_TRUE(isSuccess); + UserMetaData userMeta; + isSuccess = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }), userMeta); + EXPECT_TRUE(isSuccess); + CapMetaData capMetaData; + auto capKey = CapMetaRow::GetKeyFor("mockNewUuid"); + isSuccess = MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), capMetaData); + EXPECT_TRUE(isSuccess); + SwitchesMetaData switchesMetaData; + isSuccess = MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({ "mockNewUuid" }), + switchesMetaData, true); + EXPECT_TRUE(isSuccess); +} + +/** +* @tc.name: DelInitTestMeta +* @tc.desc: test Del TestMeta +* @tc.type: FUNC +* @tc.require: +* @tc.author: yl +*/ +HWTEST_F(ServiceMetaDataTest, DelTestMeta, TestSize.Level1) +{ + StoreMetaData newMeta; + newMeta.deviceId = "mockNewUuid"; + newMeta.user = "200"; + newMeta.bundleName = "test_appid_001"; + newMeta.storeId = "test_storeid_001"; + bool isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetKey(), true); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetKeyLocal(), true); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({ "mockNewUuid" }), true); + EXPECT_TRUE(isSuccess); + MetaDataManager::GetInstance().DelMeta(AutoLaunchMetaData::GetPrefix({ "mockNewUuid", newMeta.user, + "default", newMeta.bundleName, "" }), true); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }), true); + EXPECT_TRUE(isSuccess); + + isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetKey()); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({"mockNewUuid"})); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor("mockNewUuid")); + EXPECT_TRUE(isSuccess); + auto capKey = CapMetaRow::GetKeyFor("mockNewUuid"); + isSuccess = MetaDataManager::GetInstance().DelMeta(std::string(capKey.begin(), capKey.end())); + EXPECT_TRUE(isSuccess); + isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetStrategyKey()); + EXPECT_TRUE(isSuccess); +} + +/** +* @tc.name: GetKeyTest +* @tc.desc: GetKey +* @tc.type: FUNC +* @tc.require: +* @tc.author: yl +*/ +HWTEST_F(ServiceMetaDataTest, GetKey, TestSize.Level1) +{ + DeviceMetaData metaData; + std::string expectedPrefix = "DeviceMeta"; + std::string prefix = metaData.GetKey(); + EXPECT_EQ(prefix, expectedPrefix); +} + +/** +* @tc.name: ObjectUserMetaDataGetKey +* @tc.desc: ObjectUserMetaDataGetKey +* @tc.type: FUNC +*/ +HWTEST_F(ServiceMetaDataTest, ObjectUserMetaDataGetKey, TestSize.Level1) +{ + ObjectUserMetaData metaData; + std::string expectedPrefix = "ObjectUserMetaData"; + std::string prefix = metaData.GetKey(); + EXPECT_EQ(prefix, expectedPrefix); +} } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/framework/test/store_test.cpp b/services/distributeddataservice/framework/test/store_test.cpp index 7bc31f25e4a6de819cff4fdb9f756785ad325c62..24e8f52181939b49bec3c1adccfc696b78d2d903 100644 --- a/services/distributeddataservice/framework/test/store_test.cpp +++ b/services/distributeddataservice/framework/test/store_test.cpp @@ -30,6 +30,8 @@ using namespace testing::ext; using namespace OHOS::DistributedData; namespace OHOS::Test { +static constexpr const char *TEST_CLOUD_STORE = "test_cloud_store"; + class GeneralValueTest : public testing::Test { public: static void SetUpTestCase(void){}; @@ -260,4 +262,66 @@ HWTEST_F(AutoCacheTest, GetDBStore, TestSize.Level2) meta.area = GeneralStore::EL5; EXPECT_NE(AutoCache::GetInstance().GetDBStore(meta, watchers).first, GeneralError::E_SCREEN_LOCKED); } + +/** +* @tc.name: CloseStore001 +* @tc.desc: AutoCache CloseStore001 +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(AutoCacheTest, CloseStore001, TestSize.Level2) +{ + GeneralStoreMock* store = new (std::nothrow) GeneralStoreMock(); + ASSERT_NE(store, nullptr); + AutoCache::Watchers watchers; + mock_->isLocked_ = true; + StoreMetaData meta; + meta.area = GeneralStore::EL1; + meta.dataDir = "abc"; + uint32_t tokenId = 123; + std::string storeId = TEST_CLOUD_STORE; + std::string userId = ""; + AutoCache autoCache; + autoCache.stores_.Compute(tokenId, + [this, &meta, &watchers, &store](auto &, std::map &stores) -> bool { + std::string storeKey = "key"; + stores.emplace(std::piecewise_construct, std::forward_as_tuple(storeKey), + std::forward_as_tuple(store, watchers, 0, meta)); + return !stores.empty(); + }); + autoCache.CloseStore(tokenId, storeId, userId); + EXPECT_TRUE(autoCache.stores_.Empty()); +} + +/** +* @tc.name: CloseStore002 +* @tc.desc: AutoCache CloseStore002 +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(AutoCacheTest, CloseStore002, TestSize.Level2) +{ + GeneralStoreMock* store = new (std::nothrow) GeneralStoreMock(); + ASSERT_NE(store, nullptr); + AutoCache::Watchers watchers; + mock_->isLocked_ = true; + StoreMetaData meta; + meta.area = GeneralStore::EL4; + meta.dataDir = "abc"; + uint32_t tokenId = 123; + std::string storeId = TEST_CLOUD_STORE; + std::string userId = ""; + AutoCache autoCache; + autoCache.stores_.Compute(tokenId, + [this, &meta, &watchers, &store](auto &, std::map &stores) -> bool { + std::string storeKey = "key"; + stores.emplace(std::piecewise_construct, std::forward_as_tuple(storeKey), + std::forward_as_tuple(store, watchers, 0, meta)); + return !stores.empty(); + }); + autoCache.CloseStore(tokenId, storeId, userId); + EXPECT_FALSE(autoCache.stores_.Empty()); +} } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/rust/extension/cloud_db_impl.cpp b/services/distributeddataservice/rust/extension/cloud_db_impl.cpp index da137619bfc423220f73d0095506c8fc6b57fc59..3b042ba2418a717b6aa5889562af9b1e912a6f58 100644 --- a/services/distributeddataservice/rust/extension/cloud_db_impl.cpp +++ b/services/distributeddataservice/rust/extension/cloud_db_impl.cpp @@ -119,7 +119,7 @@ int32_t CloudDbImpl::BatchDelete(const std::string &table, DBVBuckets &extends) return ExtensionUtil::ConvertStatus(status); } -std::shared_ptr CloudDbImpl::Query(const std::string &table, const DBVBucket &extend) +std::pair> CloudDbImpl::Query(const std::string &table, const DBVBucket &extend) { std::string cursor; auto it = extend.find(DistributedData::SchemaMeta::CURSOR_FIELD); @@ -134,7 +134,11 @@ std::shared_ptr CloudDbImpl::Query(const std::string &table, const DBV }; OhCloudExtCloudDbData *cloudData = nullptr; auto status = OhCloudExtCloudDbBatchQuery(database_, &info, &cloudData); - return (status == ERRNO_SUCCESS && cloudData != nullptr) ? std::make_shared(cloudData) : nullptr; + if (status == ERRNO_SUCCESS && cloudData != nullptr) { + return std::make_pair(DBErr::E_OK, std::make_shared(cloudData)); + } + return status != ERRNO_SUCCESS ? std::make_pair(ExtensionUtil::ConvertStatus(status), nullptr) + : std::make_pair(DBErr::E_ERROR, nullptr); } int32_t CloudDbImpl::Lock() diff --git a/services/distributeddataservice/rust/extension/cloud_db_impl.h b/services/distributeddataservice/rust/extension/cloud_db_impl.h index 099bfaad0ddf004cbdee4b887f02f6a62eaafb12..5351ebbb9d4b5f0b4f8d32736ecd8fad8769e5b9 100644 --- a/services/distributeddataservice/rust/extension/cloud_db_impl.h +++ b/services/distributeddataservice/rust/extension/cloud_db_impl.h @@ -36,7 +36,7 @@ public: int32_t BatchUpdate(const std::string &table, DBVBuckets &&values, DBVBuckets &extends) override; int32_t BatchUpdate(const std::string &table, DBVBuckets &&values, const DBVBuckets &extends) override; int32_t BatchDelete(const std::string &table, DBVBuckets &extends) override; - std::shared_ptr Query(const std::string &table, const DBVBucket &extend) override; + std::pair> Query(const std::string &table, const DBVBucket &extend) override; int32_t Lock() override; int32_t Heartbeat() override; int32_t Unlock() override; diff --git a/services/distributeddataservice/rust/extension/cloud_server_impl.cpp b/services/distributeddataservice/rust/extension/cloud_server_impl.cpp index f47a26209787b06c9b2dcd049f4cd8fee9cd9e11..e5413cff2de360b5e1bdd0f94f13aadce5d7c206 100644 --- a/services/distributeddataservice/rust/extension/cloud_server_impl.cpp +++ b/services/distributeddataservice/rust/extension/cloud_server_impl.cpp @@ -28,11 +28,19 @@ #include "utils/anonymous.h" namespace OHOS::CloudData { -__attribute__((used)) static bool g_isInit = - DistributedData::CloudServer::RegisterCloudInstance(new (std::nothrow) CloudServerImpl()); +__attribute__((used)) static bool g_isInit = CloudServerImpl::Init(); using namespace Security::AccessToken; using DBMetaMgr = DistributedData::MetaDataManager; using Anonymous = DistributedData::Anonymous; + +bool CloudServerImpl::Init() +{ + static CloudServerImpl cloudServerInstance; + static std::once_flag onceFlag; + std::call_once(onceFlag, [&]() { DistributedData::CloudServer::RegisterCloudInstance(&cloudServerInstance); }); + return true; +} + std::pair CloudServerImpl::GetServerInfo(int32_t userId, bool needSpaceInfo) { DBCloudInfo result; @@ -544,7 +552,7 @@ int32_t CloudServerImpl::Unsubscribe(int32_t userId, const std::mapsecond); + uint32_t subId = static_cast(std::atoi(it->second.c_str())); if (OhCloudExtVectorPush(relation, &subId, sizeof(uint32_t)) != ERRNO_SUCCESS) { return DBErr::E_ERROR; } diff --git a/services/distributeddataservice/rust/extension/cloud_server_impl.h b/services/distributeddataservice/rust/extension/cloud_server_impl.h index bd7c185e7818e31a7879fd31f1a5fedc4a39aba1..debb7aadf00458b4b9f687a8c43f3abbe698f6fb 100644 --- a/services/distributeddataservice/rust/extension/cloud_server_impl.h +++ b/services/distributeddataservice/rust/extension/cloud_server_impl.h @@ -36,6 +36,7 @@ using DBRelation = DBSub::Relation; using DBErr = DistributedData::GeneralError; class CloudServerImpl : public DistributedData::CloudServer { public: + static bool Init(); std::pair GetServerInfo(int32_t userId, bool needSpaceInfo) override; std::pair GetAppSchema(int32_t userId, const std::string &bundleName) override; int32_t Subscribe(int32_t userId, const std::map> &dbs) override; diff --git a/services/distributeddataservice/service/bootstrap/include/bootstrap.h b/services/distributeddataservice/service/bootstrap/include/bootstrap.h index 785eadae22b884df1fb7716f5130e48faf3f187b..186217fc5fb7e8dd38ceb7f1754060fe66ce8a24 100644 --- a/services/distributeddataservice/service/bootstrap/include/bootstrap.h +++ b/services/distributeddataservice/service/bootstrap/include/bootstrap.h @@ -33,6 +33,7 @@ public: API_EXPORT void LoadBackup(std::shared_ptr executors); API_EXPORT void LoadAppIdMappings(); API_EXPORT void LoadThread(); + API_EXPORT void LoadDeviceSyncAppWhiteLists(); private: static constexpr const char *DEFAULT_LABEL = "distributeddata"; static constexpr const char *DEFAULT_META = "service_meta"; diff --git a/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp b/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp index 107ca6a668ef4798391a6449365ffc30fa807ae0..41f1b755fa94b4690ca7bf5869cf52b1e5148331 100644 --- a/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp +++ b/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp @@ -23,6 +23,7 @@ #include "checker/checker_manager.h" #include "cloud/cloud_config_manager.h" #include "config_factory.h" +#include "device_sync_app/device_sync_app_manager.h" #include "directory/directory_manager.h" #include "log_print.h" #include "thread/thread_manager.h" @@ -191,5 +192,18 @@ void Bootstrap::LoadThread() } ThreadManager::GetInstance().Initialize(config->minThreadNum, config->maxThreadNum, config->ipcThreadNum); } + +void Bootstrap::LoadDeviceSyncAppWhiteLists() +{ + auto *deviceSyncAppWhiteLists = ConfigFactory::GetInstance().GetDeviceSyncAppWhiteListConfig(); + if (deviceSyncAppWhiteLists == nullptr) { + return; + } + std::vector infos; + for (auto &info : deviceSyncAppWhiteLists->whiteLists) { + infos.push_back({ info.appId, info.bundleName, info.version }); + } + DeviceSyncAppManager::GetInstance().Initialize(infos); +} } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/cloud/cloud_data_translate.cpp b/services/distributeddataservice/service/cloud/cloud_data_translate.cpp index 80762e38753201781258eb3e455a9b9b3f4f2c19..b1e0983fe70b82a4dc7c03ddca301a061bb64a7b 100644 --- a/services/distributeddataservice/service/cloud/cloud_data_translate.cpp +++ b/services/distributeddataservice/service/cloud/cloud_data_translate.cpp @@ -50,7 +50,7 @@ std::vector RdbCloudDataTranslate::AssetsToBlob(const Assets &assets) auto magicU8 = reinterpret_cast(const_cast(&leMagic)); rawData.insert(rawData.end(), magicU8, magicU8 + sizeof(ASSETS_MAGIC)); rawData.insert(rawData.end(), reinterpret_cast(&num), reinterpret_cast(&num) + sizeof(num)); - for (auto &asset : assets) { + for (const auto &asset : assets) { auto data = AssetToBlob(asset); rawData.insert(rawData.end(), data.begin(), data.end()); } diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index 2492401664a18bf3233d35bc14309e7836d8da30..fe9aa097bb835088cb0917cf0a5549a2e33e97b9 100644 --- a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -61,7 +61,7 @@ using namespace DistributedDataDfx; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; using Account = AccountDelegate; using AccessTokenKit = Security::AccessToken::AccessTokenKit; -static constexpr uint32_t RESTART_SERVICE_TIME_THRESHOLD = 60; +static constexpr uint32_t RESTART_SERVICE_TIME_THRESHOLD = 120; static constexpr const char *FT_ENABLE_CLOUD = "ENABLE_CLOUD"; static constexpr const char *FT_DISABLE_CLOUD = "DISABLE_CLOUD"; static constexpr const char *FT_SWITCH_ON = "SWITCH_ON"; @@ -275,7 +275,9 @@ void CloudServiceImpl::DoClean(int32_t user, const SchemaMeta &schemaMeta, int32 storeInfo.bundleName = meta.bundleName; storeInfo.user = atoi(meta.user.c_str()); storeInfo.storeName = meta.storeId; - EventCenter::GetInstance().PostEvent(std::make_unique(CloudEvent::CLEAN_DATA, storeInfo)); + if (action != GeneralStore::CLEAN_WATER) { + EventCenter::GetInstance().PostEvent(std::make_unique(CloudEvent::CLEAN_DATA, storeInfo)); + } auto status = store->Clean({}, action, ""); if (status != E_OK) { ZLOGW("remove device data status:%{public}d, user:%{public}d, bundleName:%{public}s, " @@ -668,12 +670,17 @@ std::pair CloudServiceImpl::QueryLastSyncInfo(const s int32_t CloudServiceImpl::OnInitialize() { XCollie xcollie(__FUNCTION__, XCollie::XCOLLIE_LOG | XCollie::XCOLLIE_RECOVERY); - NetworkDelegate::GetInstance()->RegOnNetworkChange(); DistributedDB::RuntimeConfig::SetCloudTranslate(std::make_shared()); - Execute(GenTask(0, 0, CloudSyncScene::SERVICE_INIT, - { WORK_CLOUD_INFO_UPDATE, WORK_SCHEMA_UPDATE, WORK_DO_CLOUD_SYNC, WORK_SUB })); std::vector users; Account::GetInstance()->QueryUsers(users); + for (auto user : users) { + if (user == DEFAULT_USER) { + continue; + } + CleanWaterVersion(user); + } + Execute(GenTask(0, 0, CloudSyncScene::SERVICE_INIT, + { WORK_CLOUD_INFO_UPDATE, WORK_SCHEMA_UPDATE, WORK_DO_CLOUD_SYNC, WORK_SUB })); for (auto user : users) { if (user == DEFAULT_USER) { continue; @@ -688,6 +695,35 @@ int32_t CloudServiceImpl::OnInitialize() return E_OK; } +bool CloudServiceImpl::CleanWaterVersion(int32_t user) +{ + auto [status, cloudInfo] = GetCloudInfoFromMeta(user); + if (status != SUCCESS) { + return false; + } + auto stores = CheckerManager::GetInstance().GetDynamicStores(); + auto staticStores = CheckerManager::GetInstance().GetStaticStores(); + stores.insert(stores.end(), staticStores.begin(), staticStores.end()); + auto keys = cloudInfo.GetSchemaKey(); + for (const auto &[bundle, key] : keys) { + SchemaMeta schemaMeta; + if (MetaDataManager::GetInstance().LoadMeta(key, schemaMeta, true) && + schemaMeta.metaVersion < SchemaMeta::CLEAN_WATER_VERSION) { + bool found = std::any_of(stores.begin(), stores.end(), + [&schemaMeta](const CheckerManager::StoreInfo &storeInfo) { + return storeInfo.bundleName == schemaMeta.bundleName; + }); + if (!found) { + continue; + } + DoClean(user, schemaMeta, GeneralStore::CleanMode::CLEAN_WATER); + schemaMeta.metaVersion = SchemaMeta::CLEAN_WATER_VERSION; + } + MetaDataManager::GetInstance().SaveMeta(key, schemaMeta, true); + } + return true; +} + int32_t CloudServiceImpl::OnBind(const BindInfo &info) { if (executor_ != nullptr || info.executors == nullptr) { @@ -792,7 +828,8 @@ std::pair CloudServiceImpl::GetCloudInfoFromServer(int32_t u ZLOGD("cloud server is nullptr, user:%{public}d", userId); return { SERVER_UNAVAILABLE, cloudInfo }; } - return instance->GetServerInfo(cloudInfo.user, false); + auto [code, info] = instance->GetServerInfo(cloudInfo.user, false); + return { code != E_OK ? code : info.IsValid() ? E_OK : E_ERROR, info }; } int32_t CloudServiceImpl::UpdateCloudInfoFromServer(int32_t user) diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.h b/services/distributeddataservice/service/cloud/cloud_service_impl.h index c1ec1dd099cb44a31eabce1bd26ef50a685672ad..21283817f210f1f06cb0611f7a7fc4bff8aec9b3 100644 --- a/services/distributeddataservice/service/cloud/cloud_service_impl.h +++ b/services/distributeddataservice/service/cloud/cloud_service_impl.h @@ -145,6 +145,7 @@ private: bool ReleaseUserInfo(int32_t user, CloudSyncScene scene); bool DoCloudSync(int32_t user, CloudSyncScene scene); bool StopCloudSync(int32_t user, CloudSyncScene scene); + bool CleanWaterVersion(int32_t user); static std::pair GetCloudInfo(int32_t userId); static std::pair GetCloudInfoFromMeta(int32_t userId); diff --git a/services/distributeddataservice/service/cloud/sync_manager.cpp b/services/distributeddataservice/service/cloud/sync_manager.cpp index 1391796224bf894a550a943e687400803348fb65..adb7e9e532a792693a0dfd4efac47f05334b6719 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.cpp +++ b/services/distributeddataservice/service/cloud/sync_manager.cpp @@ -201,8 +201,8 @@ std::function SyncManager::GetLockChangeHandler() SyncManager::SyncManager() { - EventCenter::GetInstance().Subscribe(CloudEvent::LOCK_CLOUD_CONTAINER, GetLockChangeHandler()); - EventCenter::GetInstance().Subscribe(CloudEvent::UNLOCK_CLOUD_CONTAINER, GetLockChangeHandler()); + EventCenter::GetInstance().Subscribe(CloudEvent::LOCK_CLOUD_CONTAINER, SyncManager::GetLockChangeHandler()); + EventCenter::GetInstance().Subscribe(CloudEvent::UNLOCK_CLOUD_CONTAINER, SyncManager::GetLockChangeHandler()); EventCenter::GetInstance().Subscribe(CloudEvent::LOCAL_CHANGE, GetClientChangeHandler()); syncStrategy_ = std::make_shared(); auto metaName = Bootstrap::GetInstance().GetProcessLabel(); @@ -299,15 +299,15 @@ std::function SyncManager::GetPostEventTask(const std::vectorsecond, SyncStage::END, - E_ERROR }); + SyncManager::Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second, + SyncStage::END, E_ERROR, "!IsOn:" + schema.bundleName }); continue; } for (const auto &database : schema.databases) { if (!info.Contains(database.name)) { UpdateFinishSyncInfo({ cloud.user, cloud.id, schema.bundleName, database.name }, syncId, E_ERROR); - Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second, SyncStage::END, - E_ERROR }); + SyncManager::Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second, + SyncStage::END, E_ERROR, "!Contains:" + database.name }); continue; } StoreInfo storeInfo = { 0, schema.bundleName, database.name, cloud.apps[schema.bundleName].instanceId, @@ -317,8 +317,8 @@ std::function SyncManager::GetPostEventTask(const std::vectorsecond, SyncStage::END, - status }); + SyncManager::Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second, + SyncStage::END, status, "CheckSyncAction" }); info.SetError(status); continue; } @@ -353,13 +353,13 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount info.SetError(E_CLOUD_DISABLED); return; } - auto traceIds = GetPrepareTraceId(info, cloud); + auto traceIds = SyncManager::GetPrepareTraceId(info, cloud); BatchReport(info.user_, traceIds, SyncStage::PREPARE, E_OK); UpdateStartSyncInfo(cloudSyncInfos); auto code = IsValid(info, cloud); if (code != E_OK) { BatchUpdateFinishState(cloudSyncInfos, code); - BatchReport(info.user_, traceIds, SyncStage::END, code); + BatchReport(info.user_, traceIds, SyncStage::END, code, "!IsValid"); return; } @@ -373,7 +373,7 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount retryer(RETRY_INTERVAL, E_RETRY_TIMEOUT, GenStore::CLOUD_ERR_OFFSET + E_CLOUD_DISABLED, it == traceIds.end() ? "" : it->second); BatchUpdateFinishState(cloudSyncInfos, E_CLOUD_DISABLED); - BatchReport(info.user_, traceIds, SyncStage::END, E_CLOUD_DISABLED); + BatchReport(info.user_, traceIds, SyncStage::END, E_CLOUD_DISABLED, "empty schema:" + info.bundleName_); return; } } @@ -386,6 +386,34 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount }; } +void SyncManager::StartCloudSync(const DistributedData::SyncEvent &evt, const StoreMetaData &meta, + const AutoCache::Store &store, Retryer retryer, DistributedData::GenDetails &details) +{ + auto &storeInfo = evt.GetStoreInfo(); + GenAsync async = evt.GetAsyncDetail(); + auto prepareTraceId = evt.GetPrepareTraceId(); + auto user = evt.GetUser(); + auto &detail = details[SyncInfo::DEFAULT_ID]; + ReportSyncEvent(evt, BizState::BEGIN, E_OK); + SyncParam syncParam = { evt.GetMode(), evt.GetWait(), evt.IsCompensation(), MODE_DEFAULT, prepareTraceId }; + syncParam.asyncDownloadAsset = meta.asyncDownloadAsset; + auto [status, dbCode] = store->Sync({ SyncInfo::DEFAULT_ID }, *(evt.GetQuery()), + evt.AutoRetry() ? RetryCallback(storeInfo, retryer, evt.GetTriggerMode(), prepareTraceId, user) + : GetCallback(async, storeInfo, evt.GetTriggerMode(), prepareTraceId, user), syncParam); + if (status != E_OK) { + if (async) { + detail.code = status; + async(std::move(details)); + } + UpdateFinishSyncInfo({ storeInfo.user, GetAccountId(storeInfo.user), storeInfo.bundleName, + storeInfo.storeName }, storeInfo.syncId, E_ERROR); + if (status != GeneralError::E_NOT_SUPPORT) { + auto code = dbCode == 0 ? GenStore::CLOUD_ERR_OFFSET + status : dbCode; + ReportSyncEvent(evt, BizState::END, code); + } + } +} + std::function SyncManager::GetSyncHandler(Retryer retryer) { return [this, retryer](const Event &event) { @@ -393,13 +421,13 @@ std::function SyncManager::GetSyncHandler(Retryer retryer) auto &storeInfo = evt.GetStoreInfo(); GenAsync async = evt.GetAsyncDetail(); auto prepareTraceId = evt.GetPrepareTraceId(); - auto user = evt.GetUser(); GenDetails details; auto &detail = details[SyncInfo::DEFAULT_ID]; detail.progress = GenProgress::SYNC_FINISH; auto [hasMeta, meta] = GetMetaData(storeInfo); if (!hasMeta) { - return DoExceptionalCallback(async, details, storeInfo, prepareTraceId); + return DoExceptionalCallback(async, details, storeInfo, + {0, "", prepareTraceId, SyncStage::END, GeneralError::E_ERROR, "no meta"}); } auto [code, store] = GetStore(meta, storeInfo.user); if (code == E_SCREEN_LOCKED) { @@ -408,51 +436,35 @@ std::function SyncManager::GetSyncHandler(Retryer retryer) if (store == nullptr) { ZLOGE("store null, storeId:%{public}s, prepareTraceId:%{public}s", meta.GetStoreAlias().c_str(), prepareTraceId.c_str()); - return DoExceptionalCallback(async, details, storeInfo, prepareTraceId); + return DoExceptionalCallback(async, details, storeInfo, + {0, "", prepareTraceId, SyncStage::END, GeneralError::E_ERROR, "store null"}); } if (!meta.enableCloud) { ZLOGW("meta.enableCloud is false, storeId:%{public}s, prepareTraceId:%{public}s", meta.GetStoreAlias().c_str(), prepareTraceId.c_str()); - return DoExceptionalCallback(async, details, storeInfo, prepareTraceId, E_CLOUD_DISABLED); + return DoExceptionalCallback(async, details, storeInfo, + {0, "", prepareTraceId, SyncStage::END, E_CLOUD_DISABLED, "disable cloud"}); } ZLOGI("database:<%{public}d:%{public}s:%{public}s:%{public}s> sync start, asyncDownloadAsset?[%{public}d]", storeInfo.user, storeInfo.bundleName.c_str(), meta.GetStoreAlias().c_str(), prepareTraceId.c_str(), meta.asyncDownloadAsset); - ReportSyncEvent(evt, BizState::BEGIN, E_OK); - SyncParam syncParam = { evt.GetMode(), evt.GetWait(), evt.IsCompensation(), MODE_DEFAULT, prepareTraceId }; - syncParam.asyncDownloadAsset = meta.asyncDownloadAsset; - auto [status, dbCode] = store->Sync({ SyncInfo::DEFAULT_ID }, *(evt.GetQuery()), - evt.AutoRetry() ? RetryCallback(storeInfo, retryer, evt.GetTriggerMode(), prepareTraceId, user) - : GetCallback(async, storeInfo, evt.GetTriggerMode(), prepareTraceId, user), syncParam); - if (status != E_OK) { - if (async) { - detail.code = status; - async(std::move(details)); - } - UpdateFinishSyncInfo({ storeInfo.user, GetAccountId(storeInfo.user), storeInfo.bundleName, - storeInfo.storeName }, storeInfo.syncId, E_ERROR); - if (status != GeneralError::E_NOT_SUPPORT) { - auto code = dbCode == 0 ? GenStore::CLOUD_ERR_OFFSET + status : dbCode; - ReportSyncEvent(evt, BizState::END, code); - } - } + StartCloudSync(evt, meta, store, retryer, details); }; } void SyncManager::ReportSyncEvent(const SyncEvent &evt, BizState bizState, int32_t code) { - SyncStage syncStage = SyncStage::START; auto &storeInfo = evt.GetStoreInfo(); if (bizState == BizState::BEGIN) { - syncStage = SyncStage::START; RadarReporter::Report({storeInfo.bundleName.c_str(), CLOUD_SYNC, TRIGGER_SYNC, storeInfo.syncId, evt.GetTriggerMode()}, "GetSyncHandler", bizState); } else { - syncStage = SyncStage::END; RadarReporter::Report({storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC, storeInfo.syncId, evt.GetTriggerMode(), code}, "GetSyncHandler", bizState); } - Report({evt.GetUser(), storeInfo.bundleName, evt.GetPrepareTraceId(), syncStage, code}); + SyncStage syncStage = (bizState == BizState::BEGIN) ? SyncStage::START : SyncStage::END; + SyncManager::Report({evt.GetUser(), storeInfo.bundleName, evt.GetPrepareTraceId(), syncStage, code, + "GetSyncHandler"}); } std::function SyncManager::GetClientChangeHandler() @@ -495,8 +507,8 @@ SyncManager::Retryer SyncManager::GetRetryer(int32_t times, const SyncInfo &sync RadarReporter::Report({ info.bundleName_.c_str(), CLOUD_SYNC, FINISH_SYNC, info.syncId_, info.triggerMode_, dbCode }, "GetRetryer", BizState::END); - Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, - dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode }); + SyncManager::Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, + dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode, "GetRetryer finish" }); Report(FT_CALLBACK, info.bundleName_, static_cast(Fault::CSF_GS_CLOUD_SYNC), "code=" + std::to_string(code) + ",dbCode=" + std::to_string(static_cast(dbCode))); return true; @@ -512,8 +524,8 @@ SyncManager::Retryer SyncManager::GetRetryer(int32_t times, const SyncInfo &sync RadarReporter::Report({ info.bundleName_.c_str(), CLOUD_SYNC, FINISH_SYNC, info.syncId_, info.triggerMode_, dbCode }, "GetRetryer", BizState::END); - Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, - dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode }); + SyncManager::Report({ user, info.bundleName_, prepareTraceId, SyncStage::END, + dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode, "GetRetryer continue" }); Report(FT_CALLBACK, info.bundleName_, static_cast(Fault::CSF_GS_CLOUD_SYNC), "code=" + std::to_string(code) + ",dbCode=" + std::to_string(static_cast(dbCode))); return true; @@ -723,7 +735,7 @@ std::pair SyncManager::GetLastResults(std::mapsecond.code != -1) { - return { SUCCESS, std::move(iter->second) }; + return { SUCCESS, iter->second }; } return { E_ERROR, {} }; } @@ -757,7 +769,7 @@ std::pair> SyncManager::QueryL if (lastSyncInfoMap.find(queryKey.storeId) != lastSyncInfoMap.end()) { continue; } - auto [status, syncInfo] = GetLastSyncInfoFromMeta(queryKey); + auto [status, syncInfo] = SyncManager::GetLastSyncInfoFromMeta(queryKey); if (status == SUCCESS) { lastSyncInfoMap.insert(std::make_pair(std::move(syncInfo.storeId), std::move(syncInfo))); } @@ -831,7 +843,7 @@ std::function SyncManager::GetCallback(const Gen RadarReporter::Report({ storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC, storeInfo.syncId, triggerMode, dbCode, result.begin()->second.changeCount }, "GetCallback", BizState::END); - Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, dbCode }); + SyncManager::Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, dbCode, "GetCallback" }); if (dbCode != 0) { Report(FT_CALLBACK, storeInfo.bundleName, static_cast(Fault::CSF_GS_CLOUD_SYNC), "callback failed, dbCode=" + std::to_string(dbCode)); @@ -878,15 +890,16 @@ std::vector SyncManager::GetSchemaMeta(const CloudInfo &cloud, const } void SyncManager::DoExceptionalCallback(const GenAsync &async, GenDetails &details, const StoreInfo &storeInfo, - const std::string &prepareTraceId, int32_t code) + const ReportParam ¶m) { if (async) { - details[SyncInfo::DEFAULT_ID].code = code; + details[SyncInfo::DEFAULT_ID].code = param.errCode; async(details); } QueryKey queryKey{ storeInfo.user, GetAccountId(storeInfo.user), storeInfo.bundleName, storeInfo.storeName }; - UpdateFinishSyncInfo(queryKey, storeInfo.syncId, code); - Report({ storeInfo.user, storeInfo.bundleName, prepareTraceId, SyncStage::END, code }); + UpdateFinishSyncInfo(queryKey, storeInfo.syncId, param.errCode); + SyncManager::Report({ storeInfo.user, storeInfo.bundleName, param.prepareTraceId, SyncStage::END, + param.errCode, param.message }); } bool SyncManager::InitDefaultUser(int32_t &user) @@ -920,8 +933,8 @@ std::function SyncManager::Retr RadarReporter::Report({ storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC, storeInfo.syncId, triggerMode, code, details.begin()->second.changeCount }, "RetryCallback", BizState::END); - Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, - dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode }); + SyncManager::Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, + dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode, "RetryCallback" }); } } retryer(GetInterval(code), code, dbCode, prepareTraceId); @@ -936,10 +949,11 @@ void SyncManager::BatchUpdateFinishState(const std::vector> &apps) { apps[meta.bundleName].insert(meta.storeId); return true; diff --git a/services/distributeddataservice/service/cloud/sync_manager.h b/services/distributeddataservice/service/cloud/sync_manager.h index 885cec96ba3d986e5a5a365d5822295738f6c725..bc19b107b1c29f4ae79c2ba187c1ce91b70eeb30 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.h +++ b/services/distributeddataservice/service/cloud/sync_manager.h @@ -46,7 +46,6 @@ public: using TraceIds = std::map; using SyncStage = DistributedData::SyncStage; using ReportParam = DistributedData::ReportParam; - static std::pair GetStore(const StoreMetaData &meta, int32_t user, bool mustBind = true); class SyncInfo final { public: using Store = std::string; @@ -95,12 +94,13 @@ public: }; SyncManager(); ~SyncManager(); + static void Report(const ReportParam &reportParam); + static std::pair GetStore(const StoreMetaData &meta, int32_t user, bool mustBind = true); int32_t Bind(std::shared_ptr executor); int32_t DoCloudSync(SyncInfo syncInfo); int32_t StopCloudSync(int32_t user = 0); std::pair> QueryLastSyncInfo( const std::vector &queryKeys); - void Report(const ReportParam &reportParam); void OnScreenUnlocked(int32_t user); void CleanCompensateSync(int32_t userId); @@ -137,6 +137,17 @@ private: static std::vector GetSchemaMeta(const CloudInfo &cloud, const std::string &bundleName); static bool NeedGetCloudInfo(CloudInfo &cloud); static GeneralError IsValid(SyncInfo &info, CloudInfo &cloud); + static std::function GetLockChangeHandler(); + static TraceIds GetPrepareTraceId(const SyncInfo &info, const CloudInfo &cloud); + static void Report( + const std::string &faultType, const std::string &bundleName, int32_t errCode, const std::string &appendix); + static std::pair GetLastResults(std::map &infos); + static std::pair GetLastSyncInfoFromMeta(const QueryKey &queryKey); + static void SaveLastSyncInfo(const QueryKey &queryKey, CloudLastSyncInfo &&info); + static void BatchReport(int32_t userId, const TraceIds &traceIds, SyncStage syncStage, int32_t errCode, + const std::string &message = ""); + static void ReportSyncEvent(const DistributedData::SyncEvent &evt, DistributedDataDfx::BizState bizState, + int32_t code); Task GetSyncTask(int32_t times, bool retry, RefCount ref, SyncInfo &&syncInfo); void UpdateSchema(const SyncInfo &syncInfo); std::function GetSyncHandler(Retryer retryer); @@ -151,24 +162,16 @@ private: std::function GetPostEventTask(const std::vector &schemas, CloudInfo &cloud, SyncInfo &info, bool retry, const TraceIds &traceIds); void DoExceptionalCallback(const GenAsync &async, GenDetails &details, const StoreInfo &storeInfo, - const std::string &prepareTraceId, int32_t code = GeneralError::E_ERROR); + const ReportParam ¶m); bool InitDefaultUser(int32_t &user); std::function RetryCallback(const StoreInfo &storeInfo, Retryer retryer, int32_t triggerMode, const std::string &prepareTraceId, int32_t user); - static std::pair GetLastResults(std::map &infos); void BatchUpdateFinishState(const std::vector> &cloudSyncInfos, int32_t code); bool NeedSaveSyncInfo(const QueryKey &queryKey); - std::function GetLockChangeHandler(); - void BatchReport(int32_t userId, const TraceIds &traceIds, SyncStage syncStage, int32_t errCode); - TraceIds GetPrepareTraceId(const SyncInfo &info, const CloudInfo &cloud); + void StartCloudSync(const DistributedData::SyncEvent &evt, const StoreMetaData &meta, + const AutoCache::Store &store, Retryer retryer, DistributedData::GenDetails &details); std::pair GetMetaData(const StoreInfo &storeInfo); void AddCompensateSync(const StoreMetaData &meta); - static void Report( - const std::string &faultType, const std::string &bundleName, int32_t errCode, const std::string &appendix); - void ReportSyncEvent(const DistributedData::SyncEvent &evt, DistributedDataDfx::BizState bizState, int32_t code); - std::pair GetLastSyncInfoFromMeta(const QueryKey &queryKey); - static void SaveLastSyncInfo(const QueryKey &queryKey, CloudLastSyncInfo &&info); - static std::atomic genId_; std::shared_ptr executor_; ConcurrentMap actives_; diff --git a/services/distributeddataservice/service/config/BUILD.gn b/services/distributeddataservice/service/config/BUILD.gn index a2ea71cf44720ce97423cf1140f3de53a08ea313..b5d6368020292f8baef84a9fa95b80bfbe859348 100644 --- a/services/distributeddataservice/service/config/BUILD.gn +++ b/services/distributeddataservice/service/config/BUILD.gn @@ -29,6 +29,8 @@ ohos_source_set("distributeddata_config") { "src/model/checker_config.cpp", "src/model/cloud_config.cpp", "src/model/component_config.cpp", + "src/model/datashare_config.cpp", + "src/model/device_sync_app_white_list_config.cpp", "src/model/directory_config.cpp", "src/model/global_config.cpp", "src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/config/include/config_factory.h b/services/distributeddataservice/service/config/include/config_factory.h index bce10b04a32c1579e11d31ab5f84100eb91a15a4..a5e9dbe089defb8ad393b6afcf842ab2bfa300df 100644 --- a/services/distributeddataservice/service/config/include/config_factory.h +++ b/services/distributeddataservice/service/config/include/config_factory.h @@ -33,6 +33,8 @@ public: API_EXPORT CloudConfig *GetCloudConfig(); API_EXPORT std::vector *GetAppIdMappingConfig(); API_EXPORT ThreadConfig *GetThreadConfig(); + API_EXPORT DataShareConfig *GetDataShareConfig(); + API_EXPORT DeviceSyncAppWhiteListConfig *GetDeviceSyncAppWhiteListConfig(); private: static constexpr const char *CONF_PATH = "/system/etc/distributeddata/conf"; ConfigFactory(); diff --git a/services/distributeddataservice/service/config/include/model/datashare_config.h b/services/distributeddataservice/service/config/include/model/datashare_config.h new file mode 100644 index 0000000000000000000000000000000000000000..4487c0d1bcbaa3f4f0f6a5af936a31fb0cea4631 --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/datashare_config.h @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DATASHARE_CONFIG_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DATASHARE_CONFIG_H + +#include "serializable/serializable.h" +namespace OHOS { +namespace DistributedData { +class DataShareConfig final : public Serializable { +public: + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; + std::vector dataShareExtNames; +}; +} // namespace DistributedData +} // namespace OHOS +#endif //OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DATASHARE_CONFIG_H \ No newline at end of file diff --git a/services/distributeddataservice/service/config/include/model/device_sync_app_white_list_config.h b/services/distributeddataservice/service/config/include/model/device_sync_app_white_list_config.h new file mode 100644 index 0000000000000000000000000000000000000000..03729b9c77c52dbdf74d6498087f7856f1e36953 --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/device_sync_app_white_list_config.h @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DEVICE_SYNC_APP_WHITE_LIST_CONFIG_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DEVICE_SYNC_APP_WHITE_LIST_CONFIG_H + +#include "serializable/serializable.h" +namespace OHOS { +namespace DistributedData { +class DeviceSyncAppWhiteListConfig final : public Serializable { +public: + struct WhiteList final : public Serializable { + std::string appId; + std::string bundleName; + uint32_t version; + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; + }; + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; + + std::vector whiteLists; +}; +} // namespace DistributedData +} // namespace OHOS +#endif //OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DEVICE_SYNC_APP_WHITE_LIST_CONFIG_H diff --git a/services/distributeddataservice/service/config/include/model/global_config.h b/services/distributeddataservice/service/config/include/model/global_config.h index 91f5a237b3b7309f0e34444e1c4f2cebdb574a8f..751b91f2ee74cd9f0298290ca187ff00af2322ca 100644 --- a/services/distributeddataservice/service/config/include/model/global_config.h +++ b/services/distributeddataservice/service/config/include/model/global_config.h @@ -20,9 +20,11 @@ #include "model/checker_config.h" #include "model/cloud_config.h" #include "model/component_config.h" +#include "model/datashare_config.h" #include "model/directory_config.h" #include "model/network_config.h" #include "model/thread_config.h" +#include "model/device_sync_app_white_list_config.h" #include "serializable/serializable.h" namespace OHOS { namespace DistributedData { @@ -40,6 +42,8 @@ public: CloudConfig *cloud = nullptr; std::vector *appIdMapping = nullptr; ThreadConfig *thread = nullptr; + DataShareConfig *dataShare = nullptr; + DeviceSyncAppWhiteListConfig *deviceSyncAppWhiteList = nullptr; ~GlobalConfig(); bool Marshal(json &node) const override; bool Unmarshal(const json &node) override; diff --git a/services/distributeddataservice/service/config/src/config_factory.cpp b/services/distributeddataservice/service/config/src/config_factory.cpp index 3b05fce80631bf9ee5ea0b5bad1b6a56172cf3c8..781e3b55b4a100a2802d70587f8ec501a71c5c74 100644 --- a/services/distributeddataservice/service/config/src/config_factory.cpp +++ b/services/distributeddataservice/service/config/src/config_factory.cpp @@ -91,5 +91,15 @@ ThreadConfig *ConfigFactory::GetThreadConfig() { return config_.thread; } + +DataShareConfig *ConfigFactory::GetDataShareConfig() +{ + return config_.dataShare; +} + +DeviceSyncAppWhiteListConfig *ConfigFactory::GetDeviceSyncAppWhiteListConfig() +{ + return config_.deviceSyncAppWhiteList; +} } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/datashare_config.cpp b/services/distributeddataservice/service/config/src/model/datashare_config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0eae37a2bb68630dadcef21cf9a51dbed30ed307 --- /dev/null +++ b/services/distributeddataservice/service/config/src/model/datashare_config.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "model/datashare_config.h" +namespace OHOS { +namespace DistributedData { +bool DataShareConfig::Marshal(json &node) const +{ + SetValue(node[GET_NAME(dataShareExtNames)], dataShareExtNames); + return true; +} + +bool DataShareConfig::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(dataShareExtNames), dataShareExtNames); + return true; +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp b/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..594d3f2ae9159af93ae90a2e67edc9eabcc821ba --- /dev/null +++ b/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "model/device_sync_app_white_list_config.h" +namespace OHOS { +namespace DistributedData { +bool DeviceSyncAppWhiteListConfig::Marshal(Serializable::json &node) const +{ + SetValue(node[GET_NAME(whiteLists)], whiteLists); + return true; +} +bool DeviceSyncAppWhiteListConfig::Unmarshal(const Serializable::json &node) +{ + GetValue(node, GET_NAME(whiteLists), whiteLists); + return true; +} + +bool DeviceSyncAppWhiteListConfig::WhiteList::Marshal(Serializable::json &node) const +{ + SetValue(node[GET_NAME(appId)], appId); + SetValue(node[GET_NAME(bundleName)], bundleName); + SetValue(node[GET_NAME(version)], version); + return true; +} +bool DeviceSyncAppWhiteListConfig::WhiteList::Unmarshal(const Serializable::json &node) +{ + GetValue(node, GET_NAME(appId), appId); + GetValue(node, GET_NAME(bundleName), bundleName); + GetValue(node, GET_NAME(version), version); + return true; +} +} // namespace DistributedData +} // namespace OHOS diff --git a/services/distributeddataservice/service/config/src/model/global_config.cpp b/services/distributeddataservice/service/config/src/model/global_config.cpp index e64b012260e566a811e6883f32ab5f12e90bce1b..1956f82187097f3203048e0c3cd7c5759bc45f7c 100644 --- a/services/distributeddataservice/service/config/src/model/global_config.cpp +++ b/services/distributeddataservice/service/config/src/model/global_config.cpp @@ -30,6 +30,8 @@ bool GlobalConfig::Marshal(json &node) const SetValue(node[GET_NAME(cloud)], cloud); SetValue(node[GET_NAME(appIdMapping)], appIdMapping); SetValue(node[GET_NAME(thread)], thread); + SetValue(node[GET_NAME(dataShare)], dataShare); + SetValue(node[GET_NAME(deviceSyncAppWhiteList)], deviceSyncAppWhiteList); return true; } @@ -47,6 +49,8 @@ bool GlobalConfig::Unmarshal(const json &node) GetValue(node, GET_NAME(cloud), cloud); GetValue(node, GET_NAME(appIdMapping), appIdMapping); GetValue(node, GET_NAME(thread), thread); + GetValue(node, GET_NAME(dataShare), dataShare); + GetValue(node, GET_NAME(deviceSyncAppWhiteList), deviceSyncAppWhiteList); return true; } @@ -60,6 +64,7 @@ GlobalConfig::~GlobalConfig() delete cloud; delete appIdMapping; delete thread; + delete deviceSyncAppWhiteList; } } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/crypto/src/crypto_manager.cpp b/services/distributeddataservice/service/crypto/src/crypto_manager.cpp index 16a7754648e8b3c6362f13548d6db3c2e75bd521..e278c678fc1e6628d2c02639d6ced2393483deea 100644 --- a/services/distributeddataservice/service/crypto/src/crypto_manager.cpp +++ b/services/distributeddataservice/service/crypto/src/crypto_manager.cpp @@ -64,7 +64,7 @@ bool AddHksParams(HksParamSet *params, const CryptoManager::ParamConfig ¶mCo }; if (paramConfig.storageLevel > HKS_AUTH_STORAGE_LEVEL_DE) { hksParam.emplace_back( - HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::stoi(paramConfig.userId) }); + HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::atoi(paramConfig.userId.c_str()) }); } auto ret = HksAddParams(params, aes256Param, sizeof(aes256Param) / sizeof(aes256Param[0])); @@ -100,7 +100,7 @@ int32_t GetRootKeyParams(HksParamSet *¶ms, uint32_t storageLevel, const std: { .tag = HKS_TAG_AUTH_STORAGE_LEVEL, .uint32Param = storageLevel }, }; if (storageLevel > HKS_AUTH_STORAGE_LEVEL_DE) { - hksParam.emplace_back(HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::stoi(userId) }); + hksParam.emplace_back(HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::atoi(userId.c_str()) }); } ret = HksAddParams(params, hksParam.data(), hksParam.size()); diff --git a/services/distributeddataservice/service/data_share/BUILD.gn b/services/distributeddataservice/service/data_share/BUILD.gn index 5f435aa5e4e169b70ece36b0534ce9b73bc877a1..8bc36903c6e47bf6aadf24dfe0103e78c479b115 100644 --- a/services/distributeddataservice/service/data_share/BUILD.gn +++ b/services/distributeddataservice/service/data_share/BUILD.gn @@ -28,6 +28,7 @@ config("module_public_config") { "${datashare_path}/interfaces/inner_api/common/include", "${datashare_path}/interfaces/inner_api/consumer/include", "${data_service_path}/adapter/include/communicator", + "${data_service_path}/service/config/include", "../common", "../crypto/include", "../permission/include", @@ -48,6 +49,7 @@ ohos_source_set("data_share_service") { sources = [ "common/app_connect_manager.cpp", "common/bundle_mgr_proxy.cpp", + "common/common_utils.cpp", "common/db_delegate.cpp", "common/div_strategy.cpp", "common/extension_ability_manager.cpp", @@ -130,6 +132,8 @@ ohos_source_set("data_share_service") { "json:nlohmann_json_static", "kv_store:datamgr_common", "kv_store:distributeddb", + "qos_manager:concurrent_task_client", + "qos_manager:qos", "relational_store:native_rdb", "relational_store:rdb_data_share_adapter", "samgr:samgr_proxy", diff --git a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp index 410408bebdc46acdf66bf3aeaac84aff456fb54b..4e5e29b04eac7e6b3eb3cdfa75bab08b493bbffa 100644 --- a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp +++ b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp @@ -16,6 +16,7 @@ #include "bundle_mgr_proxy.h" #include "account/account_delegate.h" +#include "common_utils.h" #include "datashare_errno.h" #include "datashare_radar_reporter.h" #include "if_system_ability_manager.h" @@ -114,6 +115,23 @@ int BundleMgrProxy::GetBundleInfoFromBMS( return E_OK; } +int BundleMgrProxy::GetBundleInfoFromBMSWithCheck( + const std::string &bundleName, int32_t userId, BundleConfig &bundleConfig, int32_t appIndex) +{ + int res = GetBundleInfoFromBMS(bundleName, userId, bundleConfig, appIndex); + if (res != E_OK) { + return res; + } + // Not allow normal app visit normal app. + if (!DataShareThreadLocal::IsFromSystemApp() && !bundleConfig.isSystemApp) { + ZLOGE("Not allow normal app visit normal app, bundle:%{public}s, callingPid:%{public}d", + bundleName.c_str(), IPCSkeleton::GetCallingPid()); + return E_NOT_SYSTEM_APP; + } + + return E_OK; +} + std::pair BundleMgrProxy::GetCallerAppIdentifier( const std::string &bundleName, int32_t userId) { @@ -199,6 +217,7 @@ std::pair BundleMgrProxy::ConvertToDataShareBundle(AppExecFwk return std::make_pair(err, bundleConfig); } bundleConfig.extensionInfos = extensionInfos; + bundleConfig.isSystemApp = bundleInfo.applicationInfo.isSystemApp; return std::make_pair(E_OK, bundleConfig); } diff --git a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h index 71bcc496eb74f059dc2830fcd47a6aaa767bb735..c0c3d774e82fdbdbe7415ee47e27ef63020e1910 100644 --- a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h +++ b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h @@ -57,6 +57,7 @@ struct ExtensionAbilityInfo { struct BundleConfig { std::string name; bool singleton = false; + bool isSystemApp = false; std::vector hapModuleInfos; std::vector extensionInfos; }; @@ -67,6 +68,8 @@ public: static std::shared_ptr GetInstance(); int GetBundleInfoFromBMS(const std::string &bundleName, int32_t userId, BundleConfig &bundleConfig, int32_t appIndex = 0); + int GetBundleInfoFromBMSWithCheck(const std::string &bundleName, int32_t userId, + BundleConfig &bundleConfig, int32_t appIndex = 0); void Delete(const std::string &bundleName, int32_t userId, int32_t appIndex); sptr CheckBMS(); std::pair GetCallerAppIdentifier(const std::string &bundleName, int32_t userId); diff --git a/services/distributeddataservice/service/data_share/common/common_utils.cpp b/services/distributeddataservice/service/data_share/common/common_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..deeab89cba0a01c3516b8f121b8a9bc15e5b4f91 --- /dev/null +++ b/services/distributeddataservice/service/data_share/common/common_utils.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define LOG_TAG "CommonUtils" +#include "common_utils.h" + +#include "accesstoken_kit.h" +#include "config_factory.h" +#include "log_print.h" +#include "tokenid_kit.h" + +namespace OHOS::DataShare { + +bool& DataShareThreadLocal::GetFromSystemApp() +{ + static thread_local bool isFromSystemApp = true; + return isFromSystemApp; +} + +void DataShareThreadLocal::SetFromSystemApp(bool isFromSystemApp) +{ + GetFromSystemApp() = isFromSystemApp; +} + +bool DataShareThreadLocal::IsFromSystemApp() +{ + return GetFromSystemApp(); +} + +void DataShareThreadLocal::CleanFromSystemApp() +{ + SetFromSystemApp(true); +} + +bool CheckSystemAbility(uint32_t tokenId) +{ + Security::AccessToken::ATokenTypeEnum tokenType = + Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId); + return (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE || + tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL); +} + +// GetTokenType use tokenId, and IsSystemApp use fullTokenId, these are different +bool CheckSystemCallingPermission(uint32_t tokenId, uint64_t fullTokenId) +{ + if (CheckSystemAbility(tokenId)) { + return true; + } + // IsSystemAppByFullTokenID here is not IPC + return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); +} + +} // namespace OHOS::DataShare diff --git a/services/distributeddataservice/service/data_share/common/common_utils.h b/services/distributeddataservice/service/data_share/common/common_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..1b8379dc7fdb2f7329ceaac9acabeda848921454 --- /dev/null +++ b/services/distributeddataservice/service/data_share/common/common_utils.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef DATASHARESERVICE_COMMON_UTILS_H +#define DATASHARESERVICE_COMMON_UTILS_H + +#include +#include + +namespace OHOS::DataShare { +struct DataShareThreadLocal { + static bool& GetFromSystemApp(); + static void SetFromSystemApp(bool isFromSystemApp); + static bool IsFromSystemApp(); + static void CleanFromSystemApp(); +}; + +bool CheckSystemAbility(uint32_t tokenId); + +bool CheckSystemCallingPermission(uint32_t tokenId, uint64_t fullTokenId); + +} // namespace OHOS::DataShare +#endif // DATASHARESERVICE_COMMON_UTILS_H diff --git a/services/distributeddataservice/service/data_share/common/context.h b/services/distributeddataservice/service/data_share/common/context.h index 62da611a254d8d44c04454d0a122c9623d542028..d19ebf6d162a7d690c2f02bce781b0bc98e8c47d 100644 --- a/services/distributeddataservice/service/data_share/common/context.h +++ b/services/distributeddataservice/service/data_share/common/context.h @@ -37,6 +37,7 @@ public: virtual ~Context() = default; std::string uri; int32_t currentUserId = -1; + int32_t visitedUserId = -1; int32_t appIndex = 0; int32_t haMode = 0; std::string permission; diff --git a/services/distributeddataservice/service/data_share/common/db_delegate.h b/services/distributeddataservice/service/data_share/common/db_delegate.h index 67bde3ade94818ace61918e5354756df6b303efd..0cb36808d507731ba5dcdcff61549766c7fad631 100644 --- a/services/distributeddataservice/service/data_share/common/db_delegate.h +++ b/services/distributeddataservice/service/data_share/common/db_delegate.h @@ -128,8 +128,8 @@ public: static std::shared_ptr GetInstance( bool reInit = false, const std::string &dir = "", const std::shared_ptr &executors = nullptr); virtual ~KvDBDelegate() = default; - virtual int32_t Upsert(const std::string &collectionName, const KvData &value) = 0; - virtual int32_t Delete(const std::string &collectionName, const std::string &filter) = 0; + virtual std::pair Upsert(const std::string &collectionName, const KvData &value) = 0; + virtual std::pair Delete(const std::string &collectionName, const std::string &filter) = 0; virtual int32_t Get(const std::string &collectionName, const Id &id, std::string &value) = 0; virtual int32_t Get(const std::string &collectionName, const std::string &filter, const std::string &projection, std::string &result) = 0; diff --git a/services/distributeddataservice/service/data_share/common/kv_delegate.cpp b/services/distributeddataservice/service/data_share/common/kv_delegate.cpp index 06f8cc6a2f803af9f0b12b1318ff9445ddc3e7ed..be360b40b615c146e1bcbf45acd12be84951b573 100644 --- a/services/distributeddataservice/service/data_share/common/kv_delegate.cpp +++ b/services/distributeddataservice/service/data_share/common/kv_delegate.cpp @@ -40,7 +40,8 @@ const char* g_backupFiles[] = { "dataShare.db.safe", "dataShare.db.undo", }; -const char* BACKUP_SUFFIX = ".backup"; +constexpr const char* BACKUP_SUFFIX = ".backup"; +constexpr std::chrono::milliseconds COPY_TIME_OUT_MS = std::chrono::milliseconds(500); // If isBackUp is true, remove db backup files. Otherwise remove source db files. void KvDelegate::RemoveDbFile(bool isBackUp) const @@ -65,12 +66,15 @@ bool KvDelegate::CopyFile(bool isBackup) std::filesystem::copy_options options = std::filesystem::copy_options::overwrite_existing; std::error_code code; bool ret = true; + int index = 0; for (auto &fileName : g_backupFiles) { std::string src = path_ + "/" + fileName; std::string dst = src; isBackup ? dst.append(BACKUP_SUFFIX) : src.append(BACKUP_SUFFIX); + TimeoutReport timeoutReport({"", "", "", __FUNCTION__, 0}); // If src doesn't exist, error will be returned through `std::error_code` bool copyRet = std::filesystem::copy_file(src, dst, options, code); + timeoutReport.Report(("file index:" + std::to_string(index)), COPY_TIME_OUT_MS); if (!copyRet) { ZLOGE("failed to copy file %{public}s, isBackup %{public}d, err: %{public}s", fileName, isBackup, code.message().c_str()); @@ -78,6 +82,7 @@ bool KvDelegate::CopyFile(bool isBackup) RemoveDbFile(isBackup); break; } + index++; } return ret; } @@ -128,29 +133,30 @@ bool KvDelegate::RestoreIfNeed(int32_t dbStatus) return false; } -int64_t KvDelegate::Upsert(const std::string &collectionName, const std::string &filter, const std::string &value) +std::pair KvDelegate::Upsert(const std::string &collectionName, const std::string &filter, + const std::string &value) { std::lock_guard lock(mutex_); if (!Init()) { ZLOGE("init failed, %{public}s", collectionName.c_str()); - return E_ERROR; + return std::make_pair(E_ERROR, 0); } - int count = GRD_UpsertDoc(db_, collectionName.c_str(), filter.c_str(), value.c_str(), 0); + int32_t count = GRD_UpsertDoc(db_, collectionName.c_str(), filter.c_str(), value.c_str(), 0); if (count <= 0) { ZLOGE("GRD_UpSertDoc failed,status %{public}d", count); RestoreIfNeed(count); - return count; + return std::make_pair(count, 0); } Flush(); - return E_OK; + return std::make_pair(E_OK, count); } -int32_t KvDelegate::Delete(const std::string &collectionName, const std::string &filter) +std::pair KvDelegate::Delete(const std::string &collectionName, const std::string &filter) { std::lock_guard lock(mutex_); if (!Init()) { ZLOGE("init failed, %{public}s", collectionName.c_str()); - return E_ERROR; + return std::make_pair(E_ERROR, 0); } std::vector queryResults; @@ -158,23 +164,25 @@ int32_t KvDelegate::Delete(const std::string &collectionName, const std::string if (status != E_OK) { ZLOGE("db GetBatch failed, %{public}s %{public}d", filter.c_str(), status); // `GetBatch` should decide whether to restore before errors are returned, so skip restoration here. - return status; + return std::make_pair(status, 0); } + int32_t deleteCount = 0; for (auto &result : queryResults) { auto count = GRD_DeleteDoc(db_, collectionName.c_str(), result.c_str(), 0); if (count < 0) { ZLOGE("GRD_DeleteDoc failed,status %{public}d %{public}s", count, result.c_str()); if (RestoreIfNeed(count)) { - return count; + return std::make_pair(count, 0); } continue; } + deleteCount += count; } Flush(); if (queryResults.size() > 0) { ZLOGI("Delete, %{public}s, count %{public}zu", collectionName.c_str(), queryResults.size()); } - return E_OK; + return std::make_pair(E_OK, deleteCount); } bool KvDelegate::Init() @@ -232,7 +240,7 @@ KvDelegate::~KvDelegate() } } -int32_t KvDelegate::Upsert(const std::string &collectionName, const KvData &value) +std::pair KvDelegate::Upsert(const std::string &collectionName, const KvData &value) { std::string id = value.GetId(); if (value.HasVersion() && value.GetVersion() != 0) { @@ -241,7 +249,7 @@ int32_t KvDelegate::Upsert(const std::string &collectionName, const KvData &valu if (value.GetVersion() <= version) { ZLOGE("GetVersion failed,%{public}s id %{private}s %{public}d %{public}d", collectionName.c_str(), id.c_str(), value.GetVersion(), version); - return E_VERSION_NOT_NEWER; + return std::make_pair(E_VERSION_NOT_NEWER, 0); } } } diff --git a/services/distributeddataservice/service/data_share/common/kv_delegate.h b/services/distributeddataservice/service/data_share/common/kv_delegate.h index 3ec92c7cdf01e3fb8c1c79dda4c4bf859e1541f2..fce4ecf31a44784043a05c323ff0e5084f8e7024 100644 --- a/services/distributeddataservice/service/data_share/common/kv_delegate.h +++ b/services/distributeddataservice/service/data_share/common/kv_delegate.h @@ -28,8 +28,8 @@ class KvDelegate final : public KvDBDelegate { public: KvDelegate(const std::string &path, const std::shared_ptr &executors); ~KvDelegate() override; - int32_t Upsert(const std::string &collectionName, const KvData &value) override; - int32_t Delete(const std::string &collectionName, const std::string &filter) override; + std::pair Upsert(const std::string &collectionName, const KvData &value) override; + std::pair Delete(const std::string &collectionName, const std::string &filter) override; int32_t Get(const std::string &collectionName, const Id &id, std::string &value) override; int32_t Get(const std::string &collectionName, const std::string &filter, const std::string &projection, @@ -41,7 +41,8 @@ public: private: bool Init(); bool GetVersion(const std::string &collectionName, const std::string &filter, int &version); - int64_t Upsert(const std::string &collectionName, const std::string &filter, const std::string &value); + std::pair Upsert(const std::string &collectionName, const std::string &filter, + const std::string &value); void Flush(); bool RestoreIfNeed(int32_t dbStatus); void Backup(); diff --git a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp index 9ccf692579bc545f9a899c70bb0c85685d202a39..de1036ff2b24476a28b4730fe59b0adbbbd37c79 100644 --- a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp +++ b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp @@ -341,7 +341,7 @@ bool RdbDelegate::IsLimit(int count, int32_t callingPid, uint32_t callingTokenId }); ZLOGE("resultSetCount is full, pid: %{public}d, owner is %{public}s", callingPid, logStr.c_str()); std::string appendix = "callingName:" + HiViewFaultAdapter::GetCallingName(callingTokenId).first; - DataShareFaultInfo faultInfo{RESULTSET_FULL, "callingTokenId:" + std::to_string(callingTokenId), + DataShareFaultInfo faultInfo{HiViewFaultAdapter::resultsetFull, "callingTokenId:" + std::to_string(callingTokenId), "Pid:" + std::to_string(callingPid), "owner:" + logStr, __FUNCTION__, E_RESULTSET_BUSY, appendix}; HiViewFaultAdapter::ReportDataFault(faultInfo); return true; diff --git a/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp b/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp index 79ca80155a6e32bfd36ac2af3417040ab57d13b1..ba1015c3620bc284370dec48698c13ad7eaeafb1 100644 --- a/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp +++ b/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp @@ -87,6 +87,13 @@ void SchedulerManager::Stop(const Key &key) void SchedulerManager::Enable(const Key &key, int32_t userId, const DistributedData::StoreMetaData &metaData) { + Template tpl; + if (!TemplateManager::GetInstance().Get(key, userId, tpl) || + tpl.scheduler_.empty() || tpl.scheduler_.find(REMIND_TIMER_FUNC) == std::string::npos) { + ZLOGE("find template scheduler failed, %{public}s, %{public}" PRId64 ", %{public}s", + DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str()); + return; + } bool isTimerStopped = false; { std::lock_guard lock(mutex_); diff --git a/services/distributeddataservice/service/data_share/data/published_data.cpp b/services/distributeddataservice/service/data_share/data/published_data.cpp index 894a8e58346f1623103f86b440c0b39e123a9596..0e73d871ae31b29bd78076c17e069de2bf0f77ed 100644 --- a/services/distributeddataservice/service/data_share/data/published_data.cpp +++ b/services/distributeddataservice/service/data_share/data/published_data.cpp @@ -170,7 +170,7 @@ void PublishedData::Delete(const std::string &bundleName, const int32_t userId) ZLOGE("db open failed"); return; } - int32_t status = delegate->Delete(KvDBDelegate::DATA_TABLE, + auto [status, count] = delegate->Delete(KvDBDelegate::DATA_TABLE, "{\"bundleName\":\"" + bundleName + "\", \"userId\": " + std::to_string(userId) + "}"); if (status != E_OK) { ZLOGE("db Delete failed, %{public}s %{public}d", bundleName.c_str(), status); @@ -209,9 +209,9 @@ void PublishedData::ClearAging() } if (data.timestamp < lastValidTime && PublishedDataSubscriberManager::GetInstance() .GetCount(PublishedDataKey(data.key, data.bundleName, data.subscriberId)) == 0) { - status = delegate->Delete(KvDBDelegate::DATA_TABLE, + auto [errorCode, count] = delegate->Delete(KvDBDelegate::DATA_TABLE, Id(PublishedData::GenId(data.key, data.bundleName, data.subscriberId), data.userId)); - if (status != E_OK) { + if (errorCode != E_OK) { ZLOGE("db Delete failed, %{public}s %{public}s", data.key.c_str(), data.bundleName.c_str()); } agingSize++; @@ -249,8 +249,8 @@ void PublishedData::UpdateTimestamp( return; } data.timestamp = now; - status = delegate->Upsert(KvDBDelegate::DATA_TABLE, PublishedData(data)); - if (status == E_OK) { + auto [errorCode, count] = delegate->Upsert(KvDBDelegate::DATA_TABLE, PublishedData(data)); + if (errorCode == E_OK) { ZLOGI("update timestamp %{private}s", data.key.c_str()); } } diff --git a/services/distributeddataservice/service/data_share/data/template_data.cpp b/services/distributeddataservice/service/data_share/data/template_data.cpp index baf5dc4d5dda77ae2d5773dba7ec7c9410ec25f7..79219aedefc4cb40bb85498c80b35a826049e236 100644 --- a/services/distributeddataservice/service/data_share/data/template_data.cpp +++ b/services/distributeddataservice/service/data_share/data/template_data.cpp @@ -135,13 +135,15 @@ bool TemplateData::Delete(const std::string &bundleName, const int32_t userId) ZLOGE("db open failed"); return false; } - auto status = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE, + auto [status, count] = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE, "{\"bundleName\":\"" + bundleName + "\", \"userId\": " + std::to_string(userId) + "}"); if (status != E_OK) { ZLOGE("db DeleteById failed, %{public}d", status); return false; } - delegate->NotifyBackup(); + if (count > 0) { + delegate->NotifyBackup(); + } return true; } @@ -154,12 +156,14 @@ bool TemplateData::Add(const std::string &uri, const int32_t userId, const std:: return false; } TemplateData data(uri, bundleName, subscriberId, userId, aTemplate); - auto status = delegate->Upsert(KvDBDelegate::TEMPLATE_TABLE, data); + auto [status, count] = delegate->Upsert(KvDBDelegate::TEMPLATE_TABLE, data); if (status != E_OK) { ZLOGE("db Upsert failed, %{public}d", status); return false; } - delegate->NotifyBackup(); + if (count > 0) { + delegate->NotifyBackup(); + } return true; } @@ -171,13 +175,15 @@ bool TemplateData::Delete( ZLOGE("db open failed"); return false; } - auto status = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE, + auto [status, count] = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE, static_cast(Id(TemplateData::GenId(uri, bundleName, subscriberId), userId))); if (status != E_OK) { ZLOGE("db DeleteById failed, %{public}d", status); return false; } - delegate->NotifyBackup(); + if (count > 0) { + delegate->NotifyBackup(); + } return true; } diff --git a/services/distributeddataservice/service/data_share/data_provider_config.cpp b/services/distributeddataservice/service/data_share/data_provider_config.cpp index e713b4acb9a0df4e915dab75eff1218e662fa404..74a7630fb64b124ff770c1696c298e162c8dc456 100644 --- a/services/distributeddataservice/service/data_share/data_provider_config.cpp +++ b/services/distributeddataservice/service/data_share/data_provider_config.cpp @@ -20,10 +20,13 @@ #include "accesstoken_kit.h" #include "account/account_delegate.h" +#include "config_factory.h" #include "datashare_errno.h" #include "hap_token_info.h" +#include "ipc_skeleton.h" #include "log_print.h" #include "strategies/general/load_config_common_strategy.h" +#include "tokenid_kit.h" #include "uri_utils.h" #include "utils/anonymous.h" @@ -61,7 +64,7 @@ std::pair DataProviderConfig::GetBundleInfo() } providerInfo_.bundleName = uriConfig_.pathSegments[0]; } - auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS( + auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck( providerInfo_.bundleName, providerInfo_.visitedUserId, bundleInfo, providerInfo_.appIndex); return std::make_pair(ret, bundleInfo); } @@ -155,7 +158,7 @@ int DataProviderConfig::GetFromExtension() return E_URI_NOT_EXIST; } BundleConfig bundleInfo; - auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS( + auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck( providerInfo_.bundleName, providerInfo_.visitedUserId, bundleInfo, providerInfo_.appIndex); if (ret != E_OK) { ZLOGE("BundleInfo failed! bundleName: %{public}s", providerInfo_.bundleName.c_str()); @@ -225,6 +228,17 @@ std::pair DataProviderConfig::GetProvider GetMetaDataFromUri(); return std::make_pair(ret, providerInfo_); } + if (ret != E_URI_NOT_EXIST) { + return std::make_pair(ret, providerInfo_); + } + auto fullTokenId = IPCSkeleton::GetCallingFullTokenID(); + Security::AccessToken::HapTokenInfo tokenInfo; + auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(IPCSkeleton::GetCallingTokenID(), tokenInfo); + if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId) + || (result == Security::AccessToken::RET_SUCCESS && !IsInExtList(tokenInfo.bundleName))) { + ZLOGE("The URI in the extension, is not allowed for silent access.! ret: %{public}d, bundleName: %{public}s," + "uri: %{public}s", ret, tokenInfo.bundleName.c_str(), providerInfo_.uri.c_str()); + } ret = GetFromExtension(); if (ret != E_OK) { ZLOGE("Get providerInfo failed! ret: %{public}d, uri: %{public}s", @@ -232,4 +246,14 @@ std::pair DataProviderConfig::GetProvider } return std::make_pair(ret, providerInfo_); } + +bool DataProviderConfig::IsInExtList(const std::string &bundleName) +{ + DataShareConfig *config = ConfigFactory::GetInstance().GetDataShareConfig(); + if (config == nullptr) { + return true; + } + std::vector& extNames = config->dataShareExtNames; + return std::find(extNames.begin(), extNames.end(), bundleName) != extNames.end(); +} } // namespace OHOS::DataShare diff --git a/services/distributeddataservice/service/data_share/data_provider_config.h b/services/distributeddataservice/service/data_share/data_provider_config.h index 6b2770dfe192333d919beb169443e5489ecdb6ea..99099ce8ac4cf8801d32c7f9072aa7dfa25818ce 100644 --- a/services/distributeddataservice/service/data_share/data_provider_config.h +++ b/services/distributeddataservice/service/data_share/data_provider_config.h @@ -63,6 +63,7 @@ private: int GetFromExtensionProperties(const ProfileInfo &profileInfo, const std::string &moduleName); void GetMetaDataFromUri(); std::pair GetBundleInfo(); + bool IsInExtList(const std::string &bundleName); enum class PATH_PARAM : int32_t { BUNDLE_NAME = 0, MODULE_NAME, diff --git a/services/distributeddataservice/service/data_share/data_share_profile_config.cpp b/services/distributeddataservice/service/data_share/data_share_profile_config.cpp index 9787d9df1dc7c2db46c955850895215c386a399c..ecf2ab8cdc64a6f349d993d1fd9770a3d3900ed2 100644 --- a/services/distributeddataservice/service/data_share/data_share_profile_config.cpp +++ b/services/distributeddataservice/service/data_share/data_share_profile_config.cpp @@ -275,9 +275,9 @@ bool DataShareProfileConfig::GetProfileInfo(const std::string &calledBundleName, { BundleConfig bundleInfo; // profile is the same when app clone - if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS(calledBundleName, + if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck(calledBundleName, currentUserId, bundleInfo) != E_OK) { - ZLOGE("data share GetBundleInfoFromBMS failed! bundleName: %{public}s, currentUserId = %{public}d", + ZLOGE("data share GetBundleInfoFromBMSWithCheck failed! bundleName: %{public}s, currentUserId = %{public}d", calledBundleName.c_str(), currentUserId); return false; } diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp index a837f76f94fd64a2ad543c4eb976173a5ae91d9b..4029047bab8a89080ffdc0924ab8b0c7f0620296 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp @@ -24,6 +24,7 @@ #include "app_connect_manager.h" #include "common_event_manager.h" #include "common_event_support.h" +#include "concurrent_task_client.h" #include "data_ability_observer_interface.h" #include "data_share_profile_config.h" #include "dataobs_mgr_client.h" @@ -83,11 +84,17 @@ public: void DataShareServiceImpl::SystemAbilityStatusChangeListener::OnAddSystemAbility( int32_t systemAbilityId, const std::string &deviceId) { - if (systemAbilityId != COMMON_EVENT_SERVICE_ID) { - return; - } - ZLOGI("Common event service start. saId:%{public}d", systemAbilityId); - InitSubEvent(); + ZLOGI("saId:%{public}d", systemAbilityId); + if (systemAbilityId == COMMON_EVENT_SERVICE_ID) { + InitSubEvent(); + } else if (systemAbilityId == CONCURRENT_TASK_SERVICE_ID) { + std::unordered_map payload; + // get current thread pid + payload["pid"] = std::to_string(getpid()); + // request qos auth for current pid + OHOS::ConcurrentTask::ConcurrentTaskClient::GetInstance().RequestAuth(payload); + } + return; } DataShareServiceImpl::Factory::Factory() @@ -118,7 +125,8 @@ std::pair DataShareServiceImpl::InsertEx(const std::string &ur callingTokenId}, true); auto [errCode, ret] = dbDelegate->InsertEx(providerInfo.tableName, valuesBucket); if (errCode == E_OK && ret > 0) { - NotifyChange(uri); + // only notify specific userId + NotifyChange(uri, providerInfo.visitedUserId); RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData); } else { ReportExcuteFault(callingTokenId, providerInfo, errCode, func); @@ -129,7 +137,7 @@ std::pair DataShareServiceImpl::InsertEx(const std::string &ur return ExecuteEx(uri, extUri, IPCSkeleton::GetCallingTokenID(), false, callBack); } -bool DataShareServiceImpl::NotifyChange(const std::string &uri) +bool DataShareServiceImpl::NotifyChange(const std::string &uri, int32_t userId) { RadarReporter::RadarReport report(RadarReporter::NOTIFY_OBSERVER_DATA_CHANGE, RadarReporter::NOTIFY_DATA_CHANGE, __FUNCTION__); @@ -139,8 +147,7 @@ bool DataShareServiceImpl::NotifyChange(const std::string &uri) report.SetError(RadarReporter::DATA_OBS_EMPTY_ERROR); return false; } - - ErrCode ret = obsMgrClient->NotifyChange(Uri(uri)); + ErrCode ret = obsMgrClient->NotifyChange(Uri(uri), userId); if (ret != ERR_OK) { ZLOGE("obsMgrClient->NotifyChange error return %{public}d", ret); report.SetError(RadarReporter::NOTIFY_ERROR); @@ -166,7 +173,7 @@ std::pair DataShareServiceImpl::UpdateEx(const std::string &ur callingTokenId}, true); auto [errCode, ret] = dbDelegate->UpdateEx(providerInfo.tableName, predicate, valuesBucket); if (errCode == E_OK && ret > 0) { - NotifyChange(uri); + NotifyChange(uri, providerInfo.visitedUserId); RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData); } else { ReportExcuteFault(callingTokenId, providerInfo, errCode, func); @@ -194,7 +201,7 @@ std::pair DataShareServiceImpl::DeleteEx(const std::string &ur callingTokenId}, true); auto [errCode, ret] = dbDelegate->DeleteEx(providerInfo.tableName, predicate); if (errCode == E_OK && ret > 0) { - NotifyChange(uri); + NotifyChange(uri, providerInfo.visitedUserId); RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData); } else { ReportExcuteFault(callingTokenId, providerInfo, errCode, func); @@ -251,7 +258,7 @@ int32_t DataShareServiceImpl::AddTemplate(const std::string &uri, const int64_t uri.c_str(), subscriberId, tpltId.bundleName_.c_str(), tplt.predicates_.size()); return templateStrategy_.Execute(context, [&uri, &tpltId, &tplt, &context]() -> int32_t { auto result = TemplateManager::GetInstance().Add( - Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->currentUserId, tplt); + Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->visitedUserId, tplt); RdbSubscriberManager::GetInstance().Emit(context->uri, tpltId.subscriberId_, tpltId.bundleName_, context); return result; }); @@ -270,7 +277,7 @@ int32_t DataShareServiceImpl::DelTemplate(const std::string &uri, const int64_t DistributedData::Anonymous::Change(uri).c_str(), subscriberId, tpltId.bundleName_.c_str()); return templateStrategy_.Execute(context, [&uri, &tpltId, &context]() -> int32_t { return TemplateManager::GetInstance().Delete( - Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->currentUserId); + Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->visitedUserId); }); } @@ -339,7 +346,7 @@ std::vector DataShareServiceImpl::Publish(const Data &data, con continue; } publishedData.emplace_back(context->uri, context->calledBundleName, item.subscriberId_); - userId = context->currentUserId; + userId = context->visitedUserId; } if (!publishedData.empty()) { PublishedDataSubscriberManager::GetInstance().Emit(publishedData, userId, callerBundleName); @@ -369,7 +376,8 @@ std::vector DataShareServiceImpl::SubscribeRdbData( auto context = std::make_shared(uri); results.emplace_back(uri, subscribeStrategy_.Execute(context, [&id, &observer, &context, this]() { return RdbSubscriberManager::GetInstance().Add( - Key(context->uri, id.subscriberId_, id.bundleName_), observer, context, binderInfo_.executors); + Key(context->uri, id.subscriberId_, id.bundleName_), + observer, context, binderInfo_.executors); })); } return results; @@ -437,7 +445,7 @@ std::vector DataShareServiceImpl::SubscribePublishedData(const result = subscribeStrategy_.Execute(context, [&subscriberId, &observer, &context]() { return PublishedDataSubscriberManager::GetInstance().Add( PublishedDataKey(context->uri, context->callerBundleName, subscriberId), observer, - context->callerTokenId); + context->callerTokenId, context->visitedUserId); }); results.emplace_back(uri, result); if (result == E_OK) { @@ -445,10 +453,10 @@ std::vector DataShareServiceImpl::SubscribePublishedData(const if (binderInfo_.executors != nullptr) { binderInfo_.executors->Execute([context, subscriberId]() { PublishedData::UpdateTimestamp( - context->uri, context->calledBundleName, subscriberId, context->currentUserId); + context->uri, context->calledBundleName, subscriberId, context->visitedUserId); }); } - userId = context->currentUserId; + userId = context->visitedUserId; } } if (!publishedKeys.empty()) { @@ -477,7 +485,7 @@ std::vector DataShareServiceImpl::UnsubscribePublishedData(cons if (result == E_OK && binderInfo_.executors != nullptr) { binderInfo_.executors->Execute([context, subscriberId]() { PublishedData::UpdateTimestamp( - context->uri, context->calledBundleName, subscriberId, context->currentUserId); + context->uri, context->calledBundleName, subscriberId, context->visitedUserId); }); } return result; @@ -510,7 +518,7 @@ std::vector DataShareServiceImpl::EnablePubSubs(const std::vect if (result == E_OK && binderInfo_.executors != nullptr) { binderInfo_.executors->Execute([context, subscriberId]() { PublishedData::UpdateTimestamp( - context->uri, context->calledBundleName, subscriberId, context->currentUserId); + context->uri, context->calledBundleName, subscriberId, context->visitedUserId); }); } results.emplace_back(uri, result); @@ -519,7 +527,7 @@ std::vector DataShareServiceImpl::EnablePubSubs(const std::vect if (PublishedDataSubscriberManager::GetInstance().IsNotifyOnEnabled(pKey, context->callerTokenId)) { publishedKeys.emplace_back(pKey); } - userId = context->currentUserId; + userId = context->visitedUserId; } } if (!publishedKeys.empty()) { @@ -548,7 +556,7 @@ std::vector DataShareServiceImpl::DisablePubSubs(const std::vec if (result == E_OK && binderInfo_.executors != nullptr) { binderInfo_.executors->Execute([context, subscriberId]() { PublishedData::UpdateTimestamp( - context->uri, context->calledBundleName, subscriberId, context->currentUserId); + context->uri, context->calledBundleName, subscriberId, context->visitedUserId); }); } return result; @@ -589,6 +597,7 @@ int32_t DataShareServiceImpl::OnBind(const BindInfo &binderInfo) DBDelegate::SetExecutorPool(binderInfo.executors); HiViewAdapter::GetInstance().SetThreadPool(binderInfo.executors); SubscribeCommonEvent(); + SubscribeConcurrentTask(); SubscribeTimeChanged(); SubscribeChange(); ZLOGI("end"); @@ -606,6 +615,17 @@ void DataShareServiceImpl::SubscribeCommonEvent() systemManager->SubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, callback); } +void DataShareServiceImpl::SubscribeConcurrentTask() +{ + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + ZLOGE("System mgr is nullptr"); + return; + } + sptr callback(new SystemAbilityStatusChangeListener()); + systemManager->SubscribeSystemAbility(CONCURRENT_TASK_SERVICE_ID, callback); +} + void DataShareServiceImpl::SubscribeChange() { EventCenter::GetInstance().Subscribe(RemoteChangeEvent::RDB_META_SAVE, [this](const Event &event) { @@ -1135,7 +1155,7 @@ void DataShareServiceImpl::ReportExcuteFault(uint32_t callingTokenId, DataProvid int32_t errCode, std::string &func) { std::string appendix = "callingName:" + HiViewFaultAdapter::GetCallingName(callingTokenId).first; - DataShareFaultInfo faultInfo = {CURD_FAILED, providerInfo.bundleName, providerInfo.moduleName, + DataShareFaultInfo faultInfo = {HiViewFaultAdapter::curdFailed, providerInfo.bundleName, providerInfo.moduleName, providerInfo.storeName, func, errCode, appendix}; HiViewFaultAdapter::ReportDataFault(faultInfo); } @@ -1150,13 +1170,14 @@ bool DataShareServiceImpl::VerifyPermission(const std::string &bundleName, const } } else { Security::AccessToken::HapTokenInfo tokenInfo; - auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo); - if (result == Security::AccessToken::RET_SUCCESS && tokenInfo.bundleName == bundleName) { - return true; - } // Provider from ProxyData, which does not allow empty permissions and cannot be access without configured if (permission.empty()) { - ZLOGE("Permission empty! token:0x%{public}x, bundleName:%{public}s", tokenId, bundleName.c_str()); + ZLOGI("Permission empty! token:0x%{public}x, bundleName:%{public}s", tokenId, bundleName.c_str()); + auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo); + if (result == Security::AccessToken::RET_SUCCESS && tokenInfo.bundleName == bundleName) { + return true; + } + ZLOGE("Permission denied!"); return false; } // If the permission is NO_PERMISSION, access is also allowed diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.h b/services/distributeddataservice/service/data_share/data_share_service_impl.h index e4d0a7d9d5d94a535750aa961947d451d9392512..90ee77d4a8b5aa4654ae278ce142d95101e3e3d7 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_impl.h +++ b/services/distributeddataservice/service/data_share/data_share_service_impl.h @@ -118,13 +118,14 @@ private: void RegisterDataShareServiceInfo(); void RegisterHandler(); bool SubscribeTimeChanged(); - bool NotifyChange(const std::string &uri); + bool NotifyChange(const std::string &uri, int32_t userId); bool GetCallerBundleName(std::string &bundleName); std::pair ExecuteEx(const std::string &uri, const std::string &extUri, const int32_t tokenId, bool isRead, ExecuteCallbackEx callback); std::pair GetCallerInfo(std::string &bundleName, int32_t &appIndex); int32_t GetBMSAndMetaDataStatus(const std::string &uri, const int32_t tokenId); void SubscribeCommonEvent(); + void SubscribeConcurrentTask(); static void InitSubEvent(); void AutoLaunch(const DistributedData::Event &event); void SubscribeChange(); diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp index 229afde9572d7e6fbe7db80d62848490b6cfdfb6..170de1bcb8964843755595f357a3103401f804e7 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp @@ -18,6 +18,7 @@ #include "data_share_service_stub.h" #include +#include "common_utils.h" #include "data_share_obs_proxy.h" #include "hiview_adapter.h" #include "hiview_fault_adapter.h" @@ -25,10 +26,25 @@ #include "ishared_result_set.h" #include "itypes_util.h" #include "log_print.h" +#include "qos.h" #include "utils/anonymous.h" namespace OHOS { namespace DataShare { + +class DataShareServiceStub::QosManager { +public: + QosManager() + { + // set thread qos QOS_USER_INTERACTIVE + QOS::SetThreadQos(QOS::QosLevel::QOS_USER_INTERACTIVE); + } + ~QosManager() + { + QOS::ResetThreadQos(); + } +}; + bool DataShareServiceStub::CheckInterfaceToken(MessageParcel &data) { auto localDescriptor = IDataShareService::GetDescriptor(); @@ -51,6 +67,8 @@ int32_t DataShareServiceStub::OnInsertEx(MessageParcel &data, MessageParcel &rep return IPC_STUB_INVALID_DATA_ERR; } auto [errCode, status] = InsertEx(uri, extUri, bucket); + ZLOGI("Insert uri:%{public}s, errCode:%{public}x, status:%{public}x", + DistributedData::Anonymous::Change(uri).c_str(), errCode, status); if (!ITypesUtil::Marshal(reply, errCode, status)) { ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status); return IPC_STUB_WRITE_PARCEL_ERR; @@ -70,6 +88,8 @@ int32_t DataShareServiceStub::OnUpdateEx(MessageParcel &data, MessageParcel &rep return IPC_STUB_INVALID_DATA_ERR; } auto [errCode, status] = UpdateEx(uri, extUri, predicate, bucket); + ZLOGI("Update uri:%{public}s, errCode:%{public}x, status:%{public}x", + DistributedData::Anonymous::Change(uri).c_str(), errCode, status); if (!ITypesUtil::Marshal(reply, errCode, status)) { ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status); return IPC_STUB_WRITE_PARCEL_ERR; @@ -87,6 +107,8 @@ int32_t DataShareServiceStub::OnDeleteEx(MessageParcel &data, MessageParcel &rep return IPC_STUB_INVALID_DATA_ERR; } auto [errCode, status] = DeleteEx(uri, extUri, predicate); + ZLOGI("Delete uri:%{public}s, errCode:%{public}x, status:%{public}x", + DistributedData::Anonymous::Change(uri).c_str(), errCode, status); if (!ITypesUtil::Marshal(reply, errCode, status)) { ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status); return IPC_STUB_WRITE_PARCEL_ERR; @@ -327,16 +349,35 @@ int32_t DataShareServiceStub::OnNotifyConnectDone(MessageParcel &data, MessagePa int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply) { + // set thread qos + DataShareServiceStub::QosManager qos; + // check thread qos + QOS::QosLevel curLevel; + int qosRet = QOS::GetThreadQos(curLevel); + int tryTimes = TRY_TIMES; while (!isReady_.load() && tryTimes > 0) { tryTimes--; std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); } auto callingPid = IPCSkeleton::GetCallingPid(); + auto fullTokenId = IPCSkeleton::GetCallingFullTokenID(); + bool isSystemApp = CheckSystemCallingPermission(IPCSkeleton::GetCallingTokenID(), fullTokenId); + DataShareThreadLocal::SetFromSystemApp(isSystemApp); + if (code >= DATA_SHARE_CMD_SYSTEM_CODE) { + if (!isSystemApp) { + ZLOGE("CheckSystemCallingPermission fail, token:%{public}" PRIx64 + ", callingPid:%{public}d, code:%{public}u", fullTokenId, callingPid, code); + return E_NOT_SYSTEM_APP; + } + code = code - DATA_SHARE_CMD_SYSTEM_CODE; + } if (code != DATA_SHARE_SERVICE_CMD_QUERY && code != DATA_SHARE_SERVICE_CMD_GET_SILENT_PROXY_STATUS) { - ZLOGI("code:%{public}u, callingPid:%{public}d", code, callingPid); + ZLOGI("code:%{public}u, callingPid:%{public}d, qosRet:%{public}d, curLevel:%{public}d", + code, callingPid, qosRet, curLevel); } if (!CheckInterfaceToken(data)) { + DataShareThreadLocal::CleanFromSystemApp(); return DATA_SHARE_ERROR; } int res = -1; @@ -355,6 +396,7 @@ int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Me } HiViewAdapter::GetInstance().ReportDataStatistic(callerInfo); } + DataShareThreadLocal::CleanFromSystemApp(); return res; } diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.h b/services/distributeddataservice/service/data_share/data_share_service_stub.h index d13b2099344894592e4804216ed2b2ef2a231625..47603e95941e975dec375523ecf6d7bbc25f0a81 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_stub.h +++ b/services/distributeddataservice/service/data_share/data_share_service_stub.h @@ -27,6 +27,7 @@ public: void SetServiceReady(); private: + class QosManager; static constexpr std::chrono::milliseconds TIME_THRESHOLD = std::chrono::milliseconds(500); static bool CheckInterfaceToken(MessageParcel& data); int32_t OnQuery(MessageParcel& data, MessageParcel& reply); diff --git a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp index 6f8713521a0b4f483f70526afbd4c6dac0aa73aa..5b6bdc45b60f3850458c1137baab0981c54d2622 100644 --- a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp +++ b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp @@ -86,19 +86,19 @@ std::pair HiViewFaultAdapter::GetCallingName(uint32_t callingT return std::make_pair(callingName, result); } -void TimeoutReport::Report() +void TimeoutReport::Report(const std::string &timeoutAppendix, const std::chrono::milliseconds timeoutms) { auto end = std::chrono::steady_clock::now(); std::chrono::milliseconds duration = std::chrono::duration_cast(end - start); // Used to report DFX timeout faults - if (needFaultReport && duration > DFX_TIME_OUT_MS) { + if (needFaultReport && duration > HiViewFaultAdapter::dfxTimeOutMs) { DFXReport(duration); } // Used to report log timeout - if (duration > TIME_OUT_MS) { + if (duration > timeoutms) { int64_t milliseconds = duration.count(); - ZLOGE("over time when doing %{public}s, cost:%{public}" PRIi64 "ms", dfxInfo.businessType.c_str(), - milliseconds); + ZLOGE("over time when doing %{public}s, %{public}s, cost:%{public}" PRIi64 "ms", + dfxInfo.businessType.c_str(), timeoutAppendix.c_str(), milliseconds); } } @@ -107,11 +107,11 @@ void TimeoutReport::Report(const std::string &user, uint32_t callingPid, int32_t auto end = std::chrono::steady_clock::now(); std::chrono::milliseconds duration = std::chrono::duration_cast(end - start); // Used to report DFX timeout faults - if (needFaultReport && duration > DFX_TIME_OUT_MS) { + if (needFaultReport && duration > HiViewFaultAdapter::dfxTimeOutMs) { DFXReport(duration); } // Used to report log timeout - if (duration > TIME_OUT_MS) { + if (duration > HiViewFaultAdapter::timeOutMs) { int64_t milliseconds = duration.count(); std::string timeoutAppendix = "bundleName: " + dfxInfo.bundleName + ", user: " + user + ", callingPid: " + std::to_string(callingPid); @@ -134,8 +134,8 @@ void TimeoutReport::DFXReport(const std::chrono::milliseconds &duration) int64_t milliseconds = duration.count(); std::string appendix = "callingName:" + HiViewFaultAdapter::GetCallingName(dfxInfo.callingTokenId).first; appendix += ",cost:" + std::to_string(milliseconds) + "ms"; - DataShareFaultInfo faultInfo{TIME_OUT, dfxInfo.bundleName, dfxInfo.moduleName, dfxInfo.storeName, - dfxInfo.businessType, errorCode, appendix}; + DataShareFaultInfo faultInfo{HiViewFaultAdapter::timeOut, dfxInfo.bundleName, dfxInfo.moduleName, + dfxInfo.storeName, dfxInfo.businessType, errorCode, appendix}; HiViewFaultAdapter::ReportDataFault(faultInfo); } } diff --git a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h index 00cb42a5873f0e20605ad5d2a2946e706596c554..3b001e62d850779a3add7862037264bfe148d9cf 100644 --- a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h +++ b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h @@ -34,6 +34,17 @@ struct DataShareFaultInfo { std::string appendix; }; +class HiViewFaultAdapter { +public: + static constexpr const std::chrono::milliseconds timeOutMs = std::chrono::milliseconds(300); + static constexpr const std::chrono::milliseconds dfxTimeOutMs = std::chrono::milliseconds(2000); + static constexpr const char* timeOut = "TIME_OUT"; + static constexpr const char* resultsetFull = "RESULTSET_FULL"; + static constexpr const char* curdFailed = "CURD_FAILED"; + static void ReportDataFault(const DataShareFaultInfo &faultInfo); + static std::pair GetCallingName(uint32_t callingTokenid); +}; + // TimeoutReport is used for recording the time usage of multiple interfaces; // It can set up a timeout threshold, and when the time usage exceeds this threshold, will print log; // If want to record DFX fault report, need to set needFaultReport to true (default is false); @@ -54,24 +65,12 @@ struct TimeoutReport { explicit TimeoutReport(const DfxInfo &dfxInfo, bool needFaultReport = false) : dfxInfo(dfxInfo), needFaultReport(needFaultReport) {} - void Report(); + void Report(const std::string &timeoutAppendix = "", + const std::chrono::milliseconds timeoutms = HiViewFaultAdapter::timeOutMs); void Report(const std::string &user, uint32_t callingPid, int32_t appIndex = -1, int32_t instanceId = -1); void DFXReport(const std::chrono::milliseconds &duration); ~TimeoutReport() = default; }; - - -class HiViewFaultAdapter { -public: - static void ReportDataFault(const DataShareFaultInfo &faultInfo); - static std::pair GetCallingName(uint32_t callingTokenid); -}; - -inline const char* TIME_OUT = "TIME_OUT"; -inline const char* RESULTSET_FULL = "RESULTSET_FULL"; -inline const char* CURD_FAILED = "CURD_FAILED"; -inline const std::chrono::milliseconds TIME_OUT_MS = std::chrono::milliseconds(300); -inline const std::chrono::milliseconds DFX_TIME_OUT_MS = std::chrono::milliseconds(2000); } } #endif \ No newline at end of file diff --git a/services/distributeddataservice/service/data_share/idata_share_service.h b/services/distributeddataservice/service/data_share/idata_share_service.h index e57489fecdeda12978ad666a1fd1518c064aacc6..05e1fd15542f7e286c0d6ba77b36ed1f005d52a1 100644 --- a/services/distributeddataservice/service/data_share/idata_share_service.h +++ b/services/distributeddataservice/service/data_share/idata_share_service.h @@ -29,6 +29,7 @@ namespace OHOS::DataShare { class IDataShareService { public: + static constexpr int DATA_SHARE_CMD_SYSTEM_CODE = 100; enum { DATA_SHARE_SERVICE_CMD_QUERY, DATA_SHARE_SERVICE_CMD_ADD_TEMPLATE, @@ -52,7 +53,30 @@ public: DATA_SHARE_SERVICE_CMD_INSERTEX, DATA_SHARE_SERVICE_CMD_DELETEEX, DATA_SHARE_SERVICE_CMD_UPDATEEX, - DATA_SHARE_SERVICE_CMD_MAX + DATA_SHARE_SERVICE_CMD_MAX, + DATA_SHARE_SERVICE_CMD_QUERY_SYSTEM = DATA_SHARE_CMD_SYSTEM_CODE, + DATA_SHARE_SERVICE_CMD_ADD_TEMPLATE_SYSTEM, + DATA_SHARE_SERVICE_CMD_DEL_TEMPLATE_SYSTEM, + DATA_SHARE_SERVICE_CMD_PUBLISH_SYSTEM, + DATA_SHARE_SERVICE_CMD_GET_DATA_SYSTEM, + DATA_SHARE_SERVICE_CMD_SUBSCRIBE_RDB_SYSTEM, + DATA_SHARE_SERVICE_CMD_UNSUBSCRIBE_RDB_SYSTEM, + DATA_SHARE_SERVICE_CMD_ENABLE_SUBSCRIBE_RDB_SYSTEM, + DATA_SHARE_SERVICE_CMD_DISABLE_SUBSCRIBE_RDB_SYSTEM, + DATA_SHARE_SERVICE_CMD_SUBSCRIBE_PUBLISHED_SYSTEM, + DATA_SHARE_SERVICE_CMD_UNSUBSCRIBE_PUBLISHED_SYSTEM, + DATA_SHARE_SERVICE_CMD_ENABLE_SUBSCRIBE_PUBLISHED_SYSTEM, + DATA_SHARE_SERVICE_CMD_DISABLE_SUBSCRIBE_PUBLISHED_SYSTEM, + DATA_SHARE_SERVICE_CMD_NOTIFY_SYSTEM, + DATA_SHARE_SERVICE_CMD_NOTIFY_OBSERVERS_SYSTEM, + DATA_SHARE_SERVICE_CMD_SET_SILENT_SWITCH_SYSTEM, + DATA_SHARE_SERVICE_CMD_GET_SILENT_PROXY_STATUS_SYSTEM, + DATA_SHARE_SERVICE_CMD_REGISTER_OBSERVER_SYSTEM, + DATA_SHARE_SERVICE_CMD_UNREGISTER_OBSERVER_SYSTEM, + DATA_SHARE_SERVICE_CMD_INSERTEX_SYSTEM, + DATA_SHARE_SERVICE_CMD_DELETEEX_SYSTEM, + DATA_SHARE_SERVICE_CMD_UPDATEEX_SYSTEM, + DATA_SHARE_SERVICE_CMD_MAX_SYSTEM }; enum { DATA_SHARE_ERROR = -1, DATA_SHARE_OK = 0 }; diff --git a/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp index c796152ca0fcd267f999c1d713a424cecacb7785..60d643d4b8145108b87d0783cc86d1de00f1e3e7 100644 --- a/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp @@ -30,9 +30,9 @@ bool LoadConfigFromDataProxyNodeStrategy::operator()(std::shared_ptr co return false; } context->type = PUBLISHED_DATA_TYPE; - if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS( - context->calledBundleName, context->currentUserId, context->bundleInfo) != E_OK) { - ZLOGE("GetBundleInfoFromBMS failed! bundleName: %{public}s", context->calledBundleName.c_str()); + if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck( + context->calledBundleName, context->visitedUserId, context->bundleInfo) != E_OK) { + ZLOGE("GetBundleInfoFromBMSWithCheck failed! bundleName: %{public}s", context->calledBundleName.c_str()); context->errCode = E_BUNDLE_NAME_NOT_EXIST; return false; } @@ -40,10 +40,12 @@ bool LoadConfigFromDataProxyNodeStrategy::operator()(std::shared_ptr co context->permission = "reject"; return true; } + std::string uri = context->uri; + URIUtils::FormatUri(uri); for (auto const &hapModuleInfo : context->bundleInfo.hapModuleInfos) { auto proxyDatas = hapModuleInfo.proxyDatas; for (auto const &proxyData : proxyDatas) { - if (proxyData.uri != context->uri) { + if (proxyData.uri != uri) { continue; } context->permission = context->isRead ? proxyData.requiredReadPermission diff --git a/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp index 16fe91511f8148f17850e1acccb70dd233a305e5..cb4b331ac0b81cba9ec6862bd8f9068a80d8952e 100644 --- a/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp @@ -80,9 +80,9 @@ bool LoadConfigFromDataShareBundleInfoStrategy::operator()(std::shared_ptrcalledBundleName.c_str()); return false; } - if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS( - context->calledBundleName, context->currentUserId, context->bundleInfo) != E_OK) { - ZLOGE("GetBundleInfoFromBMS failed! bundleName: %{public}s", context->calledBundleName.c_str()); + if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck( + context->calledBundleName, context->visitedUserId, context->bundleInfo) != E_OK) { + ZLOGE("GetBundleInfoFromBMSWithCheck failed! bundleName: %{public}s", context->calledBundleName.c_str()); return false; } for (auto const &item : context->bundleInfo.extensionInfos) { diff --git a/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp index b8dece0fd2173572ea22fdba2f9e0bd8c833205f..9a64d37c7eec5db4b2b1e0530b9eff283ea278e1 100644 --- a/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp @@ -33,13 +33,14 @@ bool LoadConfigCommonStrategy::operator()(std::shared_ptr context) context->callerTokenId = IPCSkeleton::GetCallingTokenID(); } context->currentUserId = AccountDelegate::GetInstance()->GetUserByToken(context->callerTokenId); + context->visitedUserId = context->currentUserId; if (!URIUtils::GetAppIndexFromProxyURI(context->uri, context->appIndex)) { return false; } // sa, userId is in uri, caller token id is from first caller tokenId if (context->currentUserId == 0) { GetInfoFromProxyURI( - context->uri, context->currentUserId, context->callerTokenId, context->calledBundleName); + context->uri, context->visitedUserId, context->callerTokenId, context->calledBundleName); URIUtils::FormatUri(context->uri); } if (context->needAutoLoadCallerBundleName && context->callerBundleName.empty()) { diff --git a/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp index d5283e4d3a82bffd0cea72b2d3e3d5ab236f2e03..095a04bdb1f17f7d5a2f1e57f245c553af8bcb30 100644 --- a/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp @@ -53,12 +53,12 @@ bool LoadConfigNormalDataInfoStrategy::operator()(std::shared_ptr conte } DistributedData::StoreMetaData metaData; if (!QueryMetaData( - context->calledBundleName, context->calledStoreName, metaData, context->currentUserId, context->appIndex)) { + context->calledBundleName, context->calledStoreName, metaData, context->visitedUserId, context->appIndex)) { // connect extension and retry AAFwk::WantParams wantParams; ExtensionConnectAdaptor::TryAndWait(context->uri, context->calledBundleName, wantParams); if (!QueryMetaData( - context->calledBundleName, context->calledStoreName, metaData, context->currentUserId, context->appIndex)) { + context->calledBundleName, context->calledStoreName, metaData, context->visitedUserId, context->appIndex)) { ZLOGE("QueryMetaData fail, %{public}s", DistributedData::Anonymous::Change(context->uri).c_str()); context->errCode = NativeRdb::E_DB_NOT_EXIST; return false; diff --git a/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp index c32d5daff4c916213c3a2740683989dcf96b56a3..b024369158a8c679f6daa55640b562821bdc6750 100644 --- a/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp @@ -36,7 +36,7 @@ Data GetDataStrategy::Execute(std::shared_ptr context, int &errorCode) errorCode = context->errCode; return Data(); } - auto result = PublishedData::Query(context->calledBundleName, context->currentUserId); + auto result = PublishedData::Query(context->calledBundleName, context->visitedUserId); Data data; for (auto &item : result) { if (!CheckPermission(context, item.value.key)) { diff --git a/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp index 26b116d48aa72f13b7cd02ef3adaa4d144e59bf7..a23d516b026d911560b21b653b21b7dc63366184 100644 --- a/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp +++ b/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp @@ -42,10 +42,10 @@ int32_t PublishStrategy::Execute(std::shared_ptr context, const Publish return -1; } PublishedDataItem::DataType value = item.GetData(); - PublishedDataNode node(context->uri, context->calledBundleName, item.subscriberId_, context->currentUserId, + PublishedDataNode node(context->uri, context->calledBundleName, item.subscriberId_, context->visitedUserId, PublishedDataNode::MoveTo(value)); PublishedData data(node, context->version); - int32_t status = delegate->Upsert(KvDBDelegate::DATA_TABLE, data); + auto [status, count] = delegate->Upsert(KvDBDelegate::DATA_TABLE, data); if (status != E_OK) { ZLOGE("db Upsert failed, %{public}s %{public}s %{public}d", context->calledBundleName.c_str(), DistributedData::Anonymous::Change(context->uri).c_str(), status); diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.cpp b/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.cpp index 09dd531f94c74430032d5d8a5d107dad7a711ad4..b9bfc3c9110137efba0fd68a477c21e88c20ac8f 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.cpp +++ b/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.cpp @@ -32,15 +32,16 @@ PublishedDataSubscriberManager &PublishedDataSubscriberManager::GetInstance() return manager; } -int PublishedDataSubscriberManager::Add( - const PublishedDataKey &key, const sptr observer, uint32_t firstCallerTokenId) +int PublishedDataSubscriberManager::Add(const PublishedDataKey &key, + const sptr observer, uint32_t firstCallerTokenId, int32_t userId) { publishedDataCache_.Compute( - key, [&observer, &firstCallerTokenId, this](const PublishedDataKey &key, std::vector &value) { + key, [&observer, &firstCallerTokenId, userId, this](const PublishedDataKey &key, + std::vector &value) { ZLOGI("add publish subscriber, uri %{public}s tokenId 0x%{public}x", DistributedData::Anonymous::Change(key.key).c_str(), firstCallerTokenId); value.emplace_back(observer, firstCallerTokenId, IPCSkeleton::GetCallingTokenID(), - IPCSkeleton::GetCallingPid()); + IPCSkeleton::GetCallingPid(), userId); return true; }); return E_OK; @@ -112,6 +113,7 @@ int PublishedDataSubscriberManager::Enable(const PublishedDataKey &key, uint32_t return result ? E_OK : E_SUBSCRIBER_NOT_EXIST; } +// if arg observer is not null, notify that observer only; otherwise notify all observers void PublishedDataSubscriberManager::Emit(const std::vector &keys, int32_t userId, const std::string &ownerBundleName, const sptr observer) { @@ -133,7 +135,7 @@ void PublishedDataSubscriberManager::Emit(const std::vector &k publishedResult.erase(key); continue; } - PutInto(callbacks, val, key, observer); + PutInto(callbacks, val, key, observer, userId); break; } return false; @@ -157,7 +159,7 @@ void PublishedDataSubscriberManager::Emit(const std::vector &k void PublishedDataSubscriberManager::PutInto( std::map, std::vector> &callbacks, const std::vector &val, const PublishedDataKey &key, - const sptr observer) + const sptr observer, int32_t userId) { for (auto const &callback : val) { if (callback.enabled && callback.observer != nullptr) { @@ -165,6 +167,10 @@ void PublishedDataSubscriberManager::PutInto( if (observer != nullptr && callback.observer != observer) { continue; } + if (callback.userId != 0 && callback.userId != userId && userId != 0) { + ZLOGE("Not across user publish, from %{public}d to %{public}d", userId, callback.userId); + continue; + } callbacks[callback.observer].emplace_back(key); } } @@ -267,8 +273,8 @@ bool PublishedDataKey::operator!=(const PublishedDataKey &rhs) const } PublishedDataSubscriberManager::ObserverNode::ObserverNode(const sptr &observer, - uint32_t firstCallerTokenId, uint32_t callerTokenId, uint32_t callerPid) - : observer(observer), firstCallerTokenId(firstCallerTokenId), callerTokenId(callerTokenId), callerPid(callerPid) + uint32_t firstCallerTokenId, uint32_t callerTokenId, uint32_t callerPid, int32_t userId): observer(observer), + firstCallerTokenId(firstCallerTokenId), callerTokenId(callerTokenId), callerPid(callerPid), userId(userId) { } } // namespace OHOS::DataShare diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h b/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h index 37356d7e4cdafcff08ca7f33e9763229fae80c77..40a6fbf05690f26a127c7d3413101e9e729ac7c7 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h +++ b/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.h @@ -26,7 +26,8 @@ #include "executor_pool.h" namespace OHOS::DataShare { struct PublishedDataKey { - PublishedDataKey(const std::string &key, const std::string &bundleName, int64_t subscriberId); + PublishedDataKey(const std::string &key, const std::string &bundleName, + int64_t subscriberId); bool operator<(const PublishedDataKey &rhs) const; bool operator>(const PublishedDataKey &rhs) const; bool operator<=(const PublishedDataKey &rhs) const; @@ -42,7 +43,7 @@ class PublishedDataSubscriberManager { public: static PublishedDataSubscriberManager &GetInstance(); int Add(const PublishedDataKey &key, const sptr observer, - uint32_t firstCallerTokenId); + uint32_t firstCallerTokenId, int32_t userId); int Delete(const PublishedDataKey &key, uint32_t firstCallerTokenId); void Delete(uint32_t callerTokenId, uint32_t callerPid); int Disable(const PublishedDataKey &key, uint32_t firstCallerTokenId); @@ -58,18 +59,20 @@ public: private: struct ObserverNode { ObserverNode(const sptr &observer, uint32_t firstCallerTokenId, - uint32_t callerTokenId = 0, uint32_t callerPid = 0); + uint32_t callerTokenId = 0, uint32_t callerPid = 0, int32_t userId = 0); sptr observer; uint32_t firstCallerTokenId; uint32_t callerTokenId; uint32_t callerPid; bool enabled = true; bool isNotifyOnEnabled = false; + int32_t userId = 0; }; PublishedDataSubscriberManager() = default; void PutInto(std::map, std::vector> &, - const std::vector &, const PublishedDataKey &, const sptr); + const std::vector &, const PublishedDataKey &, const sptr, + int32_t userId); ConcurrentMap> publishedDataCache_; }; } // namespace OHOS::DataShare diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp index b03fc242d28bc638fbbd60c3701474ea9222886b..e8d34c2396461396029b2aee19215a2dd54cecfe 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp +++ b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp @@ -119,9 +119,9 @@ int RdbSubscriberManager::Add(const Key &key, const sptr ZLOGI("add subscriber, uri %{private}s tokenId 0x%{public}x", key.uri.c_str(), context->callerTokenId); auto callerTokenId = IPCSkeleton::GetCallingTokenID(); auto callerPid = IPCSkeleton::GetCallingPid(); - value.emplace_back(observer, context->callerTokenId, callerTokenId, callerPid); + value.emplace_back(observer, context->callerTokenId, callerTokenId, callerPid, context->visitedUserId); std::vector node; - node.emplace_back(observer, context->callerTokenId, callerTokenId, callerPid); + node.emplace_back(observer, context->callerTokenId, callerTokenId, callerPid, context->visitedUserId); ExecutorPool::Task task = [key, node, context, this]() { LoadConfigDataInfoStrategy loadDataInfo; if (!loadDataInfo(context)) { @@ -130,9 +130,9 @@ int RdbSubscriberManager::Add(const Key &key, const sptr return; } DistributedData::StoreMetaData metaData = RdbSubscriberManager::GenMetaDataFromContext(context); - Notify(key, context->currentUserId, node, metaData); + Notify(key, context->visitedUserId, node, metaData); if (GetEnableObserverCount(key) == 1) { - SchedulerManager::GetInstance().Start(key, context->currentUserId, metaData); + SchedulerManager::GetInstance().Start(key, context->visitedUserId, metaData); } }; executorPool->Execute(task); @@ -227,13 +227,13 @@ int RdbSubscriberManager::Enable(const Key &key, std::shared_ptr contex if (it->isNotifyOnEnabled) { std::vector node; node.emplace_back(it->observer, context->callerTokenId); - Notify(key, context->currentUserId, node, metaData); + Notify(key, context->visitedUserId, node, metaData); } } return true; }); if (isChanged) { - SchedulerManager::GetInstance().Enable(key, context->currentUserId, metaData); + SchedulerManager::GetInstance().Enable(key, context->visitedUserId, metaData); } return result ? E_OK : E_SUBSCRIBER_NOT_EXIST; } @@ -252,12 +252,12 @@ void RdbSubscriberManager::Emit(const std::string &uri, std::shared_ptr if (key.uri != uri) { return false; } - Notify(key, context->currentUserId, val, metaData); + Notify(key, context->visitedUserId, val, metaData); SetObserverNotifyOnEnabled(val); return false; }); SchedulerManager::GetInstance().Execute( - uri, context->currentUserId, metaData); + uri, context->visitedUserId, metaData); } void RdbSubscriberManager::Emit(const std::string &uri, int32_t userId, @@ -372,6 +372,12 @@ int RdbSubscriberManager::Notify(const Key &key, int32_t userId, const std::vect ZLOGI("emit, valSize: %{public}zu, dataSize:%{public}zu, uri:%{public}s,", val.size(), changeNode.data_.size(), DistributedData::Anonymous::Change(changeNode.uri_).c_str()); for (const auto &callback : val) { + // not notify across user + if (callback.userId != userId && userId != 0 && callback.userId != 0) { + ZLOGI("Not allow across notify, uri:%{public}s, from %{public}d to %{public}d.", + DistributedData::Anonymous::Change(changeNode.uri_).c_str(), userId, callback.userId); + continue; + } if (callback.enabled && callback.observer != nullptr) { callback.observer->OnChangeFromRdb(changeNode); } @@ -399,12 +405,12 @@ void RdbSubscriberManager::Emit(const std::string &uri, int64_t subscriberId, if (key.uri != uri || key.subscriberId != subscriberId) { return false; } - Notify(key, context->currentUserId, val, metaData); + Notify(key, context->visitedUserId, val, metaData); SetObserverNotifyOnEnabled(val); return false; }); Key executeKey(uri, subscriberId, bundleName); - SchedulerManager::GetInstance().Start(executeKey, context->currentUserId, metaData); + SchedulerManager::GetInstance().Start(executeKey, context->visitedUserId, metaData); } DistributedData::StoreMetaData RdbSubscriberManager::GenMetaDataFromContext(const std::shared_ptr context) @@ -418,8 +424,8 @@ DistributedData::StoreMetaData RdbSubscriberManager::GenMetaDataFromContext(cons } RdbSubscriberManager::ObserverNode::ObserverNode(const sptr &observer, - uint32_t firstCallerTokenId, uint32_t callerTokenId, uint32_t callerPid) - : observer(observer), firstCallerTokenId(firstCallerTokenId), callerTokenId(callerTokenId), callerPid(callerPid) + uint32_t firstCallerTokenId, uint32_t callerTokenId, uint32_t callerPid, int32_t userId): observer(observer), + firstCallerTokenId(firstCallerTokenId), callerTokenId(callerTokenId), callerPid(callerPid), userId(userId) { } } // namespace OHOS::DataShare \ No newline at end of file diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h index 5bb2e82d86195c066a2f781e8e1ef69a55306182..8624397f89fa5d7634cf6a918badd64f8431e551 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h +++ b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h @@ -73,13 +73,14 @@ public: private: struct ObserverNode { ObserverNode(const sptr &observer, uint32_t firstCallerTokenId, - uint32_t callerTokenId = 0, uint32_t callerPid = 0); + uint32_t callerTokenId = 0, uint32_t callerPid = 0, int32_t userId = 0); sptr observer; uint32_t firstCallerTokenId; uint32_t callerTokenId; uint32_t callerPid; bool enabled = true; bool isNotifyOnEnabled = false; + int32_t userId = 0; }; RdbSubscriberManager() = default; diff --git a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp index 957320389b6ff5ac7f121594aed0a1db5d9d930d..05a49cda23ebb8c09c8e1007fbf5d82c78d3e795 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp @@ -201,7 +201,7 @@ KVDBGeneralStore::KVDBGeneralStore(const StoreMetaData &meta) storeInfo_.bundleName = meta.bundleName; storeInfo_.storeName = meta.storeId; storeInfo_.instanceId = meta.instanceId; - storeInfo_.user = std::stoi(meta.user); + storeInfo_.user = std::atoi(meta.user.c_str()); enableCloud_ = meta.enableCloud; } @@ -521,6 +521,11 @@ int32_t KVDBGeneralStore::Clean(const std::vector &devices, int32_t case CLOUD_DATA: status = delegate_->RemoveDeviceData("", static_cast(CLOUD_DATA)); break; + case CLEAN_WATER: + ClearKvMetaDataOption option; + option.type = ClearKvMetaOpType::CLEAN_CLOUD_WATERMARK; + status = delegate_->ClearMetaData(option); + break; case NEARBY_DATA: if (devices.empty()) { status = delegate_->RemoveDeviceData(); diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index f04980ccc167301f48916a6a907e72f745330e5e..859f9eb300cb86bbefdaceebbe78d85c8e02faa2 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -245,7 +245,6 @@ Status KVDBServiceImpl::Sync(const AppId &appId, const StoreId &storeId, int32_t { StoreMetaData metaData = GetStoreMetaData(appId, storeId, subUser); MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData); - auto delay = GetSyncDelayTime(syncInfo.delay, storeId, metaData.user); if (metaData.isAutoSync && syncInfo.seqId == std::numeric_limits::max()) { DeviceMatrix::GetInstance().OnChanged(metaData); StoreMetaDataLocal localMeta; @@ -256,6 +255,18 @@ Status KVDBServiceImpl::Sync(const AppId &appId, const StoreId &storeId, int32_t return Status::SUCCESS; } } + if ((DeviceMatrix::GetInstance().IsStatics(metaData) || DeviceMatrix::GetInstance().IsDynamic(metaData)) && + !IsNeedSync(metaData, syncInfo.devices)) { + ZLOGW("no change, do not need sync, appId:%{public}s storeId:%{public}s", metaData.bundleName.c_str(), + Anonymous::Change(metaData.storeId).c_str()); + if (syncInfo.devices.empty()) { + return DEVICE_NOT_ONLINE; + } + DBResult dbResult = { {syncInfo.devices[0], DBStatus::OK} }; + DoComplete(metaData, syncInfo, RefCount(), std::move(dbResult)); + return SUCCESS; + } + auto delay = GetSyncDelayTime(syncInfo.delay, storeId, metaData.user); syncInfo.syncId = ++syncId_; RADAR_REPORT(STANDARD_DEVICE_SYNC, ADD_SYNC_TASK, RADAR_SUCCESS, BIZ_STATE, START, SYNC_STORE_ID, Anonymous::Change(storeId.storeId), SYNC_APP_ID, appId.appId, CONCURRENT_ID, @@ -266,6 +277,24 @@ Status KVDBServiceImpl::Sync(const AppId &appId, const StoreId &storeId, int32_t std::bind(&KVDBServiceImpl::DoComplete, this, metaData, syncInfo, RefCount(), std::placeholders::_1)); } +bool KVDBServiceImpl::IsNeedSync(const StoreMetaData &metaData, std::vector &devices) +{ + auto uuids = ConvertDevices(devices); + if (uuids.empty()) { + ZLOGW("no device, appId:%{public}s, storeId:%{public}s", metaData.bundleName.c_str(), + Anonymous::Change(metaData.storeId).c_str()); + return false; + } + auto code = DeviceMatrix::GetInstance().GetCode(metaData); + auto [exist, mask] = DeviceMatrix::GetInstance().GetRemoteMask(uuids[0]); + auto [existLocal, localMask] = DeviceMatrix::GetInstance().GetMask(uuids[0]); + if ((mask & code) == code || (localMask & code) == code) { + ZLOGI("record level change, code: %{public}d, localmask: %{public}d, mask: %{public}d", code, localMask, mask); + return true; + } + return false; +} + Status KVDBServiceImpl::NotifyDataChange(const AppId &appId, const StoreId &storeId, uint64_t delay) { StoreMetaData meta = GetStoreMetaData(appId, storeId); @@ -857,24 +886,6 @@ int32_t KVDBServiceImpl::OnUserChange(uint32_t code, const std::string &user, co return SUCCESS; } -bool KVDBServiceImpl::IsRemoteChange(const StoreMetaData &metaData, const std::string &device) -{ - auto code = DeviceMatrix::GetInstance().GetCode(metaData); - if (code == DeviceMatrix::INVALID_MASK) { - return true; - } - auto [dynamic, statics] = DeviceMatrix::GetInstance().IsConsistent(device); - if (metaData.dataType == DataType::TYPE_STATICS && statics) { - return false; - } - if (metaData.dataType == DataType::TYPE_DYNAMICAL && dynamic) { - return false; - } - auto [exist, mask] = DeviceMatrix::GetInstance().GetRemoteMask( - device, static_cast(metaData.dataType)); - return (mask & code) == code; -} - void KVDBServiceImpl::AddOptions(const Options &options, StoreMetaData &metaData) { metaData.isAutoSync = options.autoSync; diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.h b/services/distributeddataservice/service/kvdb/kvdb_service_impl.h index 4604f8b56eac50623014bd56fe84f06167797057..df132cf2066127222316904b922fd98c4f270507 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.h +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.h @@ -155,7 +155,7 @@ private: void RegisterHandler(); void DumpKvServiceInfo(int fd, std::map> ¶ms); void TryToSync(const StoreMetaData &metaData, bool force = false); - bool IsRemoteChange(const StoreMetaData &metaData, const std::string &device); + bool IsNeedSync(const StoreMetaData &metaData, std::vector &devices); bool IsOHOSType(const std::vector &ids); Status ConvertDbStatusNative(DBStatus status); bool CompareTripleIdentifier(const std::string &accountId, const std::string &identifier, diff --git a/services/distributeddataservice/service/kvdb/upgrade.cpp b/services/distributeddataservice/service/kvdb/upgrade.cpp index c9888a6229b4666eb597267f810bcf287964034f..7040dfb8899412a499af3c24e94fe914192ffb4d 100644 --- a/services/distributeddataservice/service/kvdb/upgrade.cpp +++ b/services/distributeddataservice/service/kvdb/upgrade.cpp @@ -25,6 +25,7 @@ #include "log_print.h" #include "metadata/meta_data_manager.h" #include "metadata/secret_key_meta_data.h" +#include "utils/anonymous.h" namespace OHOS::DistributedKv { using namespace OHOS::DistributedData; using system_clock = std::chrono::system_clock; @@ -39,7 +40,19 @@ Upgrade &Upgrade::GetInstance() Upgrade::DBStatus Upgrade::UpdateStore(const StoreMeta &old, const StoreMeta &meta, const std::vector &pwd) { - if (old.version < StoreMeta::UUID_CHANGED_TAG && old.storeType == DEVICE_COLLABORATION) { + if (old.isNeedUpdateDeviceId && !old.isEncrypt) { + auto store = GetDBStore(meta, pwd); + if (store == nullptr) { + ZLOGI("get store failed, appId:%{public}s storeId:%{public}s", old.appId.c_str(), + Anonymous::Change(old.storeId).c_str()); + return DBStatus::DB_ERROR; + } + store->OperateDataStatus(static_cast(DistributedDB::DataOperator::UPDATE_TIME) | + static_cast(DistributedDB::DataOperator::RESET_UPLOAD_CLOUD)); + } + + if ((old.version < StoreMeta::UUID_CHANGED_TAG || (old.isNeedUpdateDeviceId && !old.isEncrypt)) && + old.storeType == DEVICE_COLLABORATION) { auto upStatus = Upgrade::GetInstance().UpdateUuid(old, meta, pwd); if (upStatus != DBStatus::OK) { return DBStatus::DB_ERROR; diff --git a/services/distributeddataservice/service/object/include/object_manager.h b/services/distributeddataservice/service/object/include/object_manager.h index 2f4f6302c177cd23197b245ffd2e8a056d3cfdc5..158b5c50a01490a53088d2e1f63dc64cc64e144c 100644 --- a/services/distributeddataservice/service/object/include/object_manager.h +++ b/services/distributeddataservice/service/object/include/object_manager.h @@ -89,13 +89,14 @@ public: sptr callback, uint32_t tokenId); void SetData(const std::string &dataDir, const std::string &userId); int32_t Clear(); + int32_t InitUserMeta(); int32_t DeleteByAppId(const std::string &appId, int32_t user); void RegisterRemoteCallback(const std::string &bundleName, const std::string &sessionId, pid_t pid, uint32_t tokenId, sptr callback); void UnregisterRemoteCallback(const std::string &bundleName, pid_t pid, uint32_t tokenId, const std::string &sessionId = ""); - void NotifyChange(ObjectRecord &changedData); + void NotifyChange(const ObjectRecord &changedData); void NotifyAssetsReady(const std::string& objectKey, const std::string& bundleName, const std::string& srcNetworkId = ""); void NotifyAssetsStart(const std::string& objectKey, const std::string& srcNetworkId = ""); @@ -202,8 +203,7 @@ private: + DmAdaper::GetInstance().GetLocalDevice().udid; }; std::recursive_mutex kvStoreMutex_; - std::mutex mutex_; - DistributedDB::KvStoreDelegateManager *kvStoreDelegateManager_ = nullptr; + std::shared_ptr kvStoreDelegateManager_ = nullptr; DistributedDB::KvStoreNbDelegate *delegate_ = nullptr; ObjectDataListener *objectDataListener_ = nullptr; sptr objectAssetsRecvListener_ = nullptr; @@ -214,7 +214,6 @@ private: ConcurrentMap callbacks_; std::shared_ptr executors_; DistributedData::AssetBindInfo ConvertBindInfo(ObjectStore::AssetBindInfo& bindInfo); - VBucket ConvertVBucket(ObjectStore::ValuesBucket &vBucket); ConcurrentMap> snapshots_; // key:bundleName_sessionId ConcurrentMap bindSnapshots_; // key:bundleName_storeName ConcurrentMap restoreStatus_; // key:bundleName+sessionId diff --git a/services/distributeddataservice/service/object/include/object_service_impl.h b/services/distributeddataservice/service/object/include/object_service_impl.h index 437d49e9e47f5cda46271b5cf91686ea797edfb9..e398edface1861cb6e1ff32a6e57eb41293fba57 100644 --- a/services/distributeddataservice/service/object/include/object_service_impl.h +++ b/services/distributeddataservice/service/object/include/object_service_impl.h @@ -17,6 +17,7 @@ #define DISTRIBUTEDDATASERVICE_OBJECT_SERVICE_H #include "feature/static_acts.h" +#include "metadata/store_meta_data.h" #include "object_manager.h" #include "object_service_stub.h" #include "visibility.h" @@ -40,7 +41,6 @@ public: int32_t DeleteSnapshot(const std::string &bundleName, const std::string &sessionId) override; int32_t IsBundleNameEqualTokenId( const std::string &bundleName, const std::string &sessionId, const uint32_t &tokenId); - void Clear(); int32_t ResolveAutoLaunch(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) override; int32_t OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &appId) override; int32_t OnInitialize() override; @@ -68,6 +68,9 @@ private: }; void RegisterObjectServiceInfo(); void RegisterHandler(); + int32_t SaveMetaData(StoreMetaData& saveMeta, const std::string &user, const std::string &account); + void UpdateMetaData(); + static Factory factory_; std::shared_ptr executors_; }; diff --git a/services/distributeddataservice/service/object/src/object_asset_machine.cpp b/services/distributeddataservice/service/object/src/object_asset_machine.cpp index dcb034ad95eaa4f57291a174169edf9d19d75fe7..6d1d11fb71cf86609a5b6c0df42cf0befe6ed635 100644 --- a/services/distributeddataservice/service/object/src/object_asset_machine.cpp +++ b/services/distributeddataservice/service/object/src/object_asset_machine.cpp @@ -57,12 +57,12 @@ static int32_t Recover(int32_t eventId, ChangedAssetInfo& changedAsset, Asset& a static int32_t UpdateStore(ChangedAssetInfo& changedAsset); -static AutoCache::Store GetStore(ChangedAssetInfo& changedAsset); +static AutoCache::Store GetStore(const ChangedAssetInfo& changedAsset); static VBuckets GetMigratedData(AutoCache::Store& store, AssetBindInfo& assetBindInfo, const Asset& newAsset); static void MergeAssetData(VBucket& record, const Asset& newAsset, const AssetBindInfo& assetBindInfo); static void MergeAsset(Asset& oldAsset, const Asset& newAsset); static std::string BuildSql(const AssetBindInfo& bindInfo, Values& args); -static BindEvent::BindEventInfo MakeBindInfo(ChangedAssetInfo& changedAsset); +static BindEvent::BindEventInfo MakeBindInfo(const ChangedAssetInfo& changedAsset); static const DFAAction AssetDFA[STATUS_BUTT][EVENT_BUTT] = { { @@ -287,7 +287,7 @@ static void MergeAsset(Asset& oldAsset, const Asset& newAsset) oldAsset.path = newAsset.path; } -static AutoCache::Store GetStore(ChangedAssetInfo& changedAsset) +static AutoCache::Store GetStore(const ChangedAssetInfo& changedAsset) { StoreMetaData meta; meta.storeId = changedAsset.bindInfo.storeName; @@ -347,7 +347,7 @@ static int32_t Recover(int32_t eventId, ChangedAssetInfo& changedAsset, Asset& a return E_OK; } -static BindEvent::BindEventInfo MakeBindInfo(ChangedAssetInfo& changedAsset) +static BindEvent::BindEventInfo MakeBindInfo(const ChangedAssetInfo& changedAsset) { BindEvent::BindEventInfo bindEventInfo; bindEventInfo.bundleName = changedAsset.storeInfo.bundleName; diff --git a/services/distributeddataservice/service/object/src/object_manager.cpp b/services/distributeddataservice/service/object/src/object_manager.cpp index 3e3c554ffb209383f725c589651275c138d3d30d..51635cf04016c7d369f3f105499797f29c7460c2 100644 --- a/services/distributeddataservice/service/object/src/object_manager.cpp +++ b/services/distributeddataservice/service/object/src/object_manager.cpp @@ -29,6 +29,7 @@ #include "kvstore_utils.h" #include "log_print.h" #include "metadata/meta_data_manager.h" +#include "metadata/object_user_meta_data.h" #include "metadata/store_meta_data.h" #include "object_dms_handler.h" #include "object_radar_reporter.h" @@ -291,29 +292,25 @@ int32_t ObjectStoreManager::Retrieve( int32_t ObjectStoreManager::Clear() { ZLOGI("enter"); + DistributedData::ObjectUserMetaData userMeta; + if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(userMeta.GetKey(), userMeta, true)) { + ZLOGE("load meta error"); + return OBJECT_INNER_ERROR; + } + if (userMeta.userId.empty()) { + ZLOGI("no object user meta, don't need clean"); + return OBJECT_SUCCESS; + } std::string userId = GetCurrentUser(); if (userId.empty()) { + ZLOGE("no user error"); return OBJECT_INNER_ERROR; } - std::vector metaData; - std::string appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); - std::string metaKey = GetMetaUserIdKey(userId, appId); - if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(metaKey, metaData, true)) { - ZLOGE("no store of %{public}s", appId.c_str()); - return OBJECT_STORE_NOT_FOUND; - } - for (const auto &storeMeta : metaData) { - if (storeMeta.storeType < StoreMetaData::StoreType::STORE_OBJECT_BEGIN - || storeMeta.storeType > StoreMetaData::StoreType::STORE_OBJECT_END) { - continue; - } - if (storeMeta.user == userId) { - ZLOGI("user is same, not need to change, mate user:%{public}s::user:%{public}s.", - storeMeta.user.c_str(), userId.c_str()); - return OBJECT_SUCCESS; - } + if (userMeta.userId == userId) { + ZLOGI("user is same, don't need clear, user:%{public}s.", userId.c_str()); + return OBJECT_SUCCESS; } - ZLOGD("user is change, need to change"); + ZLOGI("user changed, need clear, userId:%{public}s", userId.c_str()); int32_t result = Open(); if (result != OBJECT_SUCCESS) { ZLOGE("Open failed, errCode = %{public}d", result); @@ -324,6 +321,33 @@ int32_t ObjectStoreManager::Clear() return result; } +int32_t ObjectStoreManager::InitUserMeta() +{ + ObjectUserMetaData userMeta; + if (DistributedData::MetaDataManager::GetInstance().LoadMeta(userMeta.GetKey(), userMeta, true)) { + ZLOGI("userId has been set, don't need clean"); + return OBJECT_SUCCESS; + } + std::string userId = GetCurrentUser(); + if (userId.empty()) { + ZLOGI("get userId error"); + return OBJECT_INNER_ERROR; + } + userMeta.userId = userId; + std::string appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); + std::string metaKey = GetMetaUserIdKey(userId, appId); + if (!DistributedData::MetaDataManager::GetInstance().DelMeta(metaKey, true)) { + ZLOGE("delete old meta error, userId:%{public}s", userId.c_str()); + return OBJECT_INNER_ERROR; + } + if (!DistributedData::MetaDataManager::GetInstance().SaveMeta(DistributedData::ObjectUserMetaData::GetKey(), + userMeta, true)) { + ZLOGE("save meta error, userId:%{public}s", userId.c_str()); + return OBJECT_INNER_ERROR; + } + return OBJECT_SUCCESS; +} + int32_t ObjectStoreManager::DeleteByAppId(const std::string &appId, int32_t user) { int32_t result = Open(); @@ -338,12 +362,6 @@ int32_t ObjectStoreManager::DeleteByAppId(const std::string &appId, int32_t user appId.c_str(), user); } Close(); - std::string userId = std::to_string(user); - std::string metaKey = GetMetaUserIdKey(userId, appId); - auto status = DistributedData::MetaDataManager::GetInstance().DelMeta(metaKey, true); - if (!status) { - ZLOGE("Delete meta failed, userId: %{public}s, appId: %{public}s", userId.c_str(), appId.c_str()); - } return result; } @@ -393,7 +411,7 @@ void ObjectStoreManager::UnregisterRemoteCallback(const std::string &bundleName, })); } -void ObjectStoreManager::NotifyChange(ObjectRecord &changedData) +void ObjectStoreManager::NotifyChange(const ObjectRecord &changedData) { ZLOGI("OnChange start, size:%{public}zu", changedData.size()); bool hasAsset = false; @@ -405,6 +423,27 @@ void ObjectStoreManager::NotifyChange(ObjectRecord &changedData) } } auto data = GetObjectData(changedData, saveInfo, hasAsset); + auto isSameAccount = DeviceManagerAdapter::GetInstance().IsSameAccount(saveInfo.sourceDeviceId); + if (!isSameAccount) { + ZLOGE("IsSameAccount failed. bundleName:%{public}s, source device:%{public}s", saveInfo.bundleName.c_str(), + Anonymous::Change(saveInfo.sourceDeviceId).c_str()); + auto status = Open(); + if (status != OBJECT_SUCCESS) { + ZLOGE("Open failed, bundleName:%{public}s, source device::%{public}s, status: %{public}d", + saveInfo.bundleName.c_str(), Anonymous::Change(saveInfo.sourceDeviceId).c_str(), status); + return; + } + std::vector> keys; + for (const auto &[key, value] : changedData) { + keys.emplace_back(key.begin(), key.end()); + } + status = delegate_->DeleteBatch(keys); + if (status != DistributedDB::DBStatus::OK) { + ZLOGE("Delete entries failed, bundleName:%{public}s, source device::%{public}s, status: %{public}d", + saveInfo.bundleName.c_str(), Anonymous::Change(saveInfo.sourceDeviceId).c_str(), status); + } + return Close(); + } if (!hasAsset) { ObjectStore::RadarReporter::ReportStateStart(std::string(__FUNCTION__), ObjectStore::DATA_RESTORE, ObjectStore::DATA_RECV, ObjectStore::RADAR_SUCCESS, ObjectStore::START, saveInfo.bundleName); @@ -520,7 +559,7 @@ void ObjectStoreManager::PullAssets(const std::map& d for (const auto& [objectId, assets] : changedAssets) { std::string networkId = DmAdaper::GetInstance().ToNetworkID(saveInfo.sourceDeviceId); auto block = std::make_shared>>(WAIT_TIME, std::tuple{ true, true }); - ObjectAssetLoader::GetInstance()->TransferAssetsAsync(std::stoi(GetCurrentUser()), + ObjectAssetLoader::GetInstance()->TransferAssetsAsync(std::atoi(GetCurrentUser().c_str()), saveInfo.bundleName, networkId, assets, [this, block](bool success) { block->SetValue({ false, success }); }); @@ -697,11 +736,15 @@ void ObjectStoreManager::DoNotifyWaitAssetTimeout(const std::string &objectKey) void ObjectStoreManager::SetData(const std::string &dataDir, const std::string &userId) { - ZLOGI("enter %{public}s", dataDir.c_str()); - kvStoreDelegateManager_ = - new DistributedDB::KvStoreDelegateManager(DistributedData::Bootstrap::GetInstance().GetProcessLabel(), userId); + ZLOGI("enter, user: %{public}s", userId.c_str()); + kvStoreDelegateManager_ = std::make_shared + (DistributedData::Bootstrap::GetInstance().GetProcessLabel(), userId); DistributedDB::KvStoreConfig kvStoreConfig { dataDir }; - kvStoreDelegateManager_->SetKvStoreConfig(kvStoreConfig); + auto status = kvStoreDelegateManager_->SetKvStoreConfig(kvStoreConfig); + if (status != DistributedDB::OK) { + ZLOGE("Set kvstore config failed, status: %{public}d", status); + return; + } userId_ = userId; } @@ -793,7 +836,7 @@ void ObjectStoreManager::ProcessOldEntry(const std::string &appId) { std::vector entries; auto status = delegate_->GetEntries(std::vector(appId.begin(), appId.end()), entries); - if (status != DistributedDB::DBStatus::NOT_FOUND) { + if (status == DistributedDB::DBStatus::NOT_FOUND) { ZLOGI("Get old entries empty, bundleName: %{public}s", appId.c_str()); return; } @@ -847,7 +890,7 @@ int32_t ObjectStoreManager::SaveToStore(const std::string &appId, const std::str saveInfoEntry.value = std::vector(saveInfoValue.begin(), saveInfoValue.end()); std::vector entries; entries.emplace_back(saveInfoEntry); - for (auto &item : data) { + for (const auto &item : data) { DistributedDB::Entry entry; std::string key = GetPropertyPrefix(appId, sessionId, toDeviceId) + timestamp + SEPERATOR + item.first; entry.key = std::vector(key.begin(), key.end()); @@ -869,12 +912,16 @@ int32_t ObjectStoreManager::SyncOnStore( const std::string &prefix, const std::vector &deviceList, SyncCallBack &callback) { std::vector syncDevices; - for (auto &device : deviceList) { + for (auto const &device : deviceList) { if (device == LOCAL_DEVICE) { ZLOGI("Save to local, do not need sync, prefix: %{public}s", prefix.c_str()); callback({{LOCAL_DEVICE, OBJECT_SUCCESS}}); return OBJECT_SUCCESS; } + if (!DeviceManagerAdapter::GetInstance().IsSameAccount(device)) { + ZLOGE("IsSameAccount failed. device:%{public}s", Anonymous::Change(device).c_str()); + continue; + } syncDevices.emplace_back(DmAdaper::GetInstance().GetUuidByNetworkId(device)); } if (syncDevices.empty()) { @@ -1056,8 +1103,8 @@ std::vector ObjectStoreManager::SplitEntryKey(const std::string &ke std::string ObjectStoreManager::GetCurrentUser() { std::vector users; - AccountDelegate::GetInstance()->QueryUsers(users); - if (users.empty()) { + if (!AccountDelegate::GetInstance()->QueryUsers(users)) { + ZLOGE("QueryUsers failed."); return ""; } return std::to_string(users[0]); @@ -1071,20 +1118,20 @@ void ObjectStoreManager::SaveUserToMeta() return; } std::string appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); - StoreMetaData userMeta; - userMeta.storeId = DistributedObject::ObjectCommon::OBJECTSTORE_DB_STOREID; - userMeta.user = userId; - userMeta.storeType = ObjectDistributedType::OBJECT_SINGLE_VERSION; - std::string userMetaKey = GetMetaUserIdKey(userId, appId); - auto saved = DistributedData::MetaDataManager::GetInstance().SaveMeta(userMetaKey, userMeta, true); + DistributedData::ObjectUserMetaData userMeta; + userMeta.userId = userId; + auto saved = DistributedData::MetaDataManager::GetInstance().SaveMeta( + DistributedData::ObjectUserMetaData::GetKey(), userMeta, true); if (!saved) { - ZLOGE("userMeta save failed"); + ZLOGE("userMeta save failed, userId:%{public}s", userId.c_str()); } } void ObjectStoreManager::CloseAfterMinute() { - executors_->Schedule(std::chrono::minutes(INTERVAL), std::bind(&ObjectStoreManager::Close, this)); + executors_->Schedule(std::chrono::minutes(INTERVAL), [this]() { + Close(); + }); } void ObjectStoreManager::SetThreadPool(std::shared_ptr executors) @@ -1110,7 +1157,7 @@ SequenceSyncManager::Result SequenceSyncManager::Process( return ERR_SID_NOT_EXIST; } std::map syncResults; - for (auto &item : results) { + for (const auto &item : results) { syncResults[item.first] = item.second == DistributedDB::DBStatus::OK ? 0 : -1; } seqIdCallbackRelations_[sequenceId](syncResults); diff --git a/services/distributeddataservice/service/object/src/object_service_impl.cpp b/services/distributeddataservice/service/object/src/object_service_impl.cpp index fdb08505e7ad12410d938f5807446a5666d7d9fc..71f6195e7a2c4182f769693e996f633a94bc5875 100644 --- a/services/distributeddataservice/service/object/src/object_service_impl.cpp +++ b/services/distributeddataservice/service/object/src/object_service_impl.cpp @@ -137,6 +137,22 @@ int32_t ObjectServiceImpl::OnInitialize() const std::string accountId = DistributedData::AccountDelegate::GetInstance()->GetCurrentAccountId(); const auto userId = DistributedData::AccountDelegate::GetInstance()->GetUserByToken(token); StoreMetaData saveMeta; + SaveMetaData(saveMeta, std::to_string(userId), accountId); + ObjectStoreManager::GetInstance()->SetData(saveMeta.dataDir, std::to_string(userId)); + ObjectStoreManager::GetInstance()->InitUserMeta(); + RegisterObjectServiceInfo(); + RegisterHandler(); + ObjectDmsHandler::GetInstance().RegisterDmsEvent(); + return OBJECT_SUCCESS; +} + +int32_t ObjectServiceImpl::SaveMetaData(StoreMetaData &saveMeta, const std::string &user, const std::string &account) +{ + auto localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + if (localDeviceId.empty()) { + ZLOGE("failed to get local device id"); + return OBJECT_INNER_ERROR; + } saveMeta.appType = "default"; saveMeta.deviceId = localDeviceId; saveMeta.storeId = DistributedObject::ObjectCommon::OBJECTSTORE_DB_STOREID; @@ -145,16 +161,15 @@ int32_t ObjectServiceImpl::OnInitialize() saveMeta.isEncrypt = false; saveMeta.bundleName = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); saveMeta.appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); - saveMeta.user = std::to_string(userId); - saveMeta.account = accountId; - saveMeta.tokenId = token; + saveMeta.user = user; + saveMeta.account = account; + saveMeta.tokenId = IPCSkeleton::GetCallingTokenID(); saveMeta.securityLevel = DistributedKv::SecurityLevel::S1; saveMeta.area = DistributedKv::Area::EL1; saveMeta.uid = IPCSkeleton::GetCallingUid(); saveMeta.storeType = ObjectDistributedType::OBJECT_SINGLE_VERSION; saveMeta.dataType = DistributedKv::DataType::TYPE_DYNAMICAL; saveMeta.dataDir = DistributedData::DirectoryManager::GetInstance().GetStorePath(saveMeta); - ObjectStoreManager::GetInstance()->SetData(saveMeta.dataDir, std::to_string(userId)); bool isSaved = DistributedData::MetaDataManager::GetInstance().SaveMeta(saveMeta.GetKey(), saveMeta) && DistributedData::MetaDataManager::GetInstance().SaveMeta(saveMeta.GetKey(), saveMeta, true); if (!isSaved) { @@ -168,18 +183,18 @@ int32_t ObjectServiceImpl::OnInitialize() if (!isSaved) { ZLOGE("Save appIdMeta failed"); } - ZLOGI("SaveMeta success appId %{public}s, storeId %{public}s", - saveMeta.appId.c_str(), saveMeta.GetStoreAlias().c_str()); - RegisterObjectServiceInfo(); - RegisterHandler(); - ObjectDmsHandler::GetInstance().RegisterDmsEvent(); + ZLOGI("SaveMeta success appId %{public}s, storeId %{public}s", saveMeta.appId.c_str(), + saveMeta.GetStoreAlias().c_str()); return OBJECT_SUCCESS; } int32_t ObjectServiceImpl::OnUserChange(uint32_t code, const std::string &user, const std::string &account) { if (code == static_cast(AccountStatus::DEVICE_ACCOUNT_SWITCHED)) { - Clear(); + int32_t status = ObjectStoreManager::GetInstance()->Clear(); + if (status != OBJECT_SUCCESS) { + ZLOGE("Clear fail user:%{public}s, status: %{public}d", user.c_str(), status); + } } return Feature::OnUserChange(code, user, account); } @@ -273,15 +288,6 @@ int32_t ObjectServiceImpl::IsBundleNameEqualTokenId( return OBJECT_SUCCESS; } -void ObjectServiceImpl::Clear() -{ - ZLOGI("begin."); - int32_t status = ObjectStoreManager::GetInstance()->Clear(); - if (status != OBJECT_SUCCESS) { - ZLOGE("save fail %{public}d", status); - } -} - int32_t ObjectServiceImpl::ObjectStatic::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) { int32_t result = ObjectStoreManager::GetInstance()->DeleteByAppId(bundleName, user); @@ -377,8 +383,9 @@ void ObjectServiceImpl::RegisterObjectServiceInfo() void ObjectServiceImpl::RegisterHandler() { - Handler handler = - std::bind(&ObjectServiceImpl::DumpObjectServiceInfo, this, std::placeholders::_1, std::placeholders::_2); + Handler handler = [this](int fd, std::map> ¶ms) { + DumpObjectServiceInfo(fd, params); + }; DumpManager::GetInstance().AddHandler("FEATURE_INFO", uintptr_t(this), handler); } diff --git a/services/distributeddataservice/service/rdb/cache_cursor.cpp b/services/distributeddataservice/service/rdb/cache_cursor.cpp index 4c3b04d3ce9d2602735adcf60d3ffd68b4e04efe..e9ce03d3c3c1e30aeda7c836617e2b41d48cf5ec 100644 --- a/services/distributeddataservice/service/rdb/cache_cursor.cpp +++ b/services/distributeddataservice/service/rdb/cache_cursor.cpp @@ -23,13 +23,13 @@ using namespace OHOS::DistributedData; CacheCursor::CacheCursor(std::vector &&records) : row_(0), maxCol_(0), records_(std::move(records)) { - maxRow_ = records_.size(); + maxRow_ = static_cast(records_.size()); if (maxRow_ > 0) { for (auto it = records_[0].begin(); it != records_[0].end(); it++) { colNames_.push_back(it->first); colTypes_.push_back(it->second.index()); } - maxCol_ = colNames_.size(); + maxCol_ = static_cast(colNames_.size()); } } diff --git a/services/distributeddataservice/service/rdb/rdb_cloud.cpp b/services/distributeddataservice/service/rdb/rdb_cloud.cpp index 0a0726079f857ccfc3eb8c92431d0be84d47bcfa..2043f3d027d2fdb9bf7d529f27dc2090566a310e 100644 --- a/services/distributeddataservice/service/rdb/rdb_cloud.cpp +++ b/services/distributeddataservice/service/rdb/rdb_cloud.cpp @@ -76,17 +76,18 @@ DBStatus RdbCloud::Query(const std::string &tableName, DBVBucket &extend, std::v { auto [nodes, status] = ConvertQuery(extend); std::shared_ptr cursor = nullptr; + int32_t code = E_OK; if (status == GeneralError::E_OK && !nodes.empty()) { RdbQuery query; query.SetQueryNodes(tableName, std::move(nodes)); - cursor = cloudDB_->Query(query, ValueProxy::Convert(std::move(extend))); + std::tie(code, cursor) = cloudDB_->Query(query, ValueProxy::Convert(std::move(extend))); } else { - cursor = cloudDB_->Query(tableName, ValueProxy::Convert(std::move(extend))); + std::tie(code, cursor) = cloudDB_->Query(tableName, ValueProxy::Convert(std::move(extend))); } - if (cursor == nullptr) { + if (cursor == nullptr || code != E_OK) { ZLOGE("cursor is null, table:%{public}s, extend:%{public}zu", Anonymous::Change(tableName).c_str(), extend.size()); - return ConvertStatus(static_cast(E_ERROR)); + return ConvertStatus(static_cast(code != E_OK ? code : E_ERROR)); } int32_t count = cursor->GetCount(); data.reserve(count); diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.cpp b/services/distributeddataservice/service/rdb/rdb_general_store.cpp index 754f258fb89577cbe40cfaa0d5fbd28dee158e81..4c4354c477ab3157aa0c124152dd094a18a564df 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.cpp +++ b/services/distributeddataservice/service/rdb/rdb_general_store.cpp @@ -26,6 +26,7 @@ #include "cloud/cloud_mark.h" #include "cloud/cloud_store_types.h" #include "cloud/schema_meta.h" +#include "device_sync_app/device_sync_app_manager.h" #include "cloud_service.h" #include "commonevent/data_sync_event.h" #include "communicator/device_manager_adapter.h" @@ -62,6 +63,7 @@ constexpr const char *INSERT = "INSERT INTO "; constexpr const char *REPLACE = "REPLACE INTO "; constexpr const char *VALUES = " VALUES "; constexpr const char *LOGOUT_DELETE_FLAG = "DELETE#ALL_CLOUDDATA"; +constexpr const char *LOGOUT_RESERVE_FLAG = "RESERVE#ALL_CLOUDDATA"; constexpr const LockAction LOCK_ACTION = static_cast(static_cast(LockAction::INSERT) | static_cast(LockAction::UPDATE) | static_cast(LockAction::DELETE) | static_cast(LockAction::DOWNLOAD)); @@ -141,7 +143,7 @@ void RdbGeneralStore::InitStoreInfo(const StoreMetaData &meta) storeInfo_.bundleName = meta.bundleName; storeInfo_.storeName = meta.storeId; storeInfo_.instanceId = meta.instanceId; - storeInfo_.user = std::stoi(meta.user); + storeInfo_.user = std::atoi(meta.user.c_str()); storeInfo_.deviceId = DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid; } @@ -897,6 +899,20 @@ void RdbGeneralStore::Report(const std::string &faultType, int32_t errCode, cons Reporter::GetInstance()->CloudSyncFault()->Report(msg); } +int32_t RdbGeneralStore::SetReference(const std::vector &references) +{ + std::vector properties; + for (const auto &reference : references) { + properties.push_back({reference.sourceTable, reference.targetTable, reference.refFields}); + } + auto status = delegate_->SetReference(properties); + if (status != DistributedDB::DBStatus::OK && status != DistributedDB::DBStatus::PROPERTY_CHANGED) { + ZLOGE("distributed table set reference failed, err:%{public}d", status); + return GeneralError::E_ERROR; + } + return GeneralError::E_OK; +} + int32_t RdbGeneralStore::SetDistributedTables(const std::vector &tables, int32_t type, const std::vector &references) { @@ -917,18 +933,17 @@ int32_t RdbGeneralStore::SetDistributedTables(const std::vector &ta return GeneralError::E_ERROR; } } - std::vector properties; - for (const auto &reference : references) { - properties.push_back({ reference.sourceTable, reference.targetTable, reference.refFields }); - } - auto status = delegate_->SetReference(properties); - if (status != DistributedDB::DBStatus::OK && status != DistributedDB::DBStatus::PROPERTY_CHANGED) { - ZLOGE("distributed table set reference failed, err:%{public}d", status); - return GeneralError::E_ERROR; + if (type == DistributedTableType::DISTRIBUTED_CLOUD) { + auto status = SetReference(references); + if (status != GeneralError::E_OK) { + return GeneralError::E_ERROR; + } } auto [exist, database] = GetDistributedSchema(observer_.meta_); - if (exist) { - delegate_->SetDistributedSchema(GetGaussDistributedSchema(database)); + if (exist && type == DistributedTableType::DISTRIBUTED_DEVICE) { + auto force = DeviceSyncAppManager::GetInstance().Check( + {observer_.meta_.appId, observer_.meta_.bundleName, database.version}); + delegate_->SetDistributedSchema(GetGaussDistributedSchema(database), force); } CloudMark metaData(storeInfo_); if (MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData, true) && metaData.isClearWaterMark) { @@ -1191,8 +1206,8 @@ void RdbGeneralStore::ObserverProxy::OnChange(DBOrigin origin, const std::string info.push_back(std::move(value)); continue; } - auto deleteKey = std::get_if(&value); - if (deleteKey != nullptr && (*deleteKey == LOGOUT_DELETE_FLAG)) { + auto key = std::get_if(&value); + if (key != nullptr && (*key == LOGOUT_DELETE_FLAG || *key == LOGOUT_RESERVE_FLAG)) { // notify to start app notifyFlag = true; } @@ -1200,8 +1215,11 @@ void RdbGeneralStore::ObserverProxy::OnChange(DBOrigin origin, const std::string } } if (notifyFlag) { - ZLOGI("post data change for cleaning cloud data"); - PostDataChange(meta_, {}, CLOUD_DATA_CLEAN); + ZLOGI("post data change for cleaning cloud data. store:%{public}s table:%{public}s data change from " + ":%{public}s", + Anonymous::Change(storeId_).c_str(), Anonymous::Change(data.tableName).c_str(), + Anonymous::Change(originalId).c_str()); + PostDataChange(meta_, {}, CLOUD_LOGOUT); } if (!data.field.empty()) { fields[std::move(data.tableName)] = std::move(*(data.field.begin())); @@ -1338,4 +1356,14 @@ RdbGeneralStore::DBProcessCB RdbGeneralStore::GetCB(SyncId syncId) return; }; } + +int32_t RdbGeneralStore::UpdateDBStatus() +{ + std::shared_lock lock(rwMutex_); + if (delegate_ == nullptr) { + ZLOGE("Database already closed! database:%{public}s", Anonymous::Change(storeInfo_.storeName).c_str()); + return GeneralError::E_ALREADY_CLOSED; + } + return delegate_->OperateDataStatus(static_cast(DataOperator::UPDATE_TIME)); +} } // namespace OHOS::DistributedRdb \ No newline at end of file diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.h b/services/distributeddataservice/service/rdb/rdb_general_store.h index d51e14ad3fd0c8377c90a38fa6a095788c6b785d..dd7c60f61e9292a3b8aa0fe2c2db345c3ad01a36 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.h +++ b/services/distributeddataservice/service/rdb/rdb_general_store.h @@ -59,6 +59,7 @@ public: bool IsBound(uint32_t user) override; bool IsValid(); int32_t Execute(const std::string &table, const std::string &sql) override; + int32_t SetReference(const std::vector &references); int32_t SetDistributedTables(const std::vector &tables, int32_t type, const std::vector &references) override; int32_t SetTrackerTable(const std::string& tableName, const std::set& trackerColNames, @@ -88,6 +89,7 @@ public: int32_t CleanTrackerData(const std::string &tableName, int64_t cursor) override; std::pair LockCloudDB() override; int32_t UnLockCloudDB() override; + int32_t UpdateDBStatus() override; private: RdbGeneralStore(const RdbGeneralStore& rdbGeneralStore); @@ -129,7 +131,7 @@ private: private: enum ChangeType { CLOUD_DATA_CHANGE = 0, - CLOUD_DATA_CLEAN + CLOUD_LOGOUT, }; void PostDataChange(const StoreMetaData &meta, const std::vector &tables, ChangeType type); friend RdbGeneralStore; diff --git a/services/distributeddataservice/service/rdb/rdb_schema_config.cpp b/services/distributeddataservice/service/rdb/rdb_schema_config.cpp index 205a39db2308eb2d3f6c17ec91ba00c4224b036e..cf84b43fbea4f3dc4d6046adceac29724500068a 100644 --- a/services/distributeddataservice/service/rdb/rdb_schema_config.cpp +++ b/services/distributeddataservice/service/rdb/rdb_schema_config.cpp @@ -39,7 +39,6 @@ bool RdbSchemaConfig::GetDistributedSchema(const StoreMetaData &meta, Database & if (!InitBundleInfo(meta.bundleName, std::atoi(meta.user.c_str()), bundleInfo)) { return false; } - std::string storeName = meta.storeId; auto ret = GetSchemaFromHap(bundleInfo, meta.storeId, database); if (ret) { database.user = meta.user; @@ -99,7 +98,7 @@ bool RdbSchemaConfig::GetSchemaFromHap( std::string jsonData(fileContent.get(), fileContent.get() + length); DbSchema databases; databases.Unmarshall(jsonData); - for (auto &schema : databases.databases) { + for (const auto &schema : databases.databases) { if (schema.name == storeName) { database = schema; return true; diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 4f9cbd8ebf7e7a5706aac5049627a0f9691dfbb1..b2d0164d168668d599b5d2736c2653e4ba8de585 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -228,7 +228,8 @@ bool RdbServiceImpl::CheckAccess(const std::string& bundleName, const std::strin storeInfo.tokenId = IPCSkeleton::GetCallingTokenID(); storeInfo.bundleName = bundleName; storeInfo.storeId = RemoveSuffix(storeName); - return !CheckerManager::GetInstance().GetAppId(storeInfo).empty(); + + return CheckerManager::GetInstance().IsValid(storeInfo); } std::string RdbServiceImpl::ObtainDistributedTableName(const std::string &device, const std::string &table) @@ -812,6 +813,20 @@ void RdbServiceImpl::SetReturnParam(StoreMetaData &metadata, RdbSyncerParam &par param.haMode_ = metadata.haMode; } +void RdbServiceImpl::SaveLaunchInfo(StoreMetaData &meta) +{ + RemoteChangeEvent::DataInfo info; + info.bundleName = meta.bundleName; + info.deviceId = meta.deviceId; + info.userId = meta.user; + if (executors_ != nullptr) { + executors_->Schedule(ExecutorPool::INVALID_DELAY, [dataInfo = std::move(info)]() mutable { + auto evt = std::make_unique(RemoteChangeEvent::RDB_META_SAVE, std::move(dataInfo)); + EventCenter::GetInstance().PostEvent(std::move(evt)); + }); + } +} + int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) { XCollie xcollie(__FUNCTION__, XCollie::XCOLLIE_LOG | XCollie::XCOLLIE_RECOVERY); @@ -823,20 +838,17 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) auto meta = GetStoreMetaData(param); StoreMetaData old; auto isCreated = MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), old, true); + meta.enableCloud = isCreated ? old.enableCloud : meta.enableCloud; if (!isCreated || meta != old) { Upgrade(param, old); ZLOGI("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " "area:%{public}d->%{public}d", meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), old.storeType, meta.storeType, old.isEncrypt, meta.isEncrypt, old.area, meta.area); + meta.isNeedUpdateDeviceId = isCreated && !TryUpdateDeviceId(param, old, meta); MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); AutoLaunchMetaData launchData; if (!MetaDataManager::GetInstance().LoadMeta(meta.GetAutoLaunchKey(), launchData, true)) { - RemoteChangeEvent::DataInfo info; - info.bundleName = meta.bundleName; - info.deviceId = meta.deviceId; - info.userId = meta.user; - auto evt = std::make_unique(RemoteChangeEvent::RDB_META_SAVE, std::move(info)); - EventCenter::GetInstance().PostEvent(std::move(evt)); + SaveLaunchInfo(meta); } } @@ -844,15 +856,10 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) SavePromiseInfo(meta, param); SaveDfxInfo(meta, param); - AppIDMetaData appIdMeta; - appIdMeta.bundleName = meta.bundleName; - appIdMeta.appId = meta.appId; - if (!MetaDataManager::GetInstance().SaveMeta(appIdMeta.GetKey(), appIdMeta, true)) { - ZLOGE("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " - "area:%{public}d->%{public}d", meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), old.storeType, - meta.storeType, old.isEncrypt, meta.isEncrypt, old.area, meta.area); + if (!SaveAppIDMeta(meta, old)) { return RDB_ERROR; } + if (param.isEncrypt_ && !param.password_.empty()) { if (SetSecretKey(param, meta) != RDB_OK) { ZLOGE("Set secret key failed, bundle:%{public}s store:%{public}s", @@ -865,6 +872,20 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) return RDB_OK; } +bool RdbServiceImpl::SaveAppIDMeta(const StoreMetaData &meta, const StoreMetaData &old) +{ + AppIDMetaData appIdMeta; + appIdMeta.bundleName = meta.bundleName; + appIdMeta.appId = meta.appId; + if (!MetaDataManager::GetInstance().SaveMeta(appIdMeta.GetKey(), appIdMeta, true)) { + ZLOGE("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " + "area:%{public}d->%{public}d", meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), old.storeType, + meta.storeType, old.isEncrypt, meta.isEncrypt, old.area, meta.area); + return false; + } + return true; +} + int32_t RdbServiceImpl::ReportStatistic(const RdbSyncerParam& param, const RdbStatEvent &statEvent) { if (!CheckAccess(param.bundleName_, param.storeName_)) { @@ -1220,8 +1241,21 @@ int32_t RdbServiceImpl::RdbStatic::OnAppUpdate(const std::string &bundleName, in std::string prefix = Database::GetPrefix({std::to_string(user), "default", bundleName}); std::vector dataBase; if (MetaDataManager::GetInstance().LoadMeta(prefix, dataBase, true)) { - for (const auto &dataBase : dataBase) { - MetaDataManager::GetInstance().DelMeta(dataBase.GetKey(), true); + for (const auto &database : dataBase) { + MetaDataManager::GetInstance().DelMeta(database.GetKey(), true); + ZLOGD("del metadata store is: %{public}s; user is: %{public}s; bundleName is: %{public}s", + Anonymous::Change(database.name).c_str(), database.user.c_str(), database.bundleName.c_str()); + StoreMetaData meta; + meta.user = database.user; + meta.deviceId = database.deviceId; + meta.storeId = database.name; + meta.bundleName = bundleName; + Database base; + if (RdbSchemaConfig::GetDistributedSchema(meta, base) && !base.name.empty() && !base.bundleName.empty()) { + MetaDataManager::GetInstance().SaveMeta(base.GetKey(), base, true); + ZLOGD("save metadata store is: %{public}s; user is: %{public}s; bundleName is: %{public}s", + Anonymous::Change(base.name).c_str(), base.user.c_str(), base.bundleName.c_str()); + } } } return CloseStore(bundleName, user, index); @@ -1649,4 +1683,26 @@ std::string RdbServiceImpl::GetSubUser(const int32_t subUser) } return userId; } + +bool RdbServiceImpl::TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, + StoreMetaData &meta) +{ + StoreMetaData syncMeta; + if (oldMeta.isNeedUpdateDeviceId && oldMeta.storeType >= StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN && + oldMeta.storeType <= StoreMetaData::StoreType::STORE_RELATIONAL_END && + MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), syncMeta)) { + auto store = GetStore(param); + if (store == nullptr) { + ZLOGE("store is null, bundleName:%{public}s storeName:%{public}s", param.bundleName_.c_str(), + Anonymous::Change(param.storeName_).c_str()); + return false; + } + auto errCode = store->UpdateDBStatus(); + if (errCode != RDB_OK) { + ZLOGE("Update failed errCode %{public}d", errCode); + return false; + } + } + return true; +} } // namespace OHOS::DistributedRdb \ No newline at end of file diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.h b/services/distributeddataservice/service/rdb/rdb_service_impl.h index a387261f3c8453459b6e953c7d41cfc695f45bf1..e58c6618f209888d123b6d7f72dd164984f99a8b 100755 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -215,6 +215,8 @@ private: static std::string GetSubUser(const int32_t subUser); static bool GetDBPassword(const StoreMetaData &metaData, DistributedDB::CipherPassword &password); + + static bool SaveAppIDMeta(const StoreMetaData &meta, const StoreMetaData &old); void GetSchema(const RdbSyncerParam ¶m); @@ -241,6 +243,10 @@ private: bool UpgradeCloneSecretKey(const StoreMetaData &meta); + bool TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, StoreMetaData &meta); + + void SaveLaunchInfo(StoreMetaData &meta); + static Factory factory_; ConcurrentMap syncAgents_; std::shared_ptr executors_; diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn old mode 100755 new mode 100644 index 9b359e5aa7403c2de5dab19fa3a08745571c26f7..9955ea5e3c3171874b3d1d5cbb783362c34fb481 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/ohos_var.gni") import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -module_output_path = "datamgr_service/distributeddatafwk" +module_output_path = "datamgr_service/datamgr_service/distributeddatafwk" ############################################################################### config("module_private_config") { @@ -85,6 +85,8 @@ ohos_unittest("CloudDataTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", @@ -126,8 +128,10 @@ ohos_unittest("CloudDataTest") { "bundle_framework:appexecfwk_core", "c_utils:utils", "device_manager:devicemanagersdk", + "googletest:gtest_main", "hicollie:libhicollie", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -142,9 +146,8 @@ ohos_unittest("CloudDataTest") { "${data_service_path}/adapter/account:distributeddata_account", "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/adapter/schema_helper:distributeddata_schema_helper", - "../../framework:distributeddatasvcfwk", + "${data_service_path}/framework:distributeddatasvcfwk", "mock:distributeddata_mock_static", - "//third_party/googletest:gtest_main", ] cflags = [ @@ -180,6 +183,8 @@ ohos_unittest("CloudServiceImplTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", @@ -221,8 +226,10 @@ ohos_unittest("CloudServiceImplTest") { "bundle_framework:appexecfwk_core", "c_utils:utils", "device_manager:devicemanagersdk", + "googletest:gtest_main", "hicollie:libhicollie", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -239,7 +246,6 @@ ohos_unittest("CloudServiceImplTest") { "${data_service_path}/adapter/schema_helper:distributeddata_schema_helper", "../../framework:distributeddatasvcfwk", "mock:distributeddata_mock_static", - "//third_party/googletest:gtest_main", ] cflags = [ @@ -259,6 +265,7 @@ ohos_unittest("CloudTest") { "ability_base:base", "ability_base:want", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -269,7 +276,6 @@ ohos_unittest("CloudTest") { "../../framework:distributeddatasvcfwk", "../../service:distributeddatasvc", "mock:distributeddata_mock_static", - "//third_party/googletest:gtest_main", ] } @@ -298,6 +304,7 @@ ohos_unittest("ValueProxyServiceTest") { "ability_base:base", "ability_base:want", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -308,7 +315,6 @@ ohos_unittest("ValueProxyServiceTest") { "${relational_store_inner_api_path}:native_rdb_static", "../../framework:distributeddatasvcfwk", "../../service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] } @@ -322,16 +328,16 @@ ohos_unittest("ConfigFactoryTest") { "ability_base:base", "ability_base:want", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", ] deps = [ "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", ] } @@ -347,15 +353,15 @@ ohos_unittest("DirectoryManagerTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", ] deps = [ "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", ] } @@ -371,15 +377,15 @@ ohos_unittest("CryptoManagerTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", ] deps = [ "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", ] } @@ -394,22 +400,27 @@ ohos_unittest("DeviceMatrixTest") { configs = [ ":module_private_config" ] + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + external_deps = [ "ability_base:base", "ability_base:want", "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", + "kv_store:distributeddb", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", - "//third_party/googletest:gtest_main", ] } @@ -450,9 +461,11 @@ ohos_unittest("KVDBGeneralStoreTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddb", ] deps = [ @@ -460,8 +473,6 @@ ohos_unittest("KVDBGeneralStoreTest") { "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/kvdb:distributeddata_kvdb", - "${kv_store_distributeddb_path}:distributeddb", - "//third_party/googletest:gtest_main", ] } @@ -567,16 +578,16 @@ ohos_unittest("RdbResultSetImplTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddb", ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/framework:distributeddatasvcfwk", - "${kv_store_distributeddb_path}:distributeddb", "${relational_store_inner_api_path}:native_rdb_static", - "//third_party/googletest:gtest_main", ] } @@ -596,6 +607,7 @@ ohos_unittest("RdbServiceTest") { "${data_service_path}/service/rdb/rdb_watcher.cpp", "cache_cursor_test.cpp", "mock/general_watcher_mock.cpp", + "mock/relational_store_manager_mock.cpp", "rdb_asset_loader_test.cpp", "rdb_cloud_test.cpp", "rdb_cursor_test.cpp", @@ -613,6 +625,57 @@ ohos_unittest("RdbServiceTest") { configs = [ ":module_private_config" ] cflags = [ + "-Wno-multichar", + "-Wno-c99-designator", + "-fno-access-control", # Ignore Private Member Access Control + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "c_utils:utils", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + ] + + deps = [ + "${data_service_path}/adapter/utils:distributeddata_utils", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", + "${relational_store_inner_api_path}:native_rdb_static", + ] +} + +ohos_unittest("RdbServiceImplTest") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + module_out_path = module_output_path + sources = [ + "mock/checker_mock.cpp", + "mock/db_change_data_mock.cpp", + "mock/db_store_mock.cpp", + "rdb_service_impl_test.cpp", + ] + + include_dirs = [ + "${data_service_path}/adapter/include/communicator", + "${data_service_path}/framework/include/eventcenter", + "${data_service_path}/service/test/mock", + ] + + defines = [ + "TEST_ON_DEVICE", + "OPENSSL_SUPPRESS_DEPRECATED", + ] + cflags = [ + "-Werror", "-Dprivate=public", "-Dprotected=public", "-Wno-multichar", @@ -625,20 +688,31 @@ ohos_unittest("RdbServiceTest") { "ability_base:want", "access_token:libaccesstoken_sdk", "access_token:libnativetoken", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "c_utils:utils", + "data_share:datashare_common", + "data_share:datashare_consumer", + "device_manager:devicemanagersdk", + "dsoftbus:softbus_client", + "hicollie:libhicollie", "hilog:libhilog", + "hisysevent:libhisysevent", + "huks:libhukssdk", "ipc:ipc_core", + "kv_store:datamgr_common", "kv_store:distributeddata_inner", "kv_store:distributeddb", + "relational_store:native_rdb", + "resource_management:global_resmgr", ] deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "${kv_store_distributeddb_path}:distributeddb", - "${relational_store_inner_api_path}:native_rdb_static", - "//third_party/googletest:gtest_main", + "${data_service_path}/service/rdb:distributeddata_rdb", ] } @@ -663,6 +737,7 @@ ohos_unittest("ObjectAssetLoaderTest") { "c_utils:utils", "dfs_service:cloudsync_asset_kit_inner", "dfs_service:distributed_file_daemon_kit_inner", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", @@ -673,7 +748,6 @@ ohos_unittest("ObjectAssetLoaderTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] cflags = [ @@ -702,6 +776,7 @@ ohos_unittest("ObjectAssetMachineTest") { "c_utils:utils", "dfs_service:cloudsync_asset_kit_inner", "dfs_service:distributed_file_daemon_kit_inner", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", @@ -712,7 +787,6 @@ ohos_unittest("ObjectAssetMachineTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] } @@ -735,6 +809,7 @@ ohos_unittest("ObjectDmsHandlerTest") { external_deps = [ "c_utils:utils", "dmsfwk:distributed_sdk", + "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", @@ -743,7 +818,6 @@ ohos_unittest("ObjectDmsHandlerTest") { deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/framework:distributeddatasvcfwk", - "//third_party/googletest:gtest_main", ] cflags = [ @@ -755,6 +829,7 @@ ohos_unittest("ObjectDmsHandlerTest") { ohos_unittest("ObjectManagerTest") { module_out_path = module_output_path sources = [ + "${data_service_path}/app/src/kvstore_meta_manager.cpp", "${data_service_path}/service/common/common_types_utils.cpp", "${data_service_path}/service/common/value_proxy.cpp", "../object/src/object_asset_loader.cpp", @@ -767,6 +842,7 @@ ohos_unittest("ObjectManagerTest") { "../object/src/object_service_stub.cpp", "../object/src/object_snapshot.cpp", "../object/src/object_types_utils.cpp", + "mock/device_manager_adapter_mock.cpp", "mock/kv_store_nb_delegate_mock.cpp", "object_manager_test.cpp", "object_service_impl_test.cpp", @@ -775,10 +851,12 @@ ohos_unittest("ObjectManagerTest") { include_dirs = [ "${dataobject_path}/frameworks/innerkitsimpl/include", + "${data_service_path}/app/src", "${data_service_path}/service/common", "${dataobject_path}/frameworks/innerkitsimpl/include/common", "${dataobject_path}/interfaces/innerkits", "${data_service_path}/adapter/include/utils", + "${data_service_path}/service/test/mock", ] configs = [ ":module_private_config" ] @@ -789,14 +867,19 @@ ohos_unittest("ObjectManagerTest") { "access_token:libtokenid_sdk", "c_utils:utils", "data_object:distributeddataobject_impl", + "dataclassification:data_transit_mgr", "dfs_service:cloudsync_asset_kit_inner", "dfs_service:distributed_file_daemon_kit_inner", "dmsfwk:distributed_sdk", + "googletest:gmock_main", + "googletest:gtest_main", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", "json:nlohmann_json_static", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "kv_store:distributeddb", "relational_store:native_rdb", ] @@ -804,7 +887,6 @@ ohos_unittest("ObjectManagerTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] cflags = [ @@ -834,6 +916,7 @@ ohos_unittest("ObjectSnapshotTest") { "c_utils:utils", "dfs_service:cloudsync_asset_kit_inner", "dfs_service:distributed_file_daemon_kit_inner", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", @@ -844,7 +927,6 @@ ohos_unittest("ObjectSnapshotTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] } @@ -879,11 +961,13 @@ ohos_unittest("MetaDataTest") { "access_token:libtoken_setproc", "c_utils:utils", "dataclassification:data_transit_mgr", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", "json:nlohmann_json_static", "kv_store:distributeddata_inner", + "kv_store:distributeddb", ] deps = [ @@ -891,8 +975,6 @@ ohos_unittest("MetaDataTest") { "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/kvdb:distributeddata_kvdb", - "${kv_store_path}/frameworks/libs/distributeddb:distributeddb", - "//third_party/googletest:gtest_main", ] } @@ -909,6 +991,8 @@ ohos_unittest("UdmfRunTimeStoreTest") { "${data_service_path}/app/src", "${data_service_path}/service/kvdb", "${data_service_path}/service/udmf", + "${data_service_path}/service/udmf/store", + "${data_service_path}/service/udmf/preprocess", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", @@ -922,14 +1006,20 @@ ohos_unittest("UdmfRunTimeStoreTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "c_utils:utils", "dataclassification:data_transit_mgr", "dsoftbus:softbus_client", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "image_framework:image", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddb", + "openssl:libcrypto_shared", + "samgr:samgr_proxy", "udmf:udmf_client", ] @@ -938,9 +1028,11 @@ ohos_unittest("UdmfRunTimeStoreTest") { "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", "${data_service_path}/service/udmf:udmf_server", - "${kv_store_path}/frameworks/libs/distributeddb:distributeddb", - "//third_party/googletest:gtest_main", - "//third_party/openssl:libcrypto_shared", + ] + + defines = [ + "private=public", + "protected=public", ] } @@ -953,6 +1045,7 @@ ohos_unittest("DataShareServiceImplTest") { module_out_path = module_output_path include_dirs = [ + "${data_service_path}/service/config/include", "${datashare_path}/frameworks/native/common/include", "${datashare_path}/interfaces/inner_api/common/include", "${datashare_path}/interfaces/inner_api/consumer/include", @@ -964,6 +1057,7 @@ ohos_unittest("DataShareServiceImplTest") { "${data_service_path}/service/crypto/src/crypto_manager.cpp", "${data_service_path}/service/data_share/common/app_connect_manager.cpp", "${data_service_path}/service/data_share/common/bundle_mgr_proxy.cpp", + "${data_service_path}/service/data_share/common/common_utils.cpp", "${data_service_path}/service/data_share/common/db_delegate.cpp", "${data_service_path}/service/data_share/common/div_strategy.cpp", "${data_service_path}/service/data_share/common/extension_ability_manager.cpp", @@ -1007,12 +1101,14 @@ ohos_unittest("DataShareServiceImplTest") { "${data_service_path}/service/kvdb/user_delegate.cpp", "${data_service_path}/service/permission/src/permission_validator.cpp", "${data_service_path}/service/permission/src/permit_delegate.cpp", + "data_share_common_test.cpp", "data_share_obs_proxy_test.cpp", "data_share_profile_config_test.cpp", "data_share_service_impl_test.cpp", "data_share_service_stub_test.cpp", "data_share_subscriber_managers_test.cpp", "data_share_types_util_test.cpp", + "kv_dalegate_test.cpp", ] configs = [ ":module_private_config" ] @@ -1044,6 +1140,7 @@ ohos_unittest("DataShareServiceImplTest") { "common_event_service:cesfwk_innerkits", "data_share:datashare_common", "device_manager:devicemanagersdk", + "googletest:gtest_main", "hicollie:libhicollie", "hilog:libhilog", "hisysevent:libhisysevent", @@ -1053,6 +1150,9 @@ ohos_unittest("DataShareServiceImplTest") { "json:nlohmann_json_static", "kv_store:distributeddata_inner", "kv_store:distributeddb", + "kv_store:distributeddb", + "qos_manager:concurrent_task_client", + "qos_manager:qos", "relational_store:native_rdb", "relational_store:rdb_data_share_adapter", "resource_management:global_resmgr", @@ -1064,13 +1164,17 @@ ohos_unittest("DataShareServiceImplTest") { "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "${kv_store_distributeddb_path}:distributeddb", - "//third_party/googletest:gtest_main", ] } ohos_unittest("KvdbServiceImplTest") { module_out_path = module_output_path + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${datamgr_service_path}/cfi_blocklist.txt" + } sources = [ "${data_service_path}/app/src/kvstore_meta_manager.cpp", "kvdb_service_impl_test.cpp", @@ -1110,10 +1214,12 @@ ohos_unittest("KvdbServiceImplTest") { "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", "googletest:gmock_main", + "googletest:gtest_main", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddb", "relational_store:native_rdb", ] @@ -1122,9 +1228,7 @@ ohos_unittest("KvdbServiceImplTest") { "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/kvdb:distributeddata_kvdb", - "${kv_store_path}/frameworks/libs/distributeddb:distributeddb", "mock:distributeddata_mock_static", - "//third_party/googletest:gtest_main", ] } @@ -1146,6 +1250,7 @@ ohos_unittest("DumpHelperTest") { external_deps = [ "c_utils:utils", + "googletest:gtest_main", "hilog:libhilog", "kv_store:distributeddata_inner", "kv_store:distributeddb", @@ -1155,7 +1260,6 @@ ohos_unittest("DumpHelperTest") { deps = [ "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "//third_party/googletest:gtest_main", ] } @@ -1186,6 +1290,7 @@ ohos_unittest("UdmfServiceImplTest") { "ability_runtime:uri_permission_mgr", "access_token:libaccesstoken_sdk", "app_file_service:remote_file_share_native", + "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "device_manager:devicemanagersdk", @@ -1195,6 +1300,7 @@ ohos_unittest("UdmfServiceImplTest") { "kv_store:distributeddata_inner", "kv_store:distributeddb", "relational_store:native_rdb", + "samgr:samgr_proxy", "udmf:udmf_client", ] } @@ -1223,6 +1329,7 @@ ohos_unittest("UdmfServiceStubTest") { "ability_runtime:uri_permission_mgr", "access_token:libaccesstoken_sdk", "app_file_service:remote_file_share_native", + "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "device_manager:devicemanagersdk", @@ -1231,6 +1338,7 @@ ohos_unittest("UdmfServiceStubTest") { "kv_store:distributeddata_inner", "kv_store:distributeddb", "relational_store:native_rdb", + "samgr:samgr_proxy", "udmf:udmf_client", ] } @@ -1299,17 +1407,98 @@ ohos_unittest("UdmfServiceStubMockTest") { "access_token:libtoken_setproc", "access_token:libtokenid_sdk", "app_file_service:remote_file_share_native", + "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "device_manager:devicemanagersdk", "googletest:gtest_main", "hilog:libhilog", + "hisysevent:libhisysevent", "hitrace:hitrace_meter", "hitrace:libhitracechain", "ipc:ipc_core", "kv_store:distributeddata_inner", "kv_store:distributeddb", "relational_store:native_rdb", + "samgr:samgr_proxy", + "udmf:udmf_client", + ] +} + +ohos_unittest("UdmfPreProcessUtilsTest") { + module_out_path = module_output_path + sources = [ "udmf_preprocess_utils_test.cpp" ] + + include_dirs = [ + "${data_service_path}/service/udmf/permission", + "${data_service_path}/service/udmf/preprocess", + ] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + deps = [ + "${data_service_path}/service:distributeddatasvc", + "${data_service_path}/service/udmf:udmf_server", + ] + + external_deps = [ + "ability_runtime:uri_permission_mgr", + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "device_manager:devicemanagersdk", + "googletest:gtest_main", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "kv_store:distributeddata_inner", + "kv_store:distributeddb", + "relational_store:native_rdb", + "udmf:udmf_client", + ] +} + +ohos_unittest("UdmfPreProcessUtilsMockTest") { + module_out_path = module_output_path + sources = [ + "${data_service_path}/service/test/mock/access_token_mock.cpp", + "${data_service_path}/service/udmf/preprocess/preprocess_utils.cpp", + "udmf_preprocess_utils_mock_test.cpp", + ] + + include_dirs = [ + "${data_service_path}/service/udmf/preprocess", + "${data_service_path}/service/test/mock", + "${data_service_path}/service/udmf/store", + "${data_service_path}/framework/include/account", + "${data_service_path}/adapter/include/communicator", + ] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + deps = [ + "${data_service_path}/service:distributeddatasvc", + "mock:distributeddata_mock_static", + ] + + external_deps = [ + "ability_runtime:uri_permission_mgr", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "access_token:libtokenid_sdk", + "app_file_service:remote_file_share_native", + "c_utils:utils", + "device_manager:devicemanagersdk", + "googletest:gmock_main", + "googletest:gtest_main", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", "udmf:udmf_client", ] } @@ -1503,6 +1692,8 @@ ohos_unittest("BootStrapMockTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", @@ -1521,8 +1712,8 @@ ohos_unittest("BootStrapMockTest") { deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", + "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/backup:distributeddata_backup", - "../../framework:distributeddatasvcfwk", ] cflags = [ @@ -1717,6 +1908,61 @@ ohos_unittest("UserDelegateMockTest") { cflags_cc = cflags } +ohos_unittest("BackupManagerServiceTest") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + module_out_path = module_output_path + sources = [ + "${data_service_path}/app/src/kvstore_meta_manager.cpp", + "backup_manager_service_test.cpp", + ] + + include_dirs = [ + "${data_service_path}/adapter/include/communicator", + "${data_service_path}/app/src", + "${data_service_path}/service/bootstrap/include/", + "${data_service_path}/service/common", + "${data_service_path}/service/crypto/include", + "${data_service_path}/service/matrix/include/", + "${data_service_path}/service/rdb", + "${data_service_path}/service/kvdb", + "${data_service_path}/service/backup/include/", + ] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "c_utils:utils", + "dataclassification:data_transit_mgr", + "device_manager:devicemanagersdk", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", + "kv_store:distributeddb", + ] + + deps = [ + "${data_service_path}/adapter/account:distributeddata_account", + "${data_service_path}/adapter/communicator:distributeddata_communicator", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service/backup:distributeddata_backup", + "${data_service_path}/service/kvdb:distributeddata_kvdb", + ] +} + ############################################################################### group("unittest") { testonly = true @@ -1740,6 +1986,8 @@ group("unittest") { if (datamgr_service_udmf) { deps += [ ":UdmfCheckerManagerTest", + ":UdmfPreProcessUtilsMockTest", + ":UdmfPreProcessUtilsTest", ":UdmfRunTimeStoreTest", ":UdmfServiceImplTest", ":UdmfServiceStubMockTest", @@ -1760,6 +2008,7 @@ group("unittest") { if (datamgr_service_rdb) { deps += [ ":RdbResultSetImplTest", + ":RdbServiceImplTest", ":RdbServiceTest", ] } @@ -1767,6 +2016,7 @@ group("unittest") { if (datamgr_service_kvdb) { deps += [ ":AuthDelegateMockTest", + ":BackupManagerServiceTest", ":KVDBGeneralStoreAbnormalTest", ":KVDBGeneralStoreTest", ":KvdbServiceImplTest", diff --git a/services/distributeddataservice/service/test/backup_manager_service_test.cpp b/services/distributeddataservice/service/test/backup_manager_service_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56a0f27e188e7af17fca669150eff90309030439 --- /dev/null +++ b/services/distributeddataservice/service/test/backup_manager_service_test.cpp @@ -0,0 +1,328 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#define LOG_TAG "BackupManagerServiceTest" + +#include +#include +#include +#include "backup_manager.h" +#include "backuprule/backup_rule_manager.h" +#include "bootstrap.h" +#include "crypto_manager.h" +#include "device_manager_adapter.h" +#include "directory/directory_manager.h" +#include "log_print.h" +#include "metadata/meta_data_manager.h" +#include "kvstore_meta_manager.h" +#include "types.h" + +using namespace testing::ext; +using namespace std; +using namespace OHOS::DistributedData; +namespace OHOS::Test { +namespace DistributedDataTest { +static constexpr uint32_t SKEY_SIZE = 32; +static constexpr int MICROSEC_TO_SEC_TEST = 1000; +static constexpr const char *TEST_BACKUP_BUNDLE = "test_backup_bundleName"; +static constexpr const char *TEST_BACKUP_STOREID = "test_backup_storeId"; +class BackupManagerServiceTest : public testing::Test { +public: + class TestRule : public BackupRuleManager::BackupRule { + public: + TestRule() + { + BackupRuleManager::GetInstance().RegisterPlugin("TestRule", [this]() -> auto { + return this; + }); + } + bool CanBackup() override + { + return false; + } + }; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static std::vector Random(uint32_t len); + void InitMetaData(); + StoreMetaData metaData_; +}; + +void BackupManagerServiceTest::SetUpTestCase(void) +{ + auto executors = std::make_shared(1, 0); + Bootstrap::GetInstance().LoadComponents(); + Bootstrap::GetInstance().LoadDirectory(); + Bootstrap::GetInstance().LoadCheckers(); + DeviceManagerAdapter::GetInstance().Init(executors); + DistributedKv::KvStoreMetaManager::GetInstance().BindExecutor(executors); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaParameter(); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaListener(); +} + +void BackupManagerServiceTest::TearDownTestCase() +{ +} + +void BackupManagerServiceTest::SetUp() +{ +} + +void BackupManagerServiceTest::TearDown() +{ +} + +void BackupManagerServiceTest::InitMetaData() +{ + metaData_.deviceId = DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid; + metaData_.bundleName = TEST_BACKUP_BUNDLE; + metaData_.appId = TEST_BACKUP_BUNDLE; + metaData_.user = "0"; + metaData_.area = OHOS::DistributedKv::EL1; + metaData_.instanceId = 0; + metaData_.isAutoSync = true; + metaData_.storeType = DistributedKv::KvStoreType::SINGLE_VERSION; + metaData_.storeId = TEST_BACKUP_STOREID; + metaData_.dataDir = "/data/service/el1/public/database/" + std::string(TEST_BACKUP_BUNDLE) + "/kvdb"; + metaData_.securityLevel = OHOS::DistributedKv::SecurityLevel::S2; +} + +std::vector BackupManagerServiceTest::Random(uint32_t len) +{ + std::random_device randomDevice; + std::uniform_int_distribution distribution(0, std::numeric_limits::max()); + std::vector key(len); + for (uint32_t i = 0; i < len; i++) { + key[i] = static_cast(distribution(randomDevice)); + } + return key; +} + +/** +* @tc.name: Init +* @tc.desc: Init testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, Init, TestSize.Level1) +{ + BackupManagerServiceTest::InitMetaData(); + StoreMetaData meta1; + meta1 = metaData_; + meta1.isBackup = false; + meta1.isDirty = false; + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta1, true)); + BackupManager::GetInstance().Init(); + + StoreMetaData meta2; + meta2 = metaData_; + meta2.isBackup = true; + meta2.isDirty = false; + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta2, true)); + BackupManager::GetInstance().Init(); + + StoreMetaData meta3; + meta3 = metaData_; + meta3.isBackup = false; + meta3.isDirty = true; + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta3, true)); + BackupManager::GetInstance().Init(); + + StoreMetaData meta4; + meta4 = metaData_; + meta4.isBackup = true; + meta4.isDirty = true; + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), meta4, true)); + BackupManager::GetInstance().Init(); +} + +/** +* @tc.name: RegisterExporter +* @tc.desc: RegisterExporter testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, RegisterExporter, TestSize.Level1) +{ + int32_t type = DistributedKv::KvStoreType::DEVICE_COLLABORATION; + BackupManager::Exporter exporter = + [](const StoreMetaData &meta, const std::string &backupPath, bool &result) + { result = true; }; + BackupManager instance; + instance.RegisterExporter(type, exporter); + EXPECT_FALSE(instance.exporters_[type] == nullptr); + instance.RegisterExporter(type, exporter); +} + +/** +* @tc.name: BackSchedule +* @tc.desc: BackSchedule testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, BackSchedule, TestSize.Level1) +{ + std::shared_ptr executors = std::make_shared(0, 1); + BackupManager instance; + instance.executors_ = nullptr; + instance.BackSchedule(executors); + EXPECT_FALSE(instance.executors_ == nullptr); +} + +/** +* @tc.name: CanBackup001 +* @tc.desc: CanBackup testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, CanBackup001, TestSize.Level1) +{ + BackupManager instance; + instance.backupSuccessTime_ = 0; + instance.backupInternal_ = 0; + bool status = instance.CanBackup(); // false false + EXPECT_TRUE(status); + + instance.backupInternal_ = MICROSEC_TO_SEC_TEST; + status = instance.CanBackup(); // true false + EXPECT_TRUE(status); + + instance.backupSuccessTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + instance.backupInternal_ = 0; + status = instance.CanBackup(); // false true + EXPECT_TRUE(status); + + instance.backupSuccessTime_ = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + instance.backupInternal_ = MICROSEC_TO_SEC_TEST; + status = instance.CanBackup(); // true true + EXPECT_FALSE(status); +} + +/** +* @tc.name: CanBackup +* @tc.desc: CanBackup testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, CanBackup, TestSize.Level1) +{ + BackupManagerServiceTest::TestRule(); + std::vector rule = { "TestRule" }; + BackupRuleManager::GetInstance().LoadBackupRules(rule); + EXPECT_FALSE(BackupRuleManager::GetInstance().CanBackup()); + bool status = BackupManager::GetInstance().CanBackup(); + EXPECT_FALSE(status); +} + +/** +* @tc.name: SaveData +* @tc.desc: SaveData testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, SaveData, TestSize.Level1) +{ + std::string path = "test"; + std::string key = "test"; + std::vector randomKey = BackupManagerServiceTest::Random(SKEY_SIZE); + SecretKeyMetaData secretKey; + secretKey.storeType = DistributedKv::KvStoreType::SINGLE_VERSION; + secretKey.sKey = randomKey; + EXPECT_EQ(secretKey.sKey.size(), SKEY_SIZE); + BackupManager::GetInstance().SaveData(path, key, secretKey); + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(key, secretKey, true)); + randomKey.assign(randomKey.size(), 0); +} + +/** +* @tc.name: GetClearType001 +* @tc.desc: GetClearType testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, GetClearType001, TestSize.Level1) +{ + StoreMetaData meta; + MetaDataManager::GetInstance().SaveMeta(StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid }), metaData_, true); + BackupManager::ClearType status = BackupManager::GetInstance().GetClearType(meta); + EXPECT_EQ(status, BackupManager::ClearType::DO_NOTHING); +} + +/** +* @tc.name: GetClearType002 +* @tc.desc: GetClearType testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, GetClearType002, TestSize.Level1) +{ + BackupManagerServiceTest::InitMetaData(); + StoreMetaData meta; + meta = metaData_; + EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(meta.GetSecretKey(), meta, true)); + + SecretKeyMetaData dbPassword; + EXPECT_TRUE(MetaDataManager::GetInstance().LoadMeta(meta.GetSecretKey(), dbPassword, true)); + SecretKeyMetaData backupPassword; + EXPECT_FALSE(MetaDataManager::GetInstance().LoadMeta(meta.GetBackupSecretKey(), backupPassword, true)); + EXPECT_FALSE(dbPassword.sKey != backupPassword.sKey); + BackupManager::ClearType status = BackupManager::GetInstance().GetClearType(meta); + EXPECT_EQ(status, BackupManager::ClearType::DO_NOTHING); +} + +/** +* @tc.name: GetPassWord +* @tc.desc: GetPassWord testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, GetPassWord, TestSize.Level1) +{ + StoreMetaData meta; + std::vector password; + bool status = BackupManager::GetInstance().GetPassWord(meta, password); + EXPECT_FALSE(status); +} + +/** +* @tc.name: IsFileExist +* @tc.desc: IsFileExist testing exception branching scenarios. +* @tc.type: FUNC +* @tc.require: +* @tc.author: suoqilong +*/ +HWTEST_F(BackupManagerServiceTest, IsFileExist, TestSize.Level1) +{ + std::string path; + bool status = BackupManager::GetInstance().IsFileExist(path); + EXPECT_FALSE(status); +} +} // namespace DistributedDataTest +} // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/cloud_data_test.cpp b/services/distributeddataservice/service/test/cloud_data_test.cpp index 107a81cf98362b96e6094e54c123be676757e33c..c73a92d27ef9627ea67e0df589ede90bca831b38 100644 --- a/services/distributeddataservice/service/test/cloud_data_test.cpp +++ b/services/distributeddataservice/service/test/cloud_data_test.cpp @@ -321,7 +321,7 @@ void CloudDataTest::TearDown() * @tc.require: * @tc.author: ht */ -HWTEST_F(CloudDataTest, GetSchema, TestSize.Level0) +HWTEST_F(CloudDataTest, GetSchema, TestSize.Level1) { auto cloudServerMock = std::make_shared(); auto user = AccountDelegate::GetInstance()->GetUserByToken(OHOS::IPCSkeleton::GetCallingTokenID()); @@ -384,7 +384,7 @@ HWTEST_F(CloudDataTest, QueryStatistics002, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryStatistics003, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryStatistics003, TestSize.Level1) { // Construct the statisticInfo data auto creator = [](const StoreMetaData &metaData) -> GeneralStore* { @@ -420,7 +420,7 @@ HWTEST_F(CloudDataTest, QueryStatistics003, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryStatistics004, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryStatistics004, TestSize.Level1) { // Construct the statisticInfo data auto creator = [](const StoreMetaData &metaData) -> GeneralStore* { @@ -494,7 +494,7 @@ HWTEST_F(CloudDataTest, QueryLastSyncInfo003, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryLastSyncInfo004, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryLastSyncInfo004, TestSize.Level1) { auto ret = cloudServiceImpl_->DisableCloud(TEST_CLOUD_ID); EXPECT_EQ(ret, CloudData::CloudService::SUCCESS); @@ -518,7 +518,7 @@ HWTEST_F(CloudDataTest, QueryLastSyncInfo004, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryLastSyncInfo005, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryLastSyncInfo005, TestSize.Level1) { std::map switches; switches.emplace(TEST_CLOUD_ID, true); @@ -739,7 +739,7 @@ HWTEST_F(CloudDataTest, QueryLastSyncInfo010, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryLastSyncInfo011, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryLastSyncInfo011, TestSize.Level1) { schemaMeta_.databases[1].name = TEST_CLOUD_STORE_1; MetaDataManager::GetInstance().SaveMeta(cloudInfo_.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta_, true); @@ -868,7 +868,7 @@ HWTEST_F(CloudDataTest, UpdateFinishSyncInfo, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, Share001, TestSize.Level0) +HWTEST_F(CloudDataTest, Share001, TestSize.Level1) { std::string sharingRes = ""; CloudData::Participants participants{}; @@ -883,7 +883,7 @@ HWTEST_F(CloudDataTest, Share001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, Unshare001, TestSize.Level0) +HWTEST_F(CloudDataTest, Unshare001, TestSize.Level1) { std::string sharingRes = ""; CloudData::Participants participants{}; @@ -898,7 +898,7 @@ HWTEST_F(CloudDataTest, Unshare001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, ChangePrivilege001, TestSize.Level0) +HWTEST_F(CloudDataTest, ChangePrivilege001, TestSize.Level1) { std::string sharingRes = ""; CloudData::Participants participants{}; @@ -913,7 +913,7 @@ HWTEST_F(CloudDataTest, ChangePrivilege001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, ChangeConfirmation001, TestSize.Level0) +HWTEST_F(CloudDataTest, ChangeConfirmation001, TestSize.Level1) { std::string sharingRes = ""; int32_t confirmation = 0; @@ -928,7 +928,7 @@ HWTEST_F(CloudDataTest, ChangeConfirmation001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, ConfirmInvitation001, TestSize.Level0) +HWTEST_F(CloudDataTest, ConfirmInvitation001, TestSize.Level1) { std::string sharingRes = ""; int32_t confirmation = 0; @@ -943,7 +943,7 @@ HWTEST_F(CloudDataTest, ConfirmInvitation001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, Exit001, TestSize.Level0) +HWTEST_F(CloudDataTest, Exit001, TestSize.Level1) { std::string sharingRes = ""; std::pair result; @@ -957,7 +957,7 @@ HWTEST_F(CloudDataTest, Exit001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, Query001, TestSize.Level0) +HWTEST_F(CloudDataTest, Query001, TestSize.Level1) { std::string sharingRes = ""; CloudData::QueryResults result; @@ -971,7 +971,7 @@ HWTEST_F(CloudDataTest, Query001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, QueryByInvitation001, TestSize.Level0) +HWTEST_F(CloudDataTest, QueryByInvitation001, TestSize.Level1) { std::string invitation = ""; CloudData::QueryResults result; @@ -1015,7 +1015,7 @@ HWTEST_F(CloudDataTest, AllocResourceAndShare001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, SetGlobalCloudStrategy001, TestSize.Level0) +HWTEST_F(CloudDataTest, SetGlobalCloudStrategy001, TestSize.Level1) { std::vector values; values.push_back(CloudData::NetWorkStrategy::WIFI); @@ -1033,7 +1033,7 @@ HWTEST_F(CloudDataTest, SetGlobalCloudStrategy001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, SetCloudStrategy001, TestSize.Level0) +HWTEST_F(CloudDataTest, SetCloudStrategy001, TestSize.Level1) { std::vector values; values.push_back(CloudData::NetWorkStrategy::WIFI); @@ -1148,7 +1148,7 @@ HWTEST_F(CloudDataTest, NotifyDataChange002, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, NotifyDataChange003, TestSize.Level0) +HWTEST_F(CloudDataTest, NotifyDataChange003, TestSize.Level1) { constexpr const int32_t userId = 100; constexpr const int32_t defaultUserId = 0; @@ -1300,7 +1300,7 @@ HWTEST_F(CloudDataTest, EnableCloud, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnEnableCloud, TestSize.Level0) +HWTEST_F(CloudDataTest, OnEnableCloud, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1321,7 +1321,7 @@ HWTEST_F(CloudDataTest, OnEnableCloud, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnDisableCloud, TestSize.Level0) +HWTEST_F(CloudDataTest, OnDisableCloud, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1340,7 +1340,7 @@ HWTEST_F(CloudDataTest, OnDisableCloud, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnChangeAppSwitch, TestSize.Level0) +HWTEST_F(CloudDataTest, OnChangeAppSwitch, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1361,7 +1361,7 @@ HWTEST_F(CloudDataTest, OnChangeAppSwitch, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnClean, TestSize.Level0) +HWTEST_F(CloudDataTest, OnClean, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1382,7 +1382,7 @@ HWTEST_F(CloudDataTest, OnClean, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnNotifyDataChange, TestSize.Level0) +HWTEST_F(CloudDataTest, OnNotifyDataChange, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1402,7 +1402,7 @@ HWTEST_F(CloudDataTest, OnNotifyDataChange, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnNotifyChange, TestSize.Level0) +HWTEST_F(CloudDataTest, OnNotifyChange, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1424,7 +1424,7 @@ HWTEST_F(CloudDataTest, OnNotifyChange, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnQueryStatistics, TestSize.Level0) +HWTEST_F(CloudDataTest, OnQueryStatistics, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1445,7 +1445,7 @@ HWTEST_F(CloudDataTest, OnQueryStatistics, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnQueryLastSyncInfo, TestSize.Level0) +HWTEST_F(CloudDataTest, OnQueryLastSyncInfo, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1466,7 +1466,7 @@ HWTEST_F(CloudDataTest, OnQueryLastSyncInfo, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnSetGlobalCloudStrategy, TestSize.Level0) +HWTEST_F(CloudDataTest, OnSetGlobalCloudStrategy, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1488,7 +1488,7 @@ HWTEST_F(CloudDataTest, OnSetGlobalCloudStrategy, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnAllocResourceAndShare, TestSize.Level0) +HWTEST_F(CloudDataTest, OnAllocResourceAndShare, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1512,7 +1512,7 @@ HWTEST_F(CloudDataTest, OnAllocResourceAndShare, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnShare, TestSize.Level0) +HWTEST_F(CloudDataTest, OnShare, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1534,7 +1534,7 @@ HWTEST_F(CloudDataTest, OnShare, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnUnshare, TestSize.Level0) +HWTEST_F(CloudDataTest, OnUnshare, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1556,7 +1556,7 @@ HWTEST_F(CloudDataTest, OnUnshare, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnExit, TestSize.Level0) +HWTEST_F(CloudDataTest, OnExit, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1577,7 +1577,7 @@ HWTEST_F(CloudDataTest, OnExit, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnChangePrivilege, TestSize.Level0) +HWTEST_F(CloudDataTest, OnChangePrivilege, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1599,7 +1599,7 @@ HWTEST_F(CloudDataTest, OnChangePrivilege, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnQuery, TestSize.Level0) +HWTEST_F(CloudDataTest, OnQuery, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1620,7 +1620,7 @@ HWTEST_F(CloudDataTest, OnQuery, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnQueryByInvitation, TestSize.Level0) +HWTEST_F(CloudDataTest, OnQueryByInvitation, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1641,7 +1641,7 @@ HWTEST_F(CloudDataTest, OnQueryByInvitation, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnConfirmInvitation, TestSize.Level0) +HWTEST_F(CloudDataTest, OnConfirmInvitation, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1663,7 +1663,7 @@ HWTEST_F(CloudDataTest, OnConfirmInvitation, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, OnChangeConfirmation, TestSize.Level0) +HWTEST_F(CloudDataTest, OnChangeConfirmation, TestSize.Level1) { MessageParcel reply; MessageParcel data; @@ -1982,7 +1982,7 @@ HWTEST_F(CloudDataTest, UpdateCloudInfoFromServer, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, GetCloudInfo, TestSize.Level0) +HWTEST_F(CloudDataTest, GetCloudInfo, TestSize.Level1) { MetaDataManager::GetInstance().DelMeta(cloudInfo_.GetKey(), true); auto ret = cloudServiceImpl_->GetCloudInfo(cloudInfo_.user); @@ -2202,7 +2202,7 @@ HWTEST_F(CloudDataTest, OnAppUninstall, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, GetCloudInfo001, TestSize.Level0) +HWTEST_F(CloudDataTest, GetCloudInfo001, TestSize.Level1) { int32_t userId = 1000; auto [status, cloudInfo] = cloudServiceImpl_->GetCloudInfo(userId); @@ -2504,7 +2504,7 @@ HWTEST_F(CloudDataTest, GetPriorityLevel004, TestSize.Level1) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, UpdateSchemaFromHap001, TestSize.Level0) +HWTEST_F(CloudDataTest, UpdateSchemaFromHap001, TestSize.Level1) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudData::CloudServiceImpl::HapInfo info = { .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE, .user = -1 }; @@ -2518,7 +2518,7 @@ HWTEST_F(CloudDataTest, UpdateSchemaFromHap001, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, UpdateSchemaFromHap002, TestSize.Level0) +HWTEST_F(CloudDataTest, UpdateSchemaFromHap002, TestSize.Level1) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudData::CloudServiceImpl::HapInfo info = { .instIndex = 0, .bundleName = "", .user = cloudInfo_.user }; @@ -2532,7 +2532,7 @@ HWTEST_F(CloudDataTest, UpdateSchemaFromHap002, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, UpdateSchemaFromHap003, TestSize.Level0) +HWTEST_F(CloudDataTest, UpdateSchemaFromHap003, TestSize.Level1) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudData::CloudServiceImpl::HapInfo info = { @@ -2552,7 +2552,7 @@ HWTEST_F(CloudDataTest, UpdateSchemaFromHap003, TestSize.Level0) * @tc.type: FUNC * @tc.require: */ -HWTEST_F(CloudDataTest, UpdateSchemaFromHap004, TestSize.Level0) +HWTEST_F(CloudDataTest, UpdateSchemaFromHap004, TestSize.Level1) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudInfo::AppInfo exampleAppInfo; @@ -2703,5 +2703,109 @@ HWTEST_F(CloudDataTest, GetPrepareTraceId, TestSize.Level0) EXPECT_EQ(evt.GetUser(), EVT_USER); EXPECT_EQ(evt.GetPrepareTraceId(), TEST_TRACE_ID); } + +/** +* @tc.name: TryUpdateDeviceId001 +* @tc.desc: TryUpdateDeviceId test +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudDataTest, TryUpdateDeviceId001, TestSize.Level1) +{ + DistributedRdb::RdbServiceImpl rdbServiceImpl; + DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; + StoreMetaData oldMeta; + oldMeta.deviceId = "oldUuidtest"; + oldMeta.user = "100"; + oldMeta.bundleName = "test_appid_001"; + oldMeta.storeId = "test_storeid_001"; + oldMeta.isNeedUpdateDeviceId = true; + oldMeta.storeType = StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN; + bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta); + EXPECT_EQ(isSuccess, true); + StoreMetaData meta1 = oldMeta; + auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); + EXPECT_EQ(ret, true); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); +} + +/** +* @tc.name: TryUpdateDeviceId002 +* @tc.desc: TryUpdateDeviceId test +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudDataTest, TryUpdateDeviceId002, TestSize.Level1) +{ + DistributedRdb::RdbServiceImpl rdbServiceImpl; + DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; + StoreMetaData oldMeta; + oldMeta.deviceId = "oldUuidtest"; + oldMeta.user = "100"; + oldMeta.bundleName = "test_appid_001"; + oldMeta.storeId = "test_storeid_001"; + oldMeta.isNeedUpdateDeviceId = false; + oldMeta.storeType = StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN; + bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta); + EXPECT_EQ(isSuccess, true); + StoreMetaData meta1 = oldMeta; + auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); + EXPECT_EQ(ret, true); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); +} + +/** +* @tc.name: TryUpdateDeviceId003 +* @tc.desc: TryUpdateDeviceId test +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudDataTest, TryUpdateDeviceId003, TestSize.Level1) +{ + DistributedRdb::RdbServiceImpl rdbServiceImpl; + DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; + StoreMetaData oldMeta; + oldMeta.deviceId = "oldUuidtest"; + oldMeta.user = "100"; + oldMeta.bundleName = "test_appid_001"; + oldMeta.storeId = "test_storeid_001"; + oldMeta.isNeedUpdateDeviceId = true; + oldMeta.storeType = StoreMetaData::StoreType::STORE_RELATIONAL_END; + bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta); + EXPECT_EQ(isSuccess, true); + StoreMetaData meta1 = oldMeta; + auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); + EXPECT_EQ(ret, true); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); +} + +/** +* @tc.name: TryUpdateDeviceId004 +* @tc.desc: TryUpdateDeviceId test +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudDataTest, TryUpdateDeviceId004, TestSize.Level1) +{ + DistributedRdb::RdbServiceImpl rdbServiceImpl; + DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; + StoreMetaData oldMeta; + oldMeta.deviceId = "oldUuidtest"; + oldMeta.user = "100"; + oldMeta.bundleName = "test_appid_001"; + oldMeta.storeId = "test_storeid_001"; + oldMeta.isNeedUpdateDeviceId = false; + oldMeta.storeType = StoreMetaData::StoreType::STORE_RELATIONAL_END; + bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta); + EXPECT_EQ(isSuccess, true); + StoreMetaData meta1 = oldMeta; + auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); + EXPECT_EQ(ret, true); + MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey()); +} } // namespace DistributedDataTest } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/cloud_service_impl_test.cpp b/services/distributeddataservice/service/test/cloud_service_impl_test.cpp index 413807f6f08b56f98f1b477f3baddf9d3bc3298e..7f1ca2f0f722744805ee2d68af4ad6df043ccf3f 100644 --- a/services/distributeddataservice/service/test/cloud_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/cloud_service_impl_test.cpp @@ -272,6 +272,23 @@ HWTEST_F(CloudServiceImplTest, GetCloudInfoFromServer001, TestSize.Level0) EXPECT_EQ(status, CloudData::CloudService::SERVER_UNAVAILABLE); } +/** + * @tc.name: GetCloudInfoFromServer002 + * @tc.desc: Test GetCloudInfoFromServer functions with cloudinfo is empty. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudServiceImplTest, GetCloudInfoFromServer002, TestSize.Level0) +{ + ZLOGI("CloudServiceImplTest GetCloudInfoFromServer002 start"); + CloudServer cloudServer; + CloudServer::RegisterCloudInstance(&cloudServer); + int user = 100; + auto [status, result] = cloudServiceImpl_->GetCloudInfoFromServer(user); + EXPECT_EQ(status, E_ERROR); + CloudServer::instance_ = nullptr; +} + /** * @tc.name: ReleaseUserInfo001 * @tc.desc: Test ReleaseUserInfo functions with invalid parameter. diff --git a/services/distributeddataservice/service/test/data_share_common_test.cpp b/services/distributeddataservice/service/test/data_share_common_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f9f92555c39c0580ed76f8ff3286fc19f0f4588 --- /dev/null +++ b/services/distributeddataservice/service/test/data_share_common_test.cpp @@ -0,0 +1,567 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#define LOG_TAG "DataShareCommonTest" + +#include +#include +#include "extension_connect_adaptor.h" +#include "data_share_profile_config.h" +#include "div_strategy.h" +#include "log_print.h" +#include "rdb_delegate.h" +#include "rdb_subscriber_manager.h" +#include "scheduler_manager.h" +#include "seq_strategy.h" +#include "strategy.h" + +namespace OHOS::Test { +using namespace testing::ext; +using namespace OHOS::DataShare; +class DataShareCommonTest : public testing::Test { +public: + static constexpr int64_t USER_TEST = 100; + static void SetUpTestCase(void){}; + static void TearDownTestCase(void){}; + void SetUp(){}; + void TearDown(){}; +}; + +/** +* @tc.name: DivStrategy001 +* @tc.desc: test DivStrategy function when three parameters are all nullptr +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(DataShareCommonTest, DivStrategy001, TestSize.Level1) +{ + ZLOGI("DataShareCommonTest DivStrategy001 start"); + std::shared_ptr check = nullptr; + std::shared_ptr trueAction = nullptr; + std::shared_ptr falseAction = nullptr; + DivStrategy divStrategy(check, trueAction, falseAction); + auto context = std::make_shared(); + bool result = divStrategy.operator()(context); + EXPECT_EQ(result, false); + ZLOGI("DataShareCommonTest DivStrategy001 end"); +} + +/** +* @tc.name: DivStrategy002 +* @tc.desc: test DivStrategy function when trueAction and falseAction are nullptr +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(DataShareCommonTest, DivStrategy002, TestSize.Level1) +{ + ZLOGI("DataShareCommonTest DivStrategy002 start"); + std::shared_ptr check = std::make_shared(); + std::shared_ptr trueAction = nullptr; + std::shared_ptr falseAction = nullptr; + DivStrategy divStrategy(check, trueAction, falseAction); + auto context = std::make_shared(); + bool result = divStrategy.operator()(context); + EXPECT_EQ(result, false); + ZLOGI("DataShareCommonTest DivStrategy002 end"); +} + +/** +* @tc.name: DivStrategy003 +* @tc.desc: test DivStrategy function when only falseAction is nullptr +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(DataShareCommonTest, DivStrategy003, TestSize.Level1) +{ + ZLOGI("DataShareCommonTest DivStrategy003 start"); + std::shared_ptr check = std::make_shared(); + std::shared_ptr trueAction = std::make_shared(); + std::shared_ptr falseAction = nullptr; + DivStrategy divStrategy(check, trueAction, falseAction); + auto context = std::make_shared(); + bool result = divStrategy.operator()(context); + EXPECT_EQ(result, false); + ZLOGI("DataShareCommonTest DivStrategy003 end"); +} + +/** +* @tc.name: SeqStrategyInit001 +* @tc.desc: test SeqStrategyInit function when item is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a seqStrategy object and strategy2 = nullptr + 2.call Init function +* @tc.experct: Init failed and return false +*/ +HWTEST_F(DataShareCommonTest, SeqStrategyInit001, TestSize.Level1) +{ + ZLOGI("SeqStrategyInit001 start"); + Strategy* strategy1 = new Strategy(); + Strategy* strategy2 = nullptr; + SeqStrategy seqStrategy; + bool result = seqStrategy.Init({strategy1, strategy2}); + EXPECT_FALSE(result); + delete strategy1; + ZLOGI("SeqStrategyInit001 end"); +} + +/** +* @tc.name: DoConnect001 +* @tc.desc: test DoConnect function when callback_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a ExtensionConnectAdaptor object and callback = nullptr + 2.call DoConnect function +* @tc.experct: DoConnect failed and return false +*/ +HWTEST_F(DataShareCommonTest, DoConnect001, TestSize.Level1) +{ + ZLOGI("DoConnect001 start"); + std::string uri = "testUri"; + std::string bundleName = "testBundle"; + AAFwk::WantParams wantParams; + ExtensionConnectAdaptor extensionConnectAdaptor; + bool result = extensionConnectAdaptor.DoConnect(uri, bundleName, wantParams); + EXPECT_FALSE(result); + ZLOGI("DoConnect001 end"); +} + +/** +* @tc.name: InsertEx001 +* @tc.desc: test InsertEx function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a rdbDelegate object and store_ = nullptr + 2.call InsertEx function +* @tc.experct: InsertEx failed and return E_DB_ERROR +*/ +HWTEST_F(DataShareCommonTest, InsertEx001, TestSize.Level1) +{ + ZLOGI("InsertEx001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string tableName = ""; + DataShare::DataShareValuesBucket valuesBucket; + std::string name0 = ""; + valuesBucket.Put("", name0); + auto result = rdbDelegate.InsertEx(tableName, valuesBucket); + EXPECT_EQ(result.first, E_DB_ERROR); + ZLOGI("InsertEx001 end"); +} + +/** +* @tc.name: UpdateEx001 +* @tc.desc: test UpdateEx function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call UpdateEx function +* @tc.experct: UpdateEx failed and return E_DB_ERROR +*/ +HWTEST_F(DataShareCommonTest, UpdateEx001, TestSize.Level1) +{ + ZLOGI("UpdateEx001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string tableName = ""; + DataShare::DataShareValuesBucket valuesBucket; + std::string name0 = ""; + valuesBucket.Put("", name0); + DataSharePredicates predicate; + auto result = rdbDelegate.UpdateEx(tableName, predicate, valuesBucket); + EXPECT_EQ(result.first, E_DB_ERROR); + ZLOGI("UpdateEx001 end"); +} + +/** +* @tc.name: DeleteEx001 +* @tc.desc: test DeleteEx function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call DeleteEx function +* @tc.experct: DeleteEx failed and return E_DB_ERROR +*/ +HWTEST_F(DataShareCommonTest, DeleteEx001, TestSize.Level1) +{ + ZLOGI("DeleteEx001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string tableName = ""; + DataSharePredicates predicate; + auto result = rdbDelegate.DeleteEx(tableName, predicate); + EXPECT_EQ(result.first, E_DB_ERROR); + ZLOGI("DeleteEx001 end"); +} + +/** +* @tc.name: Query001 +* @tc.desc: test Query function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call Query function +* @tc.experct: Query failed and return errCode +*/ +HWTEST_F(DataShareCommonTest, Query001, TestSize.Level1) +{ + ZLOGI("Query001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string tableName = ""; + DataSharePredicates predicate; + std::vector columns; + int32_t callingPid = 1; + uint32_t callingTokenId = 1; + auto result = rdbDelegate.Query(tableName, predicate, columns, callingPid, callingTokenId); + EXPECT_EQ(result.first, rdbDelegate.errCode_); + ZLOGI("Query001 end"); +} + +/** +* @tc.name: Query002 +* @tc.desc: test Query function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call Query function +* @tc.experct: Query failed and return "" +*/ +HWTEST_F(DataShareCommonTest, Query002, TestSize.Level1) +{ + ZLOGI("Query002 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string sql = "testsql"; + std::vector selectionArgs; + auto result = rdbDelegate.Query(sql, selectionArgs); + EXPECT_EQ(result, ""); + ZLOGI("Query002 end"); +} + +/** +* @tc.name: QuerySql001 +* @tc.desc: test QuerySql function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call QuerySql function +* @tc.experct: QuerySql failed and return nullptr +*/ +HWTEST_F(DataShareCommonTest, QuerySql001, TestSize.Level1) +{ + ZLOGI("QuerySql001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string sql = "testsql"; + auto result = rdbDelegate.QuerySql(sql); + EXPECT_EQ(result, nullptr); + ZLOGI("QuerySql001 end"); +} + +/** +* @tc.name: UpdateSql001 +* @tc.desc: test UpdateSql function when store_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a RdbDelegate object and store_ = nullptr + 2.call UpdateSql function +* @tc.experct: UpdateSql failed and return E_ERROR +*/ +HWTEST_F(DataShareCommonTest, UpdateSql001, TestSize.Level1) +{ + ZLOGI("UpdateSql001 start"); + DistributedData::StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = "test"; + metaData.area = 1; + int version = 0; + bool registerFunction = false; + std::string extUri = "uri"; + std::string backup = "backup"; + RdbDelegate rdbDelegate(metaData, version, registerFunction, extUri, backup); + rdbDelegate.store_ = nullptr; + std::string sql = "testsql"; + auto result = rdbDelegate.UpdateSql(sql); + EXPECT_EQ(result.first, OHOS::DataShare::E_ERROR); + ZLOGI("UpdateSql001 end"); +} + +/** +* @tc.name: EraseTimerTaskId001 +* @tc.desc: test EraseTimerTaskId function when not find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and timerCache_ is null + 2.call EraseTimerTaskId function +* @tc.experct: not find key, EraseTimerTaskId failed and return -1 +*/ +HWTEST_F(DataShareCommonTest, EraseTimerTaskId001, TestSize.Level1) +{ + ZLOGI("EraseTimerTaskId001 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + int64_t result = manager.EraseTimerTaskId(key); + EXPECT_EQ(result, -1); + ZLOGI("EraseTimerTaskId001 end"); +} + +/** +* @tc.name: EraseTimerTaskId002 +* @tc.desc: test EraseTimerTaskId function when find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and timerCache_[key] = timeid + 2.call EraseTimerTaskId function +* @tc.experct: find key, EraseTimerTaskId success and return timeid +*/ +HWTEST_F(DataShareCommonTest, EraseTimerTaskId002, TestSize.Level1) +{ + ZLOGI("EraseTimerTaskId002 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + int64_t timeid = 1; + manager.timerCache_[key] = timeid; + int64_t result = manager.EraseTimerTaskId(key); + EXPECT_EQ(result, timeid); + ZLOGI("EraseTimerTaskId002 end"); +} + +/** +* @tc.name: GetSchedulerStatus001 +* @tc.desc: test GetSchedulerStatus function when not find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and schedulerStatusCache_ is null + 2.call GetSchedulerStatus function +* @tc.experct: not find key, GetSchedulerStatus failed and return false +*/ +HWTEST_F(DataShareCommonTest, GetSchedulerStatus001, TestSize.Level1) +{ + ZLOGI("GetSchedulerStatus001 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + bool result = manager.GetSchedulerStatus(key); + EXPECT_FALSE(result); + ZLOGI("GetSchedulerStatus001 end"); +} + +/** +* @tc.name: GetSchedulerStatus002 +* @tc.desc: test GetSchedulerStatus function when find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and schedulerStatusCache_[key] = true; + 2.call GetSchedulerStatus function +* @tc.experct: find key, GetSchedulerStatus success and return true +*/ +HWTEST_F(DataShareCommonTest, GetSchedulerStatus002, TestSize.Level1) +{ + ZLOGI("GetSchedulerStatus002 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.schedulerStatusCache_[key] = true; + bool result = manager.GetSchedulerStatus(key); + EXPECT_TRUE(result); + ZLOGI("GetSchedulerStatus002 end"); +} + +/** +* @tc.name: RemoveTimer001 +* @tc.desc: test RemoveTimer function when executor_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object what timerCache_[key] = 1 and executor_ is nullptr + 2.call RemoveTimer function to remove timer +* @tc.experct: RemoveTimer failed and timerCache_ is not null +*/ +HWTEST_F(DataShareCommonTest, RemoveTimer001, TestSize.Level1) +{ + ZLOGI("RemoveTimer001 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.executor_ = nullptr; + manager.timerCache_[key] = 1; + manager.RemoveTimer(key); + EXPECT_NE(manager.timerCache_.find(key), manager.timerCache_.end()); + ZLOGI("RemoveTimer001 end"); +} + +/** +* @tc.name: RemoveTimer002 +* @tc.desc: test RemoveTimer function when executor_ is not nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and timerCache_[key] = 1 and executor_ is not nullptr + 2.call RemoveTimer function to remove timer +* @tc.experct: RemoveTimer success and timerCache_ is null +*/ +HWTEST_F(DataShareCommonTest, RemoveTimer002, TestSize.Level1) +{ + ZLOGI("RemoveTimer002 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.executor_ = std::make_shared(5, 3); + manager.timerCache_[key] = 1; + manager.RemoveTimer(key); + EXPECT_EQ(manager.timerCache_.find(key), manager.timerCache_.end()); + ZLOGI("RemoveTimer002 end"); +} + +/** +* @tc.name: ClearTimer001 +* @tc.desc: test ClearTimer function when executor_ is nullptr +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object what timerCache_[key] = 1 and executor_ is nullptr + 2.call ClearTimer function to clear timer +* @tc.experct: ClearTimer failed and timerCache_ is not empty +*/ +HWTEST_F(DataShareCommonTest, ClearTimer001, TestSize.Level1) +{ + ZLOGI("ClearTimer001 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.executor_ = nullptr; + manager.timerCache_[key] = 1; + manager.ClearTimer(); + EXPECT_FALSE(manager.timerCache_.empty()); + ZLOGI("ClearTimer001 end"); +} + +/** +* @tc.name: ClearTimer002 +* @tc.desc: test ClearTimer function when executor_ is not nullptr and find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and timerCache_[key] = 1 and executor_ is not nullptr + 2.call ClearTimer function to clear timer +* @tc.experct: ClearTimer success and timerCache_ is empty +*/ +HWTEST_F(DataShareCommonTest, ClearTimer002, TestSize.Level1) +{ + ZLOGI("ClearTimer002 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.executor_ = std::make_shared(5, 3); + manager.timerCache_[key] = 1; + manager.ClearTimer(); + EXPECT_TRUE(manager.timerCache_.empty()); + ZLOGI("ClearTimer002 end"); +} + +/** +* @tc.name: ClearTimer003 +* @tc.desc: test ClearTimer function when executor_ is not nullptr and not find key +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a SchedulerManager object and timerCache_ is null + 2.call ClearTimer function +* @tc.experct: ClearTimer failed and timerCache_ is empty +*/ +HWTEST_F(DataShareCommonTest, ClearTimer003, TestSize.Level1) +{ + ZLOGI("ClearTimer003 start"); + Key key("uri1", 1, "name1"); + auto& manager = SchedulerManager::GetInstance(); + manager.executor_ = std::make_shared(5, 3); + manager.ClearTimer(); + EXPECT_TRUE(manager.timerCache_.empty()); + ZLOGI("ClearTimer003 end"); +} +} // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/data_share_service_impl_test.cpp b/services/distributeddataservice/service/test/data_share_service_impl_test.cpp index b4f407444ea2bd99a5c8bf1656794c670b12bc1e..65f79e4d5e4f1d8dd844013777ac221e92916629 100644 --- a/services/distributeddataservice/service/test/data_share_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/data_share_service_impl_test.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2024 Huawei Device Co., Ltd. +* Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -38,6 +38,7 @@ std::string TBL_NAME0 = "name0"; std::string TBL_NAME1 = "name1"; std::string BUNDLE_NAME = "ohos.datasharetest.demo"; namespace OHOS::Test { +using OHOS::DataShare::LogLabel; class DataShareServiceImplTest : public testing::Test { public: static constexpr int64_t USER_TEST = 100; @@ -145,10 +146,10 @@ HWTEST_F(DataShareServiceImplTest, NotifyChange001, TestSize.Level1) { DataShareServiceImpl dataShareServiceImpl; std::string uri = SLIENT_ACCESS_URI; - auto result = dataShareServiceImpl.NotifyChange(uri); + auto result = dataShareServiceImpl.NotifyChange(uri, USER_TEST); EXPECT_EQ(result, true); - result = dataShareServiceImpl.NotifyChange(""); + result = dataShareServiceImpl.NotifyChange("", USER_TEST); EXPECT_EQ(result, false); } @@ -456,4 +457,38 @@ HWTEST_F(DataShareServiceImplTest, OnInitialize, TestSize.Level1) auto result = dataShareServiceImpl.OnInitialize(); EXPECT_EQ(result, 0); } + +/** +* @tc.name: GetCallerInfo001 +* @tc.desc: test GetCallerInfo function when succeeded in getting tokenID +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(DataShareServiceImplTest, GetCallerInfo001, TestSize.Level1) +{ + ZLOGI("DataShareServiceImplTest GetCallerInfo001 start"); + DataShareServiceImpl dataShareServiceImpl; + int32_t appIndex = 1; + auto result = dataShareServiceImpl.GetCallerInfo(BUNDLE_NAME, appIndex); + EXPECT_EQ(result.first, true); + ZLOGI("DataShareServiceImplTest GetCallerInfo001 end"); +} + +/** +* @tc.name: GetCallerInfo002 +* @tc.desc: test GetCallerInfo function when failed to get tokenID +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(DataShareServiceImplTest, GetCallerInfo002, TestSize.Level1) +{ + ZLOGI("DataShareServiceImplTest GetCallerInfo002 start"); + DataShareServiceImpl dataShareServiceImpl; + int32_t appIndex = 1; + auto tokenId = AccessTokenKit::GetHapTokenID(USER_TEST, "ohos.datasharetest.demo", 0); + AccessTokenKit::DeleteToken(tokenId); + auto result = dataShareServiceImpl.GetCallerInfo(BUNDLE_NAME, appIndex); + EXPECT_EQ(result.first, false); + ZLOGI("DataShareServiceImplTest GetCallerInfo002 end"); +} } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp b/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp index 9b637f18a38873109c963f12cefb15a342d5411c..467432cac81b96132ffbcf711cc2094b1e45040a 100644 --- a/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp +++ b/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp @@ -110,9 +110,9 @@ HWTEST_F(DataShareSubscriberManagersTest, Add, TestSize.Level1) nodes.emplace_back(node2); Template tpl(nodes, "select name1 as name from TBL00"); DataShare::Key key(DATA_SHARE_URI_TEST, tpltId.subscriberId_, tpltId.bundleName_); - auto result = TemplateManager::GetInstance().Add(key, context->currentUserId, tpl); + auto result = TemplateManager::GetInstance().Add(key, context->visitedUserId, tpl); EXPECT_EQ(result, DataShare::E_ERROR); - result = TemplateManager::GetInstance().Delete(key, context->currentUserId); + result = TemplateManager::GetInstance().Delete(key, context->visitedUserId); EXPECT_EQ(result, DataShare::E_ERROR); } @@ -210,7 +210,7 @@ HWTEST_F(DataShareSubscriberManagersTest, IsNotifyOnEnabled, TestSize.Level1) sptr observer; std::vector val; std::map, std::vector> callbacks; - PublishedDataSubscriberManager::GetInstance().PutInto(callbacks, val, key, observer); + PublishedDataSubscriberManager::GetInstance().PutInto(callbacks, val, key, observer, context->visitedUserId); std::vector publishedKeys; PublishedDataSubscriberManager::GetInstance().SetObserversNotifiedOnEnabled(publishedKeys); uint32_t tokenId = AccessTokenKit::GetHapTokenID(USER_TEST, BUNDLE_NAME_TEST, USER_TEST); diff --git a/services/distributeddataservice/service/test/device_matrix_test.cpp b/services/distributeddataservice/service/test/device_matrix_test.cpp index 34434a8a1504fd4d3141718323d01ce68005ed54..66e25b24303a21e609685b698b53241481def7d6 100644 --- a/services/distributeddataservice/service/test/device_matrix_test.cpp +++ b/services/distributeddataservice/service/test/device_matrix_test.cpp @@ -350,7 +350,7 @@ HWTEST_F(DeviceMatrixTest, UpdateMatrixMeta, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, Online, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, Online, TestSize.Level1) { RefCount refCount; std::string device = "Online"; @@ -367,7 +367,7 @@ HWTEST_F(DeviceMatrixTest, Online, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, Offline, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, Offline, TestSize.Level1) { RefCount refCount; std::string device = "Offline"; @@ -377,6 +377,146 @@ HWTEST_F(DeviceMatrixTest, Offline, TestSize.Level0) EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().Offline(device)); } +/** + * @tc.name: OnBroadcast + * @tc.desc: OnBroadcast testing exceptions. + * @tc.type: FUNC + * @tc.require: + * @tc.author: suoqilong + */ +HWTEST_F(DeviceMatrixTest, OnBroadcast, TestSize.Level1) +{ + std::string device; + DeviceMatrix::DataLevel dataLevel; + EXPECT_TRUE(!dataLevel.IsValid()); + auto mask = DeviceMatrix::GetInstance().OnBroadcast(device, dataLevel); + EXPECT_EQ(mask.first, DeviceMatrix::INVALID_LEVEL); // true true + + dataLevel = { + .dynamic = DeviceMatrix::META_STORE_MASK, + }; + EXPECT_FALSE(!dataLevel.IsValid()); + mask = DeviceMatrix::GetInstance().OnBroadcast(device, dataLevel); + EXPECT_EQ(mask.first, DeviceMatrix::INVALID_LEVEL); // true false + + EXPECT_FALSE(!dataLevel.IsValid()); + mask = DeviceMatrix::GetInstance().OnBroadcast(TEST_DEVICE, dataLevel); + EXPECT_EQ(mask.first, DeviceMatrix::META_STORE_MASK); // false false + + DeviceMatrix::DataLevel dataLevels; + EXPECT_TRUE(!dataLevels.IsValid()); + mask = DeviceMatrix::GetInstance().OnBroadcast(device, dataLevels); + EXPECT_EQ(mask.first, DeviceMatrix::INVALID_LEVEL); // false true +} + +/** + * @tc.name: ConvertStatics + * @tc.desc: ConvertStatics testing exceptions. + * @tc.type: FUNC + * @tc.require: + * @tc.author: suoqilong + */ +HWTEST_F(DeviceMatrixTest, ConvertStatics, TestSize.Level1) +{ + DeviceMatrix deviceMatrix; + DistributedData::MatrixMetaData meta; + uint16_t mask = 0; + uint16_t result = deviceMatrix.ConvertStatics(meta, mask); + EXPECT_EQ(result, 0); + + mask = 0xFFFF; + result = deviceMatrix.ConvertStatics(meta, mask); + EXPECT_EQ(result, 0); + + meta.version = 4; + meta.dynamic = 0x1F; + meta.deviceId = TEST_DEVICE; + meta.origin = MatrixMetaData::Origin::REMOTE_RECEIVED; + meta.dynamicInfo = { TEST_BUNDLE, dynamicStores_[0].first }; + result = deviceMatrix.ConvertStatics(meta, DeviceMatrix::INVALID_LEVEL); + EXPECT_EQ(result, 0); +} + +/** + * @tc.name: SaveSwitches + * @tc.desc: SaveSwitches testing exceptions. + * @tc.type: FUNC + * @tc.require: + * @tc.author: suoqilong + */ +HWTEST_F(DeviceMatrixTest, SaveSwitches, TestSize.Level1) +{ + DeviceMatrix deviceMatrix; + std::string device; + DeviceMatrix::DataLevel dataLevel; + dataLevel.switches = DeviceMatrix::INVALID_VALUE; + dataLevel.switchesLen = DeviceMatrix::INVALID_LENGTH; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.SaveSwitches(device, dataLevel)); + + device = "SaveSwitches"; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.SaveSwitches(device, dataLevel)); + + dataLevel.switches = 0; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.SaveSwitches(device, dataLevel)); + + dataLevel.switchesLen = 0; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.SaveSwitches(device, dataLevel)); +} + +/** + * @tc.name: Broadcast + * @tc.desc: Broadcast testing exceptions. + * @tc.type: FUNC + * @tc.require: + * @tc.author: suoqilong + */ +HWTEST_F(DeviceMatrixTest, Broadcast, TestSize.Level1) +{ + DeviceMatrix deviceMatrix; + DeviceMatrix::DataLevel dataLevel; + EXPECT_FALSE(deviceMatrix.lasts_.IsValid()); + EXPECT_NO_FATAL_FAILURE(deviceMatrix.Broadcast(dataLevel)); + + dataLevel.statics = 0; + dataLevel.dynamic = 0; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.Broadcast(dataLevel)); + + deviceMatrix.lasts_.statics = 0; + deviceMatrix.lasts_.dynamic = 0; + EXPECT_TRUE(deviceMatrix.lasts_.IsValid()); + EXPECT_NO_FATAL_FAILURE(deviceMatrix.Broadcast(dataLevel)); + + DeviceMatrix::DataLevel dataLevels; + dataLevel = dataLevels; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.Broadcast(dataLevel)); +} + +/** + * @tc.name: UpdateConsistentMeta + * @tc.desc: UpdateConsistentMeta testing exceptions. + * @tc.type: FUNC + * @tc.require: + * @tc.author: suoqilong + */ +HWTEST_F(DeviceMatrixTest, UpdateConsistentMeta, TestSize.Level1) +{ + DeviceMatrix deviceMatrix; + std::string device = "device"; + DeviceMatrix::Mask remote; + remote.statics = 0; + remote.dynamic = 0; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.UpdateConsistentMeta(device, remote)); + + remote.statics = 0x1; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.UpdateConsistentMeta(device, remote)); + + remote.dynamic = 0x1; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.UpdateConsistentMeta(device, remote)); + + remote.statics = 0; + EXPECT_NO_FATAL_FAILURE(deviceMatrix.UpdateConsistentMeta(device, remote)); +} + /** * @tc.name: OnChanged001 * @tc.desc: Test the DeviceMatrix::OnChanged method exception scenario. @@ -384,7 +524,7 @@ HWTEST_F(DeviceMatrixTest, Offline, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, OnChanged001, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, OnChanged001, TestSize.Level1) { StoreMetaData metaData; metaData.dataType = static_cast(DeviceMatrix::LevelType::STATICS - 1); @@ -392,6 +532,16 @@ HWTEST_F(DeviceMatrixTest, OnChanged001, TestSize.Level0) metaData.dataType = DeviceMatrix::LevelType::BUTT; EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().OnChanged(metaData)); + + metaData.bundleName = "distributeddata"; + metaData.tokenId = selfToken_; + metaData.storeId = "service_meta"; + metaData.dataType = 1; + metaData.dataType = DeviceMatrix::LevelType::STATICS; + EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().OnChanged(metaData)); + + StoreMetaData meta = metaData_; + EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().OnChanged(meta)); } /** @@ -401,7 +551,7 @@ HWTEST_F(DeviceMatrixTest, OnChanged001, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, OnChanged002, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, OnChanged002, TestSize.Level1) { StoreMetaData metaData; metaData.bundleName = "distributeddata"; @@ -414,36 +564,21 @@ HWTEST_F(DeviceMatrixTest, OnChanged002, TestSize.Level0) type = DeviceMatrix::LevelType::BUTT; EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().OnChanged(code, type)); -} - -/** - * @tc.name: OnExchanged001 - * @tc.desc: Test the DeviceMatrix::OnExchanged method exception scenario. - * @tc.type: FUNC - * @tc.require: - * @tc.author: suoqilong - */ -HWTEST_F(DeviceMatrixTest, OnExchanged001, TestSize.Level0) -{ - StoreMetaData metaData; - metaData.dataType = static_cast(DeviceMatrix::LevelType::STATICS - 1); - std::string device = "OnExchanged"; - EXPECT_NO_FATAL_FAILURE( - DeviceMatrix::GetInstance().OnExchanged(device, metaData, DeviceMatrix::ChangeType::CHANGE_REMOTE)); - metaData.dataType = DeviceMatrix::LevelType::BUTT; - EXPECT_NO_FATAL_FAILURE( - DeviceMatrix::GetInstance().OnExchanged(device, metaData, DeviceMatrix::ChangeType::CHANGE_REMOTE)); + StoreMetaData meta = metaData_; + code = DeviceMatrix::GetInstance().GetCode(meta); + EXPECT_EQ(code, 0); + EXPECT_NO_FATAL_FAILURE(DeviceMatrix::GetInstance().OnChanged(code, type)); } /** - * @tc.name: OnExchanged002 + * @tc.name: OnExchanged001 * @tc.desc: Test the DeviceMatrix::OnExchanged method exception scenario. * @tc.type: FUNC * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, OnExchanged002, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, OnExchanged001, TestSize.Level1) { StoreMetaData metaData; metaData.bundleName = "distributeddata"; @@ -466,19 +601,46 @@ HWTEST_F(DeviceMatrixTest, OnExchanged002, TestSize.Level0) } /** - * @tc.name: OnExchangedd003 + * @tc.name: OnExchanged002 + * @tc.desc: Test the DeviceMatrix::OnExchanged method exception scenario. + * @tc.type: FUNC + * @tc.require: + * @tc.author: suoqilong + */ +HWTEST_F(DeviceMatrixTest, OnExchanged002, TestSize.Level1) +{ + StoreMetaData metaData; + metaData.dataType = static_cast(DeviceMatrix::LevelType::STATICS - 1); + std::string device = "OnExchanged"; + EXPECT_NO_FATAL_FAILURE( + DeviceMatrix::GetInstance().OnExchanged(device, metaData, DeviceMatrix::ChangeType::CHANGE_REMOTE)); + + metaData.dataType = DeviceMatrix::LevelType::BUTT; + EXPECT_NO_FATAL_FAILURE( + DeviceMatrix::GetInstance().OnExchanged(device, metaData, DeviceMatrix::ChangeType::CHANGE_REMOTE)); +} + +/** + * @tc.name: OnExchanged003 * @tc.desc: Test the DeviceMatrix::OnExchanged method. * @tc.type: FUNC * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, OnExchangedd003, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, OnExchanged003, TestSize.Level1) { StoreMetaData metaData; - metaData.dataType = DeviceMatrix::LevelType::STATICS; + metaData.bundleName = "distributeddata"; + metaData.tokenId = selfToken_; + metaData.storeId = "service_meta"; + metaData.dataType = 1; std::string device = "OnExchanged"; EXPECT_NO_FATAL_FAILURE( DeviceMatrix::GetInstance().OnExchanged(device, metaData, DeviceMatrix::ChangeType::CHANGE_REMOTE)); + + StoreMetaData meta = metaData_; + EXPECT_NO_FATAL_FAILURE( + DeviceMatrix::GetInstance().OnExchanged(device, meta, DeviceMatrix::ChangeType::CHANGE_REMOTE)); } /** @@ -488,7 +650,7 @@ HWTEST_F(DeviceMatrixTest, OnExchangedd003, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetCode, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetCode, TestSize.Level1) { StoreMetaData metaData; metaData.bundleName = "distributeddata"; @@ -506,7 +668,7 @@ HWTEST_F(DeviceMatrixTest, GetCode, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetMask001, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetMask001, TestSize.Level1) { std::string device = "GetMask"; DeviceMatrix::LevelType type = DeviceMatrix::LevelType::STATICS; @@ -521,7 +683,7 @@ HWTEST_F(DeviceMatrixTest, GetMask001, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetMask002, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetMask002, TestSize.Level1) { std::string device = "GetMask"; DeviceMatrix::LevelType type = DeviceMatrix::LevelType::STATICS; @@ -546,7 +708,7 @@ HWTEST_F(DeviceMatrixTest, GetMask002, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetRemoteMask001, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetRemoteMask001, TestSize.Level1) { std::string device = "GetRemoteMask"; DeviceMatrix::LevelType type = DeviceMatrix::LevelType::STATICS; @@ -561,7 +723,7 @@ HWTEST_F(DeviceMatrixTest, GetRemoteMask001, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetRemoteMask002, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetRemoteMask002, TestSize.Level1) { std::string device = "GetRemoteMask"; StoreMetaData meta = metaData_; @@ -591,7 +753,7 @@ HWTEST_F(DeviceMatrixTest, GetRemoteMask002, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetRecvLevel, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetRecvLevel, TestSize.Level1) { std::string device = "GetRemoteMask"; DeviceMatrix::LevelType type = DeviceMatrix::LevelType::STATICS; @@ -618,7 +780,7 @@ HWTEST_F(DeviceMatrixTest, GetRecvLevel, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, GetConsLevel, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, GetConsLevel, TestSize.Level1) { std::string device = "GetRemoteMask"; DeviceMatrix::LevelType type = DeviceMatrix::LevelType::STATICS; @@ -645,7 +807,7 @@ HWTEST_F(DeviceMatrixTest, GetConsLevel, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, UpdateLevel, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, UpdateLevel, TestSize.Level1) { uint16_t level = 0; DeviceMatrix::LevelType type = static_cast(DeviceMatrix::LevelType::STATICS - 1); @@ -670,19 +832,31 @@ HWTEST_F(DeviceMatrixTest, UpdateLevel, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, IsDynamic, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, IsDynamic, TestSize.Level1) { StoreMetaData meta; meta.bundleName = "distributeddata"; meta.tokenId = selfToken_; - meta.storeId = "service_meta"; + meta.storeId = ""; meta.dataType = DeviceMatrix::LevelType::STATICS; bool isDynamic = DeviceMatrix::GetInstance().IsDynamic(meta); EXPECT_EQ(isDynamic, false); meta.dataType = DeviceMatrix::LevelType::DYNAMIC; isDynamic = DeviceMatrix::GetInstance().IsDynamic(meta); + EXPECT_EQ(isDynamic, false); + + meta.storeId = "service_meta"; + isDynamic = DeviceMatrix::GetInstance().IsDynamic(meta); EXPECT_EQ(isDynamic, true); + + meta.tokenId = 1; + isDynamic = DeviceMatrix::GetInstance().IsDynamic(meta); + EXPECT_EQ(isDynamic, false); + + meta.storeId = ""; + isDynamic = DeviceMatrix::GetInstance().IsDynamic(meta); + EXPECT_EQ(isDynamic, false); } /** @@ -692,7 +866,7 @@ HWTEST_F(DeviceMatrixTest, IsDynamic, TestSize.Level0) * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(DeviceMatrixTest, IsValid, TestSize.Level0) +HWTEST_F(DeviceMatrixTest, IsValid, TestSize.Level1) { DistributedData::DeviceMatrix::DataLevel dataLevel; EXPECT_EQ(dataLevel.IsValid(), false); @@ -719,7 +893,7 @@ public: * @tc.require: * @tc.author: suoqilong */ -HWTEST_F(MatrixEventTest, IsValid, TestSize.Level0) +HWTEST_F(MatrixEventTest, IsValid, TestSize.Level1) { DistributedData::MatrixEvent::MatrixData matrixData; EXPECT_EQ(matrixData.IsValid(), false); diff --git a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn index 30cc77cc748c64e3ef674068fafafea32640ed01..ca4c9f00502e6f43a21f481cf2f3be90f6e42475 100644 --- a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn @@ -82,6 +82,8 @@ ohos_fuzztest("CloudServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", @@ -133,6 +135,7 @@ ohos_fuzztest("CloudServiceStubFuzzTest") { "device_manager:devicemanagersdk", "hicollie:libhicollie", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", diff --git a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn index 67dd09415dd34bb43fbcf57b9e30b2ac55a2a287..dfb20f04e232c9d0a260fd140a2be847a4a0d2e0 100644 --- a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn @@ -24,6 +24,7 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "${data_service_path}/app/src", "${data_service_path}/framework/include", "${data_service_path}/service/common", + "${data_service_path}/service/config/include", "${data_service_path}/service/crypto/include", "${data_service_path}/service/data_share/common", "${data_service_path}/service/data_share/data", @@ -55,6 +56,7 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "${data_service_path}/service/crypto/src/crypto_manager.cpp", "${data_service_path}/service/data_share/common/app_connect_manager.cpp", "${data_service_path}/service/data_share/common/bundle_mgr_proxy.cpp", + "${data_service_path}/service/data_share/common/common_utils.cpp", "${data_service_path}/service/data_share/common/db_delegate.cpp", "${data_service_path}/service/data_share/common/div_strategy.cpp", "${data_service_path}/service/data_share/common/extension_ability_manager.cpp", @@ -104,6 +106,7 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "${data_service_path}/adapter/account:distributeddata_account", "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", ] external_deps = [ @@ -129,6 +132,8 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "ipc:ipc_core", "kv_store:distributeddata_inner", "kv_store:distributeddb", + "qos_manager:concurrent_task_client", + "qos_manager:qos", "relational_store:native_rdb", "relational_store:rdb_data_share_adapter", "resource_management:global_resmgr", diff --git a/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn index 3e39786a14cb2ef917721b9244cd6e435aa41ee3..2fd165553fc82a02c25e2bec66fe165409078770 100644 --- a/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/dumphelper_fuzzer/BUILD.gn @@ -70,6 +70,7 @@ ohos_fuzztest("DumpHelperFuzzTest") { "device_auth:deviceauth_sdk", "device_manager:devicemanagersdk", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", diff --git a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn index 458b5897bf2849a02ae9326a051db12313c77e9d..87efa4b39748655714529db3064e91d4c3811773 100644 --- a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn @@ -69,6 +69,8 @@ ohos_fuzztest("KvdbServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn index 336b0dbfc3561fdf79595a75894079899c6f2b08..e3d93e45b12bc78a313eddf3fe9dc341d70375f3 100755 --- a/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn @@ -68,6 +68,8 @@ ohos_fuzztest("ObjectServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", diff --git a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn index b7dffe3f17867dc5a05fdec07e096a7063ef0b4d..984eddf37dd2aad45543a029a8ed40df530a584d 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn @@ -75,6 +75,7 @@ ohos_fuzztest("RdbResultSetStubFuzzTest") { "device_auth:deviceauth_sdk", "device_manager:devicemanagersdk", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", diff --git a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp index 9f10a09f56a02b58b1632964830086c41f89a9dc..14d6d1c69b3ab60f12046ce66f5568fc8dfd4760 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/rdbresultsetstub_fuzzer.cpp @@ -15,29 +15,31 @@ #include "rdbresultsetstub_fuzzer.h" +#include + #include #include #include +#include "message_parcel.h" #include "rdb_result_set_impl.h" #include "rdb_result_set_stub.h" -#include "message_parcel.h" -#include "store/cursor.h" #include "securec.h" +#include "store/cursor.h" using namespace OHOS::DistributedRdb; - namespace OHOS { +using Code = NativeRdb::RemoteResultSet::Code; const std::u16string INTERFACE_TOKEN = u"OHOS::NativeRdb.IResultSet"; -constexpr uint32_t CODE_MIN = 0; -constexpr uint32_t CODE_MAX = NativeRdb::RemoteResultSet::Code::CMD_MAX + 1; bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) { - uint32_t code = static_cast(*data) % (CODE_MAX - CODE_MIN + 1) + CODE_MIN; + FuzzedDataProvider provider(data, size); + uint32_t code = provider.ConsumeIntegralInRange(0, Code::CMD_MAX); + std::vector remaining_data = provider.ConsumeRemainingBytes(); MessageParcel request; request.WriteInterfaceToken(INTERFACE_TOKEN); - request.WriteBuffer(data, size); + request.WriteBuffer(static_cast(remaining_data.data()), remaining_data.size()); request.RewindRead(0); MessageParcel reply; MessageOption option; @@ -52,11 +54,6 @@ bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { - if (data == nullptr) { - return 0; - } - OHOS::OnRemoteRequestFuzz(data, size); - return 0; } \ No newline at end of file diff --git a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn index 43309645c3d16e6b79f0699cab22f4d3f8c1cb21..e9d34a5d4a598a535c27086e462f96e83ef44e55 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn @@ -74,6 +74,8 @@ ohos_fuzztest("RdbServiceStubFuzzTest") { "${data_service_path}/service/config/src/model/checker_config.cpp", "${data_service_path}/service/config/src/model/cloud_config.cpp", "${data_service_path}/service/config/src/model/component_config.cpp", + "${data_service_path}/service/config/src/model/datashare_config.cpp", + "${data_service_path}/service/config/src/model/device_sync_app_white_list_config.cpp", "${data_service_path}/service/config/src/model/directory_config.cpp", "${data_service_path}/service/config/src/model/global_config.cpp", "${data_service_path}/service/config/src/model/network_config.cpp", @@ -120,6 +122,7 @@ ohos_fuzztest("RdbServiceStubFuzzTest") { "device_manager:devicemanagersdk", "hicollie:libhicollie", "hilog:libhilog", + "hisysevent:libhisysevent", "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", diff --git a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp index a9ef6e03d54f52e11cc42b2dc16ba8dd4b1795bc..60767879aa99d8763621d53b71b031de094bacfa 100644 --- a/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/rdbservicestub_fuzzer.cpp @@ -15,20 +15,20 @@ #include "rdbservicestub_fuzzer.h" +#include + #include #include #include "ipc_skeleton.h" -#include "rdb_service_impl.h" #include "message_parcel.h" +#include "rdb_service_impl.h" #include "securec.h" using namespace OHOS::DistributedRdb; namespace OHOS { const std::u16string INTERFACE_TOKEN = u"OHOS.DistributedRdb.IRdbService"; -constexpr uint32_t CODE_MIN = 0; -constexpr uint32_t CODE_MAX = static_cast(RdbServiceCode::RDB_SERVICE_CMD_MAX) + 1; constexpr size_t NUM_MIN = 5; constexpr size_t NUM_MAX = 12; @@ -39,10 +39,13 @@ bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) rdbServiceImpl->OnBind( { "RdbServiceStubFuzz", static_cast(IPCSkeleton::GetSelfTokenID()), std::move(executor) }); - uint32_t code = static_cast(*data) % (CODE_MAX - CODE_MIN + 1) + CODE_MIN; + FuzzedDataProvider provider(data, size); + uint32_t code = + provider.ConsumeIntegralInRange(0, static_cast(RdbServiceCode::RDB_SERVICE_CMD_MAX)); + std::vector remaining_data = provider.ConsumeRemainingBytes(); MessageParcel request; request.WriteInterfaceToken(INTERFACE_TOKEN); - request.WriteBuffer(data, size); + request.WriteBuffer(static_cast(remaining_data.data()), remaining_data.size()); request.RewindRead(0); MessageParcel reply; std::shared_ptr rdbServiceStub = rdbServiceImpl; @@ -54,11 +57,6 @@ bool OnRemoteRequestFuzz(const uint8_t *data, size_t size) /* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { - if (data == nullptr) { - return 0; - } - OHOS::OnRemoteRequestFuzz(data, size); - return 0; } \ No newline at end of file diff --git a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn index e3e58f256fb914e20ecf39a18b653ed03062d357..27778e7e3510bfea62c572d1da3c0866496de80b 100644 --- a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn @@ -57,13 +57,16 @@ ohos_fuzztest("UdmfServiceFuzzTest") { "ability_runtime:uri_permission_mgr", "access_token:libaccesstoken_sdk", "access_token:libtoken_setproc", + "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "hilog:libhilog", + "hisysevent:libhisysevent", "ipc:ipc_core", "kv_store:distributeddata_inner", "kv_store:distributeddata_mgr", "kv_store:distributeddb", + "samgr:samgr_proxy", "udmf:udmf_client", ] } diff --git a/services/distributeddataservice/service/test/kv_dalegate_test.cpp b/services/distributeddataservice/service/test/kv_dalegate_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4920e91b27f44372162090c3a70b5e1951d9831d --- /dev/null +++ b/services/distributeddataservice/service/test/kv_dalegate_test.cpp @@ -0,0 +1,403 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#define LOG_TAG "KvDelegateTest" + +#include +#include +#include "data_share_profile_config.h" +#include "executor_pool.h" +#include "grd_error.h" +#include "kv_delegate.h" +#include "log_print.h" + +namespace OHOS::Test { +using namespace testing::ext; +using namespace OHOS::DataShare; +class KvDelegateTest : public testing::Test { +public: + static constexpr int64_t USER_TEST = 100; + static void SetUpTestCase(void){}; + static void TearDownTestCase(void){}; + void SetUp(){}; + void TearDown(){}; +}; + +const char* g_backupFiles[] = { + "dataShare.db", + "dataShare.db.redo", + "dataShare.db.safe", + "dataShare.db.undo", +}; +const char* BACKUP_SUFFIX = ".backup"; +std::shared_ptr executors = std::make_shared(5, 3); + +/** +* @tc.name: RestoreIfNeedt001 +* @tc.desc: test RestoreIfNeed function when dbstatus is GRD_INVALID_FILE_FORMAT +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(KvDelegateTest, RestoreIfNeed001, TestSize.Level1) +{ + ZLOGI("KvDelegateTest RestoreIfNeed001 start"); + int32_t dbstatus = GRD_INVALID_FILE_FORMAT; + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + bool result = kvDelegate.RestoreIfNeed(dbstatus); + EXPECT_EQ(result, true); + ZLOGI("KvDelegateTest RestoreIfNeed001 end"); +} + +/** +* @tc.name: RestoreIfNeedt002 +* @tc.desc: test RestoreIfNeed function when dbstatus is GRD_REBUILD_DATABASE +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(KvDelegateTest, RestoreIfNeed002, TestSize.Level1) +{ + ZLOGI("KvDelegateTest RestoreIfNeed002 start"); + int32_t dbstatus = GRD_REBUILD_DATABASE; + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + bool result = kvDelegate.RestoreIfNeed(dbstatus); + EXPECT_EQ(result, true); + ZLOGI("KvDelegateTest RestoreIfNeed002 end"); +} + +/** +* @tc.name: RestoreIfNeedt003 +* @tc.desc: test RestoreIfNeed function when dbstatus is GRD_TIME_OUT +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(KvDelegateTest, RestoreIfNeed003, TestSize.Level1) +{ + ZLOGI("KvDelegateTest RestoreIfNeed003 start"); + int32_t dbstatus = GRD_TIME_OUT; + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + bool result = kvDelegate.RestoreIfNeed(dbstatus); + EXPECT_EQ(result, false); + ZLOGI("KvDelegateTest RestoreIfNeed003 end"); +} + +/** +* @tc.name: GetVersion001 +* @tc.desc: test GetVersion function when get version failed +* @tc.type: FUNC +* @tc.require:SQL +*/ +HWTEST_F(KvDelegateTest, GetVersion001, TestSize.Level1) +{ + ZLOGI("KvDelegateTest GetVersion001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + std::string collectionname = "testname"; + std::string filter = "testfilter"; + int version = 0; + bool result = kvDelegate.GetVersion(collectionname, filter, version); + EXPECT_EQ(result, false); + ZLOGI("KvDelegateTest GetVersion001 end"); +} + +/** +* @tc.name: Upsert001 +* @tc.desc: test Upsert function when GDR_DBOpen failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= false + 2.call Upsert function to upsert filter +* @tc.experct: Upsert failed and return E_ERROR +*/ +HWTEST_F(KvDelegateTest, Upsert001, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Upsert001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + std::string collectionName = "test"; + std::string filter = "filter"; + std::string value = "value"; + auto result = kvDelegate.Upsert(collectionName, filter, value); + EXPECT_EQ(result.first, E_ERROR); + ZLOGI("KvDelegateTest Upsert001 end"); +} + +/** +* @tc.name: Upsert002 +* @tc.desc: test Upsert function when GRD_UpsertDoc failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= true + 2.call Upsert function to upsert filter +* @tc.experct: Upsert failed and return GRD_INVALID_ARGS +*/ +HWTEST_F(KvDelegateTest, Upsert002, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Upsert001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.isInitDone_= true; + std::string collectionName = "test"; + std::string filter = "filter"; + std::string value = "value"; + auto result = kvDelegate.Upsert(collectionName, filter, value); + EXPECT_EQ(result.first, GRD_INVALID_ARGS); + ZLOGI("KvDelegateTest Upsert002 end"); +} + +/** +* @tc.name: Delete001 +* @tc.desc: test Delete function when GDR_DBOpen failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= false + 2.call Delete function to Delete filter +* @tc.experct: Delete failed and return E_ERROR +*/ +HWTEST_F(KvDelegateTest, Delete001, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Delete001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + std::string collectionName = "test"; + std::string filter = "filter"; + auto result = kvDelegate.Delete(collectionName, filter); + EXPECT_EQ(result.first, E_ERROR); + ZLOGI("KvDelegateTest Delete001 end"); +} + +/** +* @tc.name: Delete002 +* @tc.desc: test Delete function when GRD_DeleteDoc failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= true + 2.call Delete function to Delete filter +* @tc.experct: Delete failed and return GRD_INVALID_ARGS +*/ +HWTEST_F(KvDelegateTest, Delete002, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Delete002 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.isInitDone_= true; + std::string collectionName = "test"; + std::string filter = "filter"; + auto result = kvDelegate.Delete(collectionName, filter); + EXPECT_EQ(result.first, GRD_INVALID_ARGS); + ZLOGI("KvDelegateTest Delete002 end"); +} + +/** +* @tc.name: Init001 +* @tc.desc: test Init function when isInitDone_ = true +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= true + 2.call Init function +* @tc.experct: Init failed and return true +*/ +HWTEST_F(KvDelegateTest, Init001, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Init001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.isInitDone_ = true; + auto result = kvDelegate.Init(); + EXPECT_TRUE(result); + ZLOGI("KvDelegateTest Init001 end"); +} + +/** +* @tc.name: Init002 +* @tc.desc: test Init function when isInitDone_ = false +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= false + 2.call Init function +* @tc.experct: Init failed and return false +*/ +HWTEST_F(KvDelegateTest, Init002, TestSize.Level1) +{ + ZLOGI("KvDelegateTest Init002 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + auto result = kvDelegate.Init(); + EXPECT_FALSE(result); + ZLOGI("KvDelegateTest Init002 end"); +} + +/** +* @tc.name: Get001 +* @tc.desc: test Get function when GDR_DBOpen failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= false + 2.call Get function +* @tc.experct: Get failed and return E_ERROR +*/ +HWTEST_F(KvDelegateTest, Get001, TestSize.Level1) +{ + ZLOGI("Get001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + std::string collectionName = "test"; + std::string filter = "filter"; + std::string projection = "projection"; + std::string value = "value"; + std::string result = "result"; + auto result1 = kvDelegate.Get(collectionName, filter, projection, result); + EXPECT_EQ(result1, E_ERROR); + ZLOGI("Get001 end"); +} + +/** +* @tc.name: Get002 +* @tc.desc: test Get function when GRD_FindDoc failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= true + 2.call Get function +* @tc.experct: Get failed and return GRD_INVALID_ARGS +*/ +HWTEST_F(KvDelegateTest, Get002, TestSize.Level1) +{ + ZLOGI("Get002 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.isInitDone_ = true; + std::string collectionName = "test"; + std::string filter = "filter"; + std::string projection = "projection"; + std::string value = "value"; + std::string result = "result"; + auto result1 = kvDelegate.Get(collectionName, filter, projection, result); + EXPECT_EQ(result1, GRD_INVALID_ARGS); + ZLOGI("Get002 end"); +} + +/** +* @tc.name: Backup001 +* @tc.desc: test Backup function when hasChange_ is true +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.hasChange_ = true + 2.call Backup function +* @tc.experct: need backup and change kvDelegate.hasChange_ to false +*/ +HWTEST_F(KvDelegateTest, Backup001, TestSize.Level1) +{ + ZLOGI("Backup001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.hasChange_ = true; + kvDelegate.Backup(); + EXPECT_FALSE(kvDelegate.hasChange_); + ZLOGI("Backup001 end"); +} + +/** +* @tc.name: Backup002 +* @tc.desc: test Backup function when hasChange_ is false +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.hasChange_ = false + 2.call Backup function +* @tc.experct: no need to backup and kvDelegate.hasChange_ not change +*/ +HWTEST_F(KvDelegateTest, Backup002, TestSize.Level1) +{ + ZLOGI("Backup002 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.Backup(); + EXPECT_FALSE(kvDelegate.hasChange_); + ZLOGI("Backup002 end"); +} + +/** +* @tc.name: GetBatch001 +* @tc.desc: test GetBatch function when GDR_DBOpen failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= false + 2.call GetBach function +* @tc.experct: GetBach failed and return E_ERROR +*/ +HWTEST_F(KvDelegateTest, GetBatch001, TestSize.Level1) +{ + ZLOGI("GetBatch001 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + std::string collectionName = "test"; + std::string filter = "filter"; + std::string projection = "projection"; + std::string value = "value"; + std::vector result; + auto result1 = kvDelegate.GetBatch(collectionName, filter, projection, result); + EXPECT_EQ(result1, E_ERROR); + ZLOGI("GetBatch001 end"); +} + +/** +* @tc.name: GetBatch002 +* @tc.desc: test GetBatch function when GRD_FindDoc failed +* @tc.type: FUNC +* @tc.require:issueIBX9E1 +* @tc.precon: None +* @tc.step: + 1.Creat a kvDelegate object and kvDelegate.isInitDone_= true + 2.call GetBatch function +* @tc.experct: GetBatch failed and return GRD_INVALID_ARGS +*/ +HWTEST_F(KvDelegateTest, GetBatch002, TestSize.Level1) +{ + ZLOGI("GetBatch002 start"); + std::string path = "path/to/your/db"; + KvDelegate kvDelegate(path, executors); + kvDelegate.isInitDone_ = true; + std::string collectionName = "test"; + std::string filter = "filter"; + std::string projection = "projection"; + std::string value = "value"; + std::vector result; + auto result1 = kvDelegate.GetBatch(collectionName, filter, projection, result); + EXPECT_EQ(result1, GRD_INVALID_ARGS); + ZLOGI("GetBatch001 end"); +} +} // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/kvdb_general_store_test.cpp b/services/distributeddataservice/service/test/kvdb_general_store_test.cpp index 6da7e1d416e751d92b0ce2ee2ed87f452df334bc..57ca2a4151c1c89d58b79ea4fa83b305beac9e36 100644 --- a/services/distributeddataservice/service/test/kvdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_general_store_test.cpp @@ -567,7 +567,7 @@ HWTEST_F(KVDBGeneralStoreTest, Clean, TestSize.Level0) std::string tableName = "tableName"; auto ret = store->Clean(devices, -1, tableName); EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS); - ret = store->Clean(devices, 5, tableName); + ret = store->Clean(devices, 6, tableName); EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS); ret = store->Clean(devices, GeneralStore::CleanMode::NEARBY_DATA, tableName); EXPECT_EQ(ret, GeneralError::E_ALREADY_CLOSED); @@ -587,6 +587,9 @@ HWTEST_F(KVDBGeneralStoreTest, Clean, TestSize.Level0) ret = store->Clean(devices, GeneralStore::CleanMode::LOCAL_DATA, tableName); EXPECT_EQ(ret, GeneralError::E_ERROR); + + ret = store->Clean(devices, GeneralStore::CleanMode::CLEAN_WATER, tableName); + EXPECT_EQ(ret, GeneralError::E_OK); } /** diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index ba28f19a5afbd43ae321c13f819798c105a2734f..7b7d7382e8187d15e71f8c7b5890a889a395a568 100644 --- a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp @@ -13,10 +13,10 @@ * limitations under the License. */ #define LOG_TAG "KvdbServiceImplTest" -#include "kvdb_service_impl.h" - -#include #include +#include + +#include #include #include "bootstrap.h" @@ -27,6 +27,8 @@ #include "distributed_kv_data_manager.h" #include "event_center.h" #include "ipc_skeleton.h" +#include "kvdb_query.h" +#include "kvdb_service_impl.h" #include "kvdb_service_stub.h" #include "kvstore_death_recipient.h" #include "kvstore_meta_manager.h" @@ -34,9 +36,9 @@ #include "log_print.h" #include "mock/access_token_mock.h" #include "mock/meta_data_manager_mock.h" +#include "nativetoken_kit.h" #include "network_delegate.h" #include "network_delegate_mock.h" -#include "nativetoken_kit.h" #include "token_setproc.h" #include "types.h" #include "utils/anonymous.h" @@ -63,23 +65,28 @@ using UserId = OHOS::DistributedKv::UserId; using StoreMetaData = OHOS::DistributedData::StoreMetaData; using SyncEnd = OHOS::DistributedKv::KvStoreSyncManager::SyncEnd; using DBResult = std::map; +using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; +using DBLaunchParam = OHOS::DistributedKv::KVDBServiceImpl::DBLaunchParam; static OHOS::DistributedKv::StoreId storeId = { "kvdb_test_storeid" }; static OHOS::DistributedKv::AppId appId = { "ohos.test.kvdb" }; - +static constexpr const char *TEST_USER = "0"; namespace OHOS::Test { namespace DistributedDataTest { class KvdbServiceImplTest : public testing::Test { public: static inline std::shared_ptr accTokenMock = nullptr; static inline std::shared_ptr metaDataManagerMock = nullptr; + static inline std::shared_ptr> metaDataMock = nullptr; static constexpr size_t NUM_MIN = 5; static constexpr size_t NUM_MAX = 12; + static constexpr uint32_t TOKENID1 = 123; + static constexpr uint32_t TOKENID2 = 456; static DistributedKvDataManager manager; static Options create; static UserId userId; std::shared_ptr kvStore; - + std::shared_ptr executors_; static AppId appId; static StoreId storeId64; static StoreId storeId65; @@ -89,12 +96,14 @@ public: static void RemoveAllStore(OHOS::DistributedKv::DistributedKvDataManager &manager); void SetUp(); void TearDown(); - + void CreateStoreMetaData(std::vector &datas, DBLaunchParam param); KvdbServiceImplTest(); protected: std::shared_ptr kvdbServiceImpl_; static NetworkDelegateMock delegate_; + StoreMetaData metaData_; + Options options_; }; class CloudServerMock : public CloudServer { @@ -147,6 +156,8 @@ void KvdbServiceImplTest::SetUpTestCase(void) BAccessTokenKit::accessTokenkit = accTokenMock; metaDataManagerMock = std::make_shared(); BMetaDataManager::metaDataManager = metaDataManagerMock; + metaDataMock = std::make_shared>(); + BMetaData::metaDataManager = metaDataMock; NetworkDelegate::RegisterNetworkInstance(&delegate_); } @@ -160,11 +171,22 @@ void KvdbServiceImplTest::TearDownTestCase() BAccessTokenKit::accessTokenkit = nullptr; metaDataManagerMock = nullptr; BMetaDataManager::metaDataManager = nullptr; + metaDataMock = nullptr; + BMetaData::metaDataManager = nullptr; } void KvdbServiceImplTest::SetUp(void) { kvdbServiceImpl_ = std::make_shared(); + + options_.isNeedCompress = true; + metaData_.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + metaData_.bundleName = appId.appId; + metaData_.storeId = storeId.storeId; + metaData_.user = TEST_USER; + metaData_.tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + metaData_.version = 1; + MetaDataManager::GetInstance().DelMeta(metaData_.GetKey()); } void KvdbServiceImplTest::TearDown(void) @@ -179,7 +201,60 @@ void SyncEndCallback(const std::map &statu } } -KvdbServiceImplTest::KvdbServiceImplTest(void) {} +KvdbServiceImplTest::KvdbServiceImplTest(void) +{ +} + +void KvdbServiceImplTest::CreateStoreMetaData(std::vector &datas, DBLaunchParam param) +{ + std::vector metaData; + + // 1: storeType out of range. + StoreMetaData meta1; + meta1.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN - 1; + metaData.push_back(meta1); + + StoreMetaData meta2; + meta2.storeType = StoreMetaData::StoreType::STORE_KV_END + 1; + metaData.push_back(meta2); + + // 2: user ID mismatch. + StoreMetaData meta3; + meta3.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN; + meta3.user = "user2"; // param.userId = "user1" + metaData.push_back(meta3); + + // 3: appId equals to process label. + StoreMetaData meta4; + meta4.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN; + meta4.appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); + metaData.push_back(meta4); + + // 4: The identifier does not match and CompareTripleIdentifier is false. + StoreMetaData meta5; + meta5.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN; + meta5.storeId = "store_id_1"; + meta5.appId = "app_id_1"; + metaData.push_back(meta5); + + // 5: Normal execution logic. + StoreMetaData meta6; + meta6.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN; + meta6.user = param.userId; // param.userId = "user1" + meta6.appId = "valid_app_id"; + meta6.storeId = "store_id_2"; + meta6.tokenId = TOKENID1; + metaData.push_back(meta6); + + // 6: trigger SetEqualIdentifier. + StoreMetaData meta7; + meta7.storeType = StoreMetaData::StoreType::STORE_KV_BEGIN; + meta7.user = param.userId; + meta7.appId = "valid_app_id"; + meta7.storeId = "store_id_3"; + meta7.tokenId = TOKENID2; + metaData.push_back(meta7); +} /** * @tc.name: KvdbServiceImpl001 @@ -217,8 +292,9 @@ HWTEST_F(KvdbServiceImplTest, KvdbServiceImpl001, TestSize.Level0) status = kvdbServiceImpl_->UnsubscribeSwitchData(appId); EXPECT_EQ(status, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return - (ATokenTypeEnum::TOKEN_NATIVE)).WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); status = kvdbServiceImpl_->Close(appId, id1, 0); EXPECT_EQ(status, Status::SUCCESS); } @@ -242,7 +318,7 @@ HWTEST_F(KvdbServiceImplTest, OnInitialize001, TestSize.Level0) auto event = std::make_unique(CloudEvent::CLOUD_SYNC, storeInfo); EXPECT_NE(event, nullptr); result = EventCenter::GetInstance().PostEvent(move(event)); - EXPECT_EQ(result, 1); // CODE_SYNC + EXPECT_EQ(result, 1); // CODE_SYNC auto event1 = std::make_unique(CloudEvent::CLEAN_DATA, storeInfo); EXPECT_NE(event1, nullptr); result = EventCenter::GetInstance().PostEvent(move(event1)); @@ -306,8 +382,9 @@ HWTEST_F(KvdbServiceImplTest, DeleteTest001, TestSize.Level0) Status status1 = manager.GetSingleKvStore(create, appId, storeId, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status1, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return - (ATokenTypeEnum::TOKEN_NATIVE)).WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); auto status = kvdbServiceImpl_->Delete(appId, storeId, 0); ZLOGI("DeleteTest001 status = :%{public}d", status); ASSERT_EQ(status, Status::SUCCESS); @@ -324,8 +401,9 @@ HWTEST_F(KvdbServiceImplTest, DeleteTest002, TestSize.Level0) ZLOGI("DeleteTest002 start"); AppId appId01 = { "ohos.kvdbserviceimpl.test01" }; StoreId storeId01 = { "meta_test_storeid" }; - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return - (ATokenTypeEnum::TOKEN_NATIVE)).WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); auto status = kvdbServiceImpl_->Delete(appId01, storeId01, 0); ZLOGI("DeleteTest002 status = :%{public}d", status); ASSERT_EQ(status, Status::SUCCESS); @@ -339,9 +417,11 @@ HWTEST_F(KvdbServiceImplTest, DeleteTest002, TestSize.Level0) */ HWTEST_F(KvdbServiceImplTest, DeleteTest003, TestSize.Level0) { - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); - EXPECT_CALL(*accTokenMock, GetHapTokenInfo(testing::_, testing::_)).WillOnce(testing::Return(-1)) + EXPECT_CALL(*accTokenMock, GetHapTokenInfo(testing::_, testing::_)) + .WillOnce(testing::Return(-1)) .WillRepeatedly(testing::Return(-1)); int32_t status = kvdbServiceImpl_->Delete(appId, storeId, 0); EXPECT_EQ(status, DistributedKv::ILLEGAL_STATE); @@ -355,9 +435,11 @@ HWTEST_F(KvdbServiceImplTest, DeleteTest003, TestSize.Level0) */ HWTEST_F(KvdbServiceImplTest, CloseTest001, TestSize.Level0) { - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); - EXPECT_CALL(*accTokenMock, GetHapTokenInfo(testing::_, testing::_)).WillOnce(testing::Return(-1)) + EXPECT_CALL(*accTokenMock, GetHapTokenInfo(testing::_, testing::_)) + .WillOnce(testing::Return(-1)) .WillRepeatedly(testing::Return(-1)); int32_t status = kvdbServiceImpl_->Close(appId, storeId, 0); EXPECT_EQ(status, DistributedKv::ILLEGAL_STATE); @@ -372,29 +454,29 @@ HWTEST_F(KvdbServiceImplTest, CloseTest001, TestSize.Level0) HWTEST_F(KvdbServiceImplTest, OnAsyncCompleteTest001, TestSize.Level0) { DistributedKv::Statistic upload; - upload.failed = 1; // test - upload.success = 1; // test - upload.total = 1; // test + upload.failed = 1; // test + upload.success = 1; // test + upload.total = 1; // test upload.untreated = 1; // test DistributedKv::Statistic download; - download.failed = 1; // test - download.success = 1; // test - download.total = 1; // test + download.failed = 1; // test + download.success = 1; // test + download.total = 1; // test download.untreated = 1; // test DistributedKv::TableDetail details; details.download = download; details.upload = upload; DistributedKv::ProgressDetail detail; - detail.code = 1; // test + detail.code = 1; // test detail.progress = 1; // test detail.details = details; sptr notifier; DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; - syncAgent.pid_ = 1; // test + syncAgent.pid_ = 1; // test syncAgent.switchesObserverCount_ = 1; // test syncAgent.appId_ = { "ohos.OnAsyncCompleteTest001.kvdb" }; syncAgent.notifier_ = notifier; - kvdbServiceImpl_->syncAgents_.Insert(100, syncAgent); // test + kvdbServiceImpl_->syncAgents_.Insert(100, syncAgent); // test kvdbServiceImpl_->OnAsyncComplete(1, 1, std::move(detail)); // test EXPECT_EQ(kvdbServiceImpl_->syncAgents_.Find(1).first, false); kvdbServiceImpl_->OnAsyncComplete(100, 1, std::move(detail)); // test @@ -450,7 +532,7 @@ HWTEST_F(KvdbServiceImplTest, UnregServiceNotifierTest001, TestSize.Level0) ASSERT_EQ(status1, Status::SUCCESS); sptr notifier; DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; - syncAgent.pid_ = 1; // test + syncAgent.pid_ = 1; // test syncAgent.switchesObserverCount_ = 1; // test syncAgent.appId_ = { "ohos.OnAsyncCompleteTest001.kvdb" }; syncAgent.notifier_ = notifier; @@ -534,11 +616,13 @@ HWTEST_F(KvdbServiceImplTest, EnableCapabilityTest001, TestSize.Level0) Status status1 = manager.GetSingleKvStore(create, appId, storeId, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status1, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); auto status = kvdbServiceImpl_->EnableCapability(appId, storeId, 0); ASSERT_EQ(status, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); status = kvdbServiceImpl_->EnableCapability(appId, storeId, 0); ASSERT_EQ(status, Status::ILLEGAL_STATE); @@ -555,7 +639,8 @@ HWTEST_F(KvdbServiceImplTest, GetInstIndexTest001, TestSize.Level0) Status status1 = manager.GetSingleKvStore(create, appId, storeId, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status1, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); auto status = kvdbServiceImpl_->GetInstIndex(100, appId); ASSERT_EQ(status, -1); @@ -573,13 +658,15 @@ HWTEST_F(KvdbServiceImplTest, IsNeedMetaSyncTest001, TestSize.Level0) ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status1, Status::SUCCESS); StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); - std::vector uuids{"uuidtest01"}; + std::vector uuids{ "uuidtest01" }; EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(true)).WillRepeatedly(testing::Return(true)); + .WillOnce(testing::Return(true)) + .WillRepeatedly(testing::Return(true)); auto status = kvdbServiceImpl_->IsNeedMetaSync(meta, uuids); ASSERT_EQ(status, false); EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(false)).WillRepeatedly(testing::Return(false)); + .WillOnce(testing::Return(false)) + .WillRepeatedly(testing::Return(false)); status = kvdbServiceImpl_->IsNeedMetaSync(meta, uuids); ASSERT_EQ(status, true); } @@ -597,11 +684,13 @@ HWTEST_F(KvdbServiceImplTest, GetDistributedDataMetaTest001, TestSize.Level0) ASSERT_EQ(status, Status::SUCCESS); std::string deviceId = "KvdbServiceImplTest_deviceId"; EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(false)).WillRepeatedly(testing::Return(false)); + .WillOnce(testing::Return(false)) + .WillRepeatedly(testing::Return(false)); auto meta = kvdbServiceImpl_->GetDistributedDataMeta(deviceId); ASSERT_EQ(meta.user, "0"); EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(true)).WillRepeatedly(testing::Return(true)); + .WillOnce(testing::Return(true)) + .WillRepeatedly(testing::Return(true)); meta = kvdbServiceImpl_->GetDistributedDataMeta(deviceId); ASSERT_EQ(meta.deviceId, deviceId); } @@ -637,7 +726,7 @@ HWTEST_F(KvdbServiceImplTest, DoSyncBeginTest001, TestSize.Level0) Status status = manager.GetSingleKvStore(create, appId, storeId, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status, Status::SUCCESS); - std::vector device1{"uuidtest01"}; + std::vector device1{ "uuidtest01" }; std::vector device2; StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); SyncInfo syncInfo; @@ -673,12 +762,14 @@ HWTEST_F(KvdbServiceImplTest, DoCompleteTest001, TestSize.Level0) DBResult dbResult; dbResult.insert_or_assign("DoCompleteTest_1", DBStatus::OK); dbResult.insert_or_assign("DoCompleteTest_1", DBStatus::DB_ERROR); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); status = kvdbServiceImpl_->DoComplete(meta, syncInfo, refCount, dbResult); ASSERT_EQ(status, Status::SUCCESS); syncInfo.seqId = std::numeric_limits::max(); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); status = kvdbServiceImpl_->DoComplete(meta, syncInfo, refCount, dbResult); ASSERT_EQ(status, Status::SUCCESS); @@ -698,7 +789,7 @@ HWTEST_F(KvdbServiceImplTest, ConvertDbStatusNativeTest001, TestSize.Level0) ASSERT_EQ(status, Status::DEVICE_NOT_ONLINE); DBStatus dbstatus = static_cast(DBStatus::OK - 1); status = kvdbServiceImpl_->ConvertDbStatusNative(dbstatus); - ASSERT_EQ(status, - 1); + ASSERT_EQ(status, -1); } /** @@ -751,12 +842,14 @@ HWTEST_F(KvdbServiceImplTest, DisableCapabilityTest001, TestSize.Level0) Status status1 = manager.GetSingleKvStore(create, appId, storeId, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status1, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); auto status = kvdbServiceImpl_->DisableCapability(appId, storeId, 0); ZLOGI("DisableCapabilityTest001 status = :%{public}d", status); ASSERT_EQ(status, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); status = kvdbServiceImpl_->EnableCapability(appId, storeId, 0); ASSERT_EQ(status, Status::ILLEGAL_STATE); @@ -776,12 +869,14 @@ HWTEST_F(KvdbServiceImplTest, SetCapabilityTest001, TestSize.Level0) ASSERT_EQ(status1, Status::SUCCESS); std::vector local; std::vector remote; - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_NATIVE)); auto status = kvdbServiceImpl_->SetCapability(appId, storeId, 0, local, remote); ZLOGI("SetCapabilityTest001 status = :%{public}d", status); ASSERT_EQ(status, Status::SUCCESS); - EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)).WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) + EXPECT_CALL(*accTokenMock, GetTokenTypeFlag(testing::_)) + .WillOnce(testing::Return(ATokenTypeEnum::TOKEN_HAP)) .WillRepeatedly(testing::Return(ATokenTypeEnum::TOKEN_HAP)); status = kvdbServiceImpl_->EnableCapability(appId, storeId, 0); ASSERT_EQ(status, Status::ILLEGAL_STATE); @@ -858,7 +953,7 @@ HWTEST_F(KvdbServiceImplTest, UnsubscribeTest001, TestSize.Level0) ASSERT_EQ(status1, Status::SUCCESS); sptr notifier; DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; - syncAgent.pid_ = 1; // test + syncAgent.pid_ = 1; // test syncAgent.switchesObserverCount_ = 1; // test syncAgent.appId_ = { "ohos.OnAsyncCompleteTest001.kvdb" }; syncAgent.notifier_ = notifier; @@ -882,14 +977,14 @@ HWTEST_F(KvdbServiceImplTest, GetBackupPasswordTest001, TestSize.Level0) ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status, Status::SUCCESS); std::vector> password; - status = kvdbServiceImpl_->GetBackupPassword - (appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::BACKUP_SECRET_KEY); + status = kvdbServiceImpl_->GetBackupPassword( + appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::BACKUP_SECRET_KEY); ASSERT_EQ(status, Status::ERROR); - status = kvdbServiceImpl_->GetBackupPassword - (appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::SECRET_KEY); + status = kvdbServiceImpl_->GetBackupPassword( + appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::SECRET_KEY); ASSERT_EQ(status, Status::ERROR); - status = kvdbServiceImpl_->GetBackupPassword - (appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::BUTTON); + status = kvdbServiceImpl_->GetBackupPassword( + appId, storeId, 0, password, DistributedKv::KVDBService::PasswordType::BUTTON); ASSERT_EQ(status, Status::ERROR); } @@ -915,7 +1010,8 @@ HWTEST_F(KvdbServiceImplTest, BeforeCreateTest001, TestSize.Level0) creates.cloudConfig.enableCloud = true; kvdbServiceImpl_->executors_ = std::make_shared(1, 1); EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(false)).WillRepeatedly(testing::Return(false)); + .WillOnce(testing::Return(false)) + .WillRepeatedly(testing::Return(false)); auto status = kvdbServiceImpl_->BeforeCreate(appId, storeId, creates); ASSERT_NE(status, Status::STORE_META_CHANGED); kvdbServiceImpl_->executors_ = nullptr; @@ -1040,13 +1136,14 @@ HWTEST_F(KvdbServiceImplTest, OnReadyTest001, TestSize.Level0) */ HWTEST_F(KvdbServiceImplTest, ResolveAutoLaunch, TestSize.Level0) { - StoreId id1; - id1.storeId = "id1"; - Status status = manager.GetSingleKvStore(create, appId, id1, kvStore); + StoreId id; + id.storeId = "id"; + Status status = manager.GetSingleKvStore(create, appId, id, kvStore); EXPECT_NE(kvStore, nullptr); EXPECT_EQ(status, Status::SUCCESS); std::string identifier = "identifier"; DistributedKv::KVDBServiceImpl::DBLaunchParam launchParam; + launchParam.userId = "user1"; auto result = kvdbServiceImpl_->ResolveAutoLaunch(identifier, launchParam); EXPECT_EQ(result, Status::STORE_NOT_FOUND); std::shared_ptr executors = std::make_shared(1, 0); @@ -1055,22 +1152,26 @@ HWTEST_F(KvdbServiceImplTest, ResolveAutoLaunch, TestSize.Level0) DistributedKv::KvStoreMetaManager::GetInstance().BindExecutor(executors); DistributedKv::KvStoreMetaManager::GetInstance().InitMetaParameter(); DistributedKv::KvStoreMetaManager::GetInstance().InitMetaListener(); + std::vector datas; + CreateStoreMetaData(datas, launchParam); + EXPECT_CALL(*metaDataMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillRepeatedly(testing::DoAll(testing::SetArgReferee<1>(datas), testing::Return(true))); result = kvdbServiceImpl_->ResolveAutoLaunch(identifier, launchParam); EXPECT_EQ(result, Status::SUCCESS); } /** -* @tc.name: IsRemoteChange -* @tc.desc: IsRemoteChange function test. +* @tc.name: IsNeedSync +* @tc.desc: IsNeedSync function test. * @tc.type: FUNC * @tc.author: wangbin */ -HWTEST_F(KvdbServiceImplTest, IsRemoteChangeTest, TestSize.Level0) +HWTEST_F(KvdbServiceImplTest, IsNeedSyncTest, TestSize.Level0) { StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); - std::string devices= "IsRemoteChangeTest"; - auto changes = kvdbServiceImpl_->IsRemoteChange(meta, devices); - EXPECT_EQ(changes, true); + std::vector devices = { "IsNeedSyncTest" }; + auto changes = kvdbServiceImpl_->IsNeedSync(meta, devices); + EXPECT_EQ(changes, false); } /** @@ -1081,9 +1182,9 @@ HWTEST_F(KvdbServiceImplTest, IsRemoteChangeTest, TestSize.Level0) */ HWTEST_F(KvdbServiceImplTest, PutSwitch, TestSize.Level0) { - StoreId id1; - id1.storeId = "id1"; - Status status = manager.GetSingleKvStore(create, appId, id1, kvStore); + StoreId id; + id.storeId = "id1"; + Status status = manager.GetSingleKvStore(create, appId, id, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status, Status::SUCCESS); DistributedKv::SwitchData switchData; @@ -1118,9 +1219,9 @@ HWTEST_F(KvdbServiceImplTest, PutSwitch, TestSize.Level0) */ HWTEST_F(KvdbServiceImplTest, DoCloudSync, TestSize.Level0) { - StoreId id1; - id1.storeId = "id1"; - Status status = manager.GetSingleKvStore(create, appId, id1, kvStore); + StoreId id; + id.storeId = "id1"; + Status status = manager.GetSingleKvStore(create, appId, id, kvStore); ASSERT_NE(kvStore, nullptr); ASSERT_EQ(status, Status::SUCCESS); StoreMetaData metaData; @@ -1273,5 +1374,209 @@ HWTEST_F(KvdbServiceImplTest, DoCloudSync02, TestSize.Level0) auto status = kvdbServiceImpl_->DoCloudSync(metaData, syncInfo); EXPECT_EQ(status, OHOS::DistributedKv::Status::NETWORK_ERROR); } + +/** +* @tc.name: DoCloudSync +* @tc.desc: DoCloudSync error function test. +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, DoCloudSync01, TestSize.Level0) +{ + StoreId id; + id.storeId = "id1"; + Status status = manager.GetSingleKvStore(create, appId, id, kvStore); + ASSERT_NE(kvStore, nullptr); + ASSERT_EQ(status, Status::SUCCESS); + StoreMetaData metaData; + metaData.enableCloud = false; + SyncInfo syncInfo; + status = kvdbServiceImpl_->DoCloudSync(metaData, syncInfo); + EXPECT_EQ(status, Status::NOT_SUPPORT); +} + +/** +* @tc.name: OnAsyncCompleteTest002 +* @tc.desc: OnAsyncComplete function test. +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, OnAsyncCompleteTest002, TestSize.Level0) +{ + DistributedKv::Statistic upload; + upload.failed = 1; // test + upload.success = 1; // test + upload.total = 1; // test + upload.untreated = 1; // test + DistributedKv::Statistic download; + download.failed = 1; // test + download.success = 1; // test + download.total = 1; // test + download.untreated = 1; // test + DistributedKv::TableDetail details; + details.download = download; + details.upload = upload; + DistributedKv::ProgressDetail detail; + detail.code = 1; // test + detail.progress = 1; // test + detail.details = details; + DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; + sptr notifier = nullptr; + syncAgent.pid_ = 1; // test + syncAgent.switchesObserverCount_ = 1; // test + syncAgent.appId_ = { "ohos.OnAsyncCompleteTest.kvdb" }; + syncAgent.notifier_ = notifier; + EXPECT_EQ(notifier, nullptr); + uint32_t tokenId = 2; + uint64_t seqNum = 1; + kvdbServiceImpl_->syncAgents_.Insert(tokenId, syncAgent); + kvdbServiceImpl_->OnAsyncComplete(tokenId, seqNum, std::move(detail)); + EXPECT_TRUE(kvdbServiceImpl_->syncAgents_.Find(tokenId).first); + kvdbServiceImpl_->OnAsyncComplete(0, 1, std::move(detail)); + EXPECT_TRUE(kvdbServiceImpl_->syncAgents_.Find(tokenId).first); +} + +/** +* @tc.name: OnAsyncCompleteTest003 +* @tc.desc: OnAsyncComplete function test. +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, OnAsyncCompleteTest003, TestSize.Level0) +{ + DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; + sptr notifier; + syncAgent.pid_ = 1; // test + syncAgent.switchesObserverCount_ = 1; // test + syncAgent.appId_ = { "ohos.OnAsyncCompleteTest001.kvdb" }; + syncAgent.notifier_ = notifier; + DistributedKv::ProgressDetail detail; + auto tokenId = IPCSkeleton::GetCallingTokenID(); + kvdbServiceImpl_->syncAgents_.Insert(tokenId, syncAgent); + kvdbServiceImpl_->OnAsyncComplete(tokenId, 1, std::move(detail)); + EXPECT_TRUE(kvdbServiceImpl_->syncAgents_.Find(tokenId).first); +} + +/** +* @tc.name: DeleteTest004 +* @tc.desc: Delete Test +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, DeleteTest004, TestSize.Level0) +{ + ZLOGI("DeleteTest004 start"); + AppId appId = { "ohos.kvdbserviceimpl.test" }; + StoreId storeId = { "meta_test_storeid" }; + DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; + syncAgent.pid_ = 1; + auto tokenId = IPCSkeleton::GetCallingTokenID(); + auto status = kvdbServiceImpl_->Delete(appId, storeId, 0); + ZLOGI("DeleteTest002 status = :%{public}d", status); + EXPECT_NE(tokenId, syncAgent.pid_); + ASSERT_EQ(status, Status::SUCCESS); +} + +/** +* @tc.name: syncTest002 +* @tc.desc: Sync +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, syncTest002, TestSize.Level0) +{ + ZLOGI("syncTest002 start"); + StoreMetaData metaData; + auto mm = std::numeric_limits::max(); + metaData.isAutoSync = true; + SyncInfo syncInfo; + syncInfo.devices = { "device1", "device2" }; + syncInfo.query = "query"; + syncInfo.seqId = mm; // test + auto status = kvdbServiceImpl_->Sync(appId, storeId, 0, syncInfo); + ASSERT_EQ(syncInfo.seqId, std::numeric_limits::max()); + ZLOGI("syncTest002 status = :%{public}d", status); + ASSERT_NE(status, Status::SUCCESS); +} + +/** +* @tc.name: syncTest003 +* @tc.desc: Sync +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, syncTest003, TestSize.Level0) +{ + ZLOGI("syncTest003 start"); + StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); + StoreMetaData metaData; + metaData.isAutoSync = true; + StoreMetaDataLocal localMeta; + PolicyValue value; + value.type = OHOS::DistributedKv::PolicyType::IMMEDIATE_SYNC_ON_ONLINE; + localMeta.policies = { std::move(value) }; + SyncInfo syncInfo; + syncInfo.seqId = std::numeric_limits::max(); + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(true)) + .WillRepeatedly(testing::Return(true)); + auto status = kvdbServiceImpl_->Sync(appId, storeId, 0, syncInfo); + EXPECT_EQ(localMeta.HasPolicy(DistributedKv::IMMEDIATE_SYNC_ON_CHANGE), false); + EXPECT_NE(status, Status::SUCCESS); + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(false)) + .WillRepeatedly(testing::Return(false)); + status = kvdbServiceImpl_->Sync(appId, storeId, 0, syncInfo); + EXPECT_EQ(localMeta.HasPolicy(DistributedKv::IMMEDIATE_SYNC_ON_ONLINE), true); +} + +/** +* @tc.name: GetSyncParamTest001 +* @tc.desc: GetStoreIds +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, GetSyncParamTest002, TestSize.Level0) +{ + ZLOGI("GetSyncParamTest001 start"); + Status status1 = manager.GetSingleKvStore(create, appId, storeId, kvStore); + ASSERT_NE(kvStore, nullptr); + ASSERT_EQ(status1, Status::SUCCESS); + OHOS::DistributedKv::KvSyncParam syncparam; + DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; + syncAgent.pid_ = 1; + auto tokenId = IPCSkeleton::GetCallingTokenID(); + EXPECT_NE(tokenId, syncAgent.pid_); + auto status = kvdbServiceImpl_->GetSyncParam(appId, storeId, 0, syncparam); + ZLOGI("GetSyncParamTest002 status = :%{public}d", status); + ASSERT_EQ(status, Status::SUCCESS); +} + +/** +* @tc.name: SubscribeSwitchData +* @tc.desc: SubscribeSwitchData function test. +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(KvdbServiceImplTest, SubscribeSwitchData, TestSize.Level0) +{ + options_.isNeedCompress = false; + std::vector password{}; + StoreMetaData metaData; + auto status = kvdbServiceImpl_->AfterCreate(appId, storeId, options_, password); + ASSERT_EQ(status, Status::SUCCESS); + auto tokenId = IPCSkeleton::GetCallingTokenID(); + DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; + syncAgent.switchesObserverCount_ = 1; + syncAgent.pid_ = tokenId; + syncAgent.notifier_ = nullptr; + status = kvdbServiceImpl_->SubscribeSwitchData(appId); + EXPECT_EQ(status, Status::SUCCESS); + ASSERT_FALSE(MetaDataManager::GetInstance().LoadMeta(metaData_.GetKey(), metaData)); + kvdbServiceImpl_->syncAgents_.Insert(IPCSkeleton::GetCallingTokenID(), syncAgent); + EXPECT_EQ(tokenId, syncAgent.pid_); + status = kvdbServiceImpl_->UnregServiceNotifier(appId); + ASSERT_EQ(status, Status::SUCCESS); +} } // namespace DistributedDataTest -} // namespace OHOS::Test \ No newline at end of file +} // namespace OHOS::Test diff --git a/services/distributeddataservice/service/test/kvdb_service_test.cpp b/services/distributeddataservice/service/test/kvdb_service_test.cpp index a017163e2c43efaeda6a252629e721a0b0aa2041..80990d1797c0940418e490864cd6a8c4f2cf0b36 100644 --- a/services/distributeddataservice/service/test/kvdb_service_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_test.cpp @@ -211,6 +211,26 @@ HWTEST_F(UpgradeTest, UpdateStore, TestSize.Level0) EXPECT_EQ(dbStatus, DBStatus::OK); } +/** +* @tc.name: UpdateStore002 +* @tc.desc: UpdateStore test the return result of input with different values. +* @tc.type: FUNC +* @tc.author: yl +*/ +HWTEST_F(UpgradeTest, UpdateStore002, TestSize.Level0) +{ + DistributedKv::Upgrade upgrade; + StoreMetaData oldMeta = metaData_; + oldMeta.isNeedUpdateDeviceId = true; + std::vector password; + auto dbStatus = upgrade.UpdateStore(oldMeta, metaData_, password); + EXPECT_EQ(dbStatus, DBStatus::DB_ERROR); + + oldMeta.isEncrypt = true; + dbStatus = upgrade.UpdateStore(oldMeta, metaData_, password); + EXPECT_EQ(dbStatus, DBStatus::OK); +} + /** * @tc.name: ExportStore * @tc.desc: ExportStore test the return result of input with different values. diff --git a/services/distributeddataservice/service/test/mock/BUILD.gn b/services/distributeddataservice/service/test/mock/BUILD.gn index a0833e470a485f26a5a540bfc38bd331c749e4b4..ce0a05278abb92ca72a0fa24e51ca940ae899dfd 100644 --- a/services/distributeddataservice/service/test/mock/BUILD.gn +++ b/services/distributeddataservice/service/test/mock/BUILD.gn @@ -18,6 +18,7 @@ config("module_private_config") { include_dirs = [ "${data_service_path}/adapter/include/communicator", + "${data_service_path}/service/kvdb", "../../../framework/include/", "../../../service/rdb/", "./", @@ -27,6 +28,7 @@ config("module_private_config") { } ohos_static_library("distributeddata_mock_static") { + testonly = true branch_protector_ret = "pac_ret" sanitize = { cfi = true @@ -35,18 +37,25 @@ ohos_static_library("distributeddata_mock_static") { } sources = [ + "auth_delegate_mock.cpp", "cursor_mock.cpp", "db_change_data_mock.cpp", "db_store_mock.cpp", + "device_manager_adapter_mock.cpp", "general_store_mock.cpp", "kv_store_nb_delegate_mock.cpp", + "meta_data_manager_mock.cpp", "network_delegate_mock.cpp", "screen_lock_mock.cpp", + "user_delegate_mock.cpp", ] deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ] external_deps = [ + "device_manager:devicemanagersdk", + "googletest:gmock", + "googletest:gtest", "kv_store:distributeddata_mgr", "kv_store:distributeddb", "relational_store:native_rdb", diff --git a/services/distributeddataservice/service/test/mock/auth_delegate_mock.cpp b/services/distributeddataservice/service/test/mock/auth_delegate_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d1cf72bf6fce41841379beac07ddf35ee8e4d55 --- /dev/null +++ b/services/distributeddataservice/service/test/mock/auth_delegate_mock.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "auth_delegate_mock.h" + +namespace OHOS { +namespace DistributedData { + +AuthHandler *AuthDelegate::GetInstance() +{ + return &(AuthHandlerMock::GetInstance()); +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/auth_delegate_mock.h b/services/distributeddataservice/service/test/mock/auth_delegate_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..4524aec56731e6b9c2c8a780b7611f98a4cd13ce --- /dev/null +++ b/services/distributeddataservice/service/test/mock/auth_delegate_mock.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTEDDATA_AUTH_DELEGATE_MOCK_H +#define OHOS_DISTRIBUTEDDATA_AUTH_DELEGATE_MOCK_H + +#include + +#include + +#include "auth_delegate.h" +namespace OHOS { +namespace DistributedData { +class AuthHandlerMock : public AuthHandler { +public: + static AuthHandlerMock &GetInstance() + { + static AuthHandlerMock instance; + return instance; + } + MOCK_METHOD((std::pair), CheckAccess, + (int localUserId, int peerUserId, const std::string &peerDeviceId, const AclParams &aclParams), (override)); +}; +} // namespace DistributedData +} // namespace OHOS +#endif // OHOS_DISTRIBUTEDDATA_AUTH_DELEGATE_MOCK_H \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/checker_mock.cpp b/services/distributeddataservice/service/test/mock/checker_mock.cpp index 22a2e748e70e572a9a93a3a23c773700e2c96a67..4adc8baa74114c3f3a617c2eab73beedc64e8f63 100644 --- a/services/distributeddataservice/service/test/mock/checker_mock.cpp +++ b/services/distributeddataservice/service/test/mock/checker_mock.cpp @@ -47,7 +47,7 @@ std::string CheckerMock::GetAppId(const CheckerManager::StoreInfo &info) bool CheckerMock::IsValid(const CheckerManager::StoreInfo &info) { - return true; + return !info.bundleName.empty(); } bool CheckerMock::SetDistrustInfo(const CheckerManager::Distrust &distrust) diff --git a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp index 4723bb5e6645f765e040f7ce3ae7694a878baa85..7bc2b7e827787b60f71377ba7a571cac1ed3b3e5 100644 --- a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp +++ b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp @@ -50,6 +50,14 @@ bool DeviceManagerAdapter::IsSameAccount(const AccessCaller &accCaller, const Ac return BDeviceManagerAdapter::deviceManagerAdapter->IsSameAccount(accCaller, accCallee); } +bool DeviceManagerAdapter::IsSameAccount(const std::string &devicdId) +{ + if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { + return false; + } + return BDeviceManagerAdapter::deviceManagerAdapter->IsSameAccount(devicdId); +} + bool DeviceManagerAdapter::CheckAccessControl(const AccessCaller &accCaller, const AccessCallee &accCallee) { if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { @@ -94,6 +102,30 @@ DeviceInfo DeviceManagerAdapter::GetLocalDevice() return BDeviceManagerAdapter::deviceManagerAdapter->GetLocalDevice(); } +std::string OHOS::DistributedData::DeviceManagerAdapter::GetUuidByNetworkId(const std::string &networkId) +{ + if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { + return " "; + } + return BDeviceManagerAdapter::deviceManagerAdapter->GetUuidByNetworkId(networkId); +} + +DeviceInfo OHOS::DistributedData::DeviceManagerAdapter::GetDeviceInfo(const std::string &id) +{ + if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { + return {}; + } + return BDeviceManagerAdapter::deviceManagerAdapter->GetDeviceInfo(id); +} + +std::string OHOS::DistributedData::DeviceManagerAdapter::ToNetworkID(const std::string &id) +{ + if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { + return " "; + } + return BDeviceManagerAdapter::deviceManagerAdapter->ToNetworkID(id); +} + DeviceManagerAdapter::~DeviceManagerAdapter() { } diff --git a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h index 38ab1cac06a04bf5accb596077f4d80dd8f6947d..2a47a5510f986afd8140d6d7173b07a92603e89d 100644 --- a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h +++ b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h @@ -24,6 +24,7 @@ namespace DistributedData { using namespace OHOS::AppDistributedKv; using AccessCaller = OHOS::AppDistributedKv::AccessCaller; using AccessCallee = OHOS::AppDistributedKv::AccessCallee; +using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo; class BDeviceManagerAdapter { public: virtual std::vector GetRemoteDevices() = 0; @@ -32,6 +33,10 @@ public: virtual Status StartWatchDeviceChange(const AppDeviceChangeListener *, const PipeInfo &) = 0; virtual Status StopWatchDeviceChange(const AppDeviceChangeListener *, const PipeInfo &) = 0; virtual bool IsSameAccount(const AccessCaller &, const AccessCallee &) = 0; + virtual bool IsSameAccount(const std::string &) = 0; + virtual std::string GetUuidByNetworkId(const std::string &); + virtual DeviceInfo GetDeviceInfo(const std::string &); + virtual std::string ToNetworkID(const std::string &); virtual bool CheckAccessControl(const AccessCaller &, const AccessCallee &) = 0; virtual DeviceInfo GetLocalDevice() = 0; static inline std::shared_ptr deviceManagerAdapter = nullptr; @@ -47,6 +52,10 @@ public: MOCK_METHOD(Status, StartWatchDeviceChange, (const AppDeviceChangeListener *, const PipeInfo &)); MOCK_METHOD(Status, StopWatchDeviceChange, (const AppDeviceChangeListener *, const PipeInfo &)); MOCK_METHOD(bool, IsSameAccount, (const AccessCaller &, const AccessCallee &)); + MOCK_METHOD(bool, IsSameAccount, (const std::string &)); + MOCK_METHOD(std::string, GetUuidByNetworkId, (const std::string &)); + MOCK_METHOD(DeviceInfo, GetDeviceInfo, (const std::string &)); + MOCK_METHOD(std::string, ToNetworkID, (const std::string &)); MOCK_METHOD(bool, CheckAccessControl, (const AccessCaller &, const AccessCallee &)); MOCK_METHOD(DeviceInfo, GetLocalDevice, ()); }; diff --git a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp index f955a89cd092fede075acae3244cb4b3b557c202..e5d20802cabb8cc85f18c20ced01288bb6c59a40 100644 --- a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp +++ b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp @@ -25,8 +25,32 @@ std::vector MockQuery::GetTables() return tables_; } +const std::string GetStatement() +{ + return "AS distributed_log"; +} + +void MockQuery::MakeRemoteQuery(const std::string &devices, const std::string &sql, Values &&args) +{ + isRemote_ = true; + devices_ = { devices }; + sql_ = sql; + args_ = std::move(args); +} + +void MockQuery::MakeQuery(const DistributedRdb::PredicatesMemo &predicates) +{ + if (!predicates.tables_.empty()) { + predicates_ = std::make_shared(*predicates.tables_.begin()); + predicates_->SetWhereClause("id = 1"); + } + devices_ = predicates.devices_; + tables_ = predicates.tables_; +} int32_t MockGeneralWatcher::OnChange(const Origin &origin, const PRIFields &primaryFields, ChangeInfo &&values) { + origin_ = origin; + primaryFields_ = primaryFields; return GeneralError::E_OK; } @@ -34,4 +58,4 @@ int32_t MockGeneralWatcher::OnChange(const Origin &origin, const Fields &fields, { return GeneralError::E_OK; } -} // OHOS::DistributedData +} // namespace OHOS::DistributedData diff --git a/services/distributeddataservice/service/test/mock/general_watcher_mock.h b/services/distributeddataservice/service/test/mock/general_watcher_mock.h index 41c635ff7516daad8d7a6d00b6c18664c261ff02..f82741779e798ff2e38787ea251cc6908c15aa37 100644 --- a/services/distributeddataservice/service/test/mock/general_watcher_mock.h +++ b/services/distributeddataservice/service/test/mock/general_watcher_mock.h @@ -14,12 +14,11 @@ */ #ifndef OHOS_DISTRIBUTEDDATA_SERVICE_TEST_GENERAL_WATCH_MOCK_H #define OHOS_DISTRIBUTEDDATA_SERVICE_TEST_GENERAL_WATCH_MOCK_H - -#include "store/general_value.h" +#include "rdb_query.h" #include "store/general_watcher.h" namespace OHOS::DistributedData { -class MockQuery : public GenQuery { +class MockQuery : public DistributedRdb::RdbQuery { public: ~MockQuery() = default; static constexpr uint64_t TYPE_ID = 0x20000001; @@ -28,6 +27,9 @@ public: bool IsEqual(uint64_t tid) override; std::vector GetTables() override; + const std::string GetStatement(); + void MakeRemoteQuery(const std::string &devices, const std::string &sql, DistributedData::Values &&args); + void MakeQuery(const DistributedRdb::PredicatesMemo &predicates); }; class MockGeneralWatcher : public DistributedData::GeneralWatcher { @@ -35,6 +37,10 @@ public: int32_t OnChange(const Origin &origin, const PRIFields &primaryFields, ChangeInfo &&values) override; int32_t OnChange(const Origin &origin, const Fields &fields, ChangeData &&datas) override; + +private: + Origin origin_; + PRIFields primaryFields_; }; -} // OHOS::DistributedData +} // namespace OHOS::DistributedData #endif \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.cpp b/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.cpp index 09b0962e854924d719eeb07d55c0fc37c04b3091..fd5dab19db96d5b04be1fa3509c60f512bb20475 100644 --- a/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.cpp +++ b/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.cpp @@ -337,4 +337,9 @@ KvStoreNbDelegate::DatabaseStatus KvStoreNbDelegateMock::GetDatabaseStatus() con { return {}; } + +DBStatus KvStoreNbDelegateMock::ClearMetaData(ClearKvMetaDataOption option) +{ + return DBStatus::OK; +} } // namespace DistributedDB \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.h b/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.h index 7f3d77c8d184b2d02877307072caf3024eff713e..8a97092b82cb5b7fc6f57fea11f33aec4cbf0c53 100644 --- a/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.h +++ b/services/distributeddataservice/service/test/mock/kv_store_nb_delegate_mock.h @@ -107,6 +107,7 @@ public: DBStatus Sync(const DeviceSyncOption &option, const DeviceSyncProcessCallback &onProcess); DBStatus CancelSync(uint32_t syncId); DatabaseStatus GetDatabaseStatus() const; + DBStatus ClearMetaData(ClearKvMetaDataOption option); }; } // namespace DistributedDB #endif // KV_STORE_NB_DELEGATE_H_MOCK \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/meta_data_manager_mock.cpp b/services/distributeddataservice/service/test/mock/meta_data_manager_mock.cpp index 5923f7da62783febc8a5c44cfe40524cf7ef945a..6af7ba916cee4235ee0bd83cbff1adea5c440a42 100644 --- a/services/distributeddataservice/service/test/mock/meta_data_manager_mock.cpp +++ b/services/distributeddataservice/service/test/mock/meta_data_manager_mock.cpp @@ -12,23 +12,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include #include "meta_data_manager_mock.h" +#include + +#include "metadata/capability_meta_data.h" + namespace OHOS::DistributedData { using namespace std; + OHOS::DistributedData::MetaDataManager &OHOS::DistributedData::MetaDataManager::GetInstance() { static MetaDataManager instance; return instance; } -OHOS::DistributedData::MetaDataManager::MetaDataManager() { } - -OHOS::DistributedData::MetaDataManager::~MetaDataManager() { } +OHOS::DistributedData::MetaDataManager::MetaDataManager() +{ +} +OHOS::DistributedData::MetaDataManager::~MetaDataManager() +{ +} bool OHOS::DistributedData::MetaDataManager::LoadMeta(const std::string &key, Serializable &value, bool isLocal) { return BMetaDataManager::metaDataManager->LoadMeta(key, value, isLocal); } -} \ No newline at end of file + +template<> +bool OHOS::DistributedData::MetaDataManager::LoadMeta( + const std::string &prefix, std::vector &values, bool isLocal) +{ + return BMetaData::metaDataManager->LoadMeta(prefix, values, isLocal); +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/meta_data_manager_mock.h b/services/distributeddataservice/service/test/mock/meta_data_manager_mock.h index 28b4562a629c63a549e2614ac6972a0bc081a607..6db1bf93735376706386630ac2feb29a7db7a17b 100644 --- a/services/distributeddataservice/service/test/mock/meta_data_manager_mock.h +++ b/services/distributeddataservice/service/test/mock/meta_data_manager_mock.h @@ -16,10 +16,11 @@ #define OHOS_META_DATA_MANAGER_MOCK_H #include + +#include "metadata/appid_meta_data.h" #include "metadata/meta_data_manager.h" -#include "metadata/strategy_meta_data.h" #include "metadata/store_meta_data.h" -#include "metadata/appid_meta_data.h" +#include "metadata/strategy_meta_data.h" namespace OHOS::DistributedData { class BMetaDataManager { @@ -27,13 +28,23 @@ public: virtual bool LoadMeta(const std::string &, Serializable &, bool) = 0; BMetaDataManager() = default; virtual ~BMetaDataManager() = default; -private: static inline std::shared_ptr metaDataManager = nullptr; }; - class MetaDataManagerMock : public BMetaDataManager { public: - MOCK_METHOD(bool, LoadMeta, (const std::string &, Serializable &, bool)); + MOCK_METHOD(bool, LoadMeta, (const std::string &, Serializable &, bool), (override)); +}; + +template class BMetaData { +public: + virtual bool LoadMeta(const std::string &, std::vector &, bool) = 0; + BMetaData() = default; + virtual ~BMetaData() = default; + static inline std::shared_ptr> metaDataManager = nullptr; +}; +template class MetaDataMock : public BMetaData { +public: + MOCK_METHOD(bool, LoadMeta, (const std::string &, std::vector &, bool), (override)); }; -} +} // namespace OHOS::DistributedData #endif //OHOS_META_DATA_MANAGER_MOCK_H diff --git a/services/distributeddataservice/service/test/mock/network_delegate_mock.cpp b/services/distributeddataservice/service/test/mock/network_delegate_mock.cpp index ce26d253bd9fb435436d56b19abd26d18d2dda5c..cfab2309bdb8df8927d2991961301889bb038938 100644 --- a/services/distributeddataservice/service/test/mock/network_delegate_mock.cpp +++ b/services/distributeddataservice/service/test/mock/network_delegate_mock.cpp @@ -30,5 +30,10 @@ void NetworkDelegateMock::RegOnNetworkChange() { return; } + +void NetworkDelegateMock::BindExecutor(std::shared_ptr executors) +{ + return; +} } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/network_delegate_mock.h b/services/distributeddataservice/service/test/mock/network_delegate_mock.h index 474e57c32a0247d0078be1276864fee4c4b4a5d6..5e199efbeccc66d5a2dc408c16ed48374da1bc5b 100644 --- a/services/distributeddataservice/service/test/mock/network_delegate_mock.h +++ b/services/distributeddataservice/service/test/mock/network_delegate_mock.h @@ -24,6 +24,7 @@ public: bool IsNetworkAvailable() override; NetworkType GetNetworkType(bool retrieve = false) override; void RegOnNetworkChange() override; + void BindExecutor(std::shared_ptr executors) override; bool isNetworkAvailable_ = true; virtual ~NetworkDelegateMock() = default; }; diff --git a/services/distributeddataservice/service/test/mock/relational_store_delegate_mock.h b/services/distributeddataservice/service/test/mock/relational_store_delegate_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..0f5308d450420f32df105b114cdf0199d968cdf4 --- /dev/null +++ b/services/distributeddataservice/service/test/mock/relational_store_delegate_mock.h @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef RELATIONAL_STORE_DELEGATE_MOCK_H +#define RELATIONAL_STORE_DELEGATE_MOCK_H +#include "rdb_general_store.h" +namespace DistributedDB { +class MockRelationalStoreDelegate : public DistributedDB::RelationalStoreDelegate { +public: + ~MockRelationalStoreDelegate() = default; + + DBStatus Sync(const std::vector &devices, DistributedDB::SyncMode mode, const Query &query, + const SyncStatusCallback &onComplete, bool wait) override + { + return DBStatus::OK; + } + + int32_t GetCloudSyncTaskCount() override + { + static int32_t count = 0; + count = (count + 1) % 2; // The result of count + 1 is the remainder of 2. + return count; + } + + DBStatus RemoveDeviceData(const std::string &device, const std::string &tableName) override + { + return DBStatus::OK; + } + + DBStatus RemoteQuery(const std::string &device, const RemoteCondition &condition, uint64_t timeout, + std::shared_ptr &result) override + { + if (device == "test") { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } + + DBStatus RemoveDeviceData() override + { + return DBStatus::OK; + } + + DBStatus Sync(const std::vector &devices, DistributedDB::SyncMode mode, const Query &query, + const SyncProcessCallback &onProcess, int64_t waitTime) override + { + return DBStatus::OK; + } + + DBStatus SetCloudDB(const std::shared_ptr &cloudDb) override + { + return DBStatus::OK; + } + + DBStatus SetCloudDbSchema(const DataBaseSchema &schema) override + { + return DBStatus::OK; + } + + DBStatus RegisterObserver(StoreObserver *observer) override + { + return DBStatus::OK; + } + + DBStatus UnRegisterObserver() override + { + return DBStatus::OK; + } + + DBStatus UnRegisterObserver(StoreObserver *observer) override + { + return DBStatus::OK; + } + + DBStatus SetIAssetLoader(const std::shared_ptr &loader) override + { + return DBStatus::OK; + } + + DBStatus Sync(const CloudSyncOption &option, const SyncProcessCallback &onProcess) override + { + return DBStatus::OK; + } + + DBStatus SetTrackerTable(const TrackerSchema &schema) override + { + if (schema.tableName == "WITH_INVENTORY_DATA") { + return DBStatus::WITH_INVENTORY_DATA; + } + if (schema.tableName == "test") { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } + + DBStatus ExecuteSql(const SqlCondition &condition, std::vector &records) override + { + if (condition.sql == "") { + return DBStatus::DB_ERROR; + } + + std::string sqls = "INSERT INTO test ( #flag, #float, #gid, #value) VALUES ( ?, ?, ?, ?)"; + std::string sqlIn = " UPDATE test SET setSql WHERE whereSql"; + std::string sql = "REPLACE INTO test ( #flag, #float, #gid, #value) VALUES ( ?, ?, ?, ?)"; + if (condition.sql == sqls || condition.sql == sqlIn || condition.sql == sql) { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } + + DBStatus SetReference(const std::vector &tableReferenceProperty) override + { + if (gTestResult) { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } + + DBStatus CleanTrackerData(const std::string &tableName, int64_t cursor) override + { + return DBStatus::OK; + } + + DBStatus Pragma(PragmaCmd cmd, PragmaData &pragmaData) override + { + return DBStatus::OK; + } + + DBStatus UpsertData(const std::string &tableName, const std::vector &records, + RecordStatus status = RecordStatus::WAIT_COMPENSATED_SYNC) override + { + return DBStatus::OK; + } + + DBStatus SetCloudSyncConfig(const CloudSyncConfig &config) override + { + return DBStatus::OK; + } + static bool gTestResult; + +protected: + DBStatus RemoveDeviceDataInner(const std::string &device, ClearMode mode) override + { + if (gTestResult) { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } + + DBStatus CreateDistributedTableInner(const std::string &tableName, TableSyncType type) override + { + if (tableName == "test") { + return DBStatus::DB_ERROR; + } + return DBStatus::OK; + } +}; +} // namespace DistributedDB +#endif \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa61b0cc4b968a2870c7c5be5b0201d6dd9297f7 --- /dev/null +++ b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define LOG_TAG "MockRelationalStoreManager" +#include + +#include "relational_store_delegate_mock.h" +#include "relational_store_manager.h" +namespace DistributedDB { +DBStatus RelationalStoreManager::OpenStore(const std::string &path, const std::string &storeId, + const RelationalStoreDelegate::Option &option, RelationalStoreDelegate *&delegate) +{ + delegate = new (std::nothrow) MockRelationalStoreDelegate(); + if (delegate == nullptr) { + return DB_ERROR; + } + delegate->CreateDistributedTable("naturalbase_rdb_test"); + delegate->CreateDistributedTable("naturalbase_rdb_name"); + if (storeId == "mock") { + return OK; + } + return DB_ERROR; +} + +DBStatus RelationalStoreManager::CloseStore(RelationalStoreDelegate *store) +{ + delete store; + store = nullptr; + return OK; +} +} // namespace DistributedDB \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/user_delegate_mock.cpp b/services/distributeddataservice/service/test/mock/user_delegate_mock.cpp index bc1d1353af1baa663fd793390719254226af2f78..d013c3c11a4346e70cd18cbfe76cc98a7b8c7684 100644 --- a/services/distributeddataservice/service/test/mock/user_delegate_mock.cpp +++ b/services/distributeddataservice/service/test/mock/user_delegate_mock.cpp @@ -91,7 +91,7 @@ bool UserDelegate::NotifyUserEvent(const UserDelegate::UserEvent &userEvent) void UserDelegate::LocalUserObserver::OnAccountChanged(const AccountEventInfo &eventInfo, int32_t timeout) { - return; + userDelegate_.NotifyUserEvent({}); } UserDelegate::LocalUserObserver::LocalUserObserver(UserDelegate &userDelegate) : userDelegate_(userDelegate) {} diff --git a/services/distributeddataservice/service/test/object_asset_loader_test.cpp b/services/distributeddataservice/service/test/object_asset_loader_test.cpp index 57aa68b6f3963c30a9dd1d9a877804a7fb99ee4e..c25e185cb9cac8f8cc2000f0d1c71384dde44027 100644 --- a/services/distributeddataservice/service/test/object_asset_loader_test.cpp +++ b/services/distributeddataservice/service/test/object_asset_loader_test.cpp @@ -20,6 +20,7 @@ #include #include "executor_pool.h" +#include "object_common.h" #include "snapshot/machine_status.h" using namespace testing::ext; @@ -206,4 +207,53 @@ HWTEST_F(ObjectAssetLoaderTest, UpdateDownloaded002, TestSize.Level0) EXPECT_EQ(success, false); EXPECT_EQ(hash, ""); } + +/** +* @tc.name: PushAsset001 +* @tc.desc: PushAsset test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectAssetLoaderTest, PushAsset001, TestSize.Level0) +{ + auto assetLoader = ObjectAssetLoader::GetInstance(); + ASSERT_NE(assetLoader, nullptr); + sptr assetObj = new AssetObj(); + assetObj->dstBundleName_ = bundleName_; + assetObj->srcBundleName_ = bundleName_; + assetObj->dstNetworkId_ = "1"; + assetObj->sessionId_ = "123"; + + sptr sendCallback = new ObjectAssetsSendListener(); + ASSERT_NE(sendCallback, nullptr); + int32_t ret = assetLoader->PushAsset(userId_, assetObj, sendCallback); + EXPECT_NE(ret, DistributedObject::OBJECT_SUCCESS); +} + +/** +* @tc.name: OnSendResult001 +* @tc.desc: OnSendResult test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectAssetLoaderTest, OnSendResult001, TestSize.Level1) +{ + sptr assetObj = nullptr; + + int32_t result = -1; + sptr sendCallback = new ObjectAssetsSendListener(); + int32_t ret = sendCallback->OnSendResult(assetObj, result); + EXPECT_EQ(ret, result); + + assetObj = new AssetObj(); + assetObj->dstBundleName_ = bundleName_; + assetObj->srcBundleName_ = bundleName_; + assetObj->dstNetworkId_ = "1"; + assetObj->sessionId_ = "123"; + + ret = sendCallback->OnSendResult(assetObj, result); + EXPECT_EQ(ret, result); + + result = 0; + ret = sendCallback->OnSendResult(assetObj, result); + EXPECT_EQ(ret, result); +} } // namespace OHOS::Test diff --git a/services/distributeddataservice/service/test/object_manager_test.cpp b/services/distributeddataservice/service/test/object_manager_test.cpp index 6f4a2c0a16b0d47fed7642bcfd8b6273bc1f53c9..4250b4c64b8b6b8c32f3102783047d34c415a954 100644 --- a/services/distributeddataservice/service/test/object_manager_test.cpp +++ b/services/distributeddataservice/service/test/object_manager_test.cpp @@ -20,13 +20,19 @@ #include #include +#include "bootstrap.h" +#include "device_manager_adapter_mock.h" #include "executor_pool.h" +#include "kvstore_meta_manager.h" #include "kv_store_nb_delegate_mock.h" #include "object_types.h" #include "snapshot/machine_status.h" using namespace testing::ext; using namespace OHOS::DistributedObject; +using namespace OHOS::DistributedData; +using namespace std; +using namespace testing; using AssetValue = OHOS::CommonType::AssetValue; using RestoreStatus = OHOS::DistributedObject::ObjectStoreManager::RestoreStatus; namespace OHOS::Test { @@ -35,6 +41,8 @@ class ObjectManagerTest : public testing::Test { public: void SetUp(); void TearDown(); + static void SetUpTestCase(void); + static void TearDownTestCase(void); protected: Asset asset_; @@ -52,6 +60,7 @@ protected: pid_t pid_ = 10; uint32_t tokenId_ = 100; AssetValue assetValue_; + static inline std::shared_ptr devMgrAdapterMock = nullptr; }; void ObjectManagerTest::SetUp() @@ -91,6 +100,24 @@ void ObjectManagerTest::SetUp() assetBindInfo_ = AssetBindInfo; } +void ObjectManagerTest::SetUpTestCase(void) +{ + devMgrAdapterMock = make_shared(); + BDeviceManagerAdapter::deviceManagerAdapter = devMgrAdapterMock; + std::shared_ptr executors = std::make_shared(1, 0); + Bootstrap::GetInstance().LoadDirectory(); + Bootstrap::GetInstance().LoadCheckers(); + DistributedKv::KvStoreMetaManager::GetInstance().BindExecutor(executors); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaParameter(); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaListener(); +} + +void ObjectManagerTest::TearDownTestCase(void) +{ + BDeviceManagerAdapter::deviceManagerAdapter = nullptr; + devMgrAdapterMock = nullptr; +} + void ObjectManagerTest::TearDown() {} /** @@ -166,7 +193,7 @@ HWTEST_F(ObjectManagerTest, Clear001, TestSize.Level0) { auto manager = ObjectStoreManager::GetInstance(); auto result = manager->Clear(); - ASSERT_EQ(result, OHOS::DistributedObject::OBJECT_STORE_NOT_FOUND); + ASSERT_EQ(result, OHOS::DistributedObject::OBJECT_SUCCESS); } /** @@ -349,6 +376,7 @@ HWTEST_F(ObjectManagerTest, NotifyChange002, TestSize.Level0) data.insert_or_assign(assetPrefix + ObjectStore::MODIFY_TIME_SUFFIX, value); data.insert_or_assign(assetPrefix + ObjectStore::SIZE_SUFFIX, value); data.insert_or_assign("testkey", value); + EXPECT_CALL(*devMgrAdapterMock, IsSameAccount(_)).WillOnce(Return(true)); manager->NotifyChange(data); EXPECT_TRUE(manager->restoreStatus_.Contains(bundleName+sessionId)); auto [has, taskId] = manager->objectTimer_.Find(bundleName+sessionId); @@ -524,15 +552,22 @@ HWTEST_F(ObjectManagerTest, Close001, TestSize.Level0) HWTEST_F(ObjectManagerTest, SyncOnStore001, TestSize.Level0) { auto manager = ObjectStoreManager::GetInstance(); + manager->delegate_ = manager->OpenObjectKvStore(); std::function &results)> func; func = [](const std::map &results) { return results; }; std::string prefix = "ObjectManagerTest"; std::vector deviceList; - deviceList.push_back("local"); + // not local device & syncDevices empty deviceList.push_back("local1"); + EXPECT_CALL(*devMgrAdapterMock, IsSameAccount(_)).WillOnce(Return(true)); auto result = manager->SyncOnStore(prefix, deviceList, func); + ASSERT_NE(result, OBJECT_SUCCESS); + // local device + deviceList.push_back("local"); + EXPECT_CALL(*devMgrAdapterMock, IsSameAccount(_)).WillOnce(Return(true)); + result = manager->SyncOnStore(prefix, deviceList, func); ASSERT_EQ(result, OBJECT_SUCCESS); } @@ -683,6 +718,33 @@ HWTEST_F(ObjectManagerTest, ProcessSyncCallback001, TestSize.Level0) manager->ProcessSyncCallback(results, appId_, sessionId_, deviceId_); } +/** +* @tc.name: ProcessSyncCallback002 +* @tc.desc: ProcessSyncCallback test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, ProcessSyncCallback002, TestSize.Level0) +{ + std::string dataDir = "/data/app/el2/100/database"; + auto manager = ObjectStoreManager::GetInstance(); + std::map results; + + results.insert({"remote", 1}); // for testing + ASSERT_EQ(results.empty(), false); + ASSERT_EQ(results.find("local"), results.end()); + + manager->kvStoreDelegateManager_ = nullptr; + // open store failed -> success + manager->ProcessSyncCallback(results, appId_, sessionId_, deviceId_); + + // open store success -> success + manager->SetData(dataDir, userId_); + ASSERT_NE(manager->kvStoreDelegateManager_, nullptr); + manager->delegate_ = manager->OpenObjectKvStore(); + ASSERT_NE(manager->delegate_, nullptr); + manager->ProcessSyncCallback(results, appId_, sessionId_, deviceId_); +} + /** * @tc.name: IsAssetComplete001 * @tc.desc: IsAssetComplete test. @@ -830,7 +892,7 @@ HWTEST_F(ObjectManagerTest, RegisterAssetsLister001, TestSize.Level0) } /** -* @tc.name: RegisterAssetsLister001 +* @tc.name: PushAssets001 * @tc.desc: PushAssets test. * @tc.type: FUNC * @tc.require: @@ -849,6 +911,41 @@ HWTEST_F(ObjectManagerTest, PushAssets001, TestSize.Level0) ASSERT_EQ(result, DistributedObject::OBJECT_SUCCESS); } +/** +* @tc.name: PushAssets002 +* @tc.desc: PushAssets test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, PushAssets002, TestSize.Level0) +{ + auto manager = ObjectStoreManager::GetInstance(); + std::map> data; + std::vector value{0}; + std::string data0 = "[STRING]test"; + value.insert(value.end(), data0.begin(), data0.end()); + + std::string prefix = "bundleName_sessionId_source_target_timestamp"; + std::string dataKey = prefix + "_p_data"; + std::string assetPrefix = prefix + "_p_asset0"; + std::string fieldsPrefix = "p_"; + std::string deviceIdKey = "__deviceId"; + + data.insert({assetPrefix + ObjectStore::NAME_SUFFIX, value}); + data.insert({assetPrefix + ObjectStore::URI_SUFFIX, value}); + data.insert({assetPrefix + ObjectStore::MODIFY_TIME_SUFFIX, value}); + data.insert({assetPrefix + ObjectStore::SIZE_SUFFIX, value}); + data.insert({fieldsPrefix + deviceIdKey, value}); + + manager->objectAssetsSendListener_ = nullptr; + int32_t ret = manager->PushAssets(appId_, appId_, sessionId_, data, deviceId_); + EXPECT_NE(ret, DistributedObject::OBJECT_SUCCESS); + + manager->objectAssetsSendListener_ = new ObjectAssetsSendListener(); + ASSERT_NE(manager->objectAssetsSendListener_, nullptr); + ret = manager->PushAssets(appId_, appId_, sessionId_, data, deviceId_); + EXPECT_NE(ret, DistributedObject::OBJECT_SUCCESS); +} + /** * @tc.name: AddNotifier001 * @tc.desc: AddNotifie and DeleteNotifier test. @@ -897,4 +994,117 @@ HWTEST_F(ObjectManagerTest, BindAsset001, TestSize.Level0) auto result = manager->BindAsset(tokenId, bundleName, sessionId_, assetValue_, assetBindInfo_); ASSERT_EQ(result, DistributedObject::OBJECT_DBSTATUS_ERROR); } + +/** +* @tc.name: OnFinished001 +* @tc.desc: OnFinished test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, OnFinished001, TestSize.Level1) +{ + std::string srcNetworkId = "srcNetworkId"; + sptr assetObj = nullptr; + int32_t result = 100; + ObjectAssetsRecvListener listener; + int32_t ret = listener.OnFinished(srcNetworkId, assetObj, result); + EXPECT_NE(ret, DistributedObject::OBJECT_SUCCESS); + + sptr assetObj_1 = new AssetObj(); + assetObj_1->dstBundleName_ = bundleName_; + assetObj_1->srcBundleName_ = bundleName_; + assetObj_1->dstNetworkId_ = "1"; + assetObj_1->sessionId_ = "123"; + ret = listener.OnFinished(srcNetworkId, assetObj_1, result); + EXPECT_EQ(ret, DistributedObject::OBJECT_SUCCESS); +} + +/** +* @tc.name: GetObjectData001 +* @tc.desc: GetObjectData test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, GetObjectData001, TestSize.Level1) +{ + auto manager = ObjectStoreManager::GetInstance(); + + std::string bundleName = bundleName_; + std::string sessionId = sessionId_; + std::string source = "sourceDeviceId"; + std::string target = "targetDeviceId"; + std::string timestamp = "1234567890"; + ObjectStoreManager::SaveInfo saveInfo(bundleName, sessionId, source, target, timestamp); + std::string prefix = saveInfo.ToPropertyPrefix(); + EXPECT_FALSE(prefix.empty()); + + // p_name not asset key + std::string p_name = "p_namejpg"; + std::string key = bundleName + "_" + sessionId + "_" + source + "_" + target + "_" + timestamp + "_" + p_name; + std::map> changedData = {{ key, data_ }}; + bool hasAsset = false; + auto ret = manager->GetObjectData(changedData, saveInfo, hasAsset); + EXPECT_FALSE(ret.empty()); + EXPECT_FALSE(hasAsset); +} + +/** +* @tc.name: GetObjectData002 +* @tc.desc: GetObjectData test. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, GetObjectData002, TestSize.Level1) +{ + auto manager = ObjectStoreManager::GetInstance(); + + std::string bundleName = ""; + std::string sessionId = ""; + std::string source = ""; + std::string target = ""; + std::string timestamp = ""; + ObjectStoreManager::SaveInfo saveInfo(bundleName, sessionId, source, target, timestamp); + std::string prefix = saveInfo.ToPropertyPrefix(); + EXPECT_TRUE(prefix.empty()); + + // saveInfo.bundleName, sourceDeviceId, targetDeviceId empty + saveInfo.sessionId = sessionId_; + saveInfo.timestamp = "1234567890"; + + bundleName = bundleName_; + sessionId = sessionId_; + source = "sourceDeviceId"; + target = "targetDeviceId"; + timestamp = "1234567890"; + std::string p_name = "p_name.jpg"; + std::string key = bundleName + "_" + sessionId + "_" + source + "_" + target + "_" + timestamp + "_" + p_name; + std::map> changedData = {{ key, data_ }}; + bool hasAsset = false; + auto ret = manager->GetObjectData(changedData, saveInfo, hasAsset); + EXPECT_FALSE(ret.empty()); + EXPECT_EQ(saveInfo.bundleName, bundleName); + EXPECT_TRUE(hasAsset); + + // only targetDeviceId empty + saveInfo.bundleName = "test_bundleName"; + saveInfo.sourceDeviceId = "test_source"; + // p_name not asset key + p_name = "p_namejpg"; + std::string key_1 = bundleName + "_" + sessionId + "_" + source + "_" + target + "_" + timestamp + "_" + p_name; + std::map> changedData_1 = {{ key_1, data_ }}; + hasAsset = false; + ret = manager->GetObjectData(changedData_1, saveInfo, hasAsset); + EXPECT_FALSE(ret.empty()); + EXPECT_NE(saveInfo.bundleName, bundleName); + EXPECT_FALSE(hasAsset); +} + +/** +* @tc.name: InitUserMeta001 +* @tc.desc: test clear old user meta. +* @tc.type: FUNC +*/ +HWTEST_F(ObjectManagerTest, InitUserMeta001, TestSize.Level1) +{ + auto manager = ObjectStoreManager::GetInstance(); + auto status = manager->InitUserMeta(); + ASSERT_EQ(status, DistributedObject::OBJECT_SUCCESS); +} } // namespace OHOS::Test diff --git a/services/distributeddataservice/service/test/object_service_impl_test.cpp b/services/distributeddataservice/service/test/object_service_impl_test.cpp index 7497b04dd06f40385820f7d6c520d38b36348134..4a0a0b2f3cd273cd88fbc0901649e59f781ea3d2 100644 --- a/services/distributeddataservice/service/test/object_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/object_service_impl_test.cpp @@ -94,8 +94,6 @@ HWTEST_F(ObjectServiceImplTest, OnAssetChanged001, TestSize.Level1) // bundleName not equal tokenId auto ret = objectServiceImpl->OnAssetChanged(bundleName_, sessionId_, deviceId_, asset_); EXPECT_EQ(ret, OBJECT_PERMISSION_DENIED); - ret = objectServiceImpl->OnAssetChanged(bundleName, sessionId_, deviceId_, asset_); - EXPECT_NE(ret, OBJECT_SUCCESS); } /** @@ -115,8 +113,6 @@ HWTEST_F(ObjectServiceImplTest, BindAssetStore001, TestSize.Level1) // bundleName not equal tokenId auto ret = objectServiceImpl->BindAssetStore(bundleName_, sessionId_, asset_, assetBindInfo_); EXPECT_EQ(ret, OBJECT_PERMISSION_DENIED); - ret = objectServiceImpl->BindAssetStore(bundleName, sessionId_, asset_, assetBindInfo_); - EXPECT_NE(ret, OBJECT_SUCCESS); } /** @@ -137,4 +133,22 @@ HWTEST_F(ObjectServiceImplTest, DeleteSnapshot001, TestSize.Level1) auto ret = objectServiceImpl->DeleteSnapshot(bundleName_, sessionId_); EXPECT_EQ(ret, OBJECT_PERMISSION_DENIED); } + +/** + * @tc.name: ResolveAutoLaunch001 + * @tc.desc: ResolveAutoLaunch test. + * @tc.type: FUNC + */ +HWTEST_F(ObjectServiceImplTest, ResolveAutoLaunch001, TestSize.Level1) +{ + DistributedDB::AutoLaunchParam param { + .userId = userId_, + .appId = appId_, + .storeId = "storeId", + }; + std::string identifier = "identifier"; + std::shared_ptr objectServiceImpl = std::make_shared(); + int32_t ret = objectServiceImpl->ResolveAutoLaunch(identifier, param); + EXPECT_EQ(ret, OBJECT_SUCCESS); +} } \ No newline at end of file diff --git a/services/distributeddataservice/service/test/ohos_test/BUILD.gn b/services/distributeddataservice/service/test/ohos_test/BUILD.gn index d0140c7d02939e80f9f4bb2e475752787634a3d1..ed9f42f06bcf08c2ed4e3d387a45dd0c9b7b9d9a 100644 --- a/services/distributeddataservice/service/test/ohos_test/BUILD.gn +++ b/services/distributeddataservice/service/test/ohos_test/BUILD.gn @@ -17,6 +17,5 @@ ohos_copy("copy_ohos_test") { subsystem_name = "distributeddatamgr" part_name = "datamgr_service" sources = [ "./ohos_test.xml" ] - outputs = - [ "$root_out_dir/tests/unittest/datamgr_service/resource/ohos_test.xml" ] + outputs = [ "$root_out_dir/tests/unittest/datamgr_service/datamgr_service/resource/ohos_test.xml" ] } diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index de1ef193c479ea0b586442e8fbc690b6a6ee6461..24e4dfab64a3b38cc3327102ee1adce563bb553d 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -21,6 +21,9 @@ #include "bootstrap.h" #include "cloud/schema_meta.h" +#include "error/general_error.h" +#include "errors.h" +#include "eventcenter/event_center.h" #include "gtest/gtest.h" #include "log_print.h" #include "metadata/meta_data_manager.h" @@ -29,7 +32,11 @@ #include "metadata/store_meta_data_local.h" #include "mock/general_watcher_mock.h" #include "rdb_query.h" +#include "relational_store_delegate_mock.h" #include "store/general_store.h" +#include "store/general_value.h" +#include "store_observer.h" +#include "store_types.h" #include "types.h" using namespace testing::ext; @@ -37,14 +44,15 @@ using namespace DistributedDB; using namespace OHOS::DistributedData; using namespace OHOS::DistributedRdb; using DBStatus = DistributedDB::DBStatus; -using StoreMetaData = OHOS::DistributedData::StoreMetaData; RdbGeneralStore::Values g_RdbValues = { { "0000000" }, { true }, { int64_t(100) }, { double(100) }, { int64_t(1) }, { Bytes({ 1, 2, 3, 4 }) } }; RdbGeneralStore::VBucket g_RdbVBucket = { { "#gid", { "0000000" } }, { "#flag", { true } }, { "#value", { int64_t(100) } }, { "#float", { double(100) } } }; -bool g_testResult = false; +bool MockRelationalStoreDelegate::gTestResult = false; namespace OHOS::Test { namespace DistributedRDBTest { +using StoreMetaData = OHOS::DistributedData::StoreMetaData; +using namespace OHOS::DistributedRdb; static constexpr uint32_t PRINT_ERROR_CNT = 150; static constexpr const char *BUNDLE_NAME = "test_rdb_general_store"; static constexpr const char *STORE_NAME = "test_service_rdb"; @@ -56,15 +64,18 @@ public: { Bootstrap::GetInstance().LoadDirectory(); InitMetaData(); + store = std::make_shared(metaData_); + ASSERT_NE(store, nullptr); }; void TearDown() { - g_testResult = false; + MockRelationalStoreDelegate::gTestResult = false; }; protected: void InitMetaData(); StoreMetaData metaData_; + std::shared_ptr store; }; void RdbGeneralStoreTest::InitMetaData() @@ -79,158 +90,9 @@ void RdbGeneralStoreTest::InitMetaData() metaData_.storeId = STORE_NAME; metaData_.dataDir = "/data/service/el1/public/database/" + std::string(BUNDLE_NAME) + "/rdb"; metaData_.securityLevel = DistributedKv::SecurityLevel::S2; + metaData_.isSearchable = true; } -class MockRelationalStoreDelegate : public DistributedDB::RelationalStoreDelegate { -public: - ~MockRelationalStoreDelegate() = default; - - DBStatus Sync(const std::vector &devices, DistributedDB::SyncMode mode, const Query &query, - const SyncStatusCallback &onComplete, bool wait) override - { - return DBStatus::OK; - } - - int32_t GetCloudSyncTaskCount() override - { - static int32_t count = 0; - count = (count + 1) % 2; // The result of count + 1 is the remainder of 2. - return count; - } - - DBStatus RemoveDeviceData(const std::string &device, const std::string &tableName) override - { - return DBStatus::OK; - } - - DBStatus RemoteQuery(const std::string &device, const RemoteCondition &condition, uint64_t timeout, - std::shared_ptr &result) override - { - if (device == "test") { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } - - DBStatus RemoveDeviceData() override - { - return DBStatus::OK; - } - - DBStatus Sync(const std::vector &devices, DistributedDB::SyncMode mode, const Query &query, - const SyncProcessCallback &onProcess, int64_t waitTime) override - { - return DBStatus::OK; - } - - DBStatus SetCloudDB(const std::shared_ptr &cloudDb) override - { - return DBStatus::OK; - } - - DBStatus SetCloudDbSchema(const DataBaseSchema &schema) override - { - return DBStatus::OK; - } - - DBStatus RegisterObserver(StoreObserver *observer) override - { - return DBStatus::OK; - } - - DBStatus UnRegisterObserver() override - { - return DBStatus::OK; - } - - DBStatus UnRegisterObserver(StoreObserver *observer) override - { - return DBStatus::OK; - } - - DBStatus SetIAssetLoader(const std::shared_ptr &loader) override - { - return DBStatus::OK; - } - - DBStatus Sync(const CloudSyncOption &option, const SyncProcessCallback &onProcess) override - { - return DBStatus::OK; - } - - DBStatus SetTrackerTable(const TrackerSchema &schema) override - { - if (schema.tableName == "WITH_INVENTORY_DATA") { - return DBStatus::WITH_INVENTORY_DATA; - } - if (schema.tableName == "test") { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } - - DBStatus ExecuteSql(const SqlCondition &condition, std::vector &records) override - { - if (condition.sql == "") { - return DBStatus::DB_ERROR; - } - - std::string sqls = "INSERT INTO test ( #flag, #float, #gid, #value) VALUES ( ?, ?, ?, ?)"; - std::string sqlIn = " UPDATE test SET setSql WHERE whereSql"; - std::string sql = "REPLACE INTO test ( #flag, #float, #gid, #value) VALUES ( ?, ?, ?, ?)"; - if (condition.sql == sqls || condition.sql == sqlIn || condition.sql == sql) { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } - - DBStatus SetReference(const std::vector &tableReferenceProperty) override - { - if (g_testResult) { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } - - DBStatus CleanTrackerData(const std::string &tableName, int64_t cursor) override - { - return DBStatus::OK; - } - - DBStatus Pragma(PragmaCmd cmd, PragmaData &pragmaData) override - { - return DBStatus::OK; - } - - DBStatus UpsertData(const std::string &tableName, const std::vector &records, - RecordStatus status = RecordStatus::WAIT_COMPENSATED_SYNC) override - { - return DBStatus::OK; - } - - DBStatus SetCloudSyncConfig(const CloudSyncConfig &config) override - { - return DBStatus::OK; - } - -protected: - DBStatus RemoveDeviceDataInner(const std::string &device, ClearMode mode) override - { - if (g_testResult) { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } - - DBStatus CreateDistributedTableInner(const std::string &tableName, TableSyncType type) override - { - if (tableName == "test") { - return DBStatus::DB_ERROR; - } - return DBStatus::OK; - } -}; - class MockStoreChangedData : public DistributedDB::StoreChangedData { public: std::string GetDataChangeDevice() const override @@ -248,13 +110,9 @@ public: * @tc.name: BindSnapshots001 * @tc.desc: RdbGeneralStore BindSnapshots test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, BindSnapshots001, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); BindAssets bindAssets; auto result = store->BindSnapshots(bindAssets.bindAssets); EXPECT_EQ(result, GeneralError::E_OK); @@ -264,15 +122,13 @@ HWTEST_F(RdbGeneralStoreTest, BindSnapshots001, TestSize.Level1) * @tc.name: BindSnapshots002 * @tc.desc: RdbGeneralStore BindSnapshots nullptr test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, BindSnapshots002, TestSize.Level1) { DistributedData::StoreMetaData meta; meta = metaData_; meta.isEncrypt = true; - auto store = new (std::nothrow) RdbGeneralStore(meta); + auto store = std::make_shared(meta); ASSERT_NE(store, nullptr); store->snapshots_.bindAssets = nullptr; BindAssets bindAssets; @@ -284,13 +140,9 @@ HWTEST_F(RdbGeneralStoreTest, BindSnapshots002, TestSize.Level1) * @tc.name: Bind001 * @tc.desc: RdbGeneralStore Bind bindInfo test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Bind001, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); DistributedData::Database database; GeneralStore::CloudConfig config; std::map bindInfos; @@ -330,16 +182,11 @@ HWTEST_F(RdbGeneralStoreTest, Bind001, TestSize.Level1) * @tc.name: Bind002 * @tc.desc: RdbGeneralStore Bind delegate_ is nullptr test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Bind002, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); DistributedData::Database database; std::map bindInfos; - std::shared_ptr db = std::make_shared(); std::shared_ptr loader = std::make_shared(); GeneralStore::BindInfo bindInfo(db, loader); @@ -359,13 +206,9 @@ HWTEST_F(RdbGeneralStoreTest, Bind002, TestSize.Level1) * @tc.name: Bind003 * @tc.desc: RdbGeneralStore Bind delegate_ test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Bind003, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); DistributedData::Database database; std::map bindInfos; @@ -374,8 +217,8 @@ HWTEST_F(RdbGeneralStoreTest, Bind003, TestSize.Level1) GeneralStore::BindInfo bindInfo(db, loader); uint32_t key = 1; bindInfos[key] = bindInfo; - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); GeneralStore::CloudConfig config; auto result = store->Bind(database, bindInfos, config); EXPECT_NE(store->delegate_, nullptr); @@ -386,21 +229,16 @@ HWTEST_F(RdbGeneralStoreTest, Bind003, TestSize.Level1) * @tc.name: Close * @tc.desc: RdbGeneralStore Close and IsBound function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Close, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); - auto result = store->IsBound(std::stoi(metaData_.user)); + auto result = store->IsBound(std::atoi(metaData_.user.c_str())); EXPECT_EQ(result, false); EXPECT_EQ(store->delegate_, nullptr); auto ret = store->Close(); EXPECT_EQ(ret, GeneralError::E_OK); - - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); ret = store->Close(); EXPECT_EQ(ret, GeneralError::E_BUSY); } @@ -409,7 +247,6 @@ HWTEST_F(RdbGeneralStoreTest, Close, TestSize.Level1) * @tc.name: Close * @tc.desc: RdbGeneralStore Close test * @tc.type: FUNC -* @tc.require: * @tc.author: shaoyuanzhao */ HWTEST_F(RdbGeneralStoreTest, BusyClose, TestSize.Level1) @@ -432,21 +269,16 @@ HWTEST_F(RdbGeneralStoreTest, BusyClose, TestSize.Level1) * @tc.name: Execute * @tc.desc: RdbGeneralStore Execute function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Execute, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; EXPECT_EQ(store->delegate_, nullptr); auto result = store->Execute(table, sql); EXPECT_EQ(result, GeneralError::E_ERROR); - - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->Execute(table, sql); EXPECT_EQ(result, GeneralError::E_OK); @@ -459,13 +291,9 @@ HWTEST_F(RdbGeneralStoreTest, Execute, TestSize.Level1) * @tc.name: SqlConcatenate * @tc.desc: RdbGeneralStore SqlConcatenate function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, SqlConcatenate, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); DistributedData::VBucket value; std::string strColumnSql = "strColumnSql"; std::string strRowValueSql = "strRowValueSql"; @@ -485,13 +313,9 @@ HWTEST_F(RdbGeneralStoreTest, SqlConcatenate, TestSize.Level1) * @tc.name: Insert001 * @tc.desc: RdbGeneralStore Insert error test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Insert001, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); DistributedData::VBuckets values; EXPECT_EQ(values.size(), 0); std::string table = "table"; @@ -519,23 +343,14 @@ HWTEST_F(RdbGeneralStoreTest, Insert001, TestSize.Level1) * @tc.name: Insert002 * @tc.desc: RdbGeneralStore Insert function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Insert002, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; DistributedData::VBuckets extends = { { g_RdbVBucket } }; auto result = store->Insert(table, std::move(extends)); EXPECT_EQ(result, GeneralError::E_ERROR); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; - result = store->Insert(table, std::move(extends)); - EXPECT_EQ(result, GeneralError::E_OK); - std::string test = "test"; result = store->Insert(test, std::move(extends)); EXPECT_EQ(result, GeneralError::E_ERROR); @@ -547,19 +362,19 @@ HWTEST_F(RdbGeneralStoreTest, Insert002, TestSize.Level1) result = store->Insert(test, std::move(extends)); EXPECT_EQ(result, GeneralError::E_ERROR); } + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); + result = store->Insert(table, std::move(extends)); + EXPECT_EQ(result, GeneralError::E_OK); } /** * @tc.name: Update * @tc.desc: RdbGeneralStore Update function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Update, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; std::string setSql = "setSql"; RdbGeneralStore::Values values; @@ -582,9 +397,8 @@ HWTEST_F(RdbGeneralStoreTest, Update, TestSize.Level1) result = store->Update(table, setSql, std::move(g_RdbValues), whereSql, std::move(g_RdbValues)); EXPECT_EQ(result, GeneralError::E_ERROR); - - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->Update(table, setSql, std::move(g_RdbValues), whereSql, std::move(g_RdbValues)); EXPECT_EQ(result, GeneralError::E_OK); @@ -596,13 +410,9 @@ HWTEST_F(RdbGeneralStoreTest, Update, TestSize.Level1) * @tc.name: Replace * @tc.desc: RdbGeneralStore Replace function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Replace, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; RdbGeneralStore::VBucket values; auto result = store->Replace("", std::move(g_RdbVBucket)); @@ -613,9 +423,8 @@ HWTEST_F(RdbGeneralStoreTest, Replace, TestSize.Level1) result = store->Replace(table, std::move(g_RdbVBucket)); EXPECT_EQ(result, GeneralError::E_ERROR); - - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->Replace(table, std::move(g_RdbVBucket)); EXPECT_EQ(result, GeneralError::E_OK); @@ -627,13 +436,9 @@ HWTEST_F(RdbGeneralStoreTest, Replace, TestSize.Level1) * @tc.name: Delete * @tc.desc: RdbGeneralStore Delete function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Delete, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; auto result = store->Delete(table, sql, std::move(g_RdbValues)); @@ -644,21 +449,16 @@ HWTEST_F(RdbGeneralStoreTest, Delete, TestSize.Level1) * @tc.name: Query001 * @tc.desc: RdbGeneralStore Query function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Query001, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; auto [err1, result1] = store->Query(table, sql, std::move(g_RdbValues)); EXPECT_EQ(err1, GeneralError::E_ALREADY_CLOSED); EXPECT_EQ(result1, nullptr); - - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); auto [err2, result2] = store->Query(table, sql, std::move(g_RdbValues)); EXPECT_EQ(err2, GeneralError::E_OK); EXPECT_NE(result2, nullptr); @@ -668,13 +468,9 @@ HWTEST_F(RdbGeneralStoreTest, Query001, TestSize.Level1) * @tc.name: Query002 * @tc.desc: RdbGeneralStore Query function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Query002, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string table = "table"; std::string sql = "sql"; MockQuery query; @@ -688,24 +484,65 @@ HWTEST_F(RdbGeneralStoreTest, Query002, TestSize.Level1) EXPECT_EQ(result2, nullptr); } +/** + * @tc.name: Query003 + * @tc.desc: it is not a remote query return E_ERROR. + * @tc.type: FUNC + */ +HWTEST_F(RdbGeneralStoreTest, Query003, TestSize.Level1) +{ + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); + ASSERT_NE(store, nullptr); + + MockQuery query; + const std::string devices = "device1"; + const std::string sql; + Values args; + query.lastResult = true; + std::string table = "test_table"; + auto [err, cursor] = store->Query(table, query); + EXPECT_EQ(err, GeneralError::E_ERROR); +} + +/** + * @tc.name: Query004 + * @tc.desc: Test successful remote query + * @tc.type: FUNC + */ +HWTEST_F(RdbGeneralStoreTest, Query004, TestSize.Level1) +{ + MockQuery query; + const std::string devices = "device1"; + const std::string sql; + Values args; + query.MakeRemoteQuery(devices, sql, std::move(args)); + query.lastResult = true; + + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); + + std::string table = "test_table"; + auto [err, cursor] = store->Query(table, query); + + EXPECT_EQ(err, GeneralError::E_OK); + EXPECT_NE(cursor, nullptr); +} + /** * @tc.name: MergeMigratedData * @tc.desc: RdbGeneralStore MergeMigratedData function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, MergeMigratedData, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string tableName = "tableName"; DistributedData::VBuckets extends = { { g_RdbVBucket } }; auto result = store->MergeMigratedData(tableName, std::move(extends)); EXPECT_EQ(result, GeneralError::E_ERROR); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->MergeMigratedData(tableName, std::move(extends)); EXPECT_EQ(result, GeneralError::E_OK); } @@ -714,13 +551,9 @@ HWTEST_F(RdbGeneralStoreTest, MergeMigratedData, TestSize.Level1) * @tc.name: Sync * @tc.desc: RdbGeneralStore Sync function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Sync, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); GeneralStore::Devices devices; MockQuery query; GeneralStore::DetailAsync async; @@ -728,42 +561,132 @@ HWTEST_F(RdbGeneralStoreTest, Sync, TestSize.Level1) auto result = store->Sync(devices, query, async, syncParam); EXPECT_EQ(result.first, GeneralError::E_ALREADY_CLOSED); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->Sync(devices, query, async, syncParam); EXPECT_EQ(result.first, GeneralError::E_OK); } +/** +* @tc.name: Sync +* @tc.desc: RdbGeneralStore Sync CLOUD_TIME_FIRST test +* @tc.type: FUNC +*/ +HWTEST_F(RdbGeneralStoreTest, Sync001, TestSize.Level1) +{ + GeneralStore::Devices devices; + MockQuery query; + GeneralStore::DetailAsync async; + SyncParam syncParam; + syncParam.mode = GeneralStore::CLOUD_TIME_FIRST; + + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); + auto [result1, result2] = store->Sync(devices, query, async, syncParam); + EXPECT_EQ(result1, GeneralError::E_OK); + syncParam.mode = GeneralStore::NEARBY_END; + std::tie(result1, result2) = store->Sync(devices, query, async, syncParam); + EXPECT_EQ(result1, GeneralError::E_ERROR); + syncParam.mode = GeneralStore::NEARBY_PULL_PUSH; + std::tie(result1, result2) = store->Sync(devices, query, async, syncParam); + EXPECT_EQ(result1, GeneralError::E_OK); +} + +/** +* @tc.name: Sync +* @tc.desc: RdbGeneralStore Sync DistributedTable test +* @tc.type: FUNC +*/ +HWTEST_F(RdbGeneralStoreTest, Sync002, TestSize.Level1) +{ + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); + ASSERT_NE(store, nullptr); + + GeneralStore::Devices devices; + RdbQuery query; + GeneralStore::DetailAsync async; + SyncParam syncParam; + auto [result1, result2] = store->Sync(devices, query, async, syncParam); + EXPECT_EQ(result1, GeneralError::E_OK); +} + /** * @tc.name: PreSharing * @tc.desc: RdbGeneralStore PreSharing function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, PreSharing, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); MockQuery query; auto [errCode, result] = store->PreSharing(query); EXPECT_NE(errCode, GeneralError::E_OK); EXPECT_EQ(result, nullptr); } +/** +* @tc.name: PreSharing +* @tc.desc: RdbGeneralStore PreSharing function test, return E_INVALID_ARGS. +* @tc.type: FUNC +*/ +HWTEST_F(RdbGeneralStoreTest, PreSharing001, TestSize.Level1) +{ + MockQuery query; + query.lastResult = true; + auto [errCode, result] = store->PreSharing(query); + EXPECT_EQ(errCode, GeneralError::E_INVALID_ARGS); + EXPECT_EQ(result, nullptr); +} + +/** +* @tc.name: PreSharing +* @tc.desc: RdbGeneralStore PreSharing function delegate is nullptr test. +* @tc.type: FUNC +*/ +HWTEST_F(RdbGeneralStoreTest, PreSharing002, TestSize.Level1) +{ + MockQuery query; + DistributedRdb::PredicatesMemo predicates; + predicates.devices_ = { "device1" }; + predicates.tables_ = { "tables1" }; + query.lastResult = true; + query.MakeQuery(predicates); + auto [errCode, result] = store->PreSharing(query); + EXPECT_EQ(errCode, GeneralError::E_ALREADY_CLOSED); + EXPECT_EQ(result, nullptr); +} + +/** +* @tc.name: PreSharing +* @tc.desc: RdbGeneralStore PreSharing function E_CLOUD_DISABLED test. +* @tc.type: FUNC +*/ +HWTEST_F(RdbGeneralStoreTest, PreSharing003, TestSize.Level1) +{ + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); + ASSERT_NE(store, nullptr); + MockQuery query; + DistributedRdb::PredicatesMemo predicates; + predicates.devices_ = { "device1" }; + predicates.tables_ = { "tables1" }; + query.lastResult = true; + query.MakeQuery(predicates); + auto [errCode, result] = store->PreSharing(query); + EXPECT_EQ(errCode, GeneralError::E_CLOUD_DISABLED); + ASSERT_EQ(result, nullptr); +} + /** * @tc.name: ExtractExtend * @tc.desc: RdbGeneralStore ExtractExtend function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, ExtractExtend, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); RdbGeneralStore::VBucket extend = { { "#gid", { "0000000" } }, { "#flag", { true } }, - { "#value", { int64_t(100) } }, { "#float", { double(100) } }, { "#cloud_gid", { "cloud_gid" } } }; + { "#value", { int64_t(100) } }, { "#float", { double(100) } }, { "#cloud_gid", { "cloud_gid" } }, + { "cloud_gid", { "" } } }; DistributedData::VBuckets extends = { { extend } }; auto result = store->ExtractExtend(extends); EXPECT_EQ(result.size(), extends.size()); @@ -776,13 +699,9 @@ HWTEST_F(RdbGeneralStoreTest, ExtractExtend, TestSize.Level1) * @tc.name: Clean * @tc.desc: RdbGeneralStore Clean function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string tableName = "tableName"; std::vector devices = { "device1", "device2" }; auto result = store->Clean(devices, -1, tableName); @@ -792,8 +711,8 @@ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) result = store->Clean(devices, GeneralStore::CLOUD_INFO, tableName); EXPECT_EQ(result, GeneralError::E_ALREADY_CLOSED); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->Clean(devices, GeneralStore::CLOUD_INFO, tableName); EXPECT_EQ(result, GeneralError::E_OK); result = store->Clean(devices, GeneralStore::CLOUD_DATA, tableName); @@ -802,7 +721,7 @@ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) result = store->Clean(devices1, GeneralStore::NEARBY_DATA, tableName); EXPECT_EQ(result, GeneralError::E_OK); - g_testResult = true; + MockRelationalStoreDelegate::gTestResult = true; result = store->Clean(devices, GeneralStore::CLOUD_INFO, tableName); EXPECT_EQ(result, GeneralError::E_ERROR); result = store->Clean(devices, GeneralStore::CLOUD_DATA, tableName); @@ -817,13 +736,9 @@ HWTEST_F(RdbGeneralStoreTest, Clean, TestSize.Level1) * @tc.name: Watch * @tc.desc: RdbGeneralStore Watch and Unwatch function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Watch, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); MockGeneralWatcher watcher; auto result = store->Watch(GeneralWatcher::Origin::ORIGIN_CLOUD, watcher); EXPECT_EQ(result, GeneralError::E_INVALID_ARGS); @@ -845,13 +760,9 @@ HWTEST_F(RdbGeneralStoreTest, Watch, TestSize.Level1) * @tc.name: OnChange * @tc.desc: RdbGeneralStore OnChange function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, OnChange, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); MockGeneralWatcher watcher; MockStoreChangedData data; DistributedDB::ChangedData changedData; @@ -865,12 +776,54 @@ HWTEST_F(RdbGeneralStoreTest, OnChange, TestSize.Level1) EXPECT_EQ(result, GeneralError::E_OK); } +/** +* @tc.name: OnChange001 +* @tc.desc: RdbGeneralStore OnChange function test +* @tc.type: FUNC +*/ +HWTEST_F(RdbGeneralStoreTest, OnChange001, TestSize.Level1) +{ + MockGeneralWatcher watcher; + MockStoreChangedData data; + DistributedDB::ChangedData changedData; + changedData.primaryData[0] = { { std::monostate{}, 42, 3.14, "hello", true }, + { Bytes{ 1, 2, 3, 4 }, + DistributedDB::Asset{ 1, "zhangsan", "123", "/data/test", "file://xxx", "123", "100", "100", "999", + static_cast(AssetOpType::NO_CHANGE), static_cast(AssetStatus::NORMAL), 0 }, + Bytes{ 5, 6, 7, 8 } }, + { int64_t(-123), 2.718, 100, 0.001 } }; + changedData.primaryData[1] = { { std::monostate{}, 42, 3.14, "hello", true }, + { Bytes{ 1, 2, 3, 4 }, + DistributedDB::Asset{ 1, "zhangsan", "123", "/data/test", "file://xxx", "123", "100", "100", "999", + static_cast(AssetOpType::NO_CHANGE), static_cast(AssetStatus::NORMAL), 0 }, + Bytes{ 5, 6, 7, 8 } }, + { int64_t(-123), 2.718, 100, 0.001 } }; + changedData.primaryData[2] = { { "DELETE#ALL_CLOUDDATA", std::monostate{}, 42, 3.14, "hello", true }, + { Bytes{ 1, 2, 3, 4 }, + DistributedDB::Asset{ 1, "zhangsan", "123", "/data/test", "file://xxx", "123", "100", "100", "999", + static_cast(AssetOpType::NO_CHANGE), static_cast(AssetStatus::NORMAL), 0 }, + Bytes{ 5, 6, 7, 8 } }, + { int64_t(-123), 2.718, 100, 0.001 } }; + changedData.field = { "name", "age" }; + changedData.tableName = "test"; + DistributedDB::ChangedData changedDataTmp; + changedDataTmp = changedData; + auto result = store->Watch(GeneralWatcher::Origin::ORIGIN_ALL, watcher); + EXPECT_EQ(result, GeneralError::E_OK); + store->observer_.OnChange(data); + store->observer_.OnChange(DistributedDB::Origin::ORIGIN_CLOUD, "originalId", std::move(changedData)); + EXPECT_EQ(watcher.primaryFields_[changedDataTmp.tableName], *(changedDataTmp.field.begin())); + store->observer_.OnChange(DistributedDB::Origin::ORIGIN_LOCAL, "originalId", std::move(changedDataTmp)); + ASSERT_NE(watcher.origin_.id.size(), 0); + EXPECT_EQ(watcher.origin_.id[0], "originalId"); + result = store->Unwatch(GeneralWatcher::Origin::ORIGIN_ALL, watcher); + EXPECT_EQ(result, GeneralError::E_OK); +} + /** * @tc.name: Release * @tc.desc: RdbGeneralStore Release and AddRef function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, Release, TestSize.Level1) { @@ -897,28 +850,27 @@ HWTEST_F(RdbGeneralStoreTest, Release, TestSize.Level1) * @tc.name: SetDistributedTables * @tc.desc: RdbGeneralStore SetDistributedTables function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::vector tables = { "table1", "table2" }; - int32_t type = 0; + int32_t type = DistributedTableType::DISTRIBUTED_DEVICE; std::vector references; auto result = store->SetDistributedTables(tables, type, references); EXPECT_EQ(result, GeneralError::E_ALREADY_CLOSED); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->SetDistributedTables(tables, type, references); EXPECT_EQ(result, GeneralError::E_OK); std::vector test = { "test" }; result = store->SetDistributedTables(test, type, references); EXPECT_EQ(result, GeneralError::E_ERROR); - g_testResult = true; + MockRelationalStoreDelegate::gTestResult = true; + result = store->SetDistributedTables(tables, type, references); + EXPECT_EQ(result, GeneralError::E_OK); + type = DistributedTableType::DISTRIBUTED_CLOUD; result = store->SetDistributedTables(tables, type, references); EXPECT_EQ(result, GeneralError::E_ERROR); } @@ -927,21 +879,17 @@ HWTEST_F(RdbGeneralStoreTest, SetDistributedTables, TestSize.Level1) * @tc.name: SetTrackerTable * @tc.desc: RdbGeneralStore SetTrackerTable function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, SetTrackerTable, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string tableName = "tableName"; std::set trackerColNames = { "col1", "col2" }; std::set extendColNames = { "extendColName1", "extendColName2" }; auto result = store->SetTrackerTable(tableName, trackerColNames, extendColNames); EXPECT_EQ(result, GeneralError::E_ALREADY_CLOSED); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); result = store->SetTrackerTable(tableName, trackerColNames, extendColNames); EXPECT_EQ(result, GeneralError::E_OK); result = store->SetTrackerTable("WITH_INVENTORY_DATA", trackerColNames, extendColNames); @@ -954,17 +902,13 @@ HWTEST_F(RdbGeneralStoreTest, SetTrackerTable, TestSize.Level1) * @tc.name: RemoteQuery * @tc.desc: RdbGeneralStore RemoteQuery function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, RemoteQuery, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string device = "device"; DistributedDB::RemoteCondition remoteCondition; - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); auto result = store->RemoteQuery("test", remoteCondition); EXPECT_EQ(result, nullptr); result = store->RemoteQuery(device, remoteCondition); @@ -975,13 +919,9 @@ HWTEST_F(RdbGeneralStoreTest, RemoteQuery, TestSize.Level1) * @tc.name: ConvertStatus * @tc.desc: RdbGeneralStore ConvertStatus function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, ConvertStatus, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); auto result = store->ConvertStatus(DBStatus::OK); EXPECT_EQ(result, GeneralError::E_OK); result = store->ConvertStatus(DBStatus::CLOUD_NETWORK_ERROR); @@ -1006,15 +946,12 @@ HWTEST_F(RdbGeneralStoreTest, ConvertStatus, TestSize.Level1) * @tc.name: QuerySql * @tc.desc: RdbGeneralStore QuerySql function test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, QuerySql, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); - MockRelationalStoreDelegate mockDelegate; - store->delegate_ = &mockDelegate; auto [err1, result1] = store->QuerySql("", std::move(g_RdbValues)); EXPECT_EQ(err1, GeneralError::E_ERROR); EXPECT_TRUE(result1.empty()); @@ -1028,13 +965,9 @@ HWTEST_F(RdbGeneralStoreTest, QuerySql, TestSize.Level1) * @tc.name: BuildSqlWhenCloumnEmpty * @tc.desc: test buildsql method when cloumn empty * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenCloumnEmpty, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string table = "mock_table"; std::string statement = "mock_statement"; std::vector columns; @@ -1048,13 +981,9 @@ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenCloumnEmpty, TestSize.Level1) * @tc.name: BuildSqlWhenParamValid * @tc.desc: test buildsql method when param valid * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenParamValid, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); std::string table = "mock_table"; std::string statement = "mock_statement"; std::vector columns; @@ -1071,13 +1000,9 @@ HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenParamValid, TestSize.Level1) * @tc.name: LockAndUnLockCloudDBTest * @tc.desc: lock and unlock cloudDB test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, LockAndUnLockCloudDBTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); auto result = store->LockCloudDB(); EXPECT_EQ(result.first, 1); EXPECT_EQ(result.second, 0); @@ -1089,13 +1014,9 @@ HWTEST_F(RdbGeneralStoreTest, LockAndUnLockCloudDBTest, TestSize.Level1) * @tc.name: InFinishedTest * @tc.desc: isFinished test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, InFinishedTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; bool isFinished = store->IsFinished(syncId); EXPECT_TRUE(isFinished); @@ -1105,13 +1026,9 @@ HWTEST_F(RdbGeneralStoreTest, InFinishedTest, TestSize.Level1) * @tc.name: GetRdbCloudTest * @tc.desc: getRdbCloud test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, GetRdbCloudTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); auto rdbCloud = store->GetRdbCloud(); EXPECT_EQ(rdbCloud, nullptr); } @@ -1120,13 +1037,9 @@ HWTEST_F(RdbGeneralStoreTest, GetRdbCloudTest, TestSize.Level1) * @tc.name: RegisterDetailProgressObserverTest * @tc.desc: RegisterDetailProgressObserver test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, RegisterDetailProgressObserverTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); DistributedData::GeneralStore::DetailAsync async; auto result = store->RegisterDetailProgressObserver(async); EXPECT_EQ(result, GeneralError::E_OK); @@ -1136,13 +1049,9 @@ HWTEST_F(RdbGeneralStoreTest, RegisterDetailProgressObserverTest, TestSize.Level * @tc.name: GetFinishTaskTest * @tc.desc: GetFinishTask test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, GetFinishTaskTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; auto result = store->GetFinishTask(syncId); ASSERT_NE(result, nullptr); @@ -1152,16 +1061,27 @@ HWTEST_F(RdbGeneralStoreTest, GetFinishTaskTest, TestSize.Level1) * @tc.name: GetCBTest * @tc.desc: GetCB test * @tc.type: FUNC -* @tc.require: -* @tc.author: SQL */ HWTEST_F(RdbGeneralStoreTest, GetCBTest, TestSize.Level1) { - auto store = new (std::nothrow) RdbGeneralStore(metaData_); - ASSERT_NE(store, nullptr); DistributedRdb::RdbGeneralStore::SyncId syncId = 1; auto result = store->GetCB(syncId); ASSERT_NE(result, nullptr); } + +/** +* @tc.name: UpdateDBStatus +* @tc.desc: UpdateDBStatus test +* @tc.type: FUNC +*/ +HWTEST_F(RdbGeneralStoreTest, UpdateDBStatus, TestSize.Level1) +{ + auto result = store->UpdateDBStatus(); + EXPECT_EQ(result, E_ALREADY_CLOSED); + metaData_.storeId = "mock"; + store = std::make_shared(metaData_); + result = store->UpdateDBStatus(); + EXPECT_EQ(result, E_OK); +} } // namespace DistributedRDBTest } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d6416dcbd743a486457412d7a17d3f2b8567725 --- /dev/null +++ b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp @@ -0,0 +1,1104 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "account/account_delegate.h" +#include "bootstrap.h" +#include "checker_mock.h" +#include "cloud/change_event.h" +#include "cloud/schema_meta.h" +#include "crypto_manager.h" +#include "device_manager_adapter.h" +#include "device_matrix.h" +#include "event_center.h" +#include "ipc_skeleton.h" +#include "metadata/capability_meta_data.h" +#include "metadata/meta_data_manager.h" +#include "metadata/store_meta_data.h" +#include "metadata/store_meta_data_local.h" +#include "mock/db_store_mock.h" +#include "rdb_service_impl.h" +#include "rdb_types.h" +#include "relational_store_manager.h" +#include "gtest/gtest.h" + +using namespace OHOS::DistributedRdb; +using namespace OHOS::DistributedData; +using namespace DistributedDB; +using namespace testing::ext; +using namespace testing; +using namespace std; +using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; + +namespace OHOS::Test { +namespace DistributedRDBTest { + +static constexpr const char *TEST_BUNDLE = "test_rdb_service_impl_bundleName"; +static constexpr const char *TEST_APPID = "test_rdb_service_impl_appid"; +static constexpr const char *TEST_STORE = "test_rdb_service_impl_store"; + +class RdbServiceImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + static void InitMetaData(); + void SetUp(); + void TearDown(); +protected: + static std::shared_ptr dbStoreMock_; + static StoreMetaData metaData_; + static CheckerMock checkerMock_; + static void InitMetaDataManager(); +}; + +std::shared_ptr RdbServiceImplTest::dbStoreMock_ = std::make_shared(); +StoreMetaData RdbServiceImplTest::metaData_; +CheckerMock RdbServiceImplTest::checkerMock_; + +void RdbServiceImplTest::InitMetaData() +{ + metaData_.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + metaData_.appId = TEST_APPID; + metaData_.bundleName = TEST_BUNDLE; + metaData_.tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + metaData_.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(metaData_.tokenId)); + metaData_.area = OHOS::DistributedKv::EL1; + metaData_.instanceId = 0; + metaData_.isAutoSync = true; + metaData_.storeType = DistributedRdb::RDB_DEVICE_COLLABORATION; + metaData_.storeId = TEST_STORE; +} + +void RdbServiceImplTest::InitMetaDataManager() +{ + MetaDataManager::GetInstance().Initialize(dbStoreMock_, nullptr, ""); + MetaDataManager::GetInstance().SetSyncer([](const auto &, auto) { + DeviceMatrix::GetInstance().OnChanged(DeviceMatrix::META_STORE_MASK); + }); +} + +void RdbServiceImplTest::SetUpTestCase() +{ + size_t max = 12; + size_t min = 5; + + auto dmExecutor = std::make_shared(max, min); + DeviceManagerAdapter::GetInstance().Init(dmExecutor); + InitMetaData(); + Bootstrap::GetInstance().LoadCheckers(); + CryptoManager::GetInstance().GenerateRootKey(); +} + +void RdbServiceImplTest::TearDownTestCase() +{ +} + +void RdbServiceImplTest::SetUp() +{ +} + +void RdbServiceImplTest::TearDown() +{ +} + +/** +* @tc.name: OnRemoteRequest001 +* @tc.desc: ResolveAutoLaunch LoadMeta Failed. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch001, TestSize.Level0) +{ + auto localId = DmAdapter::GetInstance().GetLocalDevice().uuid; + DistributedDB::AutoLaunchParam param; + RdbServiceImpl service; + + std::string identifier = "test_identifier"; + int32_t result = service.ResolveAutoLaunch(identifier, param); + EXPECT_EQ(result, false); +} + +/** +* @tc.name: ResolveAutoLaunch002 +* @tc.desc: ResolveAutoLaunch no meta. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch002, TestSize.Level0) +{ + InitMetaDataManager(); + auto localId = DmAdapter::GetInstance().GetLocalDevice().uuid; + DistributedDB::AutoLaunchParam param; + RdbServiceImpl service; + + std::string identifier = "test_identifier"; + int32_t result = service.ResolveAutoLaunch(identifier, param); + EXPECT_EQ(result, false); +} + +/** +* @tc.name: ResolveAutoLaunch003 +* @tc.desc: ResolveAutoLaunch has meta, identifier not match. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch003, TestSize.Level0) +{ + auto ret = MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false); + EXPECT_EQ(ret, true); + StoreMetaData meta; + meta.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + meta.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(meta.tokenId)); + meta.bundleName = TEST_BUNDLE; + meta.storeId = "ResolveAutoLaunch003"; + meta.instanceId = 0; + meta.appId = TEST_APPID; + meta.tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); + meta.area = OHOS::DistributedKv::EL1; + meta.isAutoSync = true; + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, false), true); + + DistributedDB::AutoLaunchParam param; + RdbServiceImpl service; + + std::string identifier = "test_identifier"; + int32_t result = service.ResolveAutoLaunch(identifier, param); + + EXPECT_EQ(result, false); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** +* @tc.name: ResolveAutoLaunch004 +* @tc.desc: ResolveAutoLaunch has meta, identifier match. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch004, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + DistributedDB::AutoLaunchParam param; + RdbServiceImpl service; + RelationalStoreManager userMgr(metaData_.appId, metaData_.user, metaData_.storeId); + auto identifier = userMgr.GetRelationalStoreIdentifier(metaData_.user, metaData_.appId, metaData_.storeId, true); + + int32_t result = service.ResolveAutoLaunch(identifier, param); + + EXPECT_EQ(result, true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** +* @tc.name: ResolveAutoLaunch005 +* @tc.desc: ResolveAutoLaunch has meta, identifier match, is encrypt. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch005, TestSize.Level0) +{ + auto meta = metaData_; + meta.isEncrypt = true; + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, false), true); + DistributedDB::AutoLaunchParam param; + RdbServiceImpl service; + RelationalStoreManager userMgr1(meta.appId, meta.user, meta.storeId); + auto identifier = userMgr1.GetRelationalStoreIdentifier(meta.user, meta.appId, meta.storeId, true); + + int32_t result = service.ResolveAutoLaunch(identifier, param); + + EXPECT_EQ(result, true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(meta.GetKey(), false), true); +} + +/** +* @tc.name: ResolveAutoLaunch006 +* @tc.desc: test ObtainDistributedTableName, uuid exist. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch006, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + RdbServiceImpl service; + auto deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + auto ret = service.ObtainDistributedTableName(deviceId, TEST_STORE); + EXPECT_GT(ret.length(), 0); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** +* @tc.name: ObtainDistributedTableName001 +* @tc.desc: test ObtainDistributedTableName, uuid invalid. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, ObtainDistributedTableName001, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + RdbServiceImpl service; + auto ret = service.ObtainDistributedTableName("invalid_device_id", TEST_STORE); + EXPECT_EQ(ret.length(), 0); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** +* @tc.name: TransferStringToHex001 +* @tc.desc: test TransferStringToHex, param empty. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, TransferStringToHex001, TestSize.Level0) +{ + RdbServiceImpl service; + auto ret = service.TransferStringToHex(""); + EXPECT_EQ(ret.length(), 0); +} + +/** +* @tc.name: GetCallbacks001 +* @tc.desc: test GetCallbacks. +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhaojh +*/ +HWTEST_F(RdbServiceImplTest, GetCallbacks001, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + RdbServiceImpl service; + auto ret = service.GetCallbacks(metaData_.tokenId, metaData_.storeId); + EXPECT_EQ(ret, nullptr); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** + * @tc.name: DoSync001 + * @tc.desc: Test DoSync when the store is null. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, DoSync001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + RdbService::Option option; + PredicatesMemo predicates; + AsyncDetail async; + + auto result = service.DoSync(param, option, predicates, async); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: DoSync002 + * @tc.desc: Test DoSync when meta sync is needed and succeeds. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, DoSync002, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.type_ = metaData_.storeType; + param.level_ = metaData_.securityLevel; + param.area_ = metaData_.area; + param.hapName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + param.isEncrypt_ = metaData_.isEncrypt; + param.isSearchable_ = metaData_.isSearchable; + param.haMode_ = metaData_.haMode; + param.asyncDownloadAsset_ = metaData_.asyncDownloadAsset; + + RdbService::Option option; + option.mode = DistributedData::GeneralStore::AUTO_SYNC_MODE; + option.seqNum = 1; + + PredicatesMemo predicates; + AsyncDetail async; + + auto result = service.DoSync(param, option, predicates, async); + EXPECT_EQ(result, RDB_ERROR); + + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** + * @tc.name: IsNeedMetaSync001 + * @tc.desc: Test IsNeedMetaSync when LoadMeta fails for CapMetaData. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, IsNeedMetaSync001, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + std::vector devices = {DmAdapter::GetInstance().ToUUID(metaData_.deviceId)}; + RdbServiceImpl service; + bool result = service.IsNeedMetaSync(metaData_, devices); + + EXPECT_EQ(result, true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** + * @tc.name: IsNeedMetaSync002 + * @tc.desc: Test IsNeedMetaSync when LoadMeta fails for StoreMetaData. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, IsNeedMetaSync002, TestSize.Level0) +{ + CapMetaData capMetaData; + auto capKey = CapMetaRow::GetKeyFor(metaData_.deviceId); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(std::string(capKey.begin(), capKey.end()), capMetaData), true); + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + std::vector devices = {DmAdapter::GetInstance().ToUUID(metaData_.deviceId)}; + RdbServiceImpl service; + bool result = service.IsNeedMetaSync(metaData_, devices); + + EXPECT_EQ(result, false); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** + * @tc.name: ProcessResult001 + * @tc.desc: Test ProcessResult when all results have DBStatus::OK. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, ProcessResult001, TestSize.Level0) +{ + RdbServiceImpl service; + std::map results = {{"device1", static_cast(DBStatus::OK)}, + {"device2", static_cast(DBStatus::OK)}}; + + auto result = service.ProcessResult(results); + + EXPECT_EQ(result.second.at("device1"), DBStatus::OK); + EXPECT_EQ(result.second.at("device2"), DBStatus::OK); +} + +/** + * @tc.name: ProcessResult002 + * @tc.desc: Test ProcessResult when some results have DBStatus::OK and others do not. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, ProcessResult002, TestSize.Level0) +{ + RdbServiceImpl service; + std::map results = {{"device1", static_cast(DBStatus::OK)}, + {"device2", static_cast(DBStatus::DB_ERROR)}, + {"device3", static_cast(DBStatus::OK)}}; + + auto result = service.ProcessResult(results); + + EXPECT_EQ(result.second.at("device1"), DBStatus::OK); + EXPECT_EQ(result.second.at("device2"), DBStatus::DB_ERROR); + EXPECT_EQ(result.second.at("device3"), DBStatus::OK); +} + +/** + * @tc.name: ProcessResult004 + * @tc.desc: Test ProcessResult with an empty results map. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, ProcessResult004, TestSize.Level0) +{ + RdbServiceImpl service; + std::map results; + + auto result = service.ProcessResult(results); + + EXPECT_EQ(result.first.size(), 0); + EXPECT_EQ(result.second.size(), 0); +} + +/** + * @tc.name: DoCompensateSync001 + * @tc.desc: Test DoCompensateSync when the event has valid bindInfo and COMPENSATE_SYNC event ID. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, DoCompensateSync001, TestSize.Level0) +{ + RdbServiceImpl service; + + int32_t eventId = 1; + DistributedData::BindEvent::BindEventInfo bindInfo; + bindInfo.bundleName = TEST_BUNDLE; + bindInfo.tokenId = metaData_.tokenId; + bindInfo.user = metaData_.uid; + bindInfo.storeName = TEST_STORE; + bindInfo.tableName = "test_table"; + bindInfo.primaryKey = {{"key1", "value1"}, {"key2", "value2"}}; + + BindEvent event(eventId, std::move(bindInfo)); + EventCenter::GetInstance().Subscribe(CloudEvent::LOCAL_CHANGE, [this] (const Event &event) { + auto &evt = static_cast(event); + auto mode = evt.GetMode(); + EXPECT_EQ(GeneralStore::GetPriorityLevel(GeneralStore::GetHighMode(static_cast(mode))), 1); + }); + service.DoCompensateSync(event); +} + +/** + * @tc.name: ReportStatistic001 + * @tc.desc: Test ReportStatistic when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, ReportStatistic001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + RdbStatEvent statEvent; + + int32_t result = service.ReportStatistic(param, statEvent); + + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: ReportStatistic002 + * @tc.desc: Test ReportStatistic when CheckAccess success. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, ReportStatistic002, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = TEST_BUNDLE; + param.storeName_ = TEST_STORE; + RdbStatEvent statEvent; + + int32_t result = service.ReportStatistic(param, statEvent); + + EXPECT_EQ(result, OK); +} + +/** + * @tc.name: GetReuseDevice001 + * @tc.desc: Test GetReuseDevice when all devices are reusable. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetReuseDevice001, TestSize.Level0) +{ + RdbServiceImpl service; + std::vector devices = {"device1"}; + + auto result = service.GetReuseDevice(devices); + EXPECT_EQ(result.size(), 0); +} + +/** + * @tc.name: DoAutoSync001 + * @tc.desc: Test DoAutoSync when the store is null. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, DoAutoSync001, TestSize.Level0) +{ + RdbServiceImpl service; + std::vector devices = {"device1"}; + DistributedData::Database dataBase; + std::vector tables = {"table1"}; + + auto result = service.DoAutoSync(devices, dataBase, tables); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: DoOnlineSync001 + * @tc.desc: Test DoOnlineSync when all tables have deviceSyncFields. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, DoOnlineSync001, TestSize.Level0) +{ + RdbServiceImpl service; + std::vector devices = {"device1"}; + DistributedData::Database dataBase; + dataBase.name = TEST_STORE; + + DistributedData::Table table1; + table1.name = "table1"; + table1.deviceSyncFields = {"field1", "field2"}; + DistributedData::Table table2; + table2.name = "table2"; + table2.deviceSyncFields = {}; + + dataBase.tables = {table1, table2}; + + auto result = service.DoOnlineSync(devices, dataBase); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: OnReady001 + * @tc.desc: Test OnReady when LoadMeta fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, OnReady001, TestSize.Level0) +{ + RdbServiceImpl service; + std::string device = "test_device"; + + int32_t result = service.OnReady(device); + EXPECT_EQ(result, 0); +} + +/** + * @tc.name: OnReady002 + * @tc.desc: Test OnReady when no databases have autoSyncType SYNC_ON_READY or SYNC_ON_CHANGE_READY. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, OnReady002, TestSize.Level0) +{ + RdbServiceImpl service; + std::string device = metaData_.deviceId; + + DistributedData::Database dataBase1; + dataBase1.name = "test_rdb_service_impl_sync_store2"; + dataBase1.bundleName = TEST_BUNDLE; + dataBase1.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(metaData_.tokenId)); + dataBase1.autoSyncType = AutoSyncType::SYNC_ON_READY; + + DistributedData::Database dataBase2; + dataBase2.name = "test_rdb_service_impl_sync_store2"; + dataBase2.bundleName = TEST_BUNDLE; + dataBase2.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(metaData_.tokenId)); + dataBase2.autoSyncType = AutoSyncType::SYNC_ON_CHANGE_READY; + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase1.GetKey(), metaData_, true), true); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase2.GetKey(), metaData_, true), true); + int32_t result = service.OnReady(device); + + EXPECT_EQ(result, 0); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase1.GetKey(), metaData_, true), true); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase2.GetKey(), metaData_, true), true); +} + +/** + * @tc.name: SetSearchable001 + * @tc.desc: Test SetSearchable when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, SetSearchable001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + + bool isSearchable = true; + int32_t result = service.SetSearchable(param, isSearchable); + + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: SetSearchable002 + * @tc.desc: Test SetSearchable when CheckAccess succeeds and PostSearchEvent is called. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, SetSearchable002, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + + bool isSearchable = true; + int32_t result = service.SetSearchable(param, isSearchable); + + EXPECT_EQ(result, RDB_OK); +} + +/** + * @tc.name: GetPassword001 + * @tc.desc: Test GetPassword when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetPassword001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + std::vector> password; + + int32_t result = service.GetPassword(param, password); + + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: GetPassword002 + * @tc.desc: Test GetPassword when no meta data is found. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetPassword002, TestSize.Level0) +{ + auto meta = metaData_; + meta.isEncrypt = true; + std::vector sKey{2, 249, 221, 119, 177, 216, 217, 134, 185, 139, 114, 38, 140, 64, 165, 35, + 77, 169, 0, 226, 226, 166, 37, 73, 181, 229, 42, 88, 108, 111, 131, 104, + 141, 43, 96, 119, 214, 34, 177, 129, 233, 96, 98, 164, 87, 115, 187, 170}; + SecretKeyMetaData secretKey; + secretKey.sKey = CryptoManager::GetInstance().Encrypt(sKey); + secretKey.area = 0; + secretKey.storeType = meta.storeType; + secretKey.time = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true), true); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetSecretKey(), secretKey, true), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = meta.bundleName; + param.storeName_ = meta.storeId; + std::vector> password; + int32_t result = service.GetPassword(param, password); + + EXPECT_EQ(result, RDB_OK); + size_t KEY_COUNT = 2; + ASSERT_EQ(password.size(), KEY_COUNT); + EXPECT_EQ(password.at(0), sKey); + MetaDataManager::GetInstance().DelMeta(meta.GetKey(), true); + MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true); +} + +/** + * @tc.name: GetPassword003 + * @tc.desc: Test GetPassword when decryption fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetPassword003, TestSize.Level0) +{ + SecretKeyMetaData secretKey; + secretKey.sKey = {0x01, 0x02, 0x03}; // Invalid key for decryption + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetSecretKey(), secretKey, true), true); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, true), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + std::vector> password; + + int32_t result = service.GetPassword(param, password); + + EXPECT_EQ(result, RDB_ERROR); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetSecretKey(), true), true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), true), true); +} + +/** + * @tc.name: GetPassword004 + * @tc.desc: Test GetPassword when no meta data is found. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetPassword004, TestSize.Level0) +{ + auto meta = metaData_; + meta.isEncrypt = true; + std::vector sKey{2, 249, 221, 119, 177, 216, 217, 134, 185, 139, 114, 38, 140, 64, 165, 35, + 77, 169, 0, 226, 226, 166, 37, 73, 181, 229, 42, 88, 108, 111, 131, 104, + 141, 43, 96, 119, 214, 34, 177, 129, 233, 96, 98, 164, 87, 115, 187, 170}; + SecretKeyMetaData secretKey; + secretKey.sKey = CryptoManager::GetInstance().Encrypt(sKey); + secretKey.area = 0; + secretKey.storeType = meta.storeType; + secretKey.time = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true), true); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetCloneSecretKey(), secretKey, true), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = meta.bundleName; + param.storeName_ = meta.storeId; + param.type_ = meta.storeType; + std::vector> password; + + int32_t result = service.GetPassword(param, password); + + EXPECT_EQ(result, RDB_OK); + size_t KEY_COUNT = 2; + ASSERT_EQ(password.size(), KEY_COUNT); + EXPECT_EQ(password.at(1), sKey); + MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), true); + MetaDataManager::GetInstance().DelMeta(metaData_.GetCloneSecretKey(), true); +} + +/** + * @tc.name: GetPassword005 + * @tc.desc: Test GetPassword when no meta data. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetPassword005, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = TEST_BUNDLE; + param.storeName_ = TEST_STORE; + param.type_ = StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN; + std::vector> password; + + int32_t result = service.GetPassword(param, password); + + EXPECT_EQ(result, RDB_NO_META); +} + +/** + * @tc.name: SetDistributedTables001 + * @tc.desc: Test SetDistributedTables when CheckAccess not pass. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, SetDistributedTables001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + std::vector tables; + std::vector references; + + int32_t result = service.SetDistributedTables(param, tables, references, false); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: SetDistributedTables002 + * @tc.desc: Test SetDistributedTables when type is search. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, SetDistributedTables002, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = TEST_BUNDLE; + param.storeName_ = TEST_STORE; + param.type_ = StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN; + std::vector tables; + std::vector references; + + int32_t result = + service.SetDistributedTables(param, tables, references, false, + DistributedTableType::DISTRIBUTED_SEARCH); + EXPECT_EQ(result, RDB_OK); +} + +/** + * @tc.name: Sync001 + * @tc.desc: Test Sync when CheckAccess not pass. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, Sync001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + RdbService::Option option {}; + PredicatesMemo predicates; + + int32_t result = service.Sync(param, option, predicates, nullptr); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: Subscribe001 + * @tc.desc: Test Subscribe when option mode invalid. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, Subscribe001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + SubscribeOption option {}; + option.mode = SubscribeMode::SUBSCRIBE_MODE_MAX; + + int32_t result = service.Subscribe(param, option, nullptr); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: UnSubscribe001 + * @tc.desc: Test UnSubscribe when option mode invalid. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, UnSubscribe001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + SubscribeOption option {}; + option.mode = SubscribeMode::SUBSCRIBE_MODE_MAX; + + int32_t result = service.UnSubscribe(param, option, nullptr); + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: UpgradeCloneSecretKey001 + * @tc.desc: Test UpgradeCloneSecretKey when meta invalid. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, UpgradeCloneSecretKey001, TestSize.Level0) +{ + auto meta = metaData_; + meta.isEncrypt = true; + std::vector sKey{2, 249, 221, 119, 177, 216, 217, 134, 185, 139, 114, 38, 140, 64, 165, 35, + 77, 169, 0, 226, 226, 166, 37, 73, 181, 229, 42, 88, 108, 111, 131, 104, + 141, 43, 96, 119, 214, 34, 177, 129, 233, 96, 98, 164, 87, 115, 187, 170}; + SecretKeyMetaData secretKey; + secretKey.sKey = CryptoManager::GetInstance().Encrypt(sKey); + secretKey.area = -1; + secretKey.storeType = meta.storeType; + secretKey.time = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetCloneSecretKey(), secretKey, true), true); + + RdbServiceImpl service; + + auto result = service.UpgradeCloneSecretKey(meta); + ASSERT_EQ(result, true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(meta.GetCloneSecretKey(), true), true); +} + +/** + * @tc.name: GetDfxInfo001 + * @tc.desc: Test GetDfxInfo when CheckAccess not pass. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetDfxInfo001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + DistributedRdb::RdbDfxInfo dfxInfo; + + int32_t result = service.GetDfxInfo(param, dfxInfo); + EXPECT_EQ(result, RDB_ERROR); +} +/** + * @tc.name: LockCloudContainer001 + * @tc.desc: Test LockCloudContainer when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, LockCloudContainer001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + + auto result = service.LockCloudContainer(param); + + EXPECT_EQ(result.first, RDB_ERROR); + EXPECT_EQ(result.second, 0); +} + +/** + * @tc.name: LockCloudContainer002 + * @tc.desc: Test LockCloudContainer when CheckAccess succeeds and callback updates the result. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, LockCloudContainer002, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + + auto result = service.LockCloudContainer(param); + + // Simulate callback execution + EXPECT_EQ(result.first, RDB_ERROR); + EXPECT_EQ(result.second, 0); + + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** + * @tc.name: UnlockCloudContainer001 + * @tc.desc: Test UnlockCloudContainer when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, UnlockCloudContainer001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + + int32_t result = service.UnlockCloudContainer(param); + + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: UnlockCloudContainer002 + * @tc.desc: Test UnlockCloudContainer when CheckAccess succeeds and callback updates the result. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, UnlockCloudContainer002, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, false), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + + int32_t result = service.UnlockCloudContainer(param); + + // Simulate callback execution + EXPECT_EQ(result, RDB_ERROR); // Assuming the callback sets status to RDB_OK + + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), false), true); +} + +/** + * @tc.name: GetDebugInfo001 + * @tc.desc: Test GetDebugInfo when CheckAccess fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, GetDebugInfo001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + std::map debugInfo; + + int32_t result = service.GetDebugInfo(param, debugInfo); + + EXPECT_EQ(result, RDB_ERROR); + EXPECT_TRUE(debugInfo.empty()); +} + +/** + * @tc.name: VerifyPromiseInfo001 + * @tc.desc: Test VerifyPromiseInfo when LoadMeta fails. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, VerifyPromiseInfo001, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + + int32_t result = service.VerifyPromiseInfo(param); + + EXPECT_EQ(result, RDB_ERROR); +} + +/** + * @tc.name: VerifyPromiseInfo002 + * @tc.desc: Test VerifyPromiseInfo when tokenId and uid are not in promiseInfo. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhaojh + */ +HWTEST_F(RdbServiceImplTest, VerifyPromiseInfo002, TestSize.Level0) +{ + StoreMetaDataLocal localMeta; + auto tokenId = IPCSkeleton::GetCallingTokenID(); + localMeta.isAutoSync = true; + localMeta.promiseInfo.tokenIds = {tokenId}; + localMeta.promiseInfo.uids = {}; + localMeta.promiseInfo.permissionNames = {}; + + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKeyLocal(), localMeta, true), true); + + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.type_ = metaData_.storeType; + param.level_ = metaData_.securityLevel; + param.area_ = metaData_.area; + param.hapName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + param.isEncrypt_ = metaData_.isEncrypt; + param.isSearchable_ = metaData_.isSearchable; + param.haMode_ = metaData_.haMode; + param.asyncDownloadAsset_ = metaData_.asyncDownloadAsset; + param.user_ = metaData_.user; + + int32_t result = service.VerifyPromiseInfo(param); + + EXPECT_EQ(result, RDB_OK); + + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKeyLocal(), true), true); +} +} // namespace DistributedRDBTest +} // namespace OHOS::Test diff --git a/services/distributeddataservice/service/test/testCloud/BUILD.gn b/services/distributeddataservice/service/test/testCloud/BUILD.gn index e4d86447f27b4c46bb8e810db739d1450f615e43..db1355d58ddfb37cbde8928aa48dfb5ec9cdf1c0 100644 --- a/services/distributeddataservice/service/test/testCloud/BUILD.gn +++ b/services/distributeddataservice/service/test/testCloud/BUILD.gn @@ -18,8 +18,7 @@ ohos_hap("testCloud") { hap_name = "testCloud" subsystem_name = "distributeddatamgr" part_name = "datamgr_service" - final_hap_path = - "$root_out_dir/tests/unittest/datamgr_service/resource/${hap_name}.hap" + final_hap_path = "$root_out_dir/tests/unittest/datamgr_service/datamgr_service/resource/${hap_name}.hap" testonly = true deps = [ ":testCloud_ets_assets", diff --git a/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp b/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ddebf513d36b068f7297630f6707df2a13bc2a18 --- /dev/null +++ b/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp @@ -0,0 +1,78 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "preprocess_utils.h" +#include "gtest/gtest.h" +#include "access_token_mock.h" + +namespace OHOS::UDMF { +using namespace testing; +using namespace std; +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; +class UdmfPreProcessUtilsMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() {} + void TearDown() {} + static inline shared_ptr accessTokenKitMock = nullptr; +}; + +void UdmfPreProcessUtilsMockTest::SetUpTestCase(void) +{ + accessTokenKitMock = make_shared(); + BAccessTokenKit::accessTokenkit = accessTokenKitMock; +} + +void UdmfPreProcessUtilsMockTest::TearDownTestCase(void) +{ + BAccessTokenKit::accessTokenkit = nullptr; + accessTokenKitMock = nullptr; +} + +/** +* @tc.name: GetHapUidByToken001 +* @tc.desc: Abnormal test of GetHapUidByToken, AccessTokenKit GetHapTokenInfo failed +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsMockTest, GetHapUidByToken001, TestSize.Level1) +{ + uint32_t tokenId = 0; + int userId = 0; + PreProcessUtils preProcessUtils; + EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillOnce(Return(RET_SUCCESS)); + int32_t ret = preProcessUtils.GetHapUidByToken(tokenId, userId); + EXPECT_EQ(ret, E_OK); +} + +/** +* @tc.name: GetInstIndex001 +* @tc.desc: Abnormal test of GetInstIndex, AccessTokenKit GetInstIndex failed +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsMockTest, GetInstIndex001, TestSize.Level1) +{ + uint32_t tokenId = 0; + int32_t instIndex = 0; + PreProcessUtils preProcessUtils; + EXPECT_CALL(*accessTokenKitMock, GetTokenTypeFlag(_)).WillOnce(Return(TOKEN_HAP)); + EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillOnce(Return(RET_SUCCESS)); + bool ret = preProcessUtils.GetInstIndex(tokenId, instIndex); + EXPECT_EQ(ret, true); +} +}; // namespace UDMF \ No newline at end of file diff --git a/services/distributeddataservice/service/test/udmf_preprocess_utils_test.cpp b/services/distributeddataservice/service/test/udmf_preprocess_utils_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38a85bdfa64220ccbade2fe1e476733ac5625e11 --- /dev/null +++ b/services/distributeddataservice/service/test/udmf_preprocess_utils_test.cpp @@ -0,0 +1,182 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "preprocess_utils.h" +#include "gtest/gtest.h" +#include "text.h" + +namespace OHOS::UDMF { +using namespace testing::ext; +class UdmfPreProcessUtilsTest : public testing::Test { +public: + static void SetUpTestCase(void) {} + static void TearDownTestCase(void) {} + void SetUp() {} + void TearDown() {} +}; + +/** +* @tc.name: RuntimeDataImputation001 +* @tc.desc: Abnormal test of RuntimeDataImputation, option is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, RuntimeDataImputation001, TestSize.Level1) +{ + UnifiedData data; + CustomOption option; + PreProcessUtils preProcessUtils; + int32_t ret = preProcessUtils.RuntimeDataImputation(data, option); + EXPECT_EQ(ret, E_ERROR); +} + +/** +* @tc.name: GetHapUidByToken001 +* @tc.desc: Abnormal test of GetHapUidByToken, tokenId is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, GetHapUidByToken001, TestSize.Level1) +{ + uint32_t tokenId = 0; + int userId = 0; + PreProcessUtils preProcessUtils; + int32_t ret = preProcessUtils.GetHapUidByToken(tokenId, userId); + EXPECT_EQ(ret, E_ERROR); +} + +/** +* @tc.name: SetRemoteData001 +* @tc.desc: Abnormal test of SetRemoteData, data is null +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, SetRemoteData001, TestSize.Level1) +{ + UnifiedData data; + PreProcessUtils preProcessUtils; + EXPECT_NO_FATAL_FAILURE(preProcessUtils.SetRemoteData(data)); +} + +/** +* @tc.name: SetRemoteData002 +* @tc.desc: Normal test of SetRemoteData +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, SetRemoteData002, TestSize.Level1) +{ + UnifiedData data; + std::vector> inputRecords; + for (int32_t i = 0; i < 512; ++i) { + inputRecords.emplace_back(std::make_shared()); + } + data.SetRecords(inputRecords); + data.runtime_ = std::make_shared(); + PreProcessUtils preProcessUtils; + EXPECT_NO_FATAL_FAILURE(preProcessUtils.SetRemoteData(data)); +} + +/** +* @tc.name: IsFileType001 +* @tc.desc: Abnormal test of IsFileType, record is nullptr +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, IsFileType001, TestSize.Level1) +{ + std::shared_ptr record = nullptr; + PreProcessUtils preProcessUtils; + bool ret = preProcessUtils.IsFileType(record); + EXPECT_EQ(ret, false); +} + +/** +* @tc.name: GetDfsUrisFromLocal001 +* @tc.desc: Abnormal test of GetDfsUrisFromLocal, uris is null +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, GetDfsUrisFromLocal001, TestSize.Level1) +{ + const std::vector uris; + int32_t userId = 0; + UnifiedData data; + PreProcessUtils preProcessUtils; + int32_t ret = preProcessUtils.GetDfsUrisFromLocal(uris, userId, data); + EXPECT_EQ(ret, E_FS_ERROR); +} + +/** +* @tc.name: CheckUriAuthorization001 +* @tc.desc: Abnormal test of CheckUriAuthorization, uris is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, CheckUriAuthorization001, TestSize.Level1) +{ + const std::vector uris = {"test"}; + uint32_t tokenId = 0; + PreProcessUtils preProcessUtils; + bool ret = preProcessUtils.CheckUriAuthorization(uris, tokenId); + EXPECT_EQ(ret, false); +} + +/** +* @tc.name: GetInstIndex001 +* @tc.desc: Normal test of GetInstIndex +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, GetInstIndex001, TestSize.Level1) +{ + uint32_t tokenId = 0; + int32_t instIndex = 0; + PreProcessUtils preProcessUtils; + bool ret = preProcessUtils.GetInstIndex(tokenId, instIndex); + EXPECT_EQ(instIndex, 0); + EXPECT_EQ(ret, true); +} + +/** +* @tc.name: ProcessFileType001 +* @tc.desc: Abnormal test of ProcessFileType, records is nullptr +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, ProcessFileType001, TestSize.Level1) +{ + std::vector> records = { nullptr }; + std::function)> callback; + PreProcessUtils preProcessUtils; + EXPECT_NO_FATAL_FAILURE(preProcessUtils.ProcessFileType(records, callback)); +} + +/** +* @tc.name: GetHtmlFileUris001 +* @tc.desc: Abnormal test of GetHtmlFileUris, uris is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsTest, GetHtmlFileUris001, TestSize.Level1) +{ + uint32_t tokenId = 0; + UnifiedData data; + bool isLocal = false; + std::vector uris = {"test"}; + PreProcessUtils preProcessUtils; + EXPECT_NO_FATAL_FAILURE(preProcessUtils.GetHtmlFileUris(tokenId, data, isLocal, uris)); +} +}; // namespace UDMF \ No newline at end of file diff --git a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp index ec7fb210ab6927ec422e01bf588186b7495d885d..962adbcbfac4c5876b010604437a81118e42c084 100644 --- a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp +++ b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp @@ -25,11 +25,10 @@ #include "kvstore_meta_manager.h" #include "metadata/meta_data_manager.h" #include "nativetoken_kit.h" +#include "preprocess_utils.h" +#include "runtime_store.h" #include "text.h" #include "token_setproc.h" -#define private public -#include "store/runtime_store.h" -#undef private using namespace testing::ext; using namespace OHOS::DistributedData; @@ -501,7 +500,7 @@ HWTEST_F(UdmfRunTimeStoreTest, GetDetailsFromUData, TestSize.Level1) details1.insert({ "udmf_key", "udmf_value" }); auto records = data1.GetRecords(); EXPECT_EQ(records.size(), 0); - status = store->GetDetailsFromUData(data1, details1); + status = PreProcessUtils::GetDetailsFromUData(data1, details1); EXPECT_FALSE(status); status = store->Delete(KEY_PREFIX); @@ -548,10 +547,105 @@ HWTEST_F(UdmfRunTimeStoreTest, GetDetailsFromUData01, TestSize.Level1) auto outputRecords = outputData.GetRecords(); ASSERT_EQ(inputRecords.size(), 512); ASSERT_EQ(0, outputRecords.size()); - status = store->GetDetailsFromUData(inputData, details1); + status = PreProcessUtils::GetDetailsFromUData(inputData, details1); EXPECT_FALSE(status); } +/** +* @tc.name: Sync01 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Sync01, TestSize.Level1) +{ + std::vector devices = {"device"}; + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + Status ret = store->Sync(devices); + EXPECT_EQ(ret, E_DB_ERROR); +} + +/** +* @tc.name: Sync02 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Sync02, TestSize.Level1) +{ + std::vector devices = { }; + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + Status ret = store->Sync(devices); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: Sync03 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Sync03, TestSize.Level1) +{ + std::vector devices = { "device" }; + ProcessCallback callback; + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + Status ret = store->Sync(devices, callback); + EXPECT_EQ(ret, E_DB_ERROR); +} + +/** +* @tc.name: Sync04 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Sync04, TestSize.Level1) +{ + std::vector devices = { }; + ProcessCallback callback; + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + Status ret = store->Sync(devices, callback); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: Clear01 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Clear01, TestSize.Level1) +{ + static constexpr const char *DATA_PREFIX = "udmf://"; + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + Status ret = store->Clear(); + EXPECT_EQ(ret, store->Delete(DATA_PREFIX)); +} + +/** +* @tc.name: Close01 +* @tc.desc: check for legal parameters, delete entries error. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, Close01, TestSize.Level1) +{ + auto store = std::make_shared(STORE_ID); + EXPECT_NO_FATAL_FAILURE(store->Close()); +} + + /** * @tc.name: GetSummary * @tc.desc: check for legal parameters, delete entries error. @@ -572,8 +666,58 @@ HWTEST_F(UdmfRunTimeStoreTest, GetSummary, TestSize.Level1) data.AddRecord(text); Summary summary; - auto status = store->GetSummary(KEY_PREFIX, summary); + UnifiedKey key(KEY_PREFIX); + auto status = store->GetSummary(key, summary); ASSERT_EQ(status, E_DB_ERROR); } + +/** +* @tc.name: GetRuntime001 +* @tc.desc: Normal testcase of GetRuntime +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, GetRuntime001, TestSize.Level1) +{ + UnifiedData inputData; + CustomOption option = {.intention = Intention::UD_INTENTION_DRAG}; + auto status = PreProcessUtils::RuntimeDataImputation(inputData, option); + EXPECT_EQ(status, E_OK); + auto key = inputData.GetRuntime()->key.GetUnifiedKey(); + + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + status = store->PutRuntime(key, *inputData.GetRuntime()); + EXPECT_EQ(status, E_OK); + + Runtime outRuntime; + status = store->GetRuntime(key, outRuntime); + EXPECT_EQ(status, E_OK); + EXPECT_EQ(inputData.GetRuntime()->createTime, outRuntime.createTime); +} + +/** +* @tc.name: GetRuntime002 +* @tc.desc: Abnormal testcase of GetRuntime +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfRunTimeStoreTest, GetRuntime002, TestSize.Level1) +{ + UnifiedData inputData; + CustomOption option = {.intention = Intention::UD_INTENTION_DRAG}; + auto status = PreProcessUtils::RuntimeDataImputation(inputData, option); + EXPECT_EQ(status, E_OK); + auto key = inputData.GetRuntime()->key.GetUnifiedKey(); + + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + + Runtime outRuntime; + status = store->GetRuntime(key, outRuntime); + EXPECT_EQ(status, E_NOT_FOUND); +} }; // namespace DistributedDataTest }; // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp index 55830d53ba9ea71edec2abbdc73535b0dc679c15..d93a559053eff8627f4732a64cfbba2c83a59132 100644 --- a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp @@ -216,4 +216,28 @@ HWTEST_F(UdmfServiceImplTest, OnUserChangeTest001, TestSize.Level1) ASSERT_EQ(sizeAfter, 0); } +/** +* @tc.name: TransferToEntriesIfNeedTest001 +* @tc.desc: TransferToEntriesIfNeed test +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, TransferToEntriesIfNeedTest001, TestSize.Level1) +{ + UnifiedData data; + QueryOption query; + auto record1 = std::make_shared(); + auto record2 = std::make_shared(); + data.AddRecord(record1); + data.AddRecord(record2); + auto properties = std::make_shared(); + properties->tag = "records_to_entries_data_format"; + data.SetProperties(properties); + query.tokenId = 1; + UdmfServiceImpl udmfServiceImpl; + udmfServiceImpl.TransferToEntriesIfNeed(query, data); + EXPECT_TRUE(data.IsNeedTransferToEntries()); + int recordSize = 2; + EXPECT_EQ(data.GetRecords().size(), recordSize); +} }; // namespace UDMF \ No newline at end of file diff --git a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp index 373782b7eb6961ce8d2141fdbeba4a26b95560f7..910e17ca9873d44d1fce8bac64a61fba7b94d567 100644 --- a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp +++ b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp @@ -39,6 +39,13 @@ bool MetaDataManager::Subscribe(std::string prefix, Observer observer, bool isLo return false; } +bool MetaDataManager::SaveMeta(const std::string &key, const Serializable &value, bool isLocal) +{ + (void)key; + (void)value; + return true; +} + namespace OHOS::Test { namespace DistributedDataTest { class UserDelegateMockTest : public testing::Test { @@ -84,13 +91,16 @@ HWTEST_F(UserDelegateMockTest, GetLocalUserStatus, TestSize.Level0) */ HWTEST_F(UserDelegateMockTest, InitLocalUserMeta, TestSize.Level0) { - EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)).WillOnce(Return(false)); + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .Times(1) + .WillOnce(Return(false)); bool ret = UserDelegate::GetInstance().InitLocalUserMeta(); EXPECT_FALSE(ret); std::vector users; EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) - .WillRepeatedly(DoAll(SetArgReferee<0>(users), Return(true))); + .Times(1) + .WillOnce(DoAll(SetArgReferee<0>(users), Return(true))); ret = UserDelegate::GetInstance().InitLocalUserMeta(); UserDelegate::GetInstance().DeleteUsers("users"); EXPECT_FALSE(ret); @@ -140,12 +150,18 @@ HWTEST_F(UserDelegateMockTest, Init, TestSize.Level0) EXPECT_CALL(AccountDelegateMock::Init(), Subscribe(_)).WillRepeatedly(Return(0)); DeviceInfo devInfo = { .uuid = "HJJ4FGAGAAGA45WF3663FAGA" }; EXPECT_CALL(*devMgrAdapterMock, GetLocalDevice()).WillRepeatedly(Return(devInfo)); - std::shared_ptr poolPtr = std::make_shared(0, 1); + std::shared_ptr poolPtr = std::make_shared(1, 0); ASSERT_NE(poolPtr, nullptr); - UserDelegate::GetInstance().executors_ = poolPtr; - ASSERT_NE(UserDelegate::GetInstance().executors_, nullptr); - UserDelegate::GetInstance().Init(poolPtr); - ASSERT_TRUE(UserDelegate::GetInstance().executors_ != nullptr); + UserDelegate instance; + instance.executors_ = poolPtr; + ASSERT_NE(instance.executors_, nullptr); + + std::vector users = {0, 1}; + EXPECT_CALL(AccountDelegateMock::Init(), QueryUsers(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(users), Return(true))); + EXPECT_TRUE(instance.InitLocalUserMeta()); + instance.Init(poolPtr); + ASSERT_TRUE(instance.executors_ != nullptr); } } } \ No newline at end of file diff --git a/services/distributeddataservice/service/test/value_proxy_test.cpp b/services/distributeddataservice/service/test/value_proxy_test.cpp index 8ada4d4c9607cfd49fc88bb1d6f198937a613377..469d2230da7cf2cc0b7d3118310f130b6dca85c4 100644 --- a/services/distributeddataservice/service/test/value_proxy_test.cpp +++ b/services/distributeddataservice/service/test/value_proxy_test.cpp @@ -362,4 +362,103 @@ HWTEST_F(ValueProxyServiceTest, TempAssetConvertToDataStatus, TestSize.Level0) result = ValueProxy::TempAsset::ConvertToDataStatus(status); EXPECT_NE(result, DistributedData::Asset::STATUS_NORMAL); } + +/** +* @tc.name: AssetsOperator001 +* @tc.desc: AssetsOperator test. +* @tc.type: FUNC +*/ +HWTEST_F(ValueProxyServiceTest, AssetsOperator001, TestSize.Level0) +{ + ValueProxy::Assets proxy1; + ValueProxy::Assets proxy2; + ValueProxy::Assets proxy3; + proxy1.assets_.push_back(ValueProxy::Asset(DistributedDB::Asset { + .version = 1, + .status = DistributedData::Asset::Status::STATUS_INSERT, + .name = "Asset1", + .uri = "uri1", + .size = "1", + .hash = "hash1", + })); + proxy2.assets_.push_back(ValueProxy::Asset(DistributedDB::Asset { + .version = 2, + .status = DistributedData::Asset::Status::STATUS_NORMAL, + .name = "Asset2", + .uri = "uri2", + .size = "2", + .hash = "hash2", + })); + proxy2.assets_.push_back(ValueProxy::Asset(DistributedDB::Asset { + .version = 3, + .status = DistributedData::Asset::Status::STATUS_NORMAL, + .name = "Asset3", + .uri = "uri3", + .size = "3", + .hash = "hash3", + })); + // operator "=" same asset case + proxy3 = proxy1; + proxy1 = proxy3; + + // operator "=" different aseet case + proxy1 = proxy2; + EXPECT_EQ(proxy1.assets_.size(), 2); + + // operator Distributeddata Asset() + DistributedData::Asset asset = proxy1.assets_[0]; + EXPECT_EQ(asset.version, 2); + + // operator "=" noexcept same asset case + proxy2 = std::move(proxy1); + // operator "=" noexcept different asset case + proxy1 = std::move(proxy3); + EXPECT_EQ(proxy1.assets_.size(), 1); + asset = proxy1.assets_[0]; + EXPECT_EQ(asset.version, 1); +} + +/** +* @tc.name: AssetOperator001 +* @tc.desc: AssetOperator test. +* @tc.type: FUNC +*/ +HWTEST_F(ValueProxyServiceTest, AssetOperator001, TestSize.Level0) +{ + ValueProxy::Asset asset1 = DistributedDB::Asset { + .version = 1, + .status = DistributedData::Asset::Status::STATUS_INSERT, + .name = "Asset1", + .uri = "uri1", + .size = "1", + .hash = "hash1", + }; + ValueProxy::Asset asset2 = DistributedDB::Asset { + .version = 2, + .status = DistributedData::Asset::Status::STATUS_NORMAL, + .name = "Asset2", + .uri = "uri2", + .size = "2", + .hash = "hash2", + }; + ValueProxy::Asset asset3 = asset1; + DistributedData::Asset asset = asset3; + EXPECT_EQ(asset.version, 1); + + // operator "=" same asset case + asset1 = asset3; + EXPECT_EQ(asset.version, 1); + // operator "=" different aseet case + asset1 = asset2; + asset = asset1; + EXPECT_EQ(asset.version, 2); + + // operator "=" noexcept same asset case + asset2 = std::move(asset1); + EXPECT_EQ(asset.version, 2); + // operator "=" noexcept different asset case + asset1 = std::move(asset3); + asset = asset1; + EXPECT_EQ(asset.version, 1); +} } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/BUILD.gn b/services/distributeddataservice/service/udmf/BUILD.gn index 5fd2313034164e68516e8b7c9d8190ecb7ca918a..8176548a1cdd0cdfd3b02c6a6a9689f315786b0e 100644 --- a/services/distributeddataservice/service/udmf/BUILD.gn +++ b/services/distributeddataservice/service/udmf/BUILD.gn @@ -79,8 +79,11 @@ ohos_source_set("udmf_server") { "ability_runtime:uri_permission_mgr", "access_token:libtokenid_sdk", "app_file_service:remote_file_share_native", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "device_manager:devicemanagersdk", "hilog:libhilog", + "hisysevent:libhisysevent", "hitrace:hitrace_meter", "hitrace:libhitracechain", "ipc:ipc_core", diff --git a/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.cpp b/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.cpp index cc3d88659c07bafb8a2561ee2afcf9dea85e2ae7..095a95f65ddb346549999b6579cc3b8f6a73c412 100644 --- a/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.cpp +++ b/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.cpp @@ -30,7 +30,7 @@ Status LifeCyclePolicy::OnGot(const UnifiedKey &key) ZLOGE("Get store failed:%{public}s", key.intention.c_str()); return E_DB_ERROR; } - if (store->Delete(key.key) != E_OK) { + if (store->Delete(UnifiedKey(key.key).GetKeyCommonPrefix()) != E_OK) { ZLOGE("Remove data failed:%{public}s", key.intention.c_str()); return E_DB_ERROR; } @@ -92,7 +92,7 @@ Status LifeCyclePolicy::GetTimeoutKeys( } if (curTime > data.GetRuntime()->createTime + duration_cast(interval).count() || curTime < data.GetRuntime()->createTime) { - timeoutKeys.push_back(data.GetRuntime()->key.key); + timeoutKeys.push_back(UnifiedKey(data.GetRuntime()->key.key).GetKeyCommonPrefix()); } } return E_OK; diff --git a/services/distributeddataservice/service/udmf/permission/uri_permission_manager.cpp b/services/distributeddataservice/service/udmf/permission/uri_permission_manager.cpp index e9eb42a70fdb3fdc61f7aa5b7e3c9983f36de626..042325f491c49f094cf069bd1708181fb4f6739f 100644 --- a/services/distributeddataservice/service/udmf/permission/uri_permission_manager.cpp +++ b/services/distributeddataservice/service/udmf/permission/uri_permission_manager.cpp @@ -22,7 +22,7 @@ namespace OHOS { namespace UDMF { -constexpr const std::uint32_t GRANT_URI_PERMISSION_MAX_SIZE = 500; +constexpr const std::uint32_t GRANT_URI_PERMISSION_MAX_SIZE = 10000; UriPermissionManager &UriPermissionManager::GetInstance() { static UriPermissionManager instance; diff --git a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp index 94d6ad7f15bed33d5727bdd5c8548d85a272f0ac..74c7d856a45906cffa868d00365f2f58eff492b1 100644 --- a/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/data_handler.cpp @@ -21,6 +21,7 @@ namespace OHOS::UDMF { constexpr const char *UD_KEY_SEPARATOR = "/"; constexpr const char *UD_KEY_ENTRY_SEPARATOR = "#"; +constexpr const char *UD_KEY_PROPERTIES_SEPARATOR = "#properties"; Status DataHandler::MarshalToEntries(const UnifiedData &unifiedData, std::vector &entries) { @@ -34,6 +35,16 @@ Status DataHandler::MarshalToEntries(const UnifiedData &unifiedData, std::vector std::vector udKeyBytes = { unifiedKey.begin(), unifiedKey.end() }; Entry entry = { udKeyBytes, runtimeBytes }; entries.emplace_back(entry); + std::string propsKey = unifiedData.GetRuntime()->key.GetKeyCommonPrefix() + UD_KEY_PROPERTIES_SEPARATOR; + std::vector propsBytes; + auto propsTlv = TLVObject(propsBytes); + if (!TLVUtil::Writing(*unifiedData.GetProperties(), propsTlv, TAG::TAG_PROPERTIES)) { + ZLOGE("Properties info marshalling failed:%{public}s", propsKey.c_str()); + return E_WRITE_PARCEL_ERROR; + } + std::vector propsKeyBytes = { propsKey.begin(), propsKey.end() }; + Entry propsEntry = { propsKeyBytes, propsBytes }; + entries.emplace_back(std::move(propsEntry)); return BuildEntries(unifiedData.GetRecords(), unifiedKey, entries); } @@ -75,7 +86,14 @@ Status DataHandler::UnmarshalEntryItem(UnifiedData &unifiedData, const std::vect continue; } auto isStartWithKey = keyStr.find(key) == 0; - if (!isStartWithKey) { + std::string propsKey = UnifiedKey(key).GetKeyCommonPrefix() + UD_KEY_PROPERTIES_SEPARATOR; + if (!isStartWithKey && (keyStr == propsKey)) { + std::shared_ptr properties; + if (!TLVUtil::ReadTlv(properties, data, TAG::TAG_PROPERTIES)) { + ZLOGE("Unmarshall unified properties failed."); + return E_READ_PARCEL_ERROR; + } + unifiedData.SetProperties(std::move(properties)); continue; } auto isEntryItem = keyStr.rfind(UD_KEY_ENTRY_SEPARATOR) != std::string::npos; diff --git a/services/distributeddataservice/service/udmf/preprocess/data_handler.h b/services/distributeddataservice/service/udmf/preprocess/data_handler.h index 3be27dfa34bab235852fc67e59bee7a5fea3ec92..b3e89721f7566e619726a0f70eadf68c8d825d40 100644 --- a/services/distributeddataservice/service/udmf/preprocess/data_handler.h +++ b/services/distributeddataservice/service/udmf/preprocess/data_handler.h @@ -16,6 +16,7 @@ #define DATA_HANDLER_H #include "unified_data.h" +#include "tlv_util.h" #include "types_export.h" namespace OHOS::UDMF { @@ -26,6 +27,10 @@ public: static Status MarshalToEntries(const UnifiedData &unifiedData, std::vector &entries); static Status UnmarshalEntries(const std::string &key, const std::vector &entries, UnifiedData &unifiedData); + template + static Status MarshalToEntries(const T &data, Value &value, TAG tag); + template + static Status UnmarshalEntries(const Value &value, T &data, TAG tag); private: static Status BuildEntries(const std::vector> &records, @@ -34,5 +39,25 @@ private: const std::string &key, std::map> &records, std::map> &innerEntries); }; + +template +Status DataHandler::MarshalToEntries(const T &data, Value &value, TAG tag) +{ + auto tlvObject = TLVObject(value); + if (!TLVUtil::Writing(data, tlvObject, tag)) { + return E_WRITE_PARCEL_ERROR; + } + return E_OK; +} + +template +Status DataHandler::UnmarshalEntries(const Value &value, T &data, TAG tag) +{ + auto tlvObject = TLVObject(const_cast &>(value)); + if (!TLVUtil::ReadTlv(data, tlvObject, tag)) { + return E_READ_PARCEL_ERROR; + } + return E_OK; +} } // namespace UDMF::OHOS #endif // DATA_HANDLER_H \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index fcb2eb437b485ae45b01b2f2a14fabd88dff7551..b42a9d907805085c9b894c0acbd739b439f6b8cb 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -40,6 +40,11 @@ constexpr const char *FILE_SCHEME_PREFIX = "file://"; constexpr const char *DOCS_LOCAL_TAG = "/docs/"; static constexpr uint32_t DOCS_LOCAL_PATH_SUBSTR_START_INDEX = 1; static constexpr uint32_t VERIFY_URI_PERMISSION_MAX_SIZE = 500; +constexpr const char *TEMP_UNIFIED_DATA_FLAG = "temp_udmf_file_flag"; +static constexpr size_t TEMP_UDATA_RECORD_SIZE = 1; +static constexpr uint32_t PREFIX_LEN = 24; +static constexpr uint32_t INDEX_LEN = 8; +static constexpr const char PLACE_HOLDER = '0'; using namespace OHOS::DistributedDataDfx; using namespace Security::AccessToken; using namespace OHOS::AppFileService::ModuleRemoteFileShare; @@ -66,6 +71,7 @@ int32_t PreProcessUtils::RuntimeDataImputation(UnifiedData &data, CustomOption & runtime.deviceId = GetLocalDeviceId(); runtime.recordTotalNum = static_cast(data.GetRecords().size()); runtime.tokenId = option.tokenId; + runtime.sdkVersion = GetSdkVersionByToken(option.tokenId); data.SetRuntime(runtime); return E_OK; } @@ -331,7 +337,7 @@ void PreProcessUtils::ProcessRecord(std::shared_ptr record, uint3 { record->ComputeUris([&uris, &isLocal, &tokenId] (UriInfo &uriInfo) { std::string newUriStr = ""; - if (isLocal) { + if (isLocal && uriInfo.authUri.empty()) { Uri tmpUri(uriInfo.oriUri); std::string path = tmpUri.GetPath(); std::string bundleName; @@ -347,7 +353,7 @@ void PreProcessUtils::ProcessRecord(std::shared_ptr record, uint3 } uriInfo.authUri = newUriStr; } else { - newUriStr = uriInfo.dfsUri; + newUriStr = isLocal ? uriInfo.authUri : uriInfo.dfsUri; } Uri uri(newUriStr); if (uri.GetAuthority().empty()) { @@ -401,5 +407,84 @@ void PreProcessUtils::ProcessHtmlFileUris(uint32_t tokenId, UnifiedData &data, b PreProcessUtils::ClearHtmlDfsUris(data); } } + +void PreProcessUtils::SetRecordUid(UnifiedData &data) +{ + uint32_t index = 0; + auto prefix = PreProcessUtils::GenerateId().substr(0, PREFIX_LEN); + for (const auto &record : data.GetRecords()) { + std::ostringstream oss; + oss << std::setw(INDEX_LEN) << std::setfill(PLACE_HOLDER) << index; + record->SetUid(prefix + oss.str()); + index++; + } +} + +bool PreProcessUtils::GetDetailsFromUData(const UnifiedData &data, UDDetails &details) +{ + auto records = data.GetRecords(); + if (records.size() != TEMP_UDATA_RECORD_SIZE) { + ZLOGI("Records size:%{public}zu", records.size()); + return false; + } + if (records[0] == nullptr) { + ZLOGE("First record is null."); + return false; + } + if (records[0]->GetType() != UDType::FILE) { + ZLOGE("First record is not file."); + return false; + } + auto value = records[0]->GetOriginValue(); + auto obj = std::get_if>(&value); + if (obj == nullptr || *obj == nullptr) { + ZLOGE("ValueType is not Object!"); + return false; + } + std::shared_ptr detailObj; + (*obj)->GetValue(DETAILS, detailObj); + if (detailObj == nullptr) { + ZLOGE("Not contain details for object!"); + return false; + } + auto result = ObjectUtils::ConvertToUDDetails(detailObj); + if (result.find(TEMP_UNIFIED_DATA_FLAG) == result.end()) { + ZLOGE("Not find temp file."); + return false; + } + details = std::move(result); + return true; +} + +Status PreProcessUtils::GetSummaryFromDetails(const UDDetails &details, Summary &summary) +{ + for (auto &item : details) { + if (item.first == TEMP_UNIFIED_DATA_FLAG) { + continue; + } + auto int64Value = std::get_if(&item.second); + if (int64Value != nullptr) { + summary.summary[item.first] = *int64Value; + summary.totalSize += *int64Value; + } + } + return E_OK; +} + +std::string PreProcessUtils::GetSdkVersionByToken(uint32_t tokenId) +{ + if (Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) != + Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) { + ZLOGE("Caller is not application, tokenid is %{public}u", tokenId); + return ""; + } + Security::AccessToken::HapTokenInfo hapTokenInfo; + auto ret = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, hapTokenInfo); + if (ret != 0) { + ZLOGE("GetHapTokenInfo fail, tokenid is %{public}u, ret is %{public}d.", tokenId, ret); + return ""; + } + return std::to_string(hapTokenInfo.apiVersion); +} } // namespace UDMF } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h index e57061af750155aeb28d4a01fe2767b2677d3c8e..1532f4c49136116310619fbb39865319e80e42e6 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h @@ -39,10 +39,14 @@ public: static void ProcessHtmlFileUris(uint32_t tokenId, UnifiedData &data, bool isLocal, std::vector &uris); static void ProcessRecord(std::shared_ptr record, uint32_t tokenId, bool isLocal, std::vector &uris); + static void SetRecordUid(UnifiedData &data); + static bool GetDetailsFromUData(const UnifiedData &data, UDDetails &details); + static Status GetSummaryFromDetails(const UDDetails &details, Summary &summary); private: static bool CheckUriAuthorization(const std::vector& uris, uint32_t tokenId); static int32_t GetDfsUrisFromLocal(const std::vector &uris, int32_t userId, UnifiedData &data); static bool IsFileType(std::shared_ptr record); + static std::string GetSdkVersionByToken(uint32_t tokenId); }; } // namespace UDMF } // namespace OHOS diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index a8dd78f5d7c7124d8af633f699eeb0e41e6acfa4..fa6f511e98b815d45800cf80844c12ecfaf13649 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -28,6 +28,7 @@ #include "bootstrap.h" #include "directory/directory_manager.h" #include "utils/anonymous.h" +#include "preprocess_utils.h" namespace OHOS { namespace UDMF { @@ -35,9 +36,7 @@ using namespace RadarReporter; using namespace DistributedDB; using Anonymous = OHOS::DistributedData::Anonymous; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; - -constexpr const char *TEMP_UNIFIED_DATA_FLAG = "temp_udmf_file_flag"; -static constexpr size_t TEMP_UDATA_RECORD_SIZE = 1; +constexpr const char *SUMMARY_SUFIX = "#summary"; RuntimeStore::RuntimeStore(const std::string &storeId) : storeId_(storeId) { @@ -99,6 +98,10 @@ Status RuntimeStore::Put(const UnifiedData &unifiedData) { UpdateTime(); std::vector entries; + std::string intention = unifiedData.GetRuntime()->key.intention; + if (intention == UD_INTENTION_MAP.at(UD_INTENTION_DRAG)) { + PutSummary(unifiedData, entries); + } auto status = DataHandler::MarshalToEntries(unifiedData, entries); if (status != E_OK) { return status; @@ -110,7 +113,7 @@ Status RuntimeStore::Get(const std::string &key, UnifiedData &unifiedData) { UpdateTime(); std::vector entries; - if (GetEntries(key, entries) != E_OK) { + if (GetEntries(UnifiedKey(key).GetKeyCommonPrefix(), entries) != E_OK) { ZLOGE("GetEntries failed, dataPrefix: %{public}s.", key.c_str()); return E_DB_ERROR; } @@ -121,70 +124,100 @@ Status RuntimeStore::Get(const std::string &key, UnifiedData &unifiedData) return DataHandler::UnmarshalEntries(key, entries, unifiedData); } -bool RuntimeStore::GetDetailsFromUData(UnifiedData &data, UDDetails &details) +Status RuntimeStore::PutSummary(const UnifiedData &data, std::vector &entries) { - auto records = data.GetRecords(); - if (records.size() != TEMP_UDATA_RECORD_SIZE) { - return false; - } - if (records[0] == nullptr || records[0]->GetType() != UDType::FILE) { - return false; - } - auto obj = std::get>(records[0]->GetOriginValue()); - if (obj == nullptr) { - ZLOGE("ValueType is not Object!"); - return false; + UpdateTime(); + UDDetails details {}; + Summary summary; + if (PreProcessUtils::GetDetailsFromUData(data, details)) { + PreProcessUtils::GetSummaryFromDetails(details, summary); + } else { + UnifiedDataHelper::GetSummary(data, summary); } - std::shared_ptr detailObj; - obj->GetValue(DETAILS, detailObj); - if (detailObj == nullptr) { - ZLOGE("Not contain details for object!"); - return false; - } - auto result = ObjectUtils::ConvertToUDDetails(detailObj); - if (result.find(TEMP_UNIFIED_DATA_FLAG) == result.end()) { - return false; + + auto propertyKey = data.GetRuntime()->key.GetKeyCommonPrefix(); + Value value; + auto status = DataHandler::MarshalToEntries(summary, value, TAG::TAG_SUMMARY); + if (status != E_OK) { + ZLOGE("Marshal summary failed, key: %{public}s, status:%{public}d", propertyKey.c_str(), status); + return status; } - details = result; - return true; + auto summaryKey = propertyKey + SUMMARY_SUFIX; + entries.push_back({{summaryKey.begin(), summaryKey.end()}, value}); + return E_OK; } -Status RuntimeStore::GetSummaryFromDetails(const UDDetails &details, Summary &summary) +Status RuntimeStore::GetSummary(UnifiedKey &key, Summary &summary) { - for (auto &item : details) { - if (item.first != TEMP_UNIFIED_DATA_FLAG) { - auto int64Value = std::get_if(&item.second); - if (int64Value != nullptr) { - auto size = std::get(item.second); - summary.summary[item.first] = size; - summary.totalSize += size; - } + UpdateTime(); + Value value; + auto summaryKey = key.GetKeyCommonPrefix() + SUMMARY_SUFIX; + auto res = kvStore_->Get({summaryKey.begin(), summaryKey.end()}, value); + if (res != OK || value.empty()) { + ZLOGW("Get stored summary failed, key: %{public}s, status:%{public}d", summaryKey.c_str(), res); + UnifiedData unifiedData; + auto udKey = key.GetUnifiedKey(); + if (Get(udKey, unifiedData) != E_OK) { + ZLOGE("Get unified data failed, key: %{public}s", udKey.c_str()); + return E_DB_ERROR; + } + UDDetails details {}; + if (PreProcessUtils::GetDetailsFromUData(unifiedData, details)) { + return PreProcessUtils::GetSummaryFromDetails(details, summary); } + UnifiedDataHelper::GetSummary(unifiedData, summary); + return E_OK; + } + auto status = DataHandler::UnmarshalEntries(value, summary, TAG::TAG_SUMMARY); + if (status != E_OK) { + ZLOGE("Unmarshal summary failed, key: %{public}s, status:%{public}d", summaryKey.c_str(), status); + return status; } return E_OK; } -Status RuntimeStore::GetSummary(const std::string &key, Summary &summary) +Status RuntimeStore::PutRuntime(const std::string &key, const Runtime &runtime) { UpdateTime(); - UnifiedData unifiedData; - if (Get(key, unifiedData) != E_OK) { - ZLOGE("Get unified data failed, dataPrefix: %{public}s", key.c_str()); + Value value; + auto status = DataHandler::MarshalToEntries(runtime, value, TAG::TAG_RUNTIME); + if (status != E_OK) { + ZLOGE("Marshal runtime failed, key: %{public}s, status:%{public}d", key.c_str(), status); + return status; + } + auto res = kvStore_->Put({key.begin(), key.end()}, value); + if (res != OK) { + ZLOGE("Put failed, key:%{public}s, status:%{public}d", key.c_str(), res); return E_DB_ERROR; } + return E_OK; +} - UDDetails details {}; - if (GetDetailsFromUData(unifiedData, details)) { - return GetSummaryFromDetails(details, summary); +Status RuntimeStore::GetRuntime(const std::string &key, Runtime &runtime) +{ + UpdateTime(); + Value value; + auto res = kvStore_->Get({key.begin(), key.end()}, value); + if (res == NOT_FOUND) { + ZLOGW("Runtime not found, key: %{public}s", key.c_str()); + return E_NOT_FOUND; + } + if (res != OK || value.empty()) { + ZLOGE("Get failed, key: %{public}s, status:%{public}d", key.c_str(), res); + return E_DB_ERROR; + } + auto status = DataHandler::UnmarshalEntries(value, runtime, TAG::TAG_RUNTIME); + if (status != E_OK) { + ZLOGE("Unmarshal runtime failed, key: %{public}s, status:%{public}d", key.c_str(), status); + return status; } - UnifiedDataHelper::GetSummary(unifiedData, summary); return E_OK; } Status RuntimeStore::Update(const UnifiedData &unifiedData) { std::string key = unifiedData.GetRuntime()->key.key; - if (Delete(key) != E_OK) { + if (Delete(UnifiedKey(key).GetKeyCommonPrefix()) != E_OK) { UpdateTime(); ZLOGE("Delete unified data failed, dataPrefix: %{public}s.", key.c_str()); return E_DB_ERROR; @@ -342,7 +375,8 @@ Status RuntimeStore::GetBatchData(const std::string &dataPrefix, std::vector keySet; for (const auto &entry : entries) { std::string keyStr = {entry.key.begin(), entry.key.end()}; - if (std::count(keyStr.begin(), keyStr.end(), '/') == SLASH_COUNT_IN_KEY) { + if (std::count(keyStr.begin(), keyStr.end(), '/') == SLASH_COUNT_IN_KEY && + std::count(keyStr.begin(), keyStr.end(), '#') == 0) { keySet.emplace_back(keyStr); } } @@ -488,7 +522,10 @@ void RuntimeStore::SetDelegateManager(const std::string &dataDir, const std::str { delegateManager_ = std::make_shared(appId, userId, subUser); DistributedDB::KvStoreConfig kvStoreConfig { dataDir }; - delegateManager_->SetKvStoreConfig(kvStoreConfig); + auto status = delegateManager_->SetKvStoreConfig(kvStoreConfig); + if (status != DBStatus::OK) { + ZLOGE("SetKvStoreConfig failed, status: %{public}d.", status); + } } Status RuntimeStore::GetEntries(const std::string &dataPrefix, std::vector &entries) diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.h b/services/distributeddataservice/service/udmf/store/runtime_store.h index 623b9204cff2ecc041fcddab7ba0cec8474c9c88..eb83a3503cefebf22a1a7ce15f9f801508ff7228 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.h +++ b/services/distributeddataservice/service/udmf/store/runtime_store.h @@ -30,7 +30,7 @@ public: ~RuntimeStore(); Status Put(const UnifiedData &unifiedData) override; Status Get(const std::string &key, UnifiedData &unifiedData) override; - Status GetSummary(const std::string &key, Summary &summary) override; + Status GetSummary(UnifiedKey &key, Summary &summary) override; Status Update(const UnifiedData &unifiedData) override; Status Delete(const std::string &key) override; Status DeleteBatch(const std::vector &unifiedKeys) override; @@ -41,6 +41,8 @@ public: Status PutLocal(const std::string &key, const std::string &value) override; Status GetLocal(const std::string &key, std::string &value) override; Status DeleteLocal(const std::string &key) override; + Status PutRuntime(const std::string &key, const Runtime &runtime) override; + Status GetRuntime(const std::string &key, Runtime &runtime) override; void Close() override; bool Init() override; @@ -59,11 +61,10 @@ private: Status DeleteEntries(const std::vector &keys); Status UnmarshalEntries( const std::string &key, std::vector &entries, UnifiedData &unifiedData); - bool GetDetailsFromUData(UnifiedData &data, UDDetails &details); - Status GetSummaryFromDetails(const UDDetails &details, Summary &summary); bool BuildMetaDataParam(DistributedData::StoreMetaData &metaData); void NotifySyncProcss(const DevSyncProcessMap &processMap, ProcessCallback callback, const DevNameMap &deviceNameMap); + Status PutSummary(const UnifiedData &data, std::vector &entries); }; } // namespace UDMF } // namespace OHOS diff --git a/services/distributeddataservice/service/udmf/store/store.h b/services/distributeddataservice/service/udmf/store/store.h index 1a728c3747b053c6d29edae9b2a6096771c00387..aaf6fade14404514789d4b98cedfbe8b1afbcff9 100644 --- a/services/distributeddataservice/service/udmf/store/store.h +++ b/services/distributeddataservice/service/udmf/store/store.h @@ -26,7 +26,7 @@ public: using Time = std::chrono::steady_clock::time_point; virtual Status Put(const UnifiedData &unifiedData) = 0; virtual Status Get(const std::string &key, UnifiedData &unifiedData) = 0; - virtual Status GetSummary(const std::string &key, Summary &summary) = 0; + virtual Status GetSummary(UnifiedKey &key, Summary &summary) = 0; virtual Status Update(const UnifiedData &unifiedData) = 0; virtual Status Delete(const std::string &key) = 0; virtual Status DeleteBatch(const std::vector &unifiedKeys) = 0; @@ -37,6 +37,8 @@ public: virtual Status PutLocal(const std::string &key, const std::string &value) = 0; virtual Status GetLocal(const std::string &key, std::string &value) = 0; virtual Status DeleteLocal(const std::string &key) = 0; + virtual Status PutRuntime(const std::string &key, const Runtime &runtime) = 0; + virtual Status GetRuntime(const std::string &key, Runtime &runtime) = 0; virtual bool Init() = 0; virtual void Close() = 0; diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index fc75e80b05d5272c71e5e30deb559f85a64320f3..42ef97a5d3a3385b69f5e8793a8b8eb184fc1e71 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -21,23 +21,29 @@ #include "tokenid_kit.h" #include "accesstoken_kit.h" +#include "bootstrap.h" +#include "bundle_info.h" +#include "bundlemgr/bundle_mgr_proxy.h" #include "checker_manager.h" +#include "device_manager_adapter.h" +#include "iservice_registry.h" #include "lifecycle/lifecycle_manager.h" #include "log_print.h" +#include "metadata/store_meta_data.h" +#include "metadata/meta_data_manager.h" #include "preprocess_utils.h" #include "reporter.h" +#include "store_account_observer.h" +#include "system_ability_definition.h" #include "uri_permission_manager.h" #include "udmf_radar_reporter.h" -#include "device_manager_adapter.h" -#include "store_account_observer.h" +#include "unified_data_helper.h" #include "utils/anonymous.h" -#include "bootstrap.h" -#include "metadata/store_meta_data.h" -#include "metadata/meta_data_manager.h" namespace OHOS { namespace UDMF { using namespace Security::AccessToken; +using namespace OHOS::DistributedHardware; using FeatureSystem = DistributedData::FeatureSystem; using UdmfBehaviourMsg = OHOS::DistributedDataDfx::UdmfBehaviourMsg; using Reporter = OHOS::DistributedDataDfx::Reporter; @@ -50,6 +56,9 @@ constexpr const char *DATA_PREFIX = "udmf://"; constexpr const char *FILE_SCHEME = "file"; constexpr const char *PRIVILEGE_READ_AND_KEEP = "readAndKeep"; constexpr const char *MANAGE_UDMF_APP_SHARE_OPTION = "ohos.permission.MANAGE_UDMF_APP_SHARE_OPTION"; +constexpr const char *DEVICE_2IN1_TAG = "2in1"; +constexpr const char *DEVICE_PHONE_TAG = "phone"; +constexpr const char *DEVICE_DEFAULT_TAG = "default"; constexpr const char *HAP_LIST[] = {"com.ohos.pasteboarddialog"}; __attribute__((used)) UdmfServiceImpl::Factory UdmfServiceImpl::factory_; UdmfServiceImpl::Factory::Factory() @@ -133,10 +142,7 @@ int32_t UdmfServiceImpl::SaveData(CustomOption &option, UnifiedData &unifiedData return ret; } } - - for (const auto &record : unifiedData.GetRecords()) { - record->SetUid(PreProcessUtils::GenerateId()); - } + PreProcessUtils::SetRecordUid(unifiedData); auto store = StoreCache::GetInstance().GetStore(intention); if (store == nullptr) { @@ -170,6 +176,7 @@ int32_t UdmfServiceImpl::GetData(const QueryOption &query, UnifiedData &unifiedD msg.appId = bundleName; res = RetrieveData(query, unifiedData); } + TransferToEntriesIfNeed(query, unifiedData); auto errFind = ERROR_MAP.find(res); msg.result = errFind == ERROR_MAP.end() ? "E_ERROR" : errFind->second; for (const auto &record : unifiedData.GetRecords()) { @@ -183,11 +190,23 @@ int32_t UdmfServiceImpl::GetData(const QueryOption &query, UnifiedData &unifiedD return res; } -int32_t UdmfServiceImpl::RetrieveData(const QueryOption &query, UnifiedData &unifiedData) +bool UdmfServiceImpl::CheckDragParams(UnifiedKey &key, const QueryOption &query) { - UnifiedKey key(query.key); if (!key.IsValid()) { ZLOGE("Unified key: %{public}s is invalid.", query.key.c_str()); + return false; + } + if (key.intention != UD_INTENTION_MAP.at(UD_INTENTION_DRAG)) { + ZLOGE("Invalid intention:%{public}s", key.intention.c_str()); + return false; + } + return true; +} + +int32_t UdmfServiceImpl::RetrieveData(const QueryOption &query, UnifiedData &unifiedData) +{ + UnifiedKey key(query.key); + if (!CheckDragParams(key, query)) { return E_INVALID_PARAMETERS; } auto store = StoreCache::GetInstance().GetStore(key.intention); @@ -399,9 +418,7 @@ int32_t UdmfServiceImpl::UpdateData(const QueryOption &query, UnifiedData &unifi } runtime->lastModifiedTime = PreProcessUtils::GetTimestamp(); unifiedData.SetRuntime(*runtime); - for (auto &record : unifiedData.GetRecords()) { - record->SetUid(PreProcessUtils::GenerateId()); - } + PreProcessUtils::SetRecordUid(unifiedData); if (store->Update(unifiedData) != E_OK) { ZLOGE("Unified data update failed:%{public}s", key.intention.c_str()); return E_DB_ERROR; @@ -432,7 +449,7 @@ int32_t UdmfServiceImpl::DeleteData(const QueryOption &query, std::vectortokenId == query.tokenId) { unifiedDataSet.push_back(data); - deleteKeys.push_back(runtime->key.key); + deleteKeys.push_back(UnifiedKey(runtime->key.key).GetKeyCommonPrefix()); } } if (deleteKeys.empty()) { @@ -462,7 +479,7 @@ int32_t UdmfServiceImpl::GetSummary(const QueryOption &query, Summary &summary) return E_DB_ERROR; } - if (store->GetSummary(query.key, summary) != E_OK) { + if (store->GetSummary(key, summary) != E_OK) { ZLOGE("Store get summary failed:%{public}s", key.intention.c_str()); return E_DB_ERROR; } @@ -500,26 +517,23 @@ int32_t UdmfServiceImpl::AddPrivilege(const QueryOption &query, Privilege &privi return E_DB_ERROR; } - UnifiedData data; - int32_t res = store->Get(query.key, data); + Runtime runtime; + auto res = store->GetRuntime(query.key, runtime); if (res == E_NOT_FOUND) { privilegeCache_[query.key] = privilege; ZLOGW("Add privilege in cache, key: %{public}s.", query.key.c_str()); return E_OK; } if (res != E_OK) { - ZLOGE("Get data from store failed, res:%{public}d,intention: %{public}s.", res, key.intention.c_str()); + ZLOGE("Get runtime failed, res:%{public}d, key:%{public}s.", res, query.key.c_str()); return res; } - if (data.GetRuntime() == nullptr) { - return E_DB_ERROR; - } - data.GetRuntime()->privileges.emplace_back(privilege); - if (store->Update(data) != E_OK) { - ZLOGE("Update unified data failed:%{public}s", key.intention.c_str()); - return E_DB_ERROR; + runtime.privileges.emplace_back(privilege); + res = store->PutRuntime(query.key, runtime); + if (res != E_OK) { + ZLOGE("Update runtime failed, res:%{public}d, key:%{public}s", res, query.key.c_str()); } - return E_OK; + return res; } int32_t UdmfServiceImpl::Sync(const QueryOption &query, const std::vector &devices) @@ -534,6 +548,14 @@ int32_t UdmfServiceImpl::Sync(const QueryOption &query, const std::vector syncDevices; + for (auto const &device : devices) { + if (!DistributedData::DeviceManagerAdapter::GetInstance().IsSameAccount(device)) { + ZLOGW("is diff account. device:%{public}s", DistributedData::Anonymous::Change(device).c_str()); + continue; + } + syncDevices.emplace_back(device); + } RegisterAsyncProcessInfo(query.key); auto store = StoreCache::GetInstance().GetStore(key.intention); if (store == nullptr) { @@ -555,7 +577,7 @@ int32_t UdmfServiceImpl::Sync(const QueryOption &query, const std::vectorSync(devices, callback) != E_OK) { + if (store->Sync(syncDevices, callback) != E_OK) { ZLOGE("Store sync failed:%{public}s", key.intention.c_str()); RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, E_DB_ERROR, BizState::DFX_END); @@ -578,19 +600,15 @@ int32_t UdmfServiceImpl::IsRemoteData(const QueryOption &query, bool &result) return E_DB_ERROR; } - UnifiedData unifiedData; - if (store->Get(query.key, unifiedData) != E_OK) { - ZLOGE("Store get unifiedData failed:%{public}s", key.intention.c_str()); - return E_DB_ERROR; - } - std::shared_ptr runtime = unifiedData.GetRuntime(); - if (runtime == nullptr) { - ZLOGE("Store get runtime failed, key: %{public}s.", query.key.c_str()); + Runtime runtime; + auto res = store->GetRuntime(query.key, runtime); + if (res != E_OK) { + ZLOGE("Get runtime failed, res:%{public}d, key:%{public}s.", res, query.key.c_str()); return E_DB_ERROR; } std::string localDeviceId = PreProcessUtils::GetLocalDeviceId(); - if (localDeviceId != runtime->deviceId) { + if (localDeviceId != runtime.deviceId) { result = true; } return E_OK; @@ -699,15 +717,16 @@ int32_t UdmfServiceImpl::QueryDataCommon( { auto find = UD_INTENTION_MAP.find(query.intention); std::string intention = find == UD_INTENTION_MAP.end() ? intention : find->second; - if (!UnifiedDataUtils::IsValidOptions(query.key, intention)) { + UnifiedKey key(query.key); + if (!UnifiedDataUtils::IsValidOptions(key, intention, UD_INTENTION_MAP.at(UD_INTENTION_DATA_HUB))) { ZLOGE("Unified key: %{public}s and intention: %{public}s is invalid.", query.key.c_str(), intention.c_str()); return E_INVALID_PARAMETERS; } - std::string dataPrefix = DATA_PREFIX + intention; - UnifiedKey key(query.key); - key.IsValid(); - if (intention.empty()) { - dataPrefix = key.key; + std::string dataPrefix; + if (key.key.empty()) { + dataPrefix = DATA_PREFIX + intention; + } else { + dataPrefix = UnifiedKey(key.key).GetKeyCommonPrefix(); intention = key.intention; } ZLOGD("dataPrefix = %{public}s, intention: %{public}s.", dataPrefix.c_str(), intention.c_str()); @@ -838,5 +857,54 @@ int32_t UdmfServiceImpl::OnUserChange(uint32_t code, const std::string &user, co } return Feature::OnUserChange(code, user, account); } + +void UdmfServiceImpl::TransferToEntriesIfNeed(const QueryOption &query, UnifiedData &unifiedData) +{ + if (unifiedData.IsNeedTransferToEntries() && IsNeedTransferDeviceType(query)) { + unifiedData.ConvertRecordsToEntries(); + } +} + +bool UdmfServiceImpl::IsNeedTransferDeviceType(const QueryOption &query) +{ + auto deviceInfo = DmAdapter::GetInstance().GetLocalDevice(); + if (deviceInfo.deviceType != DEVICE_TYPE_PC && deviceInfo.deviceType != DEVICE_TYPE_PAD + && deviceInfo.deviceType != DEVICE_TYPE_2IN1) { + return false; + } + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + ZLOGE("Failed to get system ability mgr."); + return false; + } + auto bundleMgrProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (bundleMgrProxy == nullptr) { + ZLOGE("Failed to Get BMS SA."); + return false; + } + auto bundleManager = iface_cast(bundleMgrProxy); + if (bundleManager == nullptr) { + ZLOGE("Failed to get bundle manager"); + return false; + } + std::string bundleName; + PreProcessUtils::GetHapBundleNameByToken(query.tokenId, bundleName); + int32_t userId = DistributedData::AccountDelegate::GetInstance()->GetUserByToken( + IPCSkeleton::GetCallingFullTokenID()); + AppExecFwk::BundleInfo bundleInfo; + bundleManager->GetBundleInfoV9(bundleName, static_cast( + AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE), bundleInfo, userId); + for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) { + if (std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), + DEVICE_PHONE_TAG) == hapModuleInfo.deviceTypes.end() + && std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), + DEVICE_DEFAULT_TAG) == hapModuleInfo.deviceTypes.end() + && std::find(hapModuleInfo.deviceTypes.begin(), hapModuleInfo.deviceTypes.end(), + DEVICE_2IN1_TAG) != hapModuleInfo.deviceTypes.end()) { + return true; + } + } + return false; +} } // namespace UDMF } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.h b/services/distributeddataservice/service/udmf/udmf_service_impl.h index 93082d45a19df6e4ad212444e817a7762708ae76..da95d6eb4dc8abacaed2fefe39abd2c7395f8d70 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.h +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.h @@ -58,6 +58,9 @@ private: bool VerifyPermission(const std::string &permission, uint32_t callerTokenId); bool HasDatahubPriviledge(const std::string &bundleName); void RegisterAsyncProcessInfo(const std::string &businessUdKey); + void TransferToEntriesIfNeed(const QueryOption &query, UnifiedData &unifiedData); + bool IsNeedTransferDeviceType(const QueryOption &query); + bool CheckDragParams(UnifiedKey &key, const QueryOption &query); class Factory { public: