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/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index f3f912893b8e5116624b87af6f4ac5a03609c808..392b903b0cad9ccda72ea0ddba16b33315792e8b 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -41,6 +41,7 @@ config("module_private_config") { "${data_service_path}/app/src", "${data_service_path}/app/src/session_manager", "${data_service_path}/service/kvdb", + "${data_service_path}/service/test/mock", "${device_manager_path}/interfaces/inner_kits/native_cpp/include", "//commonlibrary/c_utils/base/include", "//utils/system/safwk/native/include", @@ -153,6 +154,7 @@ ohos_unittest("SessionManagerTest") { cfi = true cfi_cross_dso = true debug = false + blocklist = "${datamgr_service_path}/cfi_blocklist.txt" } cflags_cc = [ "-DUT_TEST" ] @@ -166,6 +168,7 @@ ohos_unittest("SessionManagerTest") { "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", "file_api:securitylabel", + "googletest:gmock", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", @@ -183,6 +186,7 @@ ohos_unittest("SessionManagerTest") { deps = [ "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/app/src/checker:distributeddata_checker", + "${data_service_path}/service/test/mock:distributeddata_mock_static", "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc", diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index 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/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 022dd5ef9250c996d52979b7e4c565ce6e7f1fa9..3c7201c8b92e8239737075f1fbe1d0460cb75dd8 100755 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -656,9 +656,9 @@ ohos_unittest("RdbServiceImplTest") { } module_out_path = module_output_path sources = [ + "mock/checker_mock.cpp", "mock/db_change_data_mock.cpp", "mock/db_store_mock.cpp", - "mock/checker_mock.cpp", "rdb_service_impl_test.cpp", ] @@ -1165,6 +1165,12 @@ ohos_unittest("DataShareServiceImplTest") { ohos_unittest("KvdbServiceImplTest") { module_out_path = module_output_path + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${datamgr_service_path}/cfi_blocklist.txt" + } sources = [ "${data_service_path}/app/src/kvstore_meta_manager.cpp", "kvdb_service_impl_test.cpp", diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index a59b778e267bdfd66786ca62d0449171a980dfe2..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,18 +27,18 @@ #include "distributed_kv_data_manager.h" #include "event_center.h" #include "ipc_skeleton.h" -#include "kvdb_service_stub.h" #include "kvdb_query.h" +#include "kvdb_service_impl.h" +#include "kvdb_service_stub.h" #include "kvstore_death_recipient.h" #include "kvstore_meta_manager.h" #include "kvstore_sync_manager.h" #include "log_print.h" -#include #include "mock/access_token_mock.h" #include "mock/meta_data_manager_mock.h" +#include "nativetoken_kit.h" #include "network_delegate.h" #include "network_delegate_mock.h" -#include "nativetoken_kit.h" #include "token_setproc.h" #include "types.h" #include "utils/anonymous.h" @@ -66,6 +66,7 @@ using StoreMetaData = OHOS::DistributedData::StoreMetaData; using SyncEnd = OHOS::DistributedKv::KvStoreSyncManager::SyncEnd; using DBResult = std::map; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; +using DBLaunchParam = OHOS::DistributedKv::KVDBServiceImpl::DBLaunchParam; static OHOS::DistributedKv::StoreId storeId = { "kvdb_test_storeid" }; static OHOS::DistributedKv::AppId appId = { "ohos.test.kvdb" }; static constexpr const char *TEST_USER = "0"; @@ -75,8 +76,11 @@ 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; @@ -92,7 +96,7 @@ public: static void RemoveAllStore(OHOS::DistributedKv::DistributedKvDataManager &manager); void SetUp(); void TearDown(); - + void CreateStoreMetaData(std::vector &datas, DBLaunchParam param); KvdbServiceImplTest(); protected: @@ -152,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_); } @@ -165,6 +171,8 @@ void KvdbServiceImplTest::TearDownTestCase() BAccessTokenKit::accessTokenkit = nullptr; metaDataManagerMock = nullptr; BMetaDataManager::metaDataManager = nullptr; + metaDataMock = nullptr; + BMetaData::metaDataManager = nullptr; } void KvdbServiceImplTest::SetUp(void) @@ -193,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 @@ -231,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); } @@ -256,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)); @@ -320,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); @@ -338,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); @@ -353,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); @@ -369,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); @@ -386,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 @@ -464,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; @@ -548,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); @@ -569,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); @@ -587,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); } @@ -611,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); } @@ -651,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; @@ -687,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); @@ -712,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); } /** @@ -765,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); @@ -790,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); @@ -872,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; @@ -896,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); } @@ -929,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; @@ -1061,6 +1143,7 @@ HWTEST_F(KvdbServiceImplTest, ResolveAutoLaunch, TestSize.Level0) EXPECT_EQ(status, Status::SUCCESS); std::string identifier = "identifier"; DistributedKv::KVDBServiceImpl::DBLaunchParam launchParam; + launchParam.userId = "user1"; auto result = kvdbServiceImpl_->ResolveAutoLaunch(identifier, launchParam); EXPECT_EQ(result, Status::STORE_NOT_FOUND); std::shared_ptr executors = std::make_shared(1, 0); @@ -1069,6 +1152,10 @@ HWTEST_F(KvdbServiceImplTest, ResolveAutoLaunch, TestSize.Level0) DistributedKv::KvStoreMetaManager::GetInstance().BindExecutor(executors); DistributedKv::KvStoreMetaManager::GetInstance().InitMetaParameter(); DistributedKv::KvStoreMetaManager::GetInstance().InitMetaListener(); + std::vector datas; + CreateStoreMetaData(datas, launchParam); + EXPECT_CALL(*metaDataMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillRepeatedly(testing::DoAll(testing::SetArgReferee<1>(datas), testing::Return(true))); result = kvdbServiceImpl_->ResolveAutoLaunch(identifier, launchParam); EXPECT_EQ(result, Status::SUCCESS); } @@ -1082,7 +1169,7 @@ HWTEST_F(KvdbServiceImplTest, ResolveAutoLaunch, TestSize.Level0) HWTEST_F(KvdbServiceImplTest, IsNeedSyncTest, TestSize.Level0) { StoreMetaData meta = kvdbServiceImpl_->GetStoreMetaData(appId, storeId); - std::vector devices= {"IsNeedSyncTest"}; + std::vector devices = { "IsNeedSyncTest" }; auto changes = kvdbServiceImpl_->IsNeedSync(meta, devices); EXPECT_EQ(changes, false); } @@ -1317,25 +1404,25 @@ HWTEST_F(KvdbServiceImplTest, DoCloudSync01, TestSize.Level0) HWTEST_F(KvdbServiceImplTest, OnAsyncCompleteTest002, TestSize.Level0) { DistributedKv::Statistic upload; - upload.failed = 1; // test - upload.success = 1; // test - upload.total = 1; // test + upload.failed = 1; // test + upload.success = 1; // test + upload.total = 1; // test upload.untreated = 1; // test DistributedKv::Statistic download; - download.failed = 1; // test - download.success = 1; // test - download.total = 1; // test + download.failed = 1; // test + download.success = 1; // test + download.total = 1; // test download.untreated = 1; // test DistributedKv::TableDetail details; details.download = download; details.upload = upload; DistributedKv::ProgressDetail detail; - detail.code = 1; // test + detail.code = 1; // test detail.progress = 1; // test detail.details = details; DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; sptr notifier = nullptr; - syncAgent.pid_ = 1; // test + syncAgent.pid_ = 1; // test syncAgent.switchesObserverCount_ = 1; // test syncAgent.appId_ = { "ohos.OnAsyncCompleteTest.kvdb" }; syncAgent.notifier_ = notifier; @@ -1359,7 +1446,7 @@ HWTEST_F(KvdbServiceImplTest, OnAsyncCompleteTest003, TestSize.Level0) { DistributedKv::KVDBServiceImpl::SyncAgent syncAgent; sptr notifier; - syncAgent.pid_ = 1; // test + syncAgent.pid_ = 1; // test syncAgent.switchesObserverCount_ = 1; // test syncAgent.appId_ = { "ohos.OnAsyncCompleteTest001.kvdb" }; syncAgent.notifier_ = notifier; @@ -1431,12 +1518,14 @@ HWTEST_F(KvdbServiceImplTest, syncTest003, TestSize.Level0) SyncInfo syncInfo; syncInfo.seqId = std::numeric_limits::max(); EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(true)).WillRepeatedly(testing::Return(true)); + .WillOnce(testing::Return(true)) + .WillRepeatedly(testing::Return(true)); auto status = kvdbServiceImpl_->Sync(appId, storeId, 0, syncInfo); EXPECT_EQ(localMeta.HasPolicy(DistributedKv::IMMEDIATE_SYNC_ON_CHANGE), false); EXPECT_NE(status, Status::SUCCESS); EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(false)).WillRepeatedly(testing::Return(false)); + .WillOnce(testing::Return(false)) + .WillRepeatedly(testing::Return(false)); status = kvdbServiceImpl_->Sync(appId, storeId, 0, syncInfo); EXPECT_EQ(localMeta.HasPolicy(DistributedKv::IMMEDIATE_SYNC_ON_ONLINE), true); } @@ -1472,7 +1561,7 @@ HWTEST_F(KvdbServiceImplTest, GetSyncParamTest002, TestSize.Level0) HWTEST_F(KvdbServiceImplTest, SubscribeSwitchData, TestSize.Level0) { options_.isNeedCompress = false; - std::vector password {}; + std::vector password{}; StoreMetaData metaData; auto status = kvdbServiceImpl_->AfterCreate(appId, storeId, options_, password); ASSERT_EQ(status, Status::SUCCESS); 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/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/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) {}