1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #define LOG_TAG "KVDBGeneralStoreTest"
16 
17 #include "kvdb_general_store.h"
18 
19 #include <gtest/gtest.h>
20 #include <random>
21 #include <thread>
22 
23 #include "bootstrap.h"
24 #include "cloud/schema_meta.h"
25 #include "cloud/asset_loader.h"
26 #include "cloud/cloud_db.h"
27 #include "crypto_manager.h"
28 #include "kvdb_query.h"
29 #include "kv_store_nb_delegate_mock.h"
30 #include "log_print.h"
31 #include "metadata/meta_data_manager.h"
32 #include "metadata/secret_key_meta_data.h"
33 #include "metadata/store_meta_data.h"
34 #include "metadata/store_meta_data_local.h"
35 #include "mock/db_store_mock.h"
36 #include "mock/general_watcher_mock.h"
37 
38 using namespace testing::ext;
39 using namespace DistributedDB;
40 using namespace OHOS::DistributedData;
41 using DBStoreMock = OHOS::DistributedData::DBStoreMock;
42 using StoreMetaData = OHOS::DistributedData::StoreMetaData;
43 using SecurityLevel = OHOS::DistributedKv::SecurityLevel;
44 using KVDBGeneralStore = OHOS::DistributedKv::KVDBGeneralStore;
45 namespace OHOS::Test {
46 namespace DistributedDataTest {
47 class KVDBGeneralStoreTest : public testing::Test {
48 public:
49     static void SetUpTestCase(void);
50     static void TearDownTestCase(void);
51     void SetUp();
52     void TearDown();
53 protected:
54     static constexpr const char *BUNDLE_NAME = "test_distributeddata";
55     static constexpr const char *STORE_NAME = "test_service_meta";
56 
57     void InitMetaData();
58     static std::vector<uint8_t> Random(uint32_t len);
59     static std::shared_ptr<DBStoreMock> dbStoreMock_;
60     StoreMetaData metaData_;
61 };
62 
63 std::shared_ptr<DBStoreMock> KVDBGeneralStoreTest::dbStoreMock_ = std::make_shared<DBStoreMock>();
64 static const uint32_t KEY_LENGTH = 32;
65 static const uint32_t ENCRYPT_KEY_LENGTH = 48;
66 
InitMetaData()67 void KVDBGeneralStoreTest::InitMetaData()
68 {
69     metaData_.bundleName = BUNDLE_NAME;
70     metaData_.appId = BUNDLE_NAME;
71     metaData_.user = "0";
72     metaData_.area = OHOS::DistributedKv::EL1;
73     metaData_.instanceId = 0;
74     metaData_.isAutoSync = true;
75     metaData_.storeType = DistributedKv::KvStoreType::SINGLE_VERSION;
76     metaData_.storeId = STORE_NAME;
77     metaData_.dataDir = "/data/service/el1/public/database/" + std::string(BUNDLE_NAME) + "/kvdb";
78     metaData_.securityLevel = SecurityLevel::S2;
79 }
80 
Random(uint32_t len)81 std::vector<uint8_t> KVDBGeneralStoreTest::Random(uint32_t len)
82 {
83     std::random_device randomDevice;
84     std::uniform_int_distribution<int> distribution(0, std::numeric_limits<uint8_t>::max());
85     std::vector<uint8_t> key(len);
86     for (uint32_t i = 0; i < len; i++) {
87         key[i] = static_cast<uint8_t>(distribution(randomDevice));
88     }
89     return key;
90 }
91 
SetUpTestCase(void)92 void KVDBGeneralStoreTest::SetUpTestCase(void)
93 {
94 }
95 
TearDownTestCase()96 void KVDBGeneralStoreTest::TearDownTestCase() {}
97 
SetUp()98 void KVDBGeneralStoreTest::SetUp()
99 {
100     Bootstrap::GetInstance().LoadDirectory();
101     InitMetaData();
102 }
103 
TearDown()104 void KVDBGeneralStoreTest::TearDown() {}
105 
106 class MockGeneralWatcher : public DistributedData::GeneralWatcher {
107 public:
OnChange(const Origin & origin,const PRIFields & primaryFields,ChangeInfo && values)108     int32_t OnChange(const Origin &origin, const PRIFields &primaryFields, ChangeInfo &&values) override
109     {
110         return GeneralError::E_OK;
111     }
112 
OnChange(const Origin & origin,const Fields & fields,ChangeData && datas)113     int32_t OnChange(const Origin &origin, const Fields &fields, ChangeData &&datas) override
114     {
115         return GeneralError::E_OK;
116     }
117 };
118 
119 class MockKvStoreChangedData : public DistributedDB::KvStoreChangedData {
120 public:
MockKvStoreChangedData()121     MockKvStoreChangedData() {}
~MockKvStoreChangedData()122     virtual ~MockKvStoreChangedData() {}
123     std::list<DistributedDB::Entry> entriesInserted = {};
124     std::list<DistributedDB::Entry> entriesUpdated = {};
125     std::list<DistributedDB::Entry> entriesDeleted = {};
126     bool isCleared = true;
GetEntriesInserted() const127     const std::list<DistributedDB::Entry>& GetEntriesInserted() const override
128     {
129         return entriesInserted;
130     }
131 
GetEntriesUpdated() const132     const std::list<DistributedDB::Entry>& GetEntriesUpdated() const override
133     {
134         return entriesUpdated;
135     }
136 
GetEntriesDeleted() const137     const std::list<Entry>& GetEntriesDeleted() const override
138     {
139         return entriesDeleted;
140     }
141 
IsCleared() const142     bool IsCleared() const override
143     {
144         return isCleared;
145     }
146 };
147 
148 /**
149 * @tc.name: GetDBPasswordTest_001
150 * @tc.desc: GetDBPassword from meta.
151 * @tc.type: FUNC
152 * @tc.require:
153 * @tc.author: Hollokin
154 */
155 HWTEST_F(KVDBGeneralStoreTest, GetDBPasswordTest_001, TestSize.Level0)
156 {
157     ZLOGI("GetDBPasswordTest start");
158     MetaDataManager::GetInstance().Initialize(dbStoreMock_, nullptr);
159     EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, true));
160     EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(metaData_.GetSecretKey(), metaData_, true));
161     auto dbPassword = KVDBGeneralStore::GetDBPassword(metaData_);
162     ASSERT_TRUE(dbPassword.GetSize() == 0);
163 }
164 
165 /**
166 * @tc.name: GetDBPasswordTest_002
167 * @tc.desc: GetDBPassword from encrypt meta.
168 * @tc.type: FUNC
169 * @tc.require:
170 * @tc.author: Hollokin
171 */
172 HWTEST_F(KVDBGeneralStoreTest, GetDBPasswordTest_002, TestSize.Level0)
173 {
174     ZLOGI("GetDBPasswordTest_002 start");
175     MetaDataManager::GetInstance().Initialize(dbStoreMock_, nullptr);
176     metaData_.isEncrypt = true;
177     EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, true));
178 
179     auto errCode = CryptoManager::GetInstance().GenerateRootKey();
180     EXPECT_EQ(errCode, CryptoManager::ErrCode::SUCCESS);
181 
182     std::vector<uint8_t> randomKey = Random(KEY_LENGTH);
183     SecretKeyMetaData secretKey;
184     secretKey.storeType = metaData_.storeType;
185     secretKey.sKey = CryptoManager::GetInstance().Encrypt(randomKey);
186     EXPECT_EQ(secretKey.sKey.size(), ENCRYPT_KEY_LENGTH);
187     EXPECT_TRUE(MetaDataManager::GetInstance().SaveMeta(metaData_.GetSecretKey(), secretKey, true));
188 
189     auto dbPassword = KVDBGeneralStore::GetDBPassword(metaData_);
190     ASSERT_TRUE(dbPassword.GetSize() != 0);
191     randomKey.assign(randomKey.size(), 0);
192 }
193 
194 /**
195 * @tc.name: GetDBSecurityTest
196 * @tc.desc: GetDBSecurity
197 * @tc.type: FUNC
198 * @tc.require:
199 * @tc.author: Hollokin
200 */
201 HWTEST_F(KVDBGeneralStoreTest, GetDBSecurityTest, TestSize.Level0)
202 {
203     auto dbSecurity = KVDBGeneralStore::GetDBSecurity(SecurityLevel::INVALID_LABEL);
204     EXPECT_EQ(dbSecurity.securityLabel, DistributedDB::NOT_SET);
205     EXPECT_EQ(dbSecurity.securityFlag, DistributedDB::ECE);
206 
207     dbSecurity = KVDBGeneralStore::GetDBSecurity(SecurityLevel::NO_LABEL);
208     EXPECT_EQ(dbSecurity.securityLabel, DistributedDB::NOT_SET);
209     EXPECT_EQ(dbSecurity.securityFlag, DistributedDB::ECE);
210 
211     dbSecurity = KVDBGeneralStore::GetDBSecurity(SecurityLevel::S0);
212     EXPECT_EQ(dbSecurity.securityLabel, DistributedDB::S0);
213     EXPECT_EQ(dbSecurity.securityFlag, DistributedDB::ECE);
214 
215     dbSecurity = KVDBGeneralStore::GetDBSecurity(SecurityLevel::S1);
216     EXPECT_EQ(dbSecurity.securityLabel, DistributedDB::S1);
217     EXPECT_EQ(dbSecurity.securityFlag, DistributedDB::ECE);
218 
219     dbSecurity = KVDBGeneralStore::GetDBSecurity(SecurityLevel::S2);
220     EXPECT_EQ(dbSecurity.securityLabel, DistributedDB::S2);
221     EXPECT_EQ(dbSecurity.securityFlag, DistributedDB::ECE);
222 
223     dbSecurity = KVDBGeneralStore::GetDBSecurity(SecurityLevel::S3);
224     EXPECT_EQ(dbSecurity.securityLabel, DistributedDB::S3);
225     EXPECT_EQ(dbSecurity.securityFlag, DistributedDB::SECE);
226 
227     dbSecurity = KVDBGeneralStore::GetDBSecurity(SecurityLevel::S4);
228     EXPECT_EQ(dbSecurity.securityLabel, DistributedDB::S4);
229     EXPECT_EQ(dbSecurity.securityFlag, DistributedDB::ECE);
230 
231     auto action = static_cast<int32_t>(SecurityLevel::S4 + 1);
232     dbSecurity = KVDBGeneralStore::GetDBSecurity(action);
233     EXPECT_EQ(dbSecurity.securityLabel, DistributedDB::NOT_SET);
234     EXPECT_EQ(dbSecurity.securityFlag, DistributedDB::ECE);
235 }
236 
237 /**
238 * @tc.name: GetDBOptionTest
239 * @tc.desc: GetDBOption from meta and dbPassword
240 * @tc.type: FUNC
241 * @tc.require:
242 * @tc.author: Hollokin
243 */
244 HWTEST_F(KVDBGeneralStoreTest, GetDBOptionTest, TestSize.Level0)
245 {
246     metaData_.isEncrypt = true;
247     auto dbPassword = KVDBGeneralStore::GetDBPassword(metaData_);
248     auto dbOption = KVDBGeneralStore::GetDBOption(metaData_, dbPassword);
249     EXPECT_EQ(dbOption.syncDualTupleMode, true);
250     EXPECT_EQ(dbOption.createIfNecessary, false);
251     EXPECT_EQ(dbOption.isMemoryDb, false);
252     EXPECT_EQ(dbOption.isEncryptedDb, metaData_.isEncrypt);
253     EXPECT_EQ(dbOption.isNeedCompressOnSync, metaData_.isNeedCompress);
254     EXPECT_EQ(dbOption.schema, metaData_.schema);
255     EXPECT_EQ(dbOption.passwd, dbPassword);
256     EXPECT_EQ(dbOption.cipher, DistributedDB::CipherType::AES_256_GCM);
257     EXPECT_EQ(dbOption.conflictResolvePolicy, DistributedDB::LAST_WIN);
258     EXPECT_EQ(dbOption.createDirByStoreIdOnly, true);
259     EXPECT_EQ(dbOption.secOption, KVDBGeneralStore::GetDBSecurity(metaData_.securityLevel));
260 }
261 
262 /**
263 * @tc.name: CloseTest
264 * @tc.desc: Close kvdb general store and  test the functionality of different branches.
265 * @tc.type: FUNC
266 * @tc.require:
267 * @tc.author: Hollokin
268 */
269 HWTEST_F(KVDBGeneralStoreTest, CloseTest, TestSize.Level0)
270 {
271     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
272     ASSERT_NE(store, nullptr);
273     auto ret = store->Close();
274     EXPECT_EQ(ret, GeneralError::E_OK);
275 
276     KvStoreNbDelegateMock mockDelegate;
277     mockDelegate.taskCountMock_ = 1;
278     store->delegate_ = &mockDelegate;
279     EXPECT_NE(store->delegate_, nullptr);
280     ret = store->Close();
281     EXPECT_EQ(ret, GeneralError::E_BUSY);
282 }
283 
284 /**
285 * @tc.name: Close
286 * @tc.desc: RdbGeneralStore Close test
287 * @tc.type: FUNC
288 * @tc.require:
289 * @tc.author: shaoyuanzhao
290 */
291 HWTEST_F(KVDBGeneralStoreTest, BusyClose, TestSize.Level0)
292 {
293     auto store = std::make_shared<KVDBGeneralStore>(metaData_);
294     ASSERT_NE(store, nullptr);
__anondde6d9770102() 295     std::thread thread([store]() {
296         std::unique_lock<decltype(store->rwMutex_)> lock(store->rwMutex_);
297         std::this_thread::sleep_for(std::chrono::seconds(1));
298     });
299     std::this_thread::sleep_for(std::chrono::milliseconds(500));
300     auto ret = store->Close();
301     EXPECT_EQ(ret, GeneralError::E_BUSY);
302     thread.join();
303     ret = store->Close();
304     EXPECT_EQ(ret, GeneralError::E_OK);
305 }
306 
307 /**
308 * @tc.name: SyncTest
309 * @tc.desc: Sync.
310 * @tc.type: FUNC
311 * @tc.require:
312 * @tc.author: Hollokin
313 */
314 HWTEST_F(KVDBGeneralStoreTest, SyncTest, TestSize.Level0)
315 {
316     ZLOGI("SyncTest start");
317     mkdir(("/data/service/el1/public/database/" + std::string(BUNDLE_NAME)).c_str(),
318         (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH));
319     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
320     ASSERT_NE(store, nullptr);
321     uint32_t syncMode = GeneralStore::SyncMode::NEARBY_SUBSCRIBE_REMOTE;
322     uint32_t highMode = GeneralStore::HighMode::MANUAL_SYNC_MODE;
323     auto mixMode = GeneralStore::MixMode(syncMode, highMode);
324     std::string kvQuery = "";
325     DistributedKv::KVDBQuery query(kvQuery);
326     SyncParam syncParam{};
327     syncParam.mode = mixMode;
328     auto ret = store->Sync(
__anondde6d9770202(const GenDetails &result) 329         {}, query, [](const GenDetails &result) {}, syncParam);
330     EXPECT_NE(ret.first, GeneralError::E_OK);
331     auto status = store->Close();
332     EXPECT_EQ(status, GeneralError::E_OK);
333 }
334 
335 /**
336 * @tc.name: BindTest
337 * @tc.desc: Bind test the functionality of different branches.
338 * @tc.type: FUNC
339 * @tc.require:
340 * @tc.author: SQL
341 */
342 HWTEST_F(KVDBGeneralStoreTest, BindTest, TestSize.Level0)
343 {
344     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
345     ASSERT_NE(store, nullptr);
346     DistributedData::Database database;
347     std::map<uint32_t, GeneralStore::BindInfo> bindInfos;
348     GeneralStore::CloudConfig config;
349     EXPECT_EQ(bindInfos.empty(), true);
350     auto ret = store->Bind(database, bindInfos, config);
351     EXPECT_EQ(ret, GeneralError::E_OK);
352 
353     std::shared_ptr<CloudDB> db;
354     std::shared_ptr<AssetLoader> loader;
355     GeneralStore::BindInfo bindInfo1(db, loader);
356     uint32_t key = 1;
357     bindInfos[key] = bindInfo1;
358     ret = store->Bind(database, bindInfos, config);
359     EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS);
360     std::shared_ptr<CloudDB> dbs = std::make_shared<CloudDB>();
361     std::shared_ptr<AssetLoader> loaders = std::make_shared<AssetLoader>();
362     GeneralStore::BindInfo bindInfo2(dbs, loaders);
363     bindInfos[key] = bindInfo2;
364     EXPECT_EQ(store->IsBound(), false);
365     ret = store->Bind(database, bindInfos, config);
366     EXPECT_EQ(ret, GeneralError::E_ALREADY_CLOSED);
367 
368     store->isBound_ = false;
369     KvStoreNbDelegateMock mockDelegate;
370     store->delegate_ = &mockDelegate;
371     EXPECT_NE(store->delegate_, nullptr);
372     EXPECT_EQ(store->IsBound(), false);
373     ret = store->Bind(database, bindInfos, config);
374     EXPECT_EQ(ret, GeneralError::E_OK);
375 
376     EXPECT_EQ(store->IsBound(), true);
377     ret = store->Bind(database, bindInfos, config);
378     EXPECT_EQ(ret, GeneralError::E_OK);
379 }
380 
381 /**
382 * @tc.name: GetDBSyncCompleteCB
383 * @tc.desc: GetDBSyncCompleteCB test the functionality of different branches.
384 * @tc.type: FUNC
385 * @tc.require:
386 * @tc.author: SQL
387 */
388 HWTEST_F(KVDBGeneralStoreTest, GetDBSyncCompleteCB, TestSize.Level0)
389 {
390     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
391     ASSERT_NE(store, nullptr);
392     GeneralStore::DetailAsync async;
393     EXPECT_EQ(async, nullptr);
394     KVDBGeneralStore::DBSyncCallback ret = store->GetDBSyncCompleteCB(async);
395     EXPECT_NE(ret, nullptr);
__anondde6d9770302(const GenDetails &result) 396     auto asyncs = [](const GenDetails &result) {};
397     EXPECT_NE(asyncs, nullptr);
398     ret = store->GetDBSyncCompleteCB(asyncs);
399     EXPECT_NE(ret, nullptr);
400 }
401 
402 /**
403 * @tc.name: CloudSync
404 * @tc.desc: CloudSync test the functionality of different branches.
405 * @tc.type: FUNC
406 * @tc.require:
407 * @tc.author: SQL
408 */
409 HWTEST_F(KVDBGeneralStoreTest, CloudSync, TestSize.Level0)
410 {
411     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
412     ASSERT_NE(store, nullptr);
413     store->SetEqualIdentifier(BUNDLE_NAME, STORE_NAME);
414     KvStoreNbDelegateMock mockDelegate;
415     store->delegate_ = &mockDelegate;
416     std::vector<std::string> devices = {"device1", "device2"};
__anondde6d9770402(const GenDetails &result) 417     auto asyncs = [](const GenDetails &result) {};
418     store->storeInfo_.user = 0;
419     auto cloudSyncMode = DistributedDB::SyncMode::SYNC_MODE_PUSH_ONLY;
420     store->SetEqualIdentifier(BUNDLE_NAME, STORE_NAME);
421     std::string prepareTraceId;
422     auto ret = store->CloudSync(devices, cloudSyncMode, asyncs, 0, prepareTraceId);
423     EXPECT_EQ(ret, DBStatus::OK);
424 
425     store->storeInfo_.user = 1;
426     cloudSyncMode = DistributedDB::SyncMode::SYNC_MODE_CLOUD_FORCE_PUSH;
427     ret = store->CloudSync(devices, cloudSyncMode, asyncs, 0, prepareTraceId);
428     EXPECT_EQ(ret, DBStatus::OK);
429 }
430 
431 /**
432 * @tc.name: Sync
433 * @tc.desc: Sync test the functionality of different branches.
434 * @tc.type: FUNC
435 * @tc.require:
436 * @tc.author: SQL
437 */
438 HWTEST_F(KVDBGeneralStoreTest, Sync, TestSize.Level0)
439 {
440     mkdir(("/data/service/el1/public/database/" + std::string(BUNDLE_NAME)).c_str(),
441         (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH));
442     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
443     ASSERT_NE(store, nullptr);
444     uint32_t syncMode = GeneralStore::SyncMode::CLOUD_BEGIN;
445     uint32_t highMode = GeneralStore::HighMode::MANUAL_SYNC_MODE;
446     auto mixMode = GeneralStore::MixMode(syncMode, highMode);
447     std::string kvQuery = "";
448     DistributedKv::KVDBQuery query(kvQuery);
449     SyncParam syncParam{};
450     syncParam.mode = mixMode;
451     KvStoreNbDelegateMock mockDelegate;
452     store->delegate_ = &mockDelegate;
__anondde6d9770502(const GenDetails &result) 453     auto ret = store->Sync({}, query, [](const GenDetails &result) {}, syncParam);
454     EXPECT_EQ(ret.first, GeneralError::E_NOT_SUPPORT);
455     GeneralStore::StoreConfig storeConfig;
456     storeConfig.enableCloud_ = true;
457     store->SetConfig(storeConfig);
__anondde6d9770602(const GenDetails &result) 458     ret = store->Sync({}, query, [](const GenDetails &result) {}, syncParam);
459     EXPECT_EQ(ret.first, GeneralError::E_OK);
460 
461     syncMode = GeneralStore::SyncMode::NEARBY_END;
462     mixMode = GeneralStore::MixMode(syncMode, highMode);
463     syncParam.mode = mixMode;
__anondde6d9770702(const GenDetails &result) 464     ret = store->Sync({}, query, [](const GenDetails &result) {}, syncParam);
465     EXPECT_EQ(ret.first, GeneralError::E_INVALID_ARGS);
466 
467     std::vector<std::string> devices = {"device1", "device2"};
468     syncMode = GeneralStore::SyncMode::NEARBY_SUBSCRIBE_REMOTE;
469     mixMode = GeneralStore::MixMode(syncMode, highMode);
470     syncParam.mode = mixMode;
__anondde6d9770802(const GenDetails &result) 471     ret = store->Sync(devices, query, [](const GenDetails &result) {}, syncParam);
472     EXPECT_EQ(ret.first, GeneralError::E_OK);
473 
474     syncMode = GeneralStore::SyncMode::NEARBY_UNSUBSCRIBE_REMOTE;
475     mixMode = GeneralStore::MixMode(syncMode, highMode);
476     syncParam.mode = mixMode;
__anondde6d9770902(const GenDetails &result) 477     ret = store->Sync(devices, query, [](const GenDetails &result) {}, syncParam);
478     EXPECT_EQ(ret.first, GeneralError::E_OK);
479 
480     syncMode = GeneralStore::SyncMode::NEARBY_PULL_PUSH;
481     mixMode = GeneralStore::MixMode(syncMode, highMode);
482     syncParam.mode = mixMode;
__anondde6d9770a02(const GenDetails &result) 483     ret = store->Sync(devices, query, [](const GenDetails &result) {}, syncParam);
484     EXPECT_EQ(ret.first, GeneralError::E_OK);
485 
486     syncMode = GeneralStore::SyncMode::MODE_BUTT;
487     mixMode = GeneralStore::MixMode(syncMode, highMode);
488     syncParam.mode = mixMode;
__anondde6d9770b02(const GenDetails &result) 489     ret = store->Sync(devices, query, [](const GenDetails &result) {}, syncParam);
490     EXPECT_EQ(ret.first, GeneralError::E_INVALID_ARGS);
491 }
492 
493 /**
494 * @tc.name: Clean
495 * @tc.desc: Clean test the functionality of different branches.
496 * @tc.type: FUNC
497 * @tc.require:
498 * @tc.author: SQL
499 */
500 HWTEST_F(KVDBGeneralStoreTest, Clean, TestSize.Level0)
501 {
502     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
503     ASSERT_NE(store, nullptr);
504     std::vector<std::string> devices = {"device1", "device2"};
505     std::string tableName = "tableName";
506     auto ret = store->Clean(devices, -1, tableName);
507     EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS);
508     ret = store->Clean(devices, 5, tableName);
509     EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS);
510     ret = store->Clean(devices, GeneralStore::CleanMode::NEARBY_DATA, tableName);
511     EXPECT_EQ(ret, GeneralError::E_ALREADY_CLOSED);
512 
513     KvStoreNbDelegateMock mockDelegate;
514     store->delegate_ = &mockDelegate;
515     ret = store->Clean(devices, GeneralStore::CleanMode::CLOUD_INFO, tableName);
516     EXPECT_EQ(ret, GeneralError::E_OK);
517 
518     ret = store->Clean(devices, GeneralStore::CleanMode::CLOUD_DATA, tableName);
519     EXPECT_EQ(ret, GeneralError::E_OK);
520 
521     ret = store->Clean({}, GeneralStore::CleanMode::NEARBY_DATA, tableName);
522     EXPECT_EQ(ret, GeneralError::E_OK);
523     ret = store->Clean(devices, GeneralStore::CleanMode::NEARBY_DATA, tableName);
524     EXPECT_EQ(ret, GeneralError::E_OK);
525 
526     ret = store->Clean(devices, GeneralStore::CleanMode::LOCAL_DATA, tableName);
527     EXPECT_EQ(ret, GeneralError::E_ERROR);
528 }
529 
530 /**
531 * @tc.name: Watch
532 * @tc.desc: Watch and Unwatch test the functionality of different branches.
533 * @tc.type: FUNC
534 * @tc.require:
535 * @tc.author: SQL
536 */
537 HWTEST_F(KVDBGeneralStoreTest, Watch, TestSize.Level0)
538 {
539     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
540     ASSERT_NE(store, nullptr);
541     DistributedDataTest::MockGeneralWatcher watcher;
542     auto ret = store->Watch(GeneralWatcher::Origin::ORIGIN_CLOUD, watcher);
543     EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS);
544     ret = store->Unwatch(GeneralWatcher::Origin::ORIGIN_CLOUD, watcher);
545     EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS);
546 
547     ret = store->Watch(GeneralWatcher::Origin::ORIGIN_ALL, watcher);
548     EXPECT_EQ(ret, GeneralError::E_OK);
549     ret = store->Watch(GeneralWatcher::Origin::ORIGIN_ALL, watcher);
550     EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS);
551 
552     ret = store->Unwatch(GeneralWatcher::Origin::ORIGIN_ALL, watcher);
553     EXPECT_EQ(ret, GeneralError::E_OK);
554     ret = store->Unwatch(GeneralWatcher::Origin::ORIGIN_ALL, watcher);
555     EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS);
556 }
557 
558 /**
559 * @tc.name: Release
560 * @tc.desc: Release and AddRef test the functionality of different branches.
561 * @tc.type: FUNC
562 * @tc.require:
563 * @tc.author: SQL
564 */
565 HWTEST_F(KVDBGeneralStoreTest, Release, TestSize.Level0)
566 {
567     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
568     ASSERT_NE(store, nullptr);
569     auto ret = store->Release();
570     EXPECT_EQ(ret, 0);
571     store = new (std::nothrow) KVDBGeneralStore(metaData_);
572     store->ref_ = 0;
573     ret = store->Release();
574     EXPECT_EQ(ret, 0);
575     store->ref_ = 2;
576     ret = store->Release();
577     EXPECT_EQ(ret, 1);
578 
579     ret = store->AddRef();
580     EXPECT_EQ(ret, 2);
581     store->ref_ = 0;
582     ret = store->AddRef();
583     EXPECT_EQ(ret, 0);
584 }
585 
586 /**
587 * @tc.name: ConvertStatus
588 * @tc.desc: ConvertStatus test the functionality of different branches.
589 * @tc.type: FUNC
590 * @tc.require:
591 * @tc.author: SQL
592 */
593 HWTEST_F(KVDBGeneralStoreTest, ConvertStatus, TestSize.Level0)
594 {
595     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
596     ASSERT_NE(store, nullptr);
597     auto ret = store->ConvertStatus(DBStatus::OK);
598     EXPECT_EQ(ret, GeneralError::E_OK);
599     ret = store->ConvertStatus(DBStatus::CLOUD_NETWORK_ERROR);
600     EXPECT_EQ(ret, GeneralError::E_NETWORK_ERROR);
601     ret = store->ConvertStatus(DBStatus::CLOUD_LOCK_ERROR);
602     EXPECT_EQ(ret, GeneralError::E_LOCKED_BY_OTHERS);
603     ret = store->ConvertStatus(DBStatus::CLOUD_FULL_RECORDS);
604     EXPECT_EQ(ret, GeneralError::E_RECODE_LIMIT_EXCEEDED);
605     ret = store->ConvertStatus(DBStatus::CLOUD_ASSET_SPACE_INSUFFICIENT);
606     EXPECT_EQ(ret, GeneralError::E_NO_SPACE_FOR_ASSET);
607     ret = store->ConvertStatus(DBStatus::CLOUD_SYNC_TASK_MERGED);
608     EXPECT_EQ(ret, GeneralError::E_SYNC_TASK_MERGED);
609     ret = store->ConvertStatus(DBStatus::DB_ERROR);
610     EXPECT_EQ(ret, GeneralError::E_DB_ERROR);
611 }
612 
613 /**
614 * @tc.name: GetWaterVersion
615 * @tc.desc: GetWaterVersion test the functionality of different branches.
616 * @tc.type: FUNC
617 * @tc.require:
618 * @tc.author: SQL
619 */
620 HWTEST_F(KVDBGeneralStoreTest, GetWaterVersion, TestSize.Level0)
621 {
622     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
623     ASSERT_NE(store, nullptr);
624     std::string deviceId = "deviceId";
625     std::vector<std::string> res = {};
626     auto ret = store->GetWaterVersion(deviceId);
627     EXPECT_EQ(ret, res);
628     KvStoreNbDelegateMock mockDelegate;
629     store->delegate_ = &mockDelegate;
630     ret = store->GetWaterVersion("");
631     EXPECT_EQ(ret, res);
632     ret = store->GetWaterVersion("test");
633     EXPECT_EQ(ret, res);
634     ret = store->GetWaterVersion("device");
635     EXPECT_EQ(ret, res);
636     res = {"deviceId"};
637     ret = store->GetWaterVersion(deviceId);
638     EXPECT_EQ(ret, res);
639 }
640 
641 /**
642 * @tc.name: OnChange
643 * @tc.desc: OnChange test the functionality of different branches.
644 * @tc.type: FUNC
645 * @tc.require:
646 * @tc.author: SQL
647 */
648 HWTEST_F(KVDBGeneralStoreTest, OnChange, TestSize.Level0)
649 {
650     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
651     ASSERT_NE(store, nullptr);
652     DistributedDataTest::MockGeneralWatcher watcher;
653     DistributedDataTest::MockKvStoreChangedData data;
654     DistributedDB::ChangedData changedData;
655     store->observer_.OnChange(data);
656     store->observer_.OnChange(DistributedDB::Origin::ORIGIN_CLOUD, "originalId", std::move(changedData));
657     auto result = store->Watch(GeneralWatcher::Origin::ORIGIN_ALL, watcher);
658     EXPECT_EQ(result, GeneralError::E_OK);
659     store->observer_.OnChange(data);
660     store->observer_.OnChange(DistributedDB::Origin::ORIGIN_CLOUD, "originalId", std::move(changedData));
661     result = store->Unwatch(GeneralWatcher::Origin::ORIGIN_ALL, watcher);
662     EXPECT_EQ(result, GeneralError::E_OK);
663 }
664 
665 /**
666 * @tc.name: Delete
667 * @tc.desc: Delete test the function.
668 * @tc.type: FUNC
669 * @tc.require:
670 * @tc.author: SQL
671 */
672 HWTEST_F(KVDBGeneralStoreTest, Delete, TestSize.Level0)
673 {
674     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
675     ASSERT_NE(store, nullptr);
676     KvStoreNbDelegateMock mockDelegate;
677     store->delegate_ = &mockDelegate;
678     store->SetDBPushDataInterceptor(DistributedKv::KvStoreType::DEVICE_COLLABORATION);
679     store->SetDBReceiveDataInterceptor(DistributedKv::KvStoreType::DEVICE_COLLABORATION);
680     DistributedData::VBuckets values;
681     auto ret = store->Insert("table", std::move(values));
682     EXPECT_EQ(ret, GeneralError::E_NOT_SUPPORT);
683 
684     DistributedData::Values args;
685     store->SetDBPushDataInterceptor(DistributedKv::KvStoreType::SINGLE_VERSION);
686     store->SetDBReceiveDataInterceptor(DistributedKv::KvStoreType::SINGLE_VERSION);
687     ret = store->Delete("table", "sql", std::move(args));
688     EXPECT_EQ(ret, GeneralError::E_NOT_SUPPORT);
689 }
690 
691 /**
692 * @tc.name: Query001
693 * @tc.desc: KVDBGeneralStoreTest Query function test
694 * @tc.type: FUNC
695 * @tc.require:
696 * @tc.author: SQL
697 */
698 HWTEST_F(KVDBGeneralStoreTest, Query001, TestSize.Level1)
699 {
700     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
701     ASSERT_NE(store, nullptr);
702     std::string table = "table";
703     std::string sql = "sql";
704     auto [errCode, result] = store->Query(table, sql, {});
705     EXPECT_EQ(errCode, GeneralError::E_NOT_SUPPORT);
706     EXPECT_EQ(result, nullptr);
707 }
708 
709 /**
710 * @tc.name: Query002
711 * @tc.desc: KVDBGeneralStoreTest Query function test
712 * @tc.type: FUNC
713 * @tc.require:
714 * @tc.author: SQL
715 */
716 HWTEST_F(KVDBGeneralStoreTest, Query002, TestSize.Level1)
717 {
718     auto store = new (std::nothrow) KVDBGeneralStore(metaData_);
719     ASSERT_NE(store, nullptr);
720     std::string table = "table";
721     MockQuery query;
722     auto [errCode, result] = store->Query(table, query);
723     EXPECT_EQ(errCode, GeneralError::E_NOT_SUPPORT);
724     EXPECT_EQ(result, nullptr);
725 }
726 } // namespace DistributedDataTest
727 } // namespace OHOS::Test