1 /*
2  * Copyright (c) 2021 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 
16 #include <gtest/gtest.h>
17 #include <thread>
18 
19 #include "db_common.h"
20 #include "db_constant.h"
21 #include "db_errno.h"
22 #include "distributeddb_data_generate_unit_test.h"
23 #include "distributeddb_tools_unit_test.h"
24 #include "log_print.h"
25 #include "platform_specific.h"
26 #include "process_system_api_adapter_impl.h"
27 #include "runtime_context.h"
28 #include "sqlite_single_ver_natural_store.h"
29 #include "storage_engine_manager.h"
30 #ifdef DB_DEBUG_ENV
31 #include "system_time.h"
32 #endif // DB_DEBUG_ENV
33 #include "kv_store_result_set_impl.h"
34 #include "kv_store_nb_delegate_impl.h"
35 #include "kv_virtual_device.h"
36 #include "virtual_communicator_aggregator.h"
37 
38 using namespace testing::ext;
39 using namespace DistributedDB;
40 using namespace DistributedDBUnitTest;
41 using namespace std;
42 
43 namespace {
44     // define some variables to init a KvStoreDelegateManager object.
45     KvStoreDelegateManager g_mgr(APP_ID, USER_ID);
46     string g_testDir;
47     KvStoreConfig g_config;
48     Key g_keyPrefix = {'A', 'B', 'C'};
49     const int RESULT_SET_COUNT = 9;
50     const int RESULT_SET_INIT_POS = -1;
51     uint8_t g_testDict[RESULT_SET_COUNT] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
52 
53     // define the g_kvNbDelegateCallback, used to get some information when open a kv store.
54     DBStatus g_kvDelegateStatus = INVALID_ARGS;
55     KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr;
56 #ifndef OMIT_MULTI_VER
57     KvStoreDelegate *g_kvDelegatePtr = nullptr;
58 
59     // the type of g_kvDelegateCallback is function<void(DBStatus, KvStoreDelegate*)>
60     auto g_kvDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1,
61         placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvDelegatePtr));
62 #endif // OMIT_MULTI_VER
63     const int OBSERVER_SLEEP_TIME = 100;
64     const int BATCH_PRESET_SIZE_TEST = 10;
65     const int DIVIDE_BATCH_PRESET_SIZE = 5;
66     const int VALUE_OFFSET = 5;
67 
68     const int DEFAULT_KEY_VALUE_SIZE = 10;
69 
70     const int CON_PUT_THREAD_NUM = 4;
71     const int PER_THREAD_PUT_NUM = 100;
72 
73     const std::string DEVICE_B = "deviceB";
74     const std::string DEVICE_C = "deviceC";
75     const std::string DEVICE_D = "deviceD";
76     VirtualCommunicatorAggregator* g_communicatorAggregator = nullptr;
77     KvVirtualDevice *g_deviceB = nullptr;
78     KvVirtualDevice *g_deviceC = nullptr;
79     KvVirtualDevice *g_deviceD = nullptr;
80     VirtualSingleVerSyncDBInterface *g_syncInterfaceB = nullptr;
81     VirtualSingleVerSyncDBInterface *g_syncInterfaceC = nullptr;
82     VirtualSingleVerSyncDBInterface *g_syncInterfaceD = nullptr;
83 
84     // the type of g_kvNbDelegateCallback is function<void(DBStatus, KvStoreDelegate*)>
85     auto g_kvNbDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1,
86         placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvNbDelegatePtr));
87 
88     enum LockState {
89         UNLOCKED = 0,
90         LOCKED
91     };
92 
InitResultSet()93     void InitResultSet()
94     {
95         Key testKey;
96         Value testValue;
97         for (int i = 0; i < RESULT_SET_COUNT; i++) {
98             testKey.clear();
99             testValue.clear();
100             // set key
101             testKey = g_keyPrefix;
102             testKey.push_back(g_testDict[i]);
103             // set value
104             testValue.push_back(g_testDict[i]);
105             // insert entry
106             EXPECT_EQ(g_kvNbDelegatePtr->Put(testKey, testValue), OK);
107         }
108     }
109 
ReadResultSet(KvStoreResultSet * readResultSet)110     void ReadResultSet(KvStoreResultSet *readResultSet)
111     {
112         if (readResultSet == nullptr) {
113             return;
114         }
115         // index from 0 to 8(first to last)
116         for (int i = 0; i < RESULT_SET_COUNT; i++) {
117             Entry entry;
118             std::vector<uint8_t> cursorKey = g_keyPrefix;
119             cursorKey.push_back(g_testDict[i]);
120             std::vector<uint8_t> cursorValue;
121             cursorValue.push_back(g_testDict[i]);
122             EXPECT_TRUE(readResultSet->MoveToNext());
123             EXPECT_EQ(readResultSet->GetEntry(entry), OK);
124             EXPECT_EQ(entry.key, cursorKey);
125             EXPECT_EQ(entry.value, cursorValue);
126             EXPECT_TRUE(!readResultSet->IsBeforeFirst());
127             EXPECT_TRUE(!readResultSet->IsAfterLast());
128         }
129         // change index to 8(last)
130         EXPECT_EQ(readResultSet->GetPosition(), RESULT_SET_COUNT - 1);
131         EXPECT_TRUE(!readResultSet->IsFirst());
132         EXPECT_TRUE(readResultSet->IsLast());
133         EXPECT_TRUE(!readResultSet->IsBeforeFirst());
134         EXPECT_TRUE(!readResultSet->IsAfterLast());
135     }
136 
CheckResultSetValue(KvStoreResultSet * readResultSet,DBStatus errCode,int position)137     void CheckResultSetValue(KvStoreResultSet *readResultSet, DBStatus errCode, int position)
138     {
139         if (readResultSet == nullptr) {
140             return;
141         }
142         Entry entry;
143         EXPECT_EQ(readResultSet->GetPosition(), position);
144         EXPECT_EQ(readResultSet->GetEntry(entry), errCode);
145         if (errCode == OK) {
146             std::vector<uint8_t> cursorKey;
147             std::vector<uint8_t> cursorValue;
148             if (position > RESULT_SET_INIT_POS && position < RESULT_SET_COUNT) {
149                 uint8_t keyPostfix = g_testDict[position];
150                 // set key
151                 cursorKey = g_keyPrefix;
152                 cursorKey.push_back(keyPostfix);
153                 // set value
154                 cursorValue.push_back(keyPostfix);
155             }
156             // check key and value
157             EXPECT_EQ(entry.key, cursorKey);
158             EXPECT_EQ(entry.value, cursorValue);
159         }
160     }
161 
162     std::vector<Entry> g_entriesForConcurrency;
PutData(KvStoreNbDelegate * kvStore,int flag)163     void PutData(KvStoreNbDelegate *kvStore, int flag)
164     {
165         for (int i = 0; i < PER_THREAD_PUT_NUM; i++) {
166             int index = flag * PER_THREAD_PUT_NUM + i;
167             kvStore->Put(g_entriesForConcurrency[index].key, g_entriesForConcurrency[index].value);
168         }
169         LOGD("%dth put has been finished", flag);
170     }
171 
CheckDataTimestamp(const std::string & storeId)172     bool CheckDataTimestamp(const std::string &storeId)
173     {
174         std::string identifier = USER_ID + "-" + APP_ID + "-" + storeId;
175         std::string hashIdentifier = DBCommon::TransferHashString(identifier);
176         std::string identifierName = DBCommon::TransferStringToHex(hashIdentifier);
177         std::string storeDir = g_testDir + "/" + identifierName + "/" + DBConstant::SINGLE_SUB_DIR + "/" +
178             DBConstant::MAINDB_DIR + "/" + DBConstant::SINGLE_VER_DATA_STORE + DBConstant::DB_EXTENSION;
179         sqlite3 *db = nullptr;
180         EXPECT_EQ(sqlite3_open_v2(storeDir.c_str(), &db, SQLITE_OPEN_READWRITE, nullptr), SQLITE_OK);
181         if (db == nullptr) {
182             return false;
183         }
184 
185         std::string selectSQL = "select timestamp from sync_data order by rowid;";
186         sqlite3_stmt *statement = nullptr;
187         EXPECT_EQ(sqlite3_prepare(db, selectSQL.c_str(), -1, &statement, NULL), SQLITE_OK);
188         std::vector<int64_t> timeVect;
189         while (sqlite3_step(statement) == SQLITE_ROW) {
190             timeVect.push_back(sqlite3_column_int64(statement, 0));
191         }
192 
193         sqlite3_finalize(statement);
194         statement = nullptr;
195         (void)sqlite3_close_v2(db);
196         db = nullptr;
197         EXPECT_EQ(timeVect.size(), g_entriesForConcurrency.size());
198         bool resultCheck = true;
199         if (g_entriesForConcurrency.size() > 1) {
200             for (size_t i = 1; i < timeVect.size(); i++) {
201                 if (timeVect[i] <= timeVect[i - 1]) {
202                     resultCheck = false;
203                     break;
204                 }
205             }
206         }
207 
208         return resultCheck;
209     }
210 
211 class DistributedDBInterfacesNBDelegateTest : public testing::Test {
212 public:
213     static void SetUpTestCase(void);
214     static void TearDownTestCase(void);
215     void SetUp();
216     void TearDown();
217 };
218 
SetUpTestCase(void)219 void DistributedDBInterfacesNBDelegateTest::SetUpTestCase(void)
220 {
221     DistributedDBToolsUnitTest::TestDirInit(g_testDir);
222     g_config.dataDir = g_testDir;
223     g_mgr.SetKvStoreConfig(g_config);
224     if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) {
225         LOGE("rm test db files error!");
226     }
227 
228     g_communicatorAggregator = new (std::nothrow) VirtualCommunicatorAggregator();
229     ASSERT_TRUE(g_communicatorAggregator != nullptr);
230     RuntimeContext::GetInstance()->SetCommunicatorAggregator(g_communicatorAggregator);
231 }
232 
TearDownTestCase(void)233 void DistributedDBInterfacesNBDelegateTest::TearDownTestCase(void)
234 {
235     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(nullptr);
236 
237     RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
238 }
239 
SetUp(void)240 void DistributedDBInterfacesNBDelegateTest::SetUp(void)
241 {
242     DistributedDBToolsUnitTest::PrintTestCaseInfo();
243     g_kvDelegateStatus = INVALID_ARGS;
244     g_kvNbDelegatePtr = nullptr;
245 #ifndef OMIT_MULTI_VER
246     g_kvDelegatePtr = nullptr;
247 #endif // OMIT_MULTI_VER
248 }
249 
TearDown(void)250 void DistributedDBInterfacesNBDelegateTest::TearDown(void)
251 {
252     if (g_kvNbDelegatePtr != nullptr) {
253         g_mgr.CloseKvStore(g_kvNbDelegatePtr);
254         g_kvNbDelegatePtr = nullptr;
255     }
256     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(nullptr);
257 }
258 
259 /**
260   * @tc.name: CombineTest001
261   * @tc.desc: Test the NbDelegate for combined operation.
262   * @tc.type: FUNC
263   * @tc.require: AR000CCPOM
264   * @tc.author: huangnaigu
265   */
266 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CombineTest001, TestSize.Level1)
267 {
268     /**
269      * @tc.steps:step1. Get the nb delegate.
270      * @tc.expected: step1. Get results OK and non-null delegate.
271      */
272     KvStoreNbDelegate::Option option = {true, false, false};
273     g_mgr.GetKvStore("distributed_nb_delegate_test", option, g_kvNbDelegateCallback);
274     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
275     EXPECT_TRUE(g_kvDelegateStatus == OK);
276     Key key;
277     key = {'A', 'C', 'Q'};
278     Value value;
279     value = {'G', 'D', 'O'};
280     Value valueRead;
281     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
282     ASSERT_TRUE(observer != nullptr);
283     /**
284      * @tc.steps:step2. Register the non-null observer for the special key.
285      * @tc.expected: step2. Register results OK.
286      */
287     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_LOCAL_ONLY, observer), OK);
288     /**
289      * @tc.steps:step3. Put the local data.
290      * @tc.expected: step3. Put returns OK.
291      */
292     EXPECT_EQ(g_kvNbDelegatePtr->PutLocal(key, value), OK);
293     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
294     /**
295      * @tc.steps:step4. Check the local data.
296      * @tc.expected: step4. The get data is equal to the put data.
297      */
298     EXPECT_EQ(g_kvNbDelegatePtr->GetLocal(key, valueRead), OK);
299     /**
300      * @tc.steps:step5. Delete the local data.
301      * @tc.expected: step5. Delete returns OK.
302      */
303     EXPECT_EQ(g_kvNbDelegatePtr->DeleteLocal(key), OK);
304     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
305     /**
306      * @tc.steps:step6. Check the local data.
307      * @tc.expected: step6. Couldn't find the deleted data.
308      */
309     EXPECT_EQ(g_kvNbDelegatePtr->GetLocal(key, valueRead), NOT_FOUND);
310     /**
311      * @tc.steps:step7. UnRegister the observer.
312      * @tc.expected: step7. Returns OK.
313      */
314     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
315     delete observer;
316     observer = nullptr;
317     Key key1;
318     key1 = {'D', 'B', 'N'};
319     Value value1;
320     value1 = {'P', 'D', 'G'};
321 
322     Key key2 = key1;
323     Value value2;
324     key2.push_back('U');
325     value2 = {'C'};
326     /**
327      * @tc.steps:step8. Put the data.
328      * @tc.expected: step8. Put returns OK.
329      */
330     EXPECT_EQ(g_kvNbDelegatePtr->Put(key1, value1), OK);
331     Value valueRead2;
332     /**
333      * @tc.steps:step9. Check the data.
334      * @tc.expected: step9. Getting the put data returns OK.
335      */
336     EXPECT_EQ(g_kvNbDelegatePtr->Get(key1, valueRead2), OK);
337     /**
338      * @tc.steps:step10. Put another data.
339      * @tc.expected: step10. Returns OK.
340      */
341     EXPECT_EQ(g_kvNbDelegatePtr->Put(key2, value2), OK);
342     std::vector<Entry> vect;
343     /**
344      * @tc.steps:step10. Get the batch data using the prefix key.
345      * @tc.expected: step10. Results OK and the batch data size is equal to the put data size.
346      */
347     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(key1, vect), OK);
348     EXPECT_EQ(vect.size(), 2UL);
349     /**
350      * @tc.steps:step11. Delete one data.
351      * @tc.expected: step11. Results OK and couldn't get the deleted data.
352      */
353     EXPECT_EQ(g_kvNbDelegatePtr->Delete(key1), OK);
354     EXPECT_EQ(g_kvNbDelegatePtr->Get(key1, valueRead2), NOT_FOUND);
355 
356     LOGD("Close store");
357     /**
358      * @tc.steps:step12. Close the kv store.
359      * @tc.expected: step12. Results OK and delete successfully.
360      */
361     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
362     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_nb_delegate_test"), OK);
363     g_kvNbDelegatePtr = nullptr;
364 }
365 
366 /**
367   * @tc.name: CreateMemoryDb001
368   * @tc.desc: Create memory database after.
369   * @tc.type: FUNC
370   * @tc.require: AR000CRAKN
371   * @tc.author: sunpeng
372   */
373 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDb001, TestSize.Level1)
374 {
375     /**
376      * @tc.steps: step1. Create Memory database by GetKvStore.
377      * @tc.expected: step1. Create successfully.
378      */
379     const KvStoreNbDelegate::Option option = {true, true};
380     g_mgr.SetKvStoreConfig(g_config);
381     g_mgr.GetKvStore("distributed_Memorykvstore_001", option, g_kvNbDelegateCallback);
382     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
383     EXPECT_TRUE(g_kvDelegateStatus == OK);
384     KvStoreNbDelegate *kvNbDelegatePtr001 = g_kvNbDelegatePtr;
385 
386     /**
387      * @tc.steps: step2. Duplicate create Memory database by GetKvStore.
388      * @tc.expected: step2. Duplicate create successfully.
389      */
390     g_mgr.GetKvStore("distributed_Memorykvstore_001", option, g_kvNbDelegateCallback);
391     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
392     EXPECT_TRUE(g_kvDelegateStatus == OK);
393     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
394 
395     /**
396      * @tc.steps: step3. Duplicate create Memory database by GetKvStore.
397      * @tc.expected: step3. Duplicate create successfully.
398      */
399     g_mgr.GetKvStore("distributed_Memorykvstore_002", option, g_kvNbDelegateCallback);
400     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
401     EXPECT_TRUE(g_kvDelegateStatus == OK);
402     KvStoreNbDelegate *kvNbDelegatePtr002 = g_kvNbDelegatePtr;
403 
404     g_mgr.CloseKvStore(kvNbDelegatePtr001);
405     g_mgr.CloseKvStore(kvNbDelegatePtr002);
406     g_kvNbDelegatePtr = nullptr;
407 }
408 
409 /**
410   * @tc.name: CreateMemoryDb002
411   * @tc.desc: The MemoryDB cannot be created or open, when the physical database has been opened
412   * @tc.type: FUNC
413   * @tc.require: AR000CRAKN
414   * @tc.author: sunpeng
415   */
416 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDb002, TestSize.Level1)
417 {
418     KvStoreNbDelegate::Option option = {true, true};
419     /**
420      * @tc.steps: step1. Create SingleVer database by GetKvStore.
421      * @tc.expected: step1. Create database success.
422      */
423     g_mgr.GetKvStore("distributed_Memorykvstore_002", option, g_kvNbDelegateCallback);
424     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
425     EXPECT_TRUE(g_kvDelegateStatus == OK);
426     KvStoreNbDelegate *delegate1 = g_kvNbDelegatePtr;
427     g_kvNbDelegatePtr = nullptr;
428 
429     /**
430      * @tc.steps: step2. Create Memory database by GetKvStore.
431      * @tc.expected: step2. Create Memory database fail.
432      */
433     option.isMemoryDb = false;
434     g_mgr.GetKvStore("distributed_Memorykvstore_002", option, g_kvNbDelegateCallback);
435     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
436     EXPECT_TRUE(g_kvDelegateStatus != OK);
437     g_mgr.CloseKvStore(delegate1);
438     delegate1 = nullptr;
439 }
440 
441 #ifndef OMIT_MULTI_VER
442 /**
443   * @tc.name: CreateMemoryDb003
444   * @tc.desc: The physical database cannot be created or open, when the MemoryDB has been opened.
445   * @tc.type: FUNC
446   * @tc.require: AR000CRAKN
447   * @tc.author: sunpeng
448   */
449 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDb003, TestSize.Level1)
450 {
451     /**
452      * @tc.steps: step1. Get singleVer kvStore by GetKvStore.
453      * @tc.expected: step1. Get database success.
454      */
455     KvStoreDelegate::Option option;
456     g_mgr.GetKvStore("distributed_Memorykvstore_003", option, g_kvDelegateCallback);
457     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
458     EXPECT_TRUE(g_kvDelegateStatus == OK);
459 
460     /**
461      * @tc.steps: step2. Create Memory database by GetKvStore.
462      * @tc.expected: step2. Create Memory database fail.
463      */
464     KvStoreNbDelegate::Option nbOption = {true, true};
465     g_mgr.GetKvStore("distributed_Memorykvstore_003", nbOption, g_kvNbDelegateCallback);
466     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
467     EXPECT_TRUE(g_kvDelegateStatus != OK);
468     g_mgr.CloseKvStore(g_kvDelegatePtr);
469     g_kvDelegatePtr = nullptr;
470 }
471 #endif // OMIT_MULTI_VER
472 
473 /**
474   * @tc.name: OperMemoryDbData001
475   * @tc.desc: Operate memory database
476   * @tc.type: FUNC
477   * @tc.require: AR000CRAKN
478   * @tc.author: sunpeng
479   */
480 HWTEST_F(DistributedDBInterfacesNBDelegateTest, OperMemoryDbData001, TestSize.Level1)
481 {
482     /**
483      * @tc.steps: step1. Create Memory database by GetKvStore.
484      */
485     const KvStoreNbDelegate::Option option = {true, true};
486     g_mgr.GetKvStore("distributed_OperMemorykvstore_001", option, g_kvNbDelegateCallback);
487     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
488     EXPECT_TRUE(g_kvDelegateStatus == OK);
489 
490     /**
491      * @tc.steps: step2. Put (KEY_1,VALUE_1)(KEY_2,VALUE_2) to Memory database.
492      * @tc.expected: step2. Success.
493      */
494     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_1, VALUE_1), OK);
495     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_2, VALUE_2), OK);
496 
497     /**
498      * @tc.steps: step3. Get (KEY_1,VALUE_1)(KEY_2,VALUE_2) to Memory database.
499      * @tc.expected: step3. Success.
500      */
501     Value readValueKey1;
502     Value readValueKey2;
503     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_1, readValueKey1), OK);
504     EXPECT_EQ(readValueKey1, VALUE_1);
505 
506     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_2, readValueKey2), OK);
507     EXPECT_EQ(readValueKey2, VALUE_2);
508 
509     /**
510      * @tc.steps: step4. Delete K1 from Memory database.
511      * @tc.expected: step4. Success.
512      */
513     EXPECT_EQ(g_kvNbDelegatePtr->Delete(KEY_1), OK);
514 
515     /**
516      * @tc.steps: step5. Get K1 from Memory database.
517      * @tc.expected: step5. NOT_FOUND.
518      */
519     readValueKey1.clear();
520     readValueKey2.clear();
521     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_1, readValueKey1), NOT_FOUND);
522 
523     /**
524      * @tc.steps: step6. Update K2 value from Memory database.
525      * @tc.expected: step6. Get the right value after the update.
526      */
527     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_2, VALUE_3), OK);
528     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_2, readValueKey2), OK);
529     EXPECT_EQ(readValueKey2, VALUE_3);
530     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
531     g_kvNbDelegatePtr = nullptr;
532 }
533 
534 /**
535   * @tc.name: CloseMemoryDb001
536   * @tc.desc: Operate memory database after reopen memory database
537   * @tc.type: FUNC
538   * @tc.require: AR000CRAKN
539   * @tc.author: sunpeng
540   */
541 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CloseMemoryDb001, TestSize.Level1)
542 {
543     /**
544      * @tc.steps: step1. Create Memory database by GetKvStore.
545      */
546     const KvStoreNbDelegate::Option option = {true, true};
547     g_mgr.SetKvStoreConfig(g_config);
548     g_mgr.GetKvStore("distributed_CloseMemorykvstore_001", option, g_kvNbDelegateCallback);
549     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
550     EXPECT_TRUE(g_kvDelegateStatus == OK);
551 
552     /**
553      * @tc.steps: step2/3. Put and get to Memory database.
554      * @tc.expected: step2/3. Success and the value is right.
555      */
556     Value readValue;
557     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_1, VALUE_1), OK);
558     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_1, readValue), OK);
559     EXPECT_EQ(readValue, VALUE_1);
560 
561     /**
562      * @tc.steps: step4. Close the Memory database.
563      * @tc.expected: step4. Success.
564      */
565     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
566 
567     /**
568      * @tc.steps: step5. Reopen the Memory database.
569      * @tc.expected: step5. Success.
570      */
571     g_mgr.GetKvStore("distributed_CloseMemorykvstore_001", option, g_kvNbDelegateCallback);
572     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
573     EXPECT_TRUE(g_kvDelegateStatus == OK);
574 
575     /**
576      * @tc.steps: step6. Get the key1 which has been put into the Memory database.
577      * @tc.expected: step6. Return NOT_FOUND.
578      */
579     readValue.clear();
580     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_1, readValue), NOT_FOUND);
581     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
582     g_kvNbDelegatePtr = nullptr;
583 }
584 
585 /**
586   * @tc.name: ResultSetTest001
587   * @tc.desc: Test the NbDelegate for result set function.
588   * @tc.type: FUNC
589   * @tc.require: AR000D08KT
590   * @tc.author: wumin
591   */
592 HWTEST_F(DistributedDBInterfacesNBDelegateTest, ResultSetTest001, TestSize.Level1)
593 {
594     /**
595      * @tc.steps: step1. initialize result set.
596      * @tc.expected: step1. Success.
597      */
598     KvStoreNbDelegate::Option option = {true, false, false};
599     g_mgr.GetKvStore("distributed_nb_delegate_result_set_test", option, g_kvNbDelegateCallback);
600     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
601     EXPECT_TRUE(g_kvDelegateStatus == OK);
602     InitResultSet();
603 
604     /**
605      * @tc.steps: step2. get entries using result set.
606      * @tc.expected: step2. Success.
607      */
608     KvStoreResultSet *readResultSet = nullptr;
609     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(g_keyPrefix, readResultSet), OK);
610     ASSERT_TRUE(readResultSet != nullptr);
611     EXPECT_EQ(readResultSet->GetCount(), RESULT_SET_COUNT);
612 
613     /**
614      * @tc.steps: step3. result function check.
615      * @tc.expected: step3. Success.
616      */
617     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_INIT_POS);
618     // index from 0 to 8(first to last)
619     ReadResultSet(readResultSet);
620     // change index to 9(after last)
621     EXPECT_TRUE(!readResultSet->MoveToNext());
622     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_COUNT);
623     // change index to 8(last)
624     EXPECT_TRUE(readResultSet->MoveToPrevious());
625     CheckResultSetValue(readResultSet, OK, RESULT_SET_COUNT - 1);
626     // change index to 0(first)
627     EXPECT_TRUE(readResultSet->MoveToFirst());
628     CheckResultSetValue(readResultSet, OK, RESULT_SET_INIT_POS + 1);
629     // change index to 8(last)
630     EXPECT_TRUE(readResultSet->MoveToLast());
631     CheckResultSetValue(readResultSet, OK, RESULT_SET_COUNT - 1);
632     // move to -4: change index to -1
633     EXPECT_TRUE(!readResultSet->MoveToPosition(RESULT_SET_INIT_POS - 3));
634     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_INIT_POS);
635     // move to 10: change index to 9
636     EXPECT_TRUE(!readResultSet->MoveToPosition(RESULT_SET_COUNT + 1));
637     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_COUNT);
638     // change index to 2
639     EXPECT_TRUE(readResultSet->MoveToPosition(RESULT_SET_INIT_POS + 3));
640     CheckResultSetValue(readResultSet, OK, RESULT_SET_INIT_POS + 3);
641     // move 0: change index to 2
642     EXPECT_TRUE(readResultSet->Move(0));
643     CheckResultSetValue(readResultSet, OK, RESULT_SET_INIT_POS + 3);
644     // change index to 6
645     EXPECT_TRUE(readResultSet->Move(RESULT_SET_INIT_POS + 5));
646     CheckResultSetValue(readResultSet, OK, RESULT_SET_INIT_POS + 7);
647     // change index to 3
648     EXPECT_TRUE(readResultSet->Move(RESULT_SET_INIT_POS - 2));
649     CheckResultSetValue(readResultSet, OK, RESULT_SET_INIT_POS + 4);
650     // move -5: change index to -1
651     EXPECT_TRUE(!readResultSet->Move(-5));
652     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_INIT_POS);
653 
654     // move INT_MIN: change index to -1
655     EXPECT_TRUE(!readResultSet->Move(INT_MIN));
656     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_INIT_POS);
657 
658     EXPECT_TRUE(readResultSet->Move(5));
659     EXPECT_TRUE(!readResultSet->Move(INT_MAX));
660     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_COUNT);
661 
662     /**
663      * @tc.steps: step4. clear the result set resource.
664      * @tc.expected: step4. Success.
665      */
666     EXPECT_EQ(g_kvNbDelegatePtr->CloseResultSet(readResultSet), OK);
667     EXPECT_TRUE(readResultSet == nullptr);
668     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
669     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_nb_delegate_result_set_test"), OK);
670     g_kvNbDelegatePtr = nullptr;
671 }
672 
673 /**
674   * @tc.name: PutBatchVerify001
675   * @tc.desc: This test case use to verify the putBatch interface function
676   * @tc.type: FUNC
677   * @tc.require: AR000CCPOM
678   * @tc.author: wumin
679   */
680 HWTEST_F(DistributedDBInterfacesNBDelegateTest, PutBatchVerify001, TestSize.Level1)
681 {
682     /**
683      * @tc.steps: step1. Get singleVer kvStore by GetKvStore.
684      * @tc.expected: step1. Get database success.
685      */
686     const KvStoreNbDelegate::Option option = {true, true};
687     g_mgr.SetKvStoreConfig(g_config);
688     g_mgr.GetKvStore("distributed_PutBatchVerify_001", option, g_kvNbDelegateCallback);
689     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
690     EXPECT_TRUE(g_kvDelegateStatus == OK);
691 
692     /**
693      * @tc.steps: step2. Insert 10 records into database.
694      * @tc.expected: step2. Insert successfully.
695      */
696     vector<Entry> entries;
697     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
698         Entry entry;
699         entry.key.push_back(i);
700         entry.value.push_back(i);
701         entries.push_back(entry);
702     }
703 
704     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), OK);
705 
706     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
707         Key key;
708         key.push_back(i);
709         Value value;
710         g_kvNbDelegatePtr->Get(key, value);
711         EXPECT_EQ(key, value);
712     }
713 
714     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
715     g_kvNbDelegatePtr = nullptr;
716 }
717 
718 /**
719   * @tc.name: PutBatchVerify002
720   * @tc.desc: This test case use to verify the putBatch interface function while conn is nullptr
721   * @tc.type: FUNC
722   * @tc.require:
723   * @tc.author: caihaoting
724   */
725 HWTEST_F(DistributedDBInterfacesNBDelegateTest, PutBatchVerify002, TestSize.Level1)
726 {
727     /**
728      * @tc.steps: step1. Get singleVer kvStore by GetKvStore.
729      * @tc.expected: step1. Get database success.
730      */
731     const KvStoreNbDelegate::Option option = {true, true};
732     g_mgr.SetKvStoreConfig(g_config);
733     g_mgr.GetKvStore("PutBatchVerify002", option, g_kvNbDelegateCallback);
734     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
735     EXPECT_TRUE(g_kvDelegateStatus == OK);
736 
737     /**
738      * @tc.steps: step2. Insert 10 records into database while conn is nullptr.
739      * @tc.expected: step2. DB_ERROR.
740      */
741     vector<Entry> entries;
742     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
743         Entry entry;
744         entry.key.push_back(i);
745         entry.value.push_back(i);
746         entries.push_back(entry);
747     }
748 
749     auto kvStoreImpl = static_cast<KvStoreNbDelegateImpl *>(g_kvNbDelegatePtr);
750     EXPECT_EQ(kvStoreImpl->Close(), OK);
751     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), DB_ERROR);
752 
753     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
754         Key key;
755         key.push_back(i);
756         Value value;
757         g_kvNbDelegatePtr->Get(key, value);
758         EXPECT_NE(key, value);
759     }
760 
761     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
762     g_kvNbDelegatePtr = nullptr;
763 }
764 
765 /**
766   * @tc.name: SingleVerPutBatch001
767   * @tc.desc: Check for illegal parameters
768   * @tc.type: FUNC
769   * @tc.require: AR000DPTQ8
770   * @tc.author: sunpeng
771   */
772 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatch001, TestSize.Level1)
773 {
774     /**
775      * @tc.steps: step1.
776      *  Create and construct three sets of vector <Entry>, each set of three data contains records:
777      *  (K1, V1) It is illegal for K1 to be greater than 1K, and V1 is 1K in size
778      *  (K2, V2) K2 is legal, V2 is greater than 4M
779      *  (K3, V3) are not legal.
780      */
781     Key illegalKey;
782     DistributedDBToolsUnitTest::GetRandomKeyValue(illegalKey, DBConstant::MAX_KEY_SIZE + 1); // 1K + 1
783     Value illegalValue;
784     DistributedDBToolsUnitTest::GetRandomKeyValue(illegalValue, DBConstant::MAX_VALUE_SIZE + 1); // 4M + 1
785     vector<Entry> entrysKeyIllegal = {KV_ENTRY_1, KV_ENTRY_2, {illegalKey, VALUE_3}};
786     vector<Entry> entrysValueIllegal = {KV_ENTRY_1, KV_ENTRY_2, {KEY_3, illegalValue}};
787     vector<Entry> entrysIllegal = {KV_ENTRY_1, KV_ENTRY_2, {illegalKey, illegalValue}};
788 
789     const KvStoreNbDelegate::Option option = {true, false};
790     g_mgr.SetKvStoreConfig(g_config);
791     g_mgr.GetKvStore("distributed_SingleVerPutBatch_001", option, g_kvNbDelegateCallback);
792     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
793     EXPECT_TRUE(g_kvDelegateStatus == OK);
794     /**
795      * @tc.steps: step2. PutBatch operates on three sets of data.
796      * @tc.expected: step2. All three operations return INVALID_ARGS.
797      */
798     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysKeyIllegal), INVALID_ARGS);
799     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysValueIllegal), INVALID_ARGS);
800     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysIllegal), INVALID_ARGS);
801 
802     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
803     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_001"), OK);
804     g_kvNbDelegatePtr = nullptr;
805 }
806 
807 /**
808   * @tc.name: SingleVerPutBatch002
809   * @tc.desc: PutBatch normal insert function test.
810   * @tc.type: FUNC
811   * @tc.require: AR000DPTQ8
812   * @tc.author: sunpeng
813   */
814 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatch002, TestSize.Level1)
815 {
816     const KvStoreNbDelegate::Option option = {true, false};
817     g_mgr.SetKvStoreConfig(g_config);
818     g_mgr.GetKvStore("distributed_SingleVerPutBatch_002", option, g_kvNbDelegateCallback);
819     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
820     EXPECT_TRUE(g_kvDelegateStatus == OK);
821     /**
822      * @tc.steps: step1.
823      *  Create and build 4 groups of vector <Entry>, which are:
824      *  Vect of empty objects;
825      *  Vect1 of a legal Entry record;
826      *  128 legal Entry records Vect2;
827      *  129 legal Entry records Vect3;
828      */
829     vector<Entry> entrysMaxNumber;
830     for (size_t i = 0; i < DBConstant::MAX_BATCH_SIZE; i++) {
831         Entry entry;
832         entry.key.push_back(i);
833         entry.value.push_back(i);
834         entrysMaxNumber.push_back(entry);
835     }
836     Key keyTemp = {'1', '1'};
837     Value valueTemp;
838     Entry entryTemp = {keyTemp, VALUE_1};
839     vector<Entry> entrysOneRecord = {entryTemp};
840     vector<Entry> entrysOverSize = entrysMaxNumber;
841     entrysOverSize.push_back(entryTemp);
842     /**
843      * @tc.steps: step2. PutBatch operates on four sets of data. and use get check the result of Vect3.
844      * @tc.expected: step2. Returns OK for 129 records, and returns OK for the rest. all get return OK.
845      */
846     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysOverSize), OK); // 128 restrictions have been lifted
847     for (size_t i = 0; i < entrysOverSize.size(); i++) {
848         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysOverSize[i].key, valueTemp), OK);
849     }
850     /**
851      * @tc.steps: step3. Use get check the result of Vect2.
852      * @tc.expected: step3. Return OK and get the correct value.
853      */
854     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysOneRecord), OK);
855     EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueTemp), OK);
856     EXPECT_EQ(valueTemp, VALUE_1);
857     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysMaxNumber), OK);
858      /**
859      * @tc.steps: step4. Use get check the result of Vect3.
860      * @tc.expected: step4. Return OK and get the correct value.
861      */
862     for (size_t i = 0; i < entrysMaxNumber.size(); i++) {
863         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysMaxNumber[i].key, valueTemp), OK);
864         EXPECT_EQ(valueTemp, entrysMaxNumber[i].value);
865     }
866 
867     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
868     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_002"), OK);
869     g_kvNbDelegatePtr = nullptr;
870 }
871 
872 /**
873   * @tc.name: SingleVerPutBatch003
874   * @tc.desc: Check interface atomicity
875   * @tc.type: FUNC
876   * @tc.require: AR000DPTQ8
877   * @tc.author: sunpeng
878   */
879 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatch003, TestSize.Level1)
880 {
881     const KvStoreNbDelegate::Option option = {true, false};
882     g_mgr.SetKvStoreConfig(g_config);
883     g_mgr.GetKvStore("distributed_SingleVerPutBatch_003", option, g_kvNbDelegateCallback);
884     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
885     EXPECT_TRUE(g_kvDelegateStatus == OK);
886     /**
887      * @tc.steps: step1. Create and construct a set of vector <Entry> with a total of 128 data,
888      * including one illegal data. And call PutBatch interface to insert.
889      */
890     vector<Entry> entrysMaxNumber;
891     for (size_t i = 0; i < DBConstant::MAX_BATCH_SIZE; i++) {
892         Entry entry;
893         entry.key.push_back(i);
894         entry.value.push_back(i);
895         entrysMaxNumber.push_back(entry);
896     }
897     Key illegalKey;
898     Value valueTemp;
899     DistributedDBToolsUnitTest::GetRandomKeyValue(illegalKey, DBConstant::MAX_KEY_SIZE + 1); // 1K + 1
900     entrysMaxNumber[0].key = illegalKey;
901 
902     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysMaxNumber), INVALID_ARGS);
903     /**
904      * @tc.steps: step2. Use Get interface to query 128 corresponding key values.
905      * @tc.expected: step2. All Get interface return NOT_FOUND.
906      */
907     EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysMaxNumber[0].key, valueTemp), INVALID_ARGS);
908     for (size_t i = 1; i < entrysMaxNumber.size(); i++) {
909         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysMaxNumber[i].key, valueTemp), NOT_FOUND);
910     }
911     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
912     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_003"), OK);
913     g_kvNbDelegatePtr = nullptr;
914 }
915 
PreparePutBatch004(vector<Entry> & entrys1,vector<Entry> & entrys2,vector<Entry> & entrys3)916 static void PreparePutBatch004(vector<Entry> &entrys1, vector<Entry> &entrys2, vector<Entry> &entrys3)
917 {
918     const KvStoreNbDelegate::Option option = {true, false};
919     g_mgr.SetKvStoreConfig(g_config);
920     g_mgr.GetKvStore("distributed_SingleVerPutBatch_004", option, g_kvNbDelegateCallback);
921     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
922     EXPECT_TRUE(g_kvDelegateStatus == OK);
923 
924     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
925         Entry entry;
926         entry.key.push_back(i);
927         entry.value.push_back(i);
928         entrys1.push_back(entry);
929     }
930 
931     for (int i = 0; i < DIVIDE_BATCH_PRESET_SIZE; i++) {
932         Entry entry;
933         entry.key.push_back(i);
934         entry.value.push_back(i + VALUE_OFFSET);
935         entrys2.push_back(entry);
936     }
937 
938     for (int i = DIVIDE_BATCH_PRESET_SIZE; i < BATCH_PRESET_SIZE_TEST; i++) {
939         Entry entry;
940         entry.key.push_back(i);
941         entry.value.push_back(i - VALUE_OFFSET);
942         entrys3.push_back(entry);
943     }
944 }
945 
946 /**
947   * @tc.name: SingleVerPutBatch004
948   * @tc.desc: Check interface data insertion and update functions.
949   * @tc.type: FUNC
950   * @tc.require: AR000DPTQ8
951   * @tc.author: sunpeng
952   */
953 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatch004, TestSize.Level1)
954 {
955     /**
956      * @tc.steps: step1.
957      *  Construct three groups of three vector <Entry>:
958      *  (1) entrys1: key1 ~ 10, corresponding to Value1 ~ 10;
959      *  (2) entrys2: key1 ~ 5, corresponding to Value6 ~ 10;
960      *  (3) entrys3: key6 ~ 10, corresponding to Value1 ~ 5;
961      */
962     vector<Entry> entrys1;
963     vector<Entry> entrys2;
964     vector<Entry> entrys3;
965     PreparePutBatch004(entrys1, entrys2, entrys3);
966     /**
967      * @tc.steps: step2. PutBatch entrys2.
968      * @tc.expected: step2. PutBatch return OK.
969      */
970     Value valueRead;
971     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys2), OK);
972     /**
973      * @tc.steps: step3. Check PutBatch result.
974      * @tc.expected: step3. Get correct value of key1~5. Key6~10 return NOT_FOUND.
975      */
976     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
977         Key keyTemp;
978         keyTemp.push_back(i);
979         if (i < DIVIDE_BATCH_PRESET_SIZE) {
980             Value valueTemp;
981             valueTemp.push_back(i + VALUE_OFFSET);
982             EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), OK);
983             EXPECT_EQ(valueRead, valueTemp);
984             continue;
985         }
986         EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), NOT_FOUND);
987     }
988     /**
989      * @tc.steps: step4. PutBatch entrys1.
990      * @tc.expected: step4. PutBatch return OK.
991      */
992     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys1), OK);
993     /**
994      * @tc.steps: step5. Check PutBatch result.
995      * @tc.expected: step5. Update and insert value of key1~10 to value1~10.
996      */
997     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
998         Key keyTemp;
999         keyTemp.push_back(i);
1000         if (i < DIVIDE_BATCH_PRESET_SIZE) {
1001             EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), OK);
1002             EXPECT_EQ(valueRead, keyTemp);
1003             continue;
1004         }
1005         EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), OK);
1006         EXPECT_EQ(valueRead, keyTemp);
1007     }
1008     /**
1009      * @tc.steps: step6. PutBatch entrys3.
1010      * @tc.expected: step6. PutBatch return OK.
1011      */
1012     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys3), OK);
1013     /**
1014      * @tc.steps: step7. Check PutBatch result of key1~10.
1015      * @tc.expected: step7. Update value of key5~10 to value1~5.
1016      */
1017     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1018         Key keyTemp;
1019         keyTemp.push_back(i);
1020         if (i < DIVIDE_BATCH_PRESET_SIZE) {
1021             EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), OK);
1022             EXPECT_EQ(valueRead, keyTemp);
1023             continue;
1024         }
1025         Value valueTemp;
1026         valueTemp.push_back(i - VALUE_OFFSET);
1027         EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), OK);
1028         EXPECT_EQ(valueRead, valueTemp);
1029     }
1030 
1031     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1032     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_004"), OK);
1033     g_kvNbDelegatePtr = nullptr;
1034 }
1035 
CreatEntrys(int recordSize,vector<Key> & keys,vector<Value> & values,vector<Entry> & entries)1036 static void CreatEntrys(int recordSize, vector<Key> &keys, vector<Value> &values, vector<Entry> &entries)
1037 {
1038     keys.clear();
1039     values.clear();
1040     entries.clear();
1041     for (int i = 0; i < recordSize; i++) {
1042         string temp = to_string(i);
1043         Entry entry;
1044         Key keyTemp;
1045         Value valueTemp;
1046         for (auto &iter : temp) {
1047             entry.key.push_back(iter);
1048             entry.value.push_back(iter);
1049             keyTemp.push_back(iter);
1050             valueTemp.push_back(iter);
1051         }
1052         keys.push_back(keyTemp);
1053         values.push_back(valueTemp);
1054         entries.push_back(entry);
1055     }
1056 }
1057 
1058 /**
1059   * @tc.name: SingleVerDeleteBatch001
1060   * @tc.desc: Check for illegal parameters.
1061   * @tc.type: FUNC
1062   * @tc.require: AR000DPTQ8
1063   * @tc.author: sunpeng
1064   */
1065 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerDeleteBatch001, TestSize.Level1)
1066 {
1067     const KvStoreNbDelegate::Option option = {true, false};
1068     g_mgr.SetKvStoreConfig(g_config);
1069     g_mgr.GetKvStore("distributed_SingleVerPutBatch_001", option, g_kvNbDelegateCallback);
1070     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1071     EXPECT_TRUE(g_kvDelegateStatus == OK);
1072     /**
1073      * @tc.steps: step1. Create and construct a set of vector <Entry>, containing a total of 10 data keys1 ~ 10,
1074      *  Value1 ~ 10, and call Putbatch interface to insert data.
1075      * @tc.expected: step1. PutBatch successfully.
1076      */
1077     vector<Entry> entries;
1078     vector<Key> keys;
1079     vector<Value> values;
1080     Value valueRead;
1081     CreatEntrys(BATCH_PRESET_SIZE_TEST, keys, values, entries);
1082     vector<Entry> entrysBase = entries;
1083     vector<Key> keysBase = keys;
1084     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysBase), OK);
1085     /**
1086      * @tc.steps: step2. Use Get to check data in database.
1087      * @tc.expected: step2. Get value1~10 by key1~10 successfully.
1088      */
1089     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1090         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysBase[i].key, valueRead), OK);
1091     }
1092     /**
1093      * @tc.steps: step3. Use DeleteBatch interface to transfer 10 + 119 extra keys (total 129).
1094      * @tc.expected: step3. Return OK.
1095      */
1096     CreatEntrys(DBConstant::MAX_BATCH_SIZE + 1, keys, values, entries);
1097     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keys), OK); // 128 restrictions have been lifted
1098     /**
1099      * @tc.steps: step4. Use Get to check data in database.
1100      * @tc.expected: step4. Key1~10 still in database.
1101      */
1102     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1103         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysBase[i].key, valueRead), NOT_FOUND);
1104     }
1105     /**
1106      * @tc.steps: step5. Use the DeleteBatch interface to pass in 10 included
1107      *  keys6 ~ 10 + 123 additional key values ​​(128 in total).
1108      * @tc.expected: step5. DeleteBatch OK.
1109      */
1110     CreatEntrys(DBConstant::MAX_BATCH_SIZE + DIVIDE_BATCH_PRESET_SIZE, keys, values, entries);
1111     keys.erase(keys.begin(), keys.begin() + DIVIDE_BATCH_PRESET_SIZE);
1112     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keys), OK);
1113     /**
1114      * @tc.steps: step6. Use Get to check key1~10 in database.
1115      * @tc.expected: step6. Key1~5 in database, key6~10 have been deleted.
1116      */
1117     for (size_t i = DIVIDE_BATCH_PRESET_SIZE; i < BATCH_PRESET_SIZE_TEST; i++) {
1118         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysBase[i].key, valueRead), NOT_FOUND);
1119     }
1120     /**
1121      * @tc.steps: step7. Repeat Putbatch key1~10, value1~10.
1122      * @tc.expected: step7. Return OK.
1123      */
1124     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysBase), OK);
1125 
1126     Key illegalKey;
1127     DistributedDBToolsUnitTest::GetRandomKeyValue(illegalKey, DBConstant::MAX_KEY_SIZE + 1); // 1K + 1
1128     keysBase.push_back(illegalKey);
1129     /**
1130      * @tc.steps: step8. Use DeleteBatch interface to pass in 10 + 1(larger than 1K) keys.
1131      * @tc.expected: step8. Return INVALID_ARGS.
1132      */
1133     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keysBase), INVALID_ARGS);
1134     /**
1135      * @tc.steps: step9. Use Get to check key1~10 in database.
1136      * @tc.expected: step9. Delete those data failed.
1137      */
1138     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1139         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysBase[i].key, valueRead), OK);
1140     }
1141     /**
1142      * @tc.steps: step10. Use DeleteBatch interface to pass in 10(in database) + 1 valid keys.
1143      * @tc.expected: step10. Delete those data successfully.
1144      */
1145     keysBase.back().erase(keysBase.back().begin(), keysBase.back().begin() + 1);
1146     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keysBase), OK);
1147     /**
1148      * @tc.steps: step11. Check data.
1149      * @tc.expected: step11. DeleteBatch successfully.
1150      */
1151     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1152         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysBase[i].key, valueRead), NOT_FOUND);
1153     }
1154 
1155     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1156     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_001"), OK);
1157     g_kvNbDelegatePtr = nullptr;
1158 }
1159 
1160 /**
1161   * @tc.name: SingleVerDeleteBatch002
1162   * @tc.desc: Check normal delete batch ability.
1163   * @tc.type: FUNC
1164   * @tc.require: AR000DPTQ8
1165   * @tc.author: sunpeng
1166   */
1167 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerDeleteBatch002, TestSize.Level1)
1168 {
1169     const KvStoreNbDelegate::Option option = {true, false};
1170     g_mgr.SetKvStoreConfig(g_config);
1171     g_mgr.GetKvStore("distributed_SingleVerPutBatch_002", option, g_kvNbDelegateCallback);
1172     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1173     EXPECT_TRUE(g_kvDelegateStatus == OK);
1174     /**
1175      * @tc.steps: step1. Create a group of vector <Entry>, containing a total of 10 data keys1 ~ 10, Value1 ~ 10,
1176      *  call the Putbatch interface to insert data.
1177      * @tc.expected: step1. Insert to database successfully.
1178      */
1179     vector<Entry> entries;
1180     vector<Key> keysBase;
1181     vector<Value> values;
1182     CreatEntrys(BATCH_PRESET_SIZE_TEST, keysBase, values, entries);
1183 
1184     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), OK);
1185     /**
1186      * @tc.steps: step2. Check data.
1187      * @tc.expected: step2. Get key1~10 successfully.
1188      */
1189     Value valueRead;
1190     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1191         EXPECT_EQ(g_kvNbDelegatePtr->Get(keysBase[i], valueRead), OK);
1192     }
1193     /**
1194      * @tc.steps: step3. DeleteBatch key1~5.
1195      * @tc.expected: step3. Return OK.
1196      */
1197     vector<Key> keys(keysBase.begin(), keysBase.begin() + DIVIDE_BATCH_PRESET_SIZE);
1198     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keys), OK);
1199     /**
1200      * @tc.steps: step4. Check key1~10.
1201      * @tc.expected: step4. Key1~5 deleted, key6~10 existed.
1202      */
1203     for (size_t i = 0; i < DIVIDE_BATCH_PRESET_SIZE; i++) {
1204         EXPECT_EQ(g_kvNbDelegatePtr->Get(keysBase[i], valueRead), NOT_FOUND);
1205     }
1206     for (size_t i = DIVIDE_BATCH_PRESET_SIZE; i < BATCH_PRESET_SIZE_TEST; i++) {
1207         EXPECT_EQ(g_kvNbDelegatePtr->Get(keysBase[i], valueRead), OK);
1208     }
1209     /**
1210      * @tc.steps: step5. DeleteBatch key1~10.
1211      * @tc.expected: step5. Return OK.
1212      */
1213     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keysBase), OK);
1214     /**
1215      * @tc.steps: step6. Check key1~10.
1216      * @tc.expected: step6. Key1~10 deleted successfully.
1217      */
1218     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1219         EXPECT_EQ(g_kvNbDelegatePtr->Get(keysBase[i], valueRead), NOT_FOUND);
1220     }
1221     /**
1222      * @tc.steps: step7. DeleteBatch key1~10 once again.
1223      * @tc.expected: step7. Return OK.
1224      */
1225     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keysBase), OK);
1226 
1227     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1228     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_002"), OK);
1229     g_kvNbDelegatePtr = nullptr;
1230 }
1231 
1232 /**
1233   * @tc.name: SingleVerDeleteBatch007
1234   * @tc.desc: Check normal delete batch while conn is nullptr.
1235   * @tc.type: FUNC
1236   * @tc.require:
1237   * @tc.author: caihaoting
1238   */
1239 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerDeleteBatch007, TestSize.Level1)
1240 {
1241     const KvStoreNbDelegate::Option option = {true, false};
1242     g_mgr.SetKvStoreConfig(g_config);
1243     g_mgr.GetKvStore("SingleVerDeleteBatch007", option, g_kvNbDelegateCallback);
1244     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1245     EXPECT_TRUE(g_kvDelegateStatus == OK);
1246     /**
1247      * @tc.steps: step1. Create a group of vector <Entry>, containing a total of 10 data keys1 ~ 10, Value1 ~ 10,
1248      *  call the Putbatch interface to insert data.
1249      * @tc.expected: step1. Insert to database successfully.
1250      */
1251     vector<Entry> entries;
1252     vector<Key> keysBase;
1253     vector<Value> values;
1254     CreatEntrys(BATCH_PRESET_SIZE_TEST, keysBase, values, entries);
1255 
1256     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), OK);
1257     /**
1258      * @tc.steps: step2. DeleteBatch operates on sets of data while conn is nullptr.
1259      * @tc.expected: step2. return DB_ERROR.
1260      */
1261     auto kvStoreImpl = static_cast<KvStoreNbDelegateImpl *>(g_kvNbDelegatePtr);
1262     EXPECT_EQ(kvStoreImpl->Close(), OK);
1263     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keysBase), DB_ERROR);
1264 
1265     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1266     EXPECT_EQ(g_mgr.DeleteKvStore("SingleVerDeleteBatch007"), OK);
1267     g_kvNbDelegatePtr = nullptr;
1268 }
1269 
1270 /**
1271   * @tc.name: SingleVerPutBatchObserver001
1272   * @tc.desc: Test the observer function of PutBatch() interface.
1273   * @tc.type: FUNC
1274   * @tc.require: AR000DPTTA
1275   * @tc.author: wumin
1276   */
1277 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatchObserver001, TestSize.Level1)
1278 {
1279     /**
1280      * @tc.steps:step1. Get the nb delegate.
1281      * @tc.expected: step1. Get results OK and non-null delegate.
1282      */
1283     KvStoreNbDelegate::Option option = {true, false, false};
1284     g_mgr.GetKvStore("distributed_SingleVerPutBatchObserver_001", option, g_kvNbDelegateCallback);
1285     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1286     EXPECT_TRUE(g_kvDelegateStatus == OK);
1287 
1288     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
1289     ASSERT_TRUE(observer != nullptr);
1290     /**
1291      * @tc.steps:step2. Register the non-null observer for the special key.
1292      * @tc.expected: step2. Register results OK.
1293      */
1294     Key key;
1295     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_NATIVE, observer), OK);
1296     // register same observer twice will return already_set
1297     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_NATIVE, observer), ALREADY_SET);
1298     /**
1299      * @tc.steps:step3. Put batch data.
1300      * @tc.expected: step3. Returns OK.
1301      */
1302     vector<Entry> entrysBase;
1303     vector<Key> keysBase;
1304     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST + 1, entrysBase, keysBase);
1305 
1306     vector<Entry> entries(entrysBase.begin(), entrysBase.end() - 1);
1307     EXPECT_EQ(entries.size(), 10UL);
1308     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), OK);
1309     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1310     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entries, observer->GetEntriesInserted()));
1311     /**
1312      * @tc.steps:step4. Delete the batch data.
1313      * @tc.expected: step4. Returns OK.
1314      */
1315     vector<Key> keys(keysBase.begin() + 5, keysBase.end());
1316     EXPECT_EQ(keys.size(), 6UL);
1317     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keys), OK);
1318     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1319     vector<Entry> entrysDel(entrysBase.begin() + 5, entrysBase.end() - 1);
1320     EXPECT_EQ(entrysDel.size(), 5UL);
1321     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrysDel, observer->GetEntriesDeleted()));
1322     /**
1323      * @tc.steps:step5. UnRegister the observer.
1324      * @tc.expected: step5. Returns OK.
1325      */
1326     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
1327     delete observer;
1328     observer = nullptr;
1329     /**
1330      * @tc.steps:step6. Close the kv store.
1331      * @tc.expected: step6. Results OK and delete successfully.
1332      */
1333     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1334     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatchObserver_001"), OK);
1335     g_kvNbDelegatePtr = nullptr;
1336 }
1337 
1338 /**
1339   * @tc.name: SingleVerPutBatchObserver002
1340   * @tc.desc: Test the observer function of PutBatch() for invalid input.
1341   * @tc.type: FUNC
1342   * @tc.require: AR000DPTTA
1343   * @tc.author: wumin
1344   */
1345 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatchObserver002, TestSize.Level4)
1346 {
1347     /**
1348      * @tc.steps:step1. Get the nb delegate.
1349      * @tc.expected: step1. Get results OK and non-null delegate.
1350      */
1351     KvStoreNbDelegate::Option option = {true, false, false};
1352     g_mgr.GetKvStore("distributed_SingleVerPutBatchObserver_002", option, g_kvNbDelegateCallback);
1353     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1354     EXPECT_TRUE(g_kvDelegateStatus == OK);
1355 
1356     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
1357     ASSERT_TRUE(observer != nullptr);
1358     /**
1359      * @tc.steps:step2. Register the non-null observer for the special key.
1360      * @tc.expected: step2. Register results OK.
1361      */
1362     Key key;
1363     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_NATIVE, observer), OK);
1364     /**
1365      * @tc.steps:step3. Put invalid batch data.
1366      * @tc.expected: step3. Returns INVALID_ARGS.
1367      */
1368     vector<Entry> entrys2;
1369     vector<Key> keys2;
1370     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrys2, keys2);
1371     EXPECT_EQ(entrys2.size(), 10UL);
1372 
1373     vector<Entry> entrysInvalid;
1374     vector<Key> keysInvalid;
1375     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrysInvalid, keysInvalid,
1376         DBConstant::MAX_KEY_SIZE + 10);
1377     EXPECT_EQ(entrysInvalid.size(), 10UL);
1378     entrys2[0].key = entrysInvalid[0].key;
1379 
1380     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys2), INVALID_ARGS);
1381     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1382     EXPECT_TRUE(observer->GetEntriesInserted().empty());
1383     /**
1384      * @tc.steps:step4. Put MAX valid value batch data.
1385      * @tc.expected: step4. Returns OK.
1386      */
1387     vector<Entry> entrys3;
1388     vector<Key> keys3;
1389 
1390     DistributedDBUnitTest::GenerateRecords(DBConstant::MAX_BATCH_SIZE, entrys3, keys3);
1391     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys3), OK);
1392     LOGD("sleep begin");
1393     // sleep 20 seconds
1394     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME * 10));
1395     LOGD("sleep end");
1396     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrys3, observer->GetEntriesInserted()));
1397     /**
1398      * @tc.steps:step5. UnRegister the observer.
1399      * @tc.expected: step5. Returns OK.
1400      */
1401     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
1402     delete observer;
1403     observer = nullptr;
1404     /**
1405      * @tc.steps:step6. Close the kv store.
1406      * @tc.expected: step6. Results OK and delete successfully.
1407      */
1408     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1409     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatchObserver_002"), OK);
1410     g_kvNbDelegatePtr = nullptr;
1411 }
1412 
1413 /**
1414   * @tc.name: SingleVerPutBatchObserver003
1415   * @tc.desc: Test the observer function of PutBatch() update function.
1416   * @tc.type: FUNC
1417   * @tc.require: AR000DPTTA
1418   * @tc.author: wumin
1419   */
1420 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatchObserver003, TestSize.Level1)
1421 {
1422     /**
1423      * @tc.steps:step1. Get the nb delegate.
1424      * @tc.expected: step1. Get results OK and non-null delegate.
1425      */
1426     KvStoreNbDelegate::Option option = {true, false, false};
1427     g_mgr.GetKvStore("distributed_SingleVerPutBatchObserver_003", option, g_kvNbDelegateCallback);
1428     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1429     EXPECT_TRUE(g_kvDelegateStatus == OK);
1430 
1431     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
1432     ASSERT_TRUE(observer != nullptr);
1433     /**
1434      * @tc.steps:step2. Register the non-null observer for the special key.
1435      * @tc.expected: step2. Register results OK.
1436      */
1437     Key key;
1438     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_NATIVE, observer), OK);
1439     /**
1440      * @tc.steps:step3. Put batch data.
1441      * @tc.expected: step3. Returns OK.
1442      */
1443     vector<Entry> entrysAdd;
1444     vector<Key> keysAdd;
1445     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrysAdd, keysAdd);
1446 
1447     EXPECT_EQ(entrysAdd.size(), 10UL);
1448     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysAdd), OK);
1449     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1450     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrysAdd, observer->GetEntriesInserted()));
1451     /**
1452      * @tc.steps:step4. Update the batch data.
1453      * @tc.expected: step4. Returns OK.
1454      */
1455     vector<Entry> entrysUpdate;
1456     vector<Key> keysUpdate;
1457     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrysUpdate, keysUpdate, DEFAULT_KEY_VALUE_SIZE,
1458         DEFAULT_KEY_VALUE_SIZE + 10);
1459 
1460     EXPECT_EQ(entrysUpdate.size(), 10UL);
1461     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysUpdate), OK);
1462     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1463     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrysUpdate, observer->GetEntriesUpdated()));
1464     /**
1465      * @tc.steps:step5. UnRegister the observer.
1466      * @tc.expected: step5. Returns OK.
1467      */
1468     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
1469     delete observer;
1470     observer = nullptr;
1471     /**
1472      * @tc.steps:step6. Close the kv store.
1473      * @tc.expected: step6. Results OK and delete successfully.
1474      */
1475     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1476     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatchObserver_003"), OK);
1477     g_kvNbDelegatePtr = nullptr;
1478 }
1479 
1480 /**
1481   * @tc.name: SingleVerPutBatchObserver004
1482   * @tc.desc: Test the observer function of PutBatch(), same keys handle.
1483   * @tc.type: FUNC
1484   * @tc.require: AR000DPTTA
1485   * @tc.author: wumin
1486   */
1487 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatchObserver004, TestSize.Level1)
1488 {
1489     /**
1490      * @tc.steps:step1. Get the nb delegate.
1491      * @tc.expected: step1. Get results OK and non-null delegate.
1492      */
1493     KvStoreNbDelegate::Option option = {true, false, false};
1494     g_mgr.GetKvStore("distributed_SingleVerPutBatchObserver_004", option, g_kvNbDelegateCallback);
1495     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1496     EXPECT_TRUE(g_kvDelegateStatus == OK);
1497 
1498     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
1499     ASSERT_TRUE(observer != nullptr);
1500     /**
1501      * @tc.steps:step2. Register the non-null observer for the special key.
1502      * @tc.expected: step2. Register results OK.
1503      */
1504     Key key;
1505     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_NATIVE, observer), OK);
1506     /**
1507      * @tc.steps:step3. Put batch data.
1508      * @tc.expected: step3. Returns OK.
1509      */
1510     vector<Entry> entrys1;
1511     vector<Key> keys1;
1512     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrys1, keys1);
1513     vector<Entry> entrys2;
1514     vector<Key> keys2;
1515     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrys2, keys2, DEFAULT_KEY_VALUE_SIZE,
1516         DEFAULT_KEY_VALUE_SIZE + 10);
1517     entrys1.insert(entrys1.end(), entrys2.begin(), entrys2.end());
1518 
1519     EXPECT_EQ(entrys1.size(), 20UL);
1520     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys1), OK);
1521     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1522     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrys2, observer->GetEntriesInserted()));
1523     EXPECT_EQ(observer->GetEntriesUpdated().size(), 0UL);
1524 
1525     vector<Entry> entrys3;
1526     vector<Key> keys3;
1527     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrys3, keys3, DEFAULT_KEY_VALUE_SIZE,
1528         DEFAULT_KEY_VALUE_SIZE + 20);
1529     vector<Entry> entrys4;
1530     vector<Key> keys4;
1531     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrys4, keys4, DEFAULT_KEY_VALUE_SIZE,
1532         DEFAULT_KEY_VALUE_SIZE + 30);
1533     entrys3.insert(entrys3.end(), entrys4.begin(), entrys4.end());
1534     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys3), OK);
1535     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1536     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrys4, observer->GetEntriesUpdated()));
1537     EXPECT_EQ(observer->GetEntriesInserted().size(), 0UL);
1538 
1539     /**
1540      * @tc.steps:step4. UnRegister the observer.
1541      * @tc.expected: step4. Returns OK.
1542      */
1543     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
1544     delete observer;
1545     observer = nullptr;
1546     /**
1547      * @tc.steps:step5. Close the kv store.
1548      * @tc.expected: step5. Results OK and delete successfully.
1549      */
1550     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1551     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatchObserver_004"), OK);
1552     g_kvNbDelegatePtr = nullptr;
1553 }
1554 
1555 /**
1556   * @tc.name: SingleVerDeleteBatchObserver001
1557   * @tc.desc: Test the observer function of DeleteBatch() interface.
1558   * @tc.type: FUNC
1559   * @tc.require: AR000DPTTA
1560   * @tc.author: wumin
1561   */
1562 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerDeleteBatchObserver001, TestSize.Level1)
1563 {
1564     /**
1565      * @tc.steps:step1. Get the nb delegate.
1566      * @tc.expected: step1. Get results OK and non-null delegate.
1567      */
1568     KvStoreNbDelegate::Option option = {true, false, false};
1569     g_mgr.GetKvStore("distributed_SingleVerDeleteBatchObserver_001", option, g_kvNbDelegateCallback);
1570     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1571     EXPECT_TRUE(g_kvDelegateStatus == OK);
1572 
1573     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
1574     ASSERT_TRUE(observer != nullptr);
1575     /**
1576      * @tc.steps:step2. Register the non-null observer for the special key.
1577      * @tc.expected: step2. Register results OK.
1578      */
1579     Key key;
1580     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_NATIVE, observer), OK);
1581     /**
1582      * @tc.steps:step3. Put batch data.
1583      * @tc.expected: step3. Returns OK.
1584      */
1585     vector<Entry> entries;
1586     vector<Key> keys;
1587     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entries, keys);
1588     EXPECT_EQ(entries.size(), 10UL);
1589 
1590     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), OK);
1591     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1592     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entries, observer->GetEntriesInserted()));
1593     /**
1594      * @tc.steps:step4. Delete the batch data.
1595      * @tc.expected: step4. Returns OK.
1596      */
1597     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keys), OK);
1598     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1599     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entries, observer->GetEntriesDeleted()));
1600     /**
1601      * @tc.steps:step5. UnRegister the observer.
1602      * @tc.expected: step5. Returns OK.
1603      */
1604     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
1605     delete observer;
1606     observer = nullptr;
1607     /**
1608      * @tc.steps:step6. Close the kv store.
1609      * @tc.expected: step6. Results OK and delete successfully.
1610      */
1611     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1612     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerDeleteBatchObserver_001"), OK);
1613     g_kvNbDelegatePtr = nullptr;
1614 }
1615 
1616 /**
1617   * @tc.name: SingleVerConcurrentPut001
1618   * @tc.desc: Test put the data concurrently, and check the timestamp.
1619   * @tc.type: FUNC
1620   * @tc.require: AR000DPTTA
1621   * @tc.author: wangbingquan
1622   */
1623 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerConcurrentPut001, TestSize.Level4)
1624 {
1625     /**
1626      * @tc.steps:step1. Get the nb delegate.
1627      * @tc.expected: step1. Get results OK and non-null delegate.
1628      */
1629     KvStoreNbDelegate::Option option = {true, false, false};
1630     g_mgr.GetKvStore("concurrentPutTest", option, g_kvNbDelegateCallback);
1631     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1632     EXPECT_TRUE(g_kvDelegateStatus == OK);
1633 
1634     for (size_t i = 0; i < CON_PUT_THREAD_NUM * PER_THREAD_PUT_NUM; i++) {
1635         Entry entry;
1636         DistributedDBToolsUnitTest::GetRandomKeyValue(entry.key, DEFAULT_KEY_VALUE_SIZE);
1637         DistributedDBToolsUnitTest::GetRandomKeyValue(entry.value);
1638         g_entriesForConcurrency.push_back(std::move(entry));
1639     }
1640 
1641     /**
1642      * @tc.steps:step2. Put data concurrently in 4 threads.
1643      * @tc.expected: step2. Put OK, and the timestamp order is same with the rowid.
1644      */
1645     std::thread thread1(std::bind(PutData, g_kvNbDelegatePtr, 0)); // 0th thread.
1646     std::thread thread2(std::bind(PutData, g_kvNbDelegatePtr, 1)); // 1th thread.
1647     std::thread thread3(std::bind(PutData, g_kvNbDelegatePtr, 2)); // 2th thread.
1648     std::thread thread4(std::bind(PutData, g_kvNbDelegatePtr, 3)); // 3th thread.
1649 
1650     thread1.join();
1651     thread2.join();
1652     thread3.join();
1653     thread4.join();
1654 
1655     EXPECT_EQ(CheckDataTimestamp("concurrentPutTest"), true);
1656 
1657     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1658     EXPECT_EQ(g_mgr.DeleteKvStore("concurrentPutTest"), OK);
1659     g_kvNbDelegatePtr = nullptr;
1660 }
1661 
1662 /**
1663   * @tc.name: SingleVerGetLocalEntries001
1664   * @tc.desc: Test GetLocalEntries interface for the single ver database.
1665   * @tc.type: FUNC
1666   * @tc.require: AR000DPTTA
1667   * @tc.author: wangbingquan
1668   */
1669 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerGetLocalEntries001, TestSize.Level1)
1670 {
1671     /**
1672      * @tc.steps:step1. Get the nb delegate.
1673      * @tc.expected: step1. Get results OK and non-null delegate.
1674      */
1675     KvStoreNbDelegate::Option option = {true, false, false};
1676     g_mgr.GetKvStore("concurrentPutTest", option, g_kvNbDelegateCallback);
1677     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1678     EXPECT_TRUE(g_kvDelegateStatus == OK);
1679 
1680     /**
1681      * @tc.steps:step2. Put one data whose key has prefix 'p' into the local zone.
1682      */
1683     Entry entry1 = {{'p'}, {'q'}};
1684     EXPECT_EQ(g_kvNbDelegatePtr->PutLocal(entry1.key, entry1.value), OK);
1685 
1686     /**
1687      * @tc.steps:step3. Get batch data whose key has prefix 'k' from the local zone.
1688      * @tc.expected: step3. Get results NOT_FOUND.
1689      */
1690     std::vector<Entry> entries;
1691     EXPECT_EQ(g_kvNbDelegatePtr->GetLocalEntries({'k'}, entries), NOT_FOUND);
1692 
1693     /**
1694      * @tc.steps:step4. Put two data whose key have prefix 'k' into the local zone.
1695      */
1696     Entry entry2 = {{'k', '1'}, {'d'}};
1697     Entry entry3 = {{'k', '2'}, {'d'}};
1698     EXPECT_EQ(g_kvNbDelegatePtr->PutLocal(entry2.key, entry2.value), OK);
1699     EXPECT_EQ(g_kvNbDelegatePtr->PutLocal(entry3.key, entry3.value), OK);
1700 
1701     /**
1702      * @tc.steps:step5. Get batch data whose key has prefix 'k' from the local zone.
1703      * @tc.expected: step5. Get results OK, and the entries size is 2.
1704      */
1705     EXPECT_EQ(g_kvNbDelegatePtr->GetLocalEntries({'k'}, entries), OK);
1706     EXPECT_EQ(entries.size(), 2UL);
1707 
1708     /**
1709      * @tc.steps:step6. Get batch data whose key has empty prefix from the local zone.
1710      * @tc.expected: step6. Get results OK, and the entries size is 3.
1711      */
1712     EXPECT_EQ(g_kvNbDelegatePtr->GetLocalEntries({}, entries), OK);
1713     EXPECT_EQ(entries.size(), 3UL);
1714 
1715     /**
1716      * @tc.steps:step7. Delete one data whose key has prefix 'k' from the local zone.
1717      */
1718     EXPECT_EQ(g_kvNbDelegatePtr->DeleteLocal(entry3.key), OK);
1719 
1720     /**
1721      * @tc.steps:step8. Get batch data whose key has prefix 'k' from the local zone.
1722      * @tc.expected: step8. Get results OK, and the entries size is 1.
1723      */
1724     EXPECT_EQ(g_kvNbDelegatePtr->GetLocalEntries({'k'}, entries), OK);
1725     EXPECT_EQ(entries.size(), 1UL);
1726 
1727     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1728     EXPECT_EQ(g_mgr.DeleteKvStore("concurrentPutTest"), OK);
1729     g_kvNbDelegatePtr = nullptr;
1730 }
1731 
PreDataForQueryByPreFixKey()1732 static vector<Entry> PreDataForQueryByPreFixKey()
1733 {
1734     vector<Entry> res;
1735     for (int i = 0; i < 5; i++) { // Random 5 for test
1736         Key key = DistributedDBToolsUnitTest::GetRandPrefixKey({'a', 'b'}, 1024);
1737         std::string validData = "{\"field_name1\":null, \"field_name2\":" + std::to_string(rand()) + "}";
1738         Value value(validData.begin(), validData.end());
1739         res.push_back({key, value});
1740     }
1741 
1742     for (int i = 0; i < 5; i++) { // Random 5 for test
1743         Key key = DistributedDBToolsUnitTest::GetRandPrefixKey({'a', 'c'}, 1024);
1744         std::string validData = "{\"field_name1\":null, \"field_name2\":" + std::to_string(rand()) + "}";
1745         Value value(validData.begin(), validData.end());
1746         res.push_back({key, value});
1747     }
1748     return res;
1749 }
1750 
1751 /**
1752   * @tc.name: QueryPreFixKey002
1753   * @tc.desc: The query method without filtering the field can query non-schma databases
1754   * @tc.type: FUNC
1755   * @tc.require: AR000EPARK
1756   * @tc.author: sunpeng
1757   */
1758 HWTEST_F(DistributedDBInterfacesNBDelegateTest, QueryPreFixKey002, TestSize.Level1)
1759 {
1760     /**
1761      * @tc.steps:step1. Create non-schma databases
1762      */
1763     KvStoreNbDelegate::Option option = {true, false, false};
1764     g_mgr.GetKvStore("QueryPreFixKey002", option, g_kvNbDelegateCallback);
1765     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1766     EXPECT_TRUE(g_kvDelegateStatus == OK);
1767 
1768     vector<Entry> entries = PreDataForQueryByPreFixKey();
1769     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), OK);
1770 
1771     /**
1772      * @tc.steps:step2. Get query object with prefixkey limit combination.
1773      * @tc.expected: step2. Get results OK, and the entries size right.
1774      */
1775     Query query = Query::Select().PrefixKey({'a', 'c'});
1776     std::vector<Entry> entriesRes;
1777     int errCode = g_kvNbDelegatePtr->GetEntries(query, entriesRes);
1778     EXPECT_EQ(errCode, OK);
1779     EXPECT_EQ(entriesRes.size(), 5ul);
1780     for (size_t i = 0; i < entriesRes.size(); i++) {
1781         EXPECT_EQ(entriesRes[i].key.front(), 'a');
1782         EXPECT_EQ(entriesRes[i].key[1], 'c');
1783     }
1784     int count = -1;
1785     g_kvNbDelegatePtr->GetCount(query, count);
1786     EXPECT_EQ(count, 5);
1787 
1788     Query query1 = Query::Select().PrefixKey({}).Limit(4, 0);
1789     errCode = g_kvNbDelegatePtr->GetEntries(query1, entriesRes);
1790     EXPECT_EQ(errCode, OK);
1791     EXPECT_EQ(entriesRes.size(), 4ul);
1792 
1793     Query query2 = Query::Select().PrefixKey(Key(1025, 'a'));
1794     errCode = g_kvNbDelegatePtr->GetEntries(query2, entriesRes);
1795     EXPECT_EQ(errCode, INVALID_ARGS);
1796 
1797     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1798     EXPECT_TRUE(g_mgr.DeleteKvStore("QueryPreFixKey002") == OK);
1799     g_kvNbDelegatePtr = nullptr;
1800 }
1801 
1802 /**
1803   * @tc.name: SingleVerGetSecurityOption001
1804   * @tc.desc: Test GetSecurityOption interface for the single ver database.
1805   * @tc.type: FUNC
1806   * @tc.require: AR000EV1G2
1807   * @tc.author: liuwenkai
1808   */
1809 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerGetSecurityOption001, TestSize.Level1)
1810 {
1811     SecurityOption savedOption;
1812     std::shared_ptr<IProcessSystemApiAdapter> adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
1813     EXPECT_TRUE(adapter);
1814     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(adapter);
1815     KvStoreNbDelegate::Option option = {true, false, false};
1816 
1817     /**
1818      * @tc.steps:step1. Create databases without securityOption.
1819      * @tc.expected: step2. Returns a non-null kvstore but can not get SecurityOption.
1820      */
1821     g_mgr.GetKvStore("SingleVerGetSecurityOption001", option, g_kvNbDelegateCallback);
1822     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1823     EXPECT_TRUE(g_kvDelegateStatus == OK);
1824     EXPECT_TRUE(g_kvNbDelegatePtr->GetSecurityOption(savedOption) == OK);
1825     EXPECT_TRUE(savedOption.securityLabel == 0);
1826     EXPECT_TRUE(savedOption.securityFlag == 0);
1827     KvStoreNbDelegate *kvNbDelegatePtr1 = g_kvNbDelegatePtr;
1828 
1829     /**
1830      * @tc.steps:step2. Create databases with new securityOption(Check ignore the new option).
1831      * @tc.expected: step2. Returns non-null kvstore.
1832      */
1833     option.secOption.securityLabel = S3;
1834     option.secOption.securityFlag = 1;
1835     g_mgr.GetKvStore("SingleVerGetSecurityOption001", option, g_kvNbDelegateCallback);
1836     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1837     EXPECT_TRUE(g_kvDelegateStatus == OK);
1838     EXPECT_TRUE(g_kvNbDelegatePtr->GetSecurityOption(savedOption) == OK);
1839     EXPECT_TRUE(savedOption.securityLabel == 0);
1840     EXPECT_TRUE(savedOption.securityFlag == 0);
1841 
1842     EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr1), OK);
1843     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1844     g_kvNbDelegatePtr = nullptr;
1845     EXPECT_TRUE(g_mgr.DeleteKvStore("SingleVerGetSecurityOption001") == OK);
1846 }
1847 
1848 /**
1849   * @tc.name: SingleVerGetSecurityOption002
1850   * @tc.desc: Test GetSecurityOption interface for the single ver database.
1851   * @tc.type: FUNC
1852   * @tc.require: AR000EV1G2
1853   * @tc.author: liuwenkai
1854   */
1855 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerGetSecurityOption002, TestSize.Level1)
1856 {
1857     SecurityOption savedOption;
1858     std::shared_ptr<IProcessSystemApiAdapter> adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
1859     EXPECT_TRUE(adapter != nullptr);
1860     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(adapter);
1861     KvStoreNbDelegate::Option option = {true, false, false};
1862 
1863     /**
1864      * @tc.steps:step1. Create databases with securityOption.
1865      * @tc.expected: step2. Returns a non-null kvstore and get right SecurityOption.
1866      */
1867     option.secOption.securityLabel = S3;
1868     option.secOption.securityFlag = 1;
1869     g_mgr.GetKvStore("SingleVerGetSecurityOption002", option, g_kvNbDelegateCallback);
1870     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1871     EXPECT_TRUE(g_kvDelegateStatus == OK);
1872     EXPECT_TRUE(g_kvNbDelegatePtr->GetSecurityOption(savedOption) == OK);
1873     EXPECT_TRUE(savedOption.securityLabel == S3);
1874     EXPECT_TRUE(savedOption.securityFlag == 1);
1875     KvStoreNbDelegate *kvNbDelegatePtr1 = g_kvNbDelegatePtr;
1876 
1877     /**
1878      * @tc.steps:step2. Create databases without securityOption.
1879      * @tc.expected: step2. Returns a non-null kvstore and get right SecurityOption.
1880      */
1881     option.secOption.securityLabel = 0;
1882     option.secOption.securityFlag = 0;
1883     g_mgr.GetKvStore("SingleVerGetSecurityOption002", option, g_kvNbDelegateCallback);
1884     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1885     EXPECT_TRUE(g_kvDelegateStatus == OK);
1886     EXPECT_TRUE(g_kvNbDelegatePtr->GetSecurityOption(savedOption) == OK);
1887     EXPECT_TRUE(savedOption.securityLabel == S3);
1888     EXPECT_TRUE(savedOption.securityFlag == 1);
1889 
1890     EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr1), OK);
1891     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1892     g_kvNbDelegatePtr = nullptr;
1893     EXPECT_TRUE(g_mgr.DeleteKvStore("SingleVerGetSecurityOption002") == OK);
1894 }
1895 
1896 /**
1897  * @tc.name: MaxLogSize001
1898  * @tc.desc: Test the pragma cmd of the max log size limit.
1899  * @tc.type: FUNC
1900  * @tc.require:
1901  * @tc.author: wangbingquan
1902  */
1903 HWTEST_F(DistributedDBInterfacesNBDelegateTest, MaxLogSize001, TestSize.Level2)
1904 {
1905     /**
1906      * @tc.steps:step1. Create database.
1907      * @tc.expected: step1. Returns a non-null kvstore.
1908      */
1909     KvStoreNbDelegate::Option option;
1910     g_mgr.GetKvStore("MaxLogSize001", option, g_kvNbDelegateCallback);
1911     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1912     EXPECT_TRUE(g_kvDelegateStatus == OK);
1913 
1914     /**
1915      * @tc.steps:step2. Setting the max log limit for the valid value.
1916      * @tc.expected: step2. Returns OK.
1917      */
1918     uint64_t logSize = DBConstant::MAX_LOG_SIZE_HIGH;
1919     PragmaData pragLimit = static_cast<PragmaData>(&logSize);
1920     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), OK);
1921 
1922     logSize = DBConstant::MAX_LOG_SIZE_LOW;
1923     pragLimit = static_cast<PragmaData>(&logSize);
1924     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), OK);
1925 
1926     logSize = 10 * 1024 * 1024; // 10M
1927     pragLimit = static_cast<PragmaData>(&logSize);
1928     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), OK);
1929 
1930     /**
1931      * @tc.steps:step3. Setting the max log limit for the invalid value.
1932      * @tc.expected: step3. Returns INLIVAD_ARGS.
1933      */
1934     logSize = DBConstant::MAX_LOG_SIZE_HIGH + 1;
1935     pragLimit = static_cast<PragmaData>(&logSize);
1936     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), INVALID_ARGS);
1937 
1938     logSize = DBConstant::MAX_LOG_SIZE_LOW - 1;
1939     pragLimit = static_cast<PragmaData>(&logSize);
1940     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), INVALID_ARGS);
1941     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1942     g_kvNbDelegatePtr = nullptr;
1943     EXPECT_TRUE(g_mgr.DeleteKvStore("MaxLogSize001") == OK);
1944 }
1945 
1946 /**
1947  * @tc.name: ForceCheckpoint002
1948  * @tc.desc: Test the checkpoint of the database.
1949  * @tc.type: FUNC
1950  * @tc.require:
1951  * @tc.author: wangbingquan
1952  */
1953 HWTEST_F(DistributedDBInterfacesNBDelegateTest, MaxLogSize002, TestSize.Level2)
1954 {
1955     /**
1956      * @tc.steps:step1. Create database.
1957      * @tc.expected: step1. Returns a non-null kvstore.
1958      */
1959     KvStoreNbDelegate::Option option;
1960     g_mgr.GetKvStore("MaxLogSize002", option, g_kvNbDelegateCallback);
1961     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1962     EXPECT_TRUE(g_kvDelegateStatus == OK);
1963 
1964     /**
1965      * @tc.steps:step2. Put the random entry into the database.
1966      * @tc.expected: step2. Returns OK.
1967      */
1968     Key key;
1969     Value value;
1970     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 30); // for 30B random key
1971     DistributedDBToolsUnitTest::GetRandomKeyValue(value, 3 * 1024 * 1024); // 3M value
1972     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
1973     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 40); // for 40B random key
1974     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
1975 
1976     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 20); // for 20B random key
1977     DistributedDBToolsUnitTest::GetRandomKeyValue(value, 1 * 1024 * 1024); // 1M value
1978     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
1979 
1980     /**
1981      * @tc.steps:step3. Get the resultset.
1982      * @tc.expected: step3. Returns OK.
1983      */
1984     KvStoreResultSet *resultSet = nullptr;
1985     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(Key{}, resultSet), OK);
1986     ASSERT_NE(resultSet, nullptr);
1987     EXPECT_EQ(resultSet->GetCount(), 3); // size of all the entries is 3
1988     EXPECT_EQ(resultSet->MoveToFirst(), true);
1989 
1990     /**
1991      * @tc.steps:step4. Put more data into the database.
1992      * @tc.expected: step4. Returns OK.
1993      */
1994     uint64_t logSize = 6 * 1024 * 1024; // 6M for initial test.
1995     PragmaData pragLimit = static_cast<PragmaData>(&logSize);
1996     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), OK);
1997     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 10); // for 10B random key(different size)
1998     DistributedDBToolsUnitTest::GetRandomKeyValue(value, 3 * 1024 * 1024); // 3MB
1999     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
2000     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 15); // for 15B random key(different size)
2001     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
2002 
2003     /**
2004      * @tc.steps:step4. Put more data into the database while the log size is over the limit.
2005      * @tc.expected: step4. Returns LOG_OVER_LIMITS.
2006      */
2007     DistributedDBToolsUnitTest::GetRandomKeyValue(value, 25); // for 25B random key(different size)
2008     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), LOG_OVER_LIMITS);
2009     EXPECT_EQ(g_kvNbDelegatePtr->Delete(key), LOG_OVER_LIMITS);
2010     EXPECT_EQ(g_kvNbDelegatePtr->StartTransaction(), LOG_OVER_LIMITS);
2011     EXPECT_EQ(g_kvNbDelegatePtr->PutLocal(key, value), LOG_OVER_LIMITS);
2012     EXPECT_EQ(g_kvNbDelegatePtr->RemoveDeviceData("deviceA"), LOG_OVER_LIMITS);
2013     EXPECT_EQ(g_kvNbDelegatePtr->RemoveDeviceData(), LOG_OVER_LIMITS);
2014     /**
2015      * @tc.steps:step4. Change the max log size limit, and put the data.
2016      * @tc.expected: step4. Returns OK.
2017      */
2018     logSize *= 10; // 10 multiple size
2019     pragLimit = static_cast<PragmaData>(&logSize);
2020     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), OK);
2021     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
2022     g_kvNbDelegatePtr->CloseResultSet(resultSet);
2023 
2024     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2025     EXPECT_EQ(g_mgr.DeleteKvStore("MaxLogSize002"), OK);
2026     g_kvNbDelegatePtr = nullptr;
2027 }
2028 
2029 /**
2030  * @tc.name: MaxLogCheckPoint001
2031  * @tc.desc: Pragma the checkpoint command.
2032  * @tc.type: FUNC
2033  * @tc.require:
2034  * @tc.author: wangbingquan
2035  */
2036 HWTEST_F(DistributedDBInterfacesNBDelegateTest, MaxLogCheckPoint001, TestSize.Level2)
2037 {
2038     /**
2039      * @tc.steps:step1. Create database.
2040      * @tc.expected: step1. Returns a non-null kvstore.
2041      */
2042     KvStoreNbDelegate::Option option;
2043     g_mgr.GetKvStore("MaxLogCheckPoint001", option, g_kvNbDelegateCallback);
2044     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2045     EXPECT_TRUE(g_kvDelegateStatus == OK);
2046 
2047     /**
2048      * @tc.steps:step2. Put the random entry into the database.
2049      * @tc.expected: step2. Returns OK.
2050      */
2051     Key key;
2052     Value value;
2053     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 30); // for 30B random key(different size)
2054     DistributedDBToolsUnitTest::GetRandomKeyValue(value, 1 * 1024 * 1024); // 1M
2055     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
2056     EXPECT_EQ(g_kvNbDelegatePtr->Delete(key), OK);
2057 
2058     /**
2059      * @tc.steps:step3. Get the disk file size, execute the checkpoint and get the disk file size.
2060      * @tc.expected: step3. Returns OK and the file size is less than the size before checkpoint.
2061      */
2062     uint64_t sizeBeforeChk = 0;
2063     g_mgr.GetKvStoreDiskSize("MaxLogCheckPoint001", sizeBeforeChk);
2064     EXPECT_GT(sizeBeforeChk, 1 * 1024 * 1024ULL); // more than 1M
2065     int param = 0;
2066     PragmaData paraData = static_cast<PragmaData>(&param);
2067     g_kvNbDelegatePtr->Pragma(EXEC_CHECKPOINT, paraData);
2068     uint64_t sizeAfterChk = 0;
2069     g_mgr.GetKvStoreDiskSize("MaxLogCheckPoint001", sizeAfterChk);
2070     EXPECT_LT(sizeAfterChk, 100 * 1024ULL); // less than 100K
2071     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2072     EXPECT_EQ(g_mgr.DeleteKvStore("MaxLogCheckPoint001"), OK);
2073     g_kvNbDelegatePtr = nullptr;
2074 }
2075 
2076 /**
2077   * @tc.name: CreateMemoryDbWithoutPath
2078   * @tc.desc: Create memory database without path.
2079   * @tc.type: FUNC
2080   * @tc.require: AR000CRAKN
2081   * @tc.author: sunpeng
2082   */
2083 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDbWithoutPath, TestSize.Level1)
2084 {
2085     /**
2086      * @tc.steps: step1. Create Memory database by GetKvStore without path.
2087      * @tc.expected: step1. Create successfully.
2088      */
2089     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2090     const KvStoreNbDelegate::Option option = {true, true};
2091     mgr.GetKvStore("memory_without_path", option, g_kvNbDelegateCallback);
2092     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2093     EXPECT_TRUE(g_kvDelegateStatus == OK);
2094     EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2095     g_kvNbDelegatePtr = nullptr;
2096 }
2097 
2098 /**
2099   * @tc.name: OpenStorePathCheckTest001
2100   * @tc.desc: Test open store with same label but different path.
2101   * @tc.type: FUNC
2102   * @tc.require: AR000GK58F
2103   * @tc.author: lianhuix
2104   */
2105 HWTEST_F(DistributedDBInterfacesNBDelegateTest, OpenStorePathCheckTest001, TestSize.Level1)
2106 {
2107     std::string dir1 = g_testDir + "/dbDir1";
2108     EXPECT_EQ(OS::MakeDBDirectory(dir1), E_OK);
2109     std::string dir2 = g_testDir + "/dbDir2";
2110     EXPECT_EQ(OS::MakeDBDirectory(dir2), E_OK);
2111 
2112     KvStoreDelegateManager mgr1(APP_ID, USER_ID);
2113     mgr1.SetKvStoreConfig({dir1});
2114 
2115     KvStoreNbDelegate *delegate1 = nullptr;
2116     auto callback1 = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1,
2117         placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(delegate1));
2118 
2119     KvStoreNbDelegate::Option option;
2120     mgr1.GetKvStore(STORE_ID_1, option, callback1);
2121     EXPECT_EQ(g_kvDelegateStatus, OK);
2122     ASSERT_NE(delegate1, nullptr);
2123 
2124     KvStoreNbDelegate *delegate2 = nullptr;
2125     auto callback2 = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1,
2126         placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(delegate2));
2127     KvStoreDelegateManager mgr2(APP_ID, USER_ID);
2128     mgr2.SetKvStoreConfig({dir2});
2129     mgr2.GetKvStore(STORE_ID_1, option, callback2);
2130     EXPECT_EQ(g_kvDelegateStatus, INVALID_ARGS);
2131     ASSERT_EQ(delegate2, nullptr);
2132 
2133     mgr1.CloseKvStore(delegate1);
2134     mgr1.DeleteKvStore(STORE_ID_1);
2135     mgr2.CloseKvStore(delegate2);
2136     mgr2.DeleteKvStore(STORE_ID_1);
2137 }
2138 
2139 namespace {
GetRealFileUrl(const std::string & dbPath,const std::string & appId,const std::string & userId,const std::string & storeId)2140 std::string GetRealFileUrl(const std::string &dbPath, const std::string &appId, const std::string &userId,
2141     const std::string &storeId)
2142 {
2143     std::string hashIdentifier = DBCommon::TransferHashString(
2144         DBCommon::GenerateIdentifierId(storeId, appId, userId));
2145     return dbPath + "/" + DBCommon::TransferStringToHex(hashIdentifier) + "/single_ver/main/gen_natural_store.db";
2146 }
2147 }
2148 
2149 /**
2150   * @tc.name: BusyTest001
2151   * @tc.desc: Test put kv data while another thread holds the transaction for one second
2152   * @tc.type: FUNC
2153   * @tc.require: AR000GK58F
2154   * @tc.author: lianhuix
2155   */
2156 HWTEST_F(DistributedDBInterfacesNBDelegateTest, BusyTest001, TestSize.Level1)
2157 {
2158     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2159     mgr.SetKvStoreConfig(g_config);
2160 
2161     const KvStoreNbDelegate::Option option = {true, false, false};
2162     mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
2163     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2164     EXPECT_TRUE(g_kvDelegateStatus == OK);
2165 
2166     std::string dbPath = GetRealFileUrl(g_config.dataDir, APP_ID, USER_ID, STORE_ID_1);
2167     sqlite3 *db = RelationalTestUtils::CreateDataBase(dbPath);
2168     RelationalTestUtils::ExecSql(db, "BEGIN IMMEDIATE;");
2169 
__anon195527440302() 2170     std::thread th([db]() {
2171         std::this_thread::sleep_for(std::chrono::milliseconds(1000));
2172         RelationalTestUtils::ExecSql(db, "COMMIT");
2173     });
2174 
2175     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_1, VALUE_1), OK);
2176 
2177     th.join();
2178     sqlite3_close_v2(db);
2179     EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2180     EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
2181     g_kvNbDelegatePtr = nullptr;
2182 }
2183 
2184 /**
2185  * @tc.name: GetKeys001
2186  * @tc.desc: Test get keys from the database.
2187  * @tc.type: FUNC
2188  * @tc.require:
2189  * @tc.author: zhangqiquan
2190  */
2191 HWTEST_F(DistributedDBInterfacesNBDelegateTest, GetKeys001, TestSize.Level1)
2192 {
2193     /**
2194      * @tc.steps:step1. Create database.
2195      * @tc.expected: step1. Returns a non-null kvstore.
2196      */
2197     KvStoreNbDelegate::Option option;
2198     g_mgr.GetKvStore("GetKeys001", option, g_kvNbDelegateCallback);
2199     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2200     EXPECT_TRUE(g_kvDelegateStatus == OK);
2201 
2202     /**
2203      * @tc.steps:step2. Put the all keys into the database.
2204      * @tc.expected: step2. Returns OK.
2205      */
2206     std::vector<Key> expectKeys = {
2207         {'k', '1', '1'},
2208         {'k', '2'},
2209         {'k', '3'},
2210         {'k', '4'}
2211     };
2212     for (const auto &key : expectKeys) {
2213         EXPECT_EQ(g_kvNbDelegatePtr->Put(key, {}), OK);
2214     }
2215     EXPECT_EQ(g_kvNbDelegatePtr->Put({'k', '2'}, {}), OK);
2216     EXPECT_EQ(g_kvNbDelegatePtr->Delete({'k', '4'}), OK);
2217 
2218     /**
2219      * @tc.steps:step3. Get the all keys.
2220      * @tc.expected: step3. Returns OK.
2221      */
2222     Key keyPrefix = {'k', '1'};
2223     std::vector<Key> actualKeys;
2224     EXPECT_EQ(g_kvNbDelegatePtr->GetKeys(keyPrefix, actualKeys), OK);
2225     EXPECT_EQ(actualKeys.size(), 1u); // get the k11
2226     for (const auto &key : actualKeys) {
2227         EXPECT_EQ(key, expectKeys[0]);
2228     }
2229     keyPrefix.clear();
2230     EXPECT_EQ(g_kvNbDelegatePtr->GetKeys(keyPrefix, actualKeys), OK);
2231     EXPECT_EQ(actualKeys.size(), 3u); // size of all the key is 3
2232 
2233     keyPrefix = {'k', '4'};
2234     EXPECT_EQ(g_kvNbDelegatePtr->GetKeys(keyPrefix, actualKeys), NOT_FOUND);
2235     EXPECT_EQ(actualKeys.size(), 0u); // not found key and size is 0
2236 
2237     DistributedDBToolsUnitTest::GetRandomKeyValue(keyPrefix, 2048); // for 2048B random key
2238     EXPECT_EQ(g_kvNbDelegatePtr->GetKeys(keyPrefix, actualKeys), INVALID_ARGS);
2239     EXPECT_EQ(actualKeys.size(), 0u); // invalid prefix key and size is 0
2240 
2241     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2242     EXPECT_EQ(g_mgr.DeleteKvStore("GetKeys001"), OK);
2243     g_kvNbDelegatePtr = nullptr;
2244 }
2245 
2246 namespace {
InitVirtualDevice(const std::string & devId,KvVirtualDevice * & devices,VirtualSingleVerSyncDBInterface * & syncInterface)2247 void InitVirtualDevice(const std::string &devId, KvVirtualDevice *&devices,
2248     VirtualSingleVerSyncDBInterface *&syncInterface)
2249 {
2250     devices = new (std::nothrow) KvVirtualDevice(devId);
2251     ASSERT_TRUE(devices != nullptr);
2252     syncInterface = new (std::nothrow) VirtualSingleVerSyncDBInterface();
2253     ASSERT_TRUE(syncInterface != nullptr);
2254     ASSERT_EQ(devices->Initialize(g_communicatorAggregator, syncInterface), E_OK);
2255 }
2256 
FreeVirtualDevice(KvVirtualDevice * & devices)2257 void FreeVirtualDevice(KvVirtualDevice *&devices)
2258 {
2259     if (devices != nullptr) {
2260         delete devices;
2261         devices = nullptr;
2262     }
2263 }
2264 }
2265 
2266 /**
2267   * @tc.name: RemoveDeviceDataTest001
2268   * @tc.desc: remove device data with devId unspecified
2269   * @tc.type: FUNC
2270   * @tc.require:
2271   * @tc.author: lianhuix
2272   */
2273 HWTEST_F(DistributedDBInterfacesNBDelegateTest, RemoveDeviceDataTest001, TestSize.Level1)
2274 {
2275     InitVirtualDevice(DEVICE_B, g_deviceB, g_syncInterfaceB);
2276     InitVirtualDevice(DEVICE_C, g_deviceC, g_syncInterfaceC);
2277     InitVirtualDevice(DEVICE_D, g_deviceD, g_syncInterfaceD);
2278 
2279     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2280     mgr.SetKvStoreConfig(g_config);
2281 
2282     const KvStoreNbDelegate::Option option = {true, false, false};
2283     mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
2284     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2285     EXPECT_EQ(g_kvDelegateStatus, OK);
2286 
2287     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_1, VALUE_1), OK);
2288     g_deviceB->PutData(KEY_2, VALUE_2, 0, 0);
2289     g_deviceC->PutData(KEY_3, VALUE_3, 0, 0);
2290     g_deviceD->PutData(KEY_4, VALUE_4, 0, 0);
2291 
2292     std::vector<std::string> devices;
2293     devices.push_back(DEVICE_B);
2294     devices.push_back(DEVICE_C);
2295     devices.push_back(DEVICE_D);
2296     DBStatus status = g_kvNbDelegatePtr->Sync(devices, SYNC_MODE_PULL_ONLY,
__anon195527440502(const std::map<std::string, DBStatus>& statusMap) 2297         [devices, this](const std::map<std::string, DBStatus>& statusMap) {
2298             ASSERT_EQ(statusMap.size(), devices.size());
2299             for (const auto &pair : statusMap) {
2300                 EXPECT_EQ(pair.second, OK);
2301             }
2302         }, true);
2303     EXPECT_EQ(status, OK);
2304 
2305     EXPECT_EQ(g_kvNbDelegatePtr->RemoveDeviceData(), OK);
2306 
2307     Value val;
2308     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_1, val), OK);
2309     EXPECT_EQ(val, VALUE_1);
2310     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_2, val), NOT_FOUND);
2311     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_3, val), NOT_FOUND);
2312     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_4, val), NOT_FOUND);
2313 
2314     EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2315     g_kvNbDelegatePtr = nullptr;
2316     EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
2317     FreeVirtualDevice(g_deviceB);
2318     FreeVirtualDevice(g_deviceC);
2319     FreeVirtualDevice(g_deviceD);
2320 }
2321 
2322 #ifdef DB_DEBUG_ENV
2323 /**
2324   * @tc.name: TimeChangeWithCloseStoreTest001
2325   * @tc.desc: Test close store with time changed
2326   * @tc.type: FUNC
2327   * @tc.require:
2328   * @tc.author: lianhuix
2329   */
2330 HWTEST_F(DistributedDBInterfacesNBDelegateTest, TimeChangeWithCloseStoreTest001, TestSize.Level3)
2331 {
2332     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2333     mgr.SetKvStoreConfig(g_config);
2334 
2335     std::atomic<bool> isFinished(false);
2336 
2337     std::vector<std::thread> slowThreads;
2338     for (int i = 0; i < 10; i++) { // 10: thread to slow donw system
__anon195527440602() 2339         std::thread th([&isFinished]() {
2340             while (!isFinished) {
2341                 // pass
2342             }
2343         });
2344         slowThreads.emplace_back(std::move(th));
2345     }
2346 
__anon195527440702() 2347     std::thread th([&isFinished]() {
2348         int timeChangedCnt = 0;
2349         while (!isFinished.load()) {
2350             OS::SetOffsetBySecond(100 - timeChangedCnt++ * 2); // 100 2 : fake system time change
2351             std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 100: wait for a while
2352         }
2353     });
2354 
2355     for (int i = 0; i < 100; i++) { // run 100 times
2356         const KvStoreNbDelegate::Option option = {true, false, false};
2357         mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
2358         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2359         EXPECT_EQ(g_kvDelegateStatus, OK);
2360         EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2361         g_kvNbDelegatePtr = nullptr;
2362     }
2363 
2364     std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // 1000: wait for a while
2365     isFinished.store(true);
2366     th.join();
2367     for (auto &it : slowThreads) {
2368         it.join();
2369     }
2370     EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
2371 }
2372 
2373 /**
2374   * @tc.name: TimeChangeWithCloseStoreTest002
2375   * @tc.desc: Test close store with time changed
2376   * @tc.type: FUNC
2377   * @tc.require:
2378   * @tc.author: zhangqiquan
2379   */
2380 HWTEST_F(DistributedDBInterfacesNBDelegateTest, TimeChangeWithCloseStoreTest002, TestSize.Level3)
2381 {
2382     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2383     mgr.SetKvStoreConfig(g_config);
2384 
2385     const KvStoreNbDelegate::Option option = {true, false, false};
2386     mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
2387     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2388     EXPECT_EQ(g_kvDelegateStatus, OK);
2389     const int threadPoolMax = 10;
2390     for (int i = 0; i < threadPoolMax; ++i) {
__anon195527440802() 2391         (void) RuntimeContext::GetInstance()->ScheduleTask([]() {
2392             std::this_thread::sleep_for(std::chrono::seconds(10)); // sleep 10s for block thread pool
2393         });
2394     }
2395     OS::SetOffsetBySecond(100); // 100 2 : fake system time change
2396     std::this_thread::sleep_for(std::chrono::seconds(1)); // sleep 1s for time tick
2397 
2398     EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2399     g_kvNbDelegatePtr = nullptr;
2400 
2401     EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
2402     RuntimeContext::GetInstance()->StopTaskPool(); // stop all async task
2403 }
2404 
2405 /**
2406   * @tc.name: TimeChangeWithCloseStoreTest003
2407   * @tc.desc: Test store close with timechange listener
2408   * @tc.type: FUNC
2409   * @tc.require:
2410   * @tc.author: zhangqiquan
2411   */
2412 HWTEST_F(DistributedDBInterfacesNBDelegateTest, TimeChangeWithCloseStoreTest003, TestSize.Level3)
2413 {
2414     /**
2415      * @tc.steps:step1. Create database.
2416      * @tc.expected: step1. Returns a non-null kvstore.
2417      */
2418     KvStoreNbDelegate::Option option;
2419     g_mgr.GetKvStore("TimeChangeWithCloseStoreTest003", option, g_kvNbDelegateCallback);
2420     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2421     EXPECT_TRUE(g_kvDelegateStatus == OK);
2422     std::shared_ptr<bool> timeChange = std::make_shared<bool>(false);
2423     int errCode = E_OK;
__anon195527440902(void *) 2424     auto *listener = RuntimeContext::GetInstance()->RegisterTimeChangedLister([timeChange](void *) {
2425         std::this_thread::sleep_for(std::chrono::seconds(10)); // block close store 10s
2426         *timeChange = true;
2427     }, nullptr, errCode);
2428     /**
2429      * @tc.steps:step2. Block time change 10s and trigger time change.
2430      * @tc.expected: step2. close store cost time > 5s.
2431      */
2432     ASSERT_EQ(errCode, E_OK);
2433     OS::SetOffsetBySecond(100); // 100 : fake system time change
2434     std::this_thread::sleep_for(std::chrono::seconds(1)); // wait 1s for time change
2435     Timestamp beginTime;
2436     (void)OS::GetCurrentSysTimeInMicrosecond(beginTime);
2437     ASSERT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2438     Timestamp endTime;
2439     (void)OS::GetCurrentSysTimeInMicrosecond(endTime);
2440     if (*timeChange) {
2441         EXPECT_GE(static_cast<int>(endTime - beginTime), 5 * 1000 * 1000); // 5 * 1000 * 1000 = 5s
2442     }
2443     listener->Drop(true);
2444     OS::SetOffsetBySecond(-100); // -100 : fake system time change
2445     g_kvNbDelegatePtr = nullptr;
2446     EXPECT_EQ(g_mgr.DeleteKvStore("TimeChangeWithCloseStoreTest003"), OK);
2447 }
2448 #endif // DB_DEBUG_ENV
2449 
2450 /**
2451   * @tc.name: ResultSetLimitTest001
2452   * @tc.desc: Get result set over limit
2453   * @tc.type: FUNC
2454   * @tc.require:
2455   * @tc.author: lianhuix
2456   */
2457 HWTEST_F(DistributedDBInterfacesNBDelegateTest, ResultSetLimitTest001, TestSize.Level0)
2458 {
2459     /**
2460      * @tc.steps:step1. Create database.
2461      * @tc.expected: step1. Returns a non-null kvstore.
2462      */
2463     KvStoreNbDelegate::Option option;
2464     g_mgr.GetKvStore("ResultSetLimitTest001", option, g_kvNbDelegateCallback);
2465     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2466     EXPECT_TRUE(g_kvDelegateStatus == OK);
2467 
2468     /**
2469      * @tc.steps:step2. Put the random entry into the database.
2470      * @tc.expected: step2. Returns OK.
2471      */
2472     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_1, VALUE_1), OK);
2473     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_2, VALUE_2), OK);
2474     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_3, VALUE_3), OK);
2475 
2476     /**
2477      * @tc.steps:step3. Get the resultset overlimit.
2478      * @tc.expected: step3. In limit returns OK, else return OVER_MAX_LIMITS.
2479      */
2480     std::vector<KvStoreResultSet *> dataResultSet;
2481     for (int i = 0; i < 8; i++) { // 8: max result set count
2482         KvStoreResultSet *resultSet = nullptr;
2483         EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(Key{}, resultSet), OK);
2484         dataResultSet.push_back(resultSet);
2485         EXPECT_NE(resultSet, nullptr);
2486     }
2487 
2488     KvStoreResultSet *resultSet = nullptr;
2489     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(Key{}, resultSet), OVER_MAX_LIMITS);
2490     EXPECT_EQ(resultSet, nullptr);
2491     if (resultSet != nullptr) {
2492         EXPECT_EQ(g_kvNbDelegatePtr->CloseResultSet(resultSet), OK);
2493     }
2494 
2495     /**
2496      * @tc.steps:step4. Close result set and store.
2497      * @tc.expected: step4. Returns OK.
2498      */
2499     for (auto it : dataResultSet) {
2500         EXPECT_EQ(g_kvNbDelegatePtr->CloseResultSet(it), OK);
2501     }
2502 
2503     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2504     EXPECT_EQ(g_mgr.DeleteKvStore("ResultSetLimitTest001"), OK);
2505     g_kvNbDelegatePtr = nullptr;
2506 }
2507 
2508 /**
2509   * @tc.name: LocalStore001
2510   * @tc.desc: Test get kv store with localOnly
2511   * @tc.type: FUNC
2512   * @tc.require:
2513   * @tc.author: zhangqiquan
2514   */
2515 HWTEST_F(DistributedDBInterfacesNBDelegateTest, LocalStore001, TestSize.Level1)
2516 {
2517     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2518     mgr.SetKvStoreConfig(g_config);
2519 
2520     /**
2521      * @tc.steps:step1. Create database with localOnly.
2522      * @tc.expected: step1. Returns a non-null store.
2523      */
2524     KvStoreNbDelegate::Option option = {true, false, false};
2525     option.localOnly = true;
2526     DBStatus openStatus = DBStatus::DB_ERROR;
2527     KvStoreNbDelegate *openDelegate = nullptr;
__anon195527440a02(DBStatus status, KvStoreNbDelegate *delegate) 2528     mgr.GetKvStore(STORE_ID_1, option, [&openStatus, &openDelegate](DBStatus status, KvStoreNbDelegate *delegate) {
2529         openStatus = status;
2530         openDelegate = delegate;
2531     });
2532     ASSERT_TRUE(openDelegate != nullptr);
2533     EXPECT_EQ(openStatus, OK);
2534     /**
2535      * @tc.steps:step2. call sync and put/get interface.
2536      * @tc.expected: step2. sync return NOT_ACTIVE.
2537      */
2538     DBStatus actionStatus = openDelegate->Sync({}, SyncMode::SYNC_MODE_PUSH_ONLY, nullptr);
2539     EXPECT_EQ(actionStatus, DBStatus::NOT_ACTIVE);
2540     Key key = {'k'};
2541     Value expectValue = {'v'};
2542     EXPECT_EQ(openDelegate->Put(key, expectValue), OK);
2543     Value actualValue;
2544     EXPECT_EQ(openDelegate->Get(key, actualValue), OK);
2545     EXPECT_EQ(actualValue, expectValue);
2546 
2547     int pragmaData = 1;
2548     auto input = static_cast<PragmaData>(&pragmaData);
2549     EXPECT_EQ(openDelegate->Pragma(SET_SYNC_RETRY, input), NOT_SUPPORT);
2550 
2551     EXPECT_EQ(mgr.CloseKvStore(openDelegate), OK);
2552 }
2553 
2554 /**
2555   * @tc.name: LocalStore002
2556   * @tc.desc: Test get kv store different local mode
2557   * @tc.type: FUNC
2558   * @tc.require:
2559   * @tc.author: zhangqiquan
2560   */
2561 HWTEST_F(DistributedDBInterfacesNBDelegateTest, LocalStore002, TestSize.Level1)
2562 {
2563     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2564     mgr.SetKvStoreConfig(g_config);
2565 
2566     /**
2567      * @tc.steps:step1. Create database with localOnly.
2568      * @tc.expected: step1. Returns a non-null store.
2569      */
2570     KvStoreNbDelegate::Option option = {true, false, false};
2571     option.localOnly = true;
2572     DBStatus openStatus = DBStatus::DB_ERROR;
2573     KvStoreNbDelegate *localDelegate = nullptr;
__anon195527440b02(DBStatus status, KvStoreNbDelegate *delegate) 2574     mgr.GetKvStore(STORE_ID_1, option, [&openStatus, &localDelegate](DBStatus status, KvStoreNbDelegate *delegate) {
2575         openStatus = status;
2576         localDelegate = delegate;
2577     });
2578     ASSERT_TRUE(localDelegate != nullptr);
2579     EXPECT_EQ(openStatus, OK);
2580     /**
2581      * @tc.steps:step2. Create database without localOnly.
2582      * @tc.expected: step2. Returns a null store.
2583      */
2584     option.localOnly = false;
2585     KvStoreNbDelegate *syncDelegate = nullptr;
__anon195527440c02(DBStatus status, KvStoreNbDelegate *delegate) 2586     mgr.GetKvStore(STORE_ID_1, option, [&openStatus, &syncDelegate](DBStatus status, KvStoreNbDelegate *delegate) {
2587         openStatus = status;
2588         syncDelegate = delegate;
2589     });
2590     EXPECT_EQ(syncDelegate, nullptr);
2591     EXPECT_EQ(openStatus, INVALID_ARGS);
2592     EXPECT_EQ(mgr.CloseKvStore(localDelegate), OK);
2593     EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
2594 }
2595 
2596 /**
2597   * @tc.name: PutSync001
2598   * @tc.desc: put data and sync at same time
2599   * @tc.type: FUNC
2600   * @tc.require:
2601   * @tc.author: zhangqiquan
2602   */
2603 HWTEST_F(DistributedDBInterfacesNBDelegateTest, PutSync001, TestSize.Level3)
2604 {
2605     /**
2606      * @tc.steps:step1. Create database with localOnly.
2607      * @tc.expected: step1. Returns a non-null store.
2608      */
2609     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2610     mgr.SetKvStoreConfig(g_config);
2611     const KvStoreNbDelegate::Option option = {true, false, false};
2612     mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
2613     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2614     EXPECT_EQ(g_kvDelegateStatus, OK);
2615     /**
2616      * @tc.steps:step2. Put data async.
2617      * @tc.expected: step2. Always returns OK.
2618      */
2619     std::atomic<bool> finish = false;
__anon195527440d02() 2620     std::thread putThread([&finish]() {
2621         while (!finish) {
2622             EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_1, VALUE_1), OK);
2623         }
2624     });
2625     /**
2626      * @tc.steps:step3. Call sync async.
2627      * @tc.expected: step3. Always returns OK.
2628      */
__anon195527440e02() 2629     std::thread syncThread([]() {
2630         std::vector<std::string> devices;
2631         devices.emplace_back("");
2632         Key key = {'k'};
2633         for (int i = 0; i < 100; ++i) { // sync 100 times
2634             Query query = Query::Select().PrefixKey(key);
2635             DBStatus status = g_kvNbDelegatePtr->Sync(devices, SYNC_MODE_PULL_ONLY, nullptr, query, true);
2636             EXPECT_EQ(status, OK);
2637         }
2638     });
2639     syncThread.join();
2640     finish = true;
2641     putThread.join();
2642     EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2643     g_kvNbDelegatePtr = nullptr;
2644     EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
2645 }
2646 
2647 /**
2648   * @tc.name: UpdateKey001
2649   * @tc.desc: Test update key
2650   * @tc.type: FUNC
2651   * @tc.require:
2652   * @tc.author: zhangqiquan
2653   */
2654 HWTEST_F(DistributedDBInterfacesNBDelegateTest, UpdateKey001, TestSize.Level0)
2655 {
2656     /**
2657      * @tc.steps:step1. Create database.
2658      * @tc.expected: step1. Returns a non-null kvstore.
2659      */
2660     KvStoreNbDelegate::Option option;
2661     g_mgr.GetKvStore("UpdateKey001", option, g_kvNbDelegateCallback);
2662     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2663     EXPECT_TRUE(g_kvDelegateStatus == OK);
2664     /**
2665      * @tc.steps:step2. Put (k1, v1) into the database.
2666      * @tc.expected: step2. Returns OK.
2667      */
2668     Key k1 = {'k', '1'};
2669     EXPECT_EQ(g_kvNbDelegatePtr->Put(k1, VALUE_1), OK);
2670     /**
2671      * @tc.steps:step3. Update (k1, v1) to (k10, v1).
2672      * @tc.expected: step3. Returns OK and get k1 return not found.
2673      */
__anon195527440f02(const Key &originKey, Key &newKey) 2674     g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
2675         newKey = originKey;
2676         newKey.push_back('0');
2677     });
2678     Value actualValue;
2679     EXPECT_EQ(g_kvNbDelegatePtr->Get(k1, actualValue), NOT_FOUND);
2680     k1.push_back('0');
2681     EXPECT_EQ(g_kvNbDelegatePtr->Get(k1, actualValue), OK);
2682     EXPECT_EQ(actualValue, VALUE_1);
2683     /**
2684      * @tc.steps:step4. Close store.
2685      * @tc.expected: step4. Returns OK.
2686      */
2687     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2688     EXPECT_EQ(g_mgr.DeleteKvStore("UpdateKey001"), OK);
2689     g_kvNbDelegatePtr = nullptr;
2690 }
2691 
2692 /**
2693   * @tc.name: UpdateKey002
2694   * @tc.desc: Test update key with transaction
2695   * @tc.type: FUNC
2696   * @tc.require:
2697   * @tc.author: zhangqiquan
2698   */
2699 HWTEST_F(DistributedDBInterfacesNBDelegateTest, UpdateKey002, TestSize.Level0)
2700 {
2701     /**
2702      * @tc.steps:step1. Create database.
2703      * @tc.expected: step1. Returns a non-null kvstore.
2704      */
2705     KvStoreNbDelegate::Option option;
2706     g_mgr.GetKvStore("UpdateKey002", option, g_kvNbDelegateCallback);
2707     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2708     EXPECT_TRUE(g_kvDelegateStatus == OK);
2709     /**
2710      * @tc.steps:step2. Put (k1, v1) into the database .
2711      * @tc.expected: step2. Returns OK.
2712      */
2713     Key k1 = {'k', '1'};
2714     EXPECT_EQ(g_kvNbDelegatePtr->Put(k1, VALUE_1), OK);
2715     g_kvNbDelegatePtr->StartTransaction();
2716     /**
2717      * @tc.steps:step3. Update (k1, v1) to (k10, v1).
2718      * @tc.expected: step3. Returns OK and get k1 return not found.
2719      */
__anon195527441002(const Key &originKey, Key &newKey) 2720     g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
2721         newKey = originKey;
2722         newKey.push_back('0');
2723     });
2724     Value actualValue;
2725     EXPECT_EQ(g_kvNbDelegatePtr->Get(k1, actualValue), NOT_FOUND);
2726     Key k10 = {'k', '1', '0'};
2727     EXPECT_EQ(g_kvNbDelegatePtr->Get(k10, actualValue), OK);
2728     EXPECT_EQ(actualValue, VALUE_1);
2729     /**
2730      * @tc.steps:step5. Rollback Transaction.
2731      * @tc.expected: step5. k10 not exist in db.
2732      */
2733     g_kvNbDelegatePtr->Rollback();
2734     EXPECT_EQ(g_kvNbDelegatePtr->Get(k10, actualValue), NOT_FOUND);
2735     EXPECT_EQ(g_kvNbDelegatePtr->Get(k1, actualValue), OK);
2736     /**
2737      * @tc.steps:step5. Commit transaction.
2738      * @tc.expected: step5. data exist in db.
2739      */
2740     g_kvNbDelegatePtr->StartTransaction();
__anon195527441102(const Key &originKey, Key &newKey) 2741     g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
2742         newKey = originKey;
2743         newKey.push_back('0');
2744     });
2745     g_kvNbDelegatePtr->Commit();
2746     EXPECT_EQ(g_kvNbDelegatePtr->Get(k10, actualValue), OK);
2747     /**
2748      * @tc.steps:step6. Close store.
2749      * @tc.expected: step6. Returns OK.
2750      */
2751     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2752     EXPECT_EQ(g_mgr.DeleteKvStore("UpdateKey002"), OK);
2753     g_kvNbDelegatePtr = nullptr;
2754 }
2755 
2756 /**
2757   * @tc.name: UpdateKey003
2758   * @tc.desc: Test update key with invalid args
2759   * @tc.type: FUNC
2760   * @tc.require:
2761   * @tc.author: zhangqiquan
2762   */
2763 HWTEST_F(DistributedDBInterfacesNBDelegateTest, UpdateKey003, TestSize.Level0)
2764 {
2765     /**
2766      * @tc.steps:step1. Create database.
2767      * @tc.expected: step1. Returns a non-null kvstore.
2768      */
2769     KvStoreNbDelegate::Option option;
2770     g_mgr.GetKvStore("UpdateKey003", option, g_kvNbDelegateCallback);
2771     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2772     EXPECT_TRUE(g_kvDelegateStatus == OK);
2773     /**
2774      * @tc.steps:step2. Put (k1, v1) into the database .
2775      * @tc.expected: step2. Returns OK.
2776      */
2777     Key k1 = {'k', '1'};
2778     Key k2 = {'k', '2'};
2779     EXPECT_EQ(g_kvNbDelegatePtr->Put(k1, VALUE_1), OK);
2780     EXPECT_EQ(g_kvNbDelegatePtr->Put(k2, VALUE_1), OK);
2781     /**
2782      * @tc.steps:step3. Update key with nullptr or invalid key.
2783      * @tc.expected: step3. Returns INVALID_ARGS.
2784      */
2785     EXPECT_EQ(g_kvNbDelegatePtr->UpdateKey(nullptr), INVALID_ARGS);
__anon195527441202(const Key &originKey, Key &newKey) 2786     DBStatus status = g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
2787         newKey.clear();
2788     });
2789     EXPECT_EQ(status, INVALID_ARGS);
__anon195527441302(const Key &originKey, Key &newKey) 2790     status = g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
2791         newKey.assign(2048u, '0'); // 2048 is invalid len
2792     });
2793     EXPECT_EQ(status, INVALID_ARGS);
__anon195527441402(const Key &originKey, Key &newKey) 2794     status = g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
2795         newKey = {'k', '3'};
2796     });
2797     EXPECT_EQ(status, CONSTRAINT);
2798     /**
2799      * @tc.steps:step4. Close store.
2800      * @tc.expected: step4. Returns OK.
2801      */
2802     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2803     EXPECT_EQ(g_mgr.DeleteKvStore("UpdateKey003"), OK);
2804     g_kvNbDelegatePtr = nullptr;
2805 }
2806 
2807 /**
2808   * @tc.name: BlockTimer001
2809   * @tc.desc: Test open close function with block timer
2810   * @tc.type: FUNC
2811   * @tc.require:
2812   * @tc.author: zhangqiquan
2813   */
2814 HWTEST_F(DistributedDBInterfacesNBDelegateTest, BlockTimer001, TestSize.Level0)
2815 {
2816     /**
2817      * @tc.steps:step1. Create database.
2818      * @tc.expected: step1. Returns a non-null store.
2819      */
2820     KvStoreNbDelegate::Option option;
2821     g_mgr.GetKvStore("BlockTimer001", option, g_kvNbDelegateCallback);
2822     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2823     EXPECT_TRUE(g_kvDelegateStatus == OK);
2824     /**
2825      * @tc.steps:step2. Create block timer.
2826      * @tc.expected: step2. create ok.
2827      */
2828     TimerId timerId = 0u;
2829     bool timerFinalize = false;
2830     std::condition_variable cv;
2831     std::mutex finalizeMutex;
2832     bool triggerTimer = false;
2833     std::condition_variable triggerCv;
2834     std::mutex triggerMutex;
__anon195527441502(TimerId id) 2835     int errCode = RuntimeContext::GetInstance()->SetTimer(1, [&triggerTimer, &triggerCv, &triggerMutex](TimerId id) {
2836         {
2837             std::lock_guard<std::mutex> autoLock(triggerMutex);
2838             triggerTimer = true;
2839         }
2840         triggerCv.notify_all();
2841         std::this_thread::sleep_for(std::chrono::seconds(5));
2842         return -E_END_TIMER;
2843     }, [&timerFinalize, &finalizeMutex, &cv]() {
2844         {
2845             std::lock_guard<std::mutex> autoLock(finalizeMutex);
2846             timerFinalize = true;
2847         }
2848         cv.notify_all();
2849     }, timerId);
2850     ASSERT_EQ(errCode, E_OK);
2851     {
2852         std::unique_lock<std::mutex> uniqueLock(triggerMutex);
__anon195527441702() 2853         triggerCv.wait(uniqueLock, [&triggerTimer]() {
2854             return triggerTimer;
2855         });
2856     }
2857     /**
2858      * @tc.steps:step3. Close store.
2859      * @tc.expected: step3. Returns OK.
2860      */
2861     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2862     std::unique_lock<std::mutex> uniqueLock(finalizeMutex);
2863     EXPECT_TRUE(timerFinalize);
__anon195527441802() 2864     cv.wait(uniqueLock, [&timerFinalize]() {
2865         return timerFinalize;
2866     });
2867     EXPECT_EQ(g_mgr.DeleteKvStore("BlockTimer001"), OK);
2868     g_kvNbDelegatePtr = nullptr;
2869 }
2870 
2871 /**
2872   * @tc.name: MigrateDeadLockTest0011
2873   * @tc.desc: Test the will not be deadlock in migration.
2874   * @tc.type: FUNC
2875   * @tc.require:
2876   * @tc.author: zhangshijie
2877   */
2878 HWTEST_F(DistributedDBInterfacesNBDelegateTest, MigrateDeadLockTest001, TestSize.Level2)
2879 {
2880     std::shared_ptr<ProcessSystemApiAdapterImpl> g_adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
2881     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(g_adapter);
2882     /**
2883      * @tc.steps:step1. Get the nb delegate.
2884      * @tc.expected: step1. Get results OK and non-null delegate.
2885      */
2886     KvStoreNbDelegate::Option option = {true, false, false};
2887     option.secOption = {S3, SECE};
2888     std::string storeId = "distributed_nb_delegate_test";
2889     g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
2890     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2891     EXPECT_TRUE(g_kvDelegateStatus == OK);
2892 
2893     KvDBProperties property;
2894     property.SetStringProp(KvDBProperties::DATA_DIR, g_testDir);
2895     property.SetStringProp(KvDBProperties::STORE_ID, storeId);
2896     property.SetIntProp(KvDBProperties::SECURITY_LABEL, S3);
2897     property.SetIntProp(KvDBProperties::SECURITY_FLAG, SECE);
2898 
2899     std::string identifier = DBCommon::GenerateIdentifierId(storeId, APP_ID, USER_ID);
2900     property.SetStringProp(KvDBProperties::IDENTIFIER_DATA, DBCommon::TransferHashString(identifier));
2901     property.SetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::SINGLE_VER_TYPE_SQLITE);
2902 
2903     int errCode;
2904     SQLiteSingleVerStorageEngine *storageEngine =
2905         static_cast<SQLiteSingleVerStorageEngine *>(StorageEngineManager::GetStorageEngine(property, errCode));
2906     ASSERT_EQ(errCode, E_OK);
2907     ASSERT_NE(storageEngine, nullptr);
2908     storageEngine->SetEngineState(EngineState::CACHEDB);
2909 
2910     /**
2911      * @tc.steps:step2. create cache db
2912      * @tc.expected: step2. operation ok
2913      */
2914     std::string cacheDir =  g_testDir + "/" + DBCommon::TransferStringToHex(DBCommon::TransferHashString(identifier)) +
2915         "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::CACHEDB_DIR;
2916     std::string cacheDB = cacheDir + "/" + DBConstant::SINGLE_VER_CACHE_STORE + DBConstant::DB_EXTENSION;
2917     EXPECT_EQ(OS::CreateFileByFileName(cacheDB), E_OK);
2918 
2919     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2920     g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
2921     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2922     EXPECT_TRUE(g_kvDelegateStatus == OK);
2923 
2924     std::this_thread::sleep_for(std::chrono::seconds(3)); // 3 is sleep seconds
2925     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2926     g_kvNbDelegatePtr = nullptr;
2927     if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) {
2928         LOGE("rm test db files error!");
2929     }
2930 }
2931 
2932 /**
2933   * @tc.name: InvalidQueryTest001
2934   * @tc.desc: Test GetEntries with range query filter by sqlite
2935   * @tc.type: FUNC
2936   * @tc.require: AR.SR.IR20230714002092.017.001
2937   * @tc.author: mazhao
2938   */
2939 HWTEST_F(DistributedDBInterfacesNBDelegateTest, InvalidQueryTest001, TestSize.Level1)
2940 {
2941     /**
2942      * @tc.steps:step1. Get the nb delegate.
2943      * @tc.expected: step1. Get results OK and non-null delegate.
2944      */
2945     KvStoreNbDelegate::Option option;
2946     g_mgr.GetKvStore("InvalidQueryTest001", option, g_kvNbDelegateCallback);
2947     std::vector<Entry> entries;
2948     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2949     EXPECT_TRUE(g_kvDelegateStatus == OK);
2950 
2951     /**
2952      * @tc.steps: step2. Use range query conditions to obtain the resultset when use sqlite engine.
2953      * @tc.expected: step2. return NOT_SUPPORT.
2954      */
2955     KvStoreResultSet *resultSet = nullptr;
2956     Query inValidQuery = Query::Select().Range({}, {});
2957     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(inValidQuery, resultSet), NOT_SUPPORT);
2958     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(inValidQuery, entries), NOT_SUPPORT);
2959 }
2960 
2961 /**
2962   * @tc.name: InvalidQueryTest002
2963   * @tc.desc: Test GetEntries with range query filter by sqlite while conn is nullptr.
2964   * @tc.type: FUNC
2965   * @tc.require:
2966   * @tc.author: caihaoting
2967   */
2968 HWTEST_F(DistributedDBInterfacesNBDelegateTest, InvalidQueryTest002, TestSize.Level1)
2969 {
2970     /**
2971      * @tc.steps: step1. initialize result set.
2972      * @tc.expected: step1. Success.
2973      */
2974     KvStoreNbDelegate::Option option = {true, false, false};
2975     g_mgr.GetKvStore("InvalidQueryTest002", option, g_kvNbDelegateCallback);
2976     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2977     EXPECT_TRUE(g_kvDelegateStatus == OK);
2978     InitResultSet();
2979 
2980     /**
2981      * @tc.steps: step2. get entries using result set while conn is nullptr.
2982      * @tc.expected: step2. DB_ERROR.
2983      */
2984     KvStoreResultSet *readResultSet = nullptr;
2985     auto kvStoreImpl = static_cast<KvStoreNbDelegateImpl *>(g_kvNbDelegatePtr);
2986     EXPECT_EQ(kvStoreImpl->Close(), OK);
2987     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(g_keyPrefix, readResultSet), DB_ERROR);
2988     ASSERT_TRUE(readResultSet == nullptr);
2989 
2990     std::vector<Entry> entries;
2991     Query query = Query::Select().PrefixKey({'a', 'c'});
2992     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(query, entries), DB_ERROR);
2993     EXPECT_EQ(entries.size(), 0UL);
2994 
2995     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(query, readResultSet), DB_ERROR);
2996     ASSERT_TRUE(readResultSet == nullptr);
2997 
2998     int count = -1;
2999     EXPECT_EQ(g_kvNbDelegatePtr->GetCount(query, count), DB_ERROR);
3000     EXPECT_EQ(count, -1);
3001 
3002     /**
3003      * @tc.steps: step3. close kvStore.
3004      * @tc.expected: step3. Success.
3005      */
3006     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
3007     EXPECT_EQ(g_mgr.DeleteKvStore("InvalidQueryTest002"), OK);
3008     g_kvNbDelegatePtr = nullptr;
3009 }
3010 
3011 /**
3012   * @tc.name: OptionValidCheck001
3013   * @tc.desc: test validation of option mode
3014   * @tc.type: FUNC
3015   * @tc.require:
3016   * @tc.author: zhangshijie
3017   */
3018 HWTEST_F(DistributedDBInterfacesNBDelegateTest, OptionModeValidCheck001, TestSize.Level0)
3019 {
3020     /**
3021      * @tc.steps:step1. Get the nb delegate.
3022      * @tc.expected: step1. Get results OK and non-null delegate.
3023      */
3024     KvStoreNbDelegate::Option option = {true, false, false};
3025     KvStoreObserverUnitTest *observer = new KvStoreObserverUnitTest();
3026     ASSERT_TRUE(observer != nullptr);
3027     option.observer = observer;
3028     std::vector<int> invalidModeVec = {0, 5, 6, 7, 9, 16};
3029     std::string storeId = "OptionModeValidCheck001";
3030     for (size_t i = 0; i < invalidModeVec.size(); i++) {
3031         option.mode = invalidModeVec.at(i);
3032         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
3033         ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
3034         EXPECT_EQ(g_kvDelegateStatus, INVALID_ARGS);
3035     }
3036 
3037     std::vector<int> validModeVec = {1, 2, 3, 4, 8};
3038     for (size_t i = 0; i < validModeVec.size(); i++) {
3039         option.mode = validModeVec.at(i);
3040         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
3041         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
3042         EXPECT_EQ(g_kvDelegateStatus, OK);
3043         EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
3044         EXPECT_EQ(g_mgr.DeleteKvStore(storeId), OK);
3045         g_kvNbDelegatePtr = nullptr;
3046     }
3047 
3048     delete observer;
3049 }
3050 
3051 /**
3052  * @tc.name: AbnormalKvStoreTest001
3053  * @tc.desc: Test KvStoreNbDelegateImpl interface while conn is nullptr.
3054  * @tc.type: FUNC
3055  * @tc.require: DTS2024073106613
3056  * @tc.author: suyue
3057  */
3058 HWTEST_F(DistributedDBInterfacesNBDelegateTest, AbnormalKvStoreTest001, TestSize.Level1)
3059 {
3060     /**
3061      * @tc.steps: step1. GetKvStore for initialize g_kvNbDelegatePtr.
3062      * @tc.expected: step1. Success.
3063      */
3064     KvStoreNbDelegate::Option option = {true, false, false};
3065     g_mgr.GetKvStore("AbnormalKvStoreTest001", option, g_kvNbDelegateCallback);
3066     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
3067     EXPECT_TRUE(g_kvDelegateStatus == OK);
3068     InitResultSet();
3069 
3070     /**
3071      * @tc.steps: step2. test KvStoreNbDelegateImpl interface while conn is nullptr.
3072      * @tc.expected: step2. return DB_ERROR.
3073      */
3074     auto kvStoreImpl = static_cast<KvStoreNbDelegateImpl *>(g_kvNbDelegatePtr);
3075     EXPECT_EQ(kvStoreImpl->Close(), OK);
3076 
3077     const Key key = {0};
3078     EXPECT_EQ(kvStoreImpl->PublishLocal(key, true, true, nullptr), DB_ERROR);
3079     EXPECT_EQ(kvStoreImpl->UnpublishToLocal(key, true, true), DB_ERROR);
3080     EXPECT_EQ(kvStoreImpl->UnpublishToLocal({}, true, true), INVALID_ARGS);
3081     EXPECT_EQ(kvStoreImpl->RemoveDeviceData(""), DB_ERROR);
3082     bool autoSync = true;
3083     PragmaData data = static_cast<PragmaData>(&autoSync);
3084     EXPECT_EQ(kvStoreImpl->Pragma(AUTO_SYNC, data), DB_ERROR);
3085     EXPECT_EQ(kvStoreImpl->SetConflictNotifier(0, nullptr), DB_ERROR);
3086     CipherPassword password;
3087     EXPECT_EQ(kvStoreImpl->Rekey(password), DB_ERROR);
3088     EXPECT_EQ(kvStoreImpl->Export("", password, true), DB_ERROR);
3089     EXPECT_EQ(kvStoreImpl->Import("", password), DB_ERROR);
3090     EXPECT_EQ(kvStoreImpl->StartTransaction(), DB_ERROR);
3091     EXPECT_EQ(kvStoreImpl->Commit(), DB_ERROR);
3092     EXPECT_EQ(kvStoreImpl->Rollback(), DB_ERROR);
3093     EXPECT_EQ(kvStoreImpl->CheckIntegrity(), DB_ERROR);
3094     SecurityOption securityOption;
3095     EXPECT_EQ(kvStoreImpl->GetSecurityOption(securityOption), DB_ERROR);
3096     EXPECT_EQ(kvStoreImpl->SetRemotePushFinishedNotify(nullptr), DB_ERROR);
3097     EXPECT_EQ(kvStoreImpl->SetEqualIdentifier("", {}), DB_ERROR);
3098     EXPECT_EQ(kvStoreImpl->SetPushDataInterceptor(nullptr), DB_ERROR);
3099 
3100     /**
3101      * @tc.steps: step3. close kvStore.
3102      * @tc.expected: step3. Success.
3103      */
3104     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
3105     EXPECT_EQ(g_mgr.DeleteKvStore("AbnormalKvStoreTest001"), OK);
3106     g_kvNbDelegatePtr = nullptr;
3107 }
3108 
3109 /**
3110  * @tc.name: AbnormalKvStoreTest002
3111  * @tc.desc: Test KvStoreNbDelegateImpl interface while conn is nullptr.
3112  * @tc.type: FUNC
3113  * @tc.require: DTS2024073106613
3114  * @tc.author: suyue
3115  */
3116 HWTEST_F(DistributedDBInterfacesNBDelegateTest, AbnormalKvStoreTest002, TestSize.Level1)
3117 {
3118     /**
3119      * @tc.steps: step1. GetKvStore for initialize g_kvNbDelegatePtr.
3120      * @tc.expected: step1. Success.
3121      */
3122     KvStoreNbDelegate::Option option = {true, false, false};
3123     g_mgr.GetKvStore("AbnormalKvStoreTest002", option, g_kvNbDelegateCallback);
3124     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
3125     EXPECT_TRUE(g_kvDelegateStatus == OK);
3126     InitResultSet();
3127 
3128     /**
3129      * @tc.steps: step2. test KvStoreNbDelegateImpl interface while conn is nullptr.
3130      * @tc.expected: step2. return DB_ERROR.
3131      */
3132     auto kvStoreImpl = static_cast<KvStoreNbDelegateImpl *>(g_kvNbDelegatePtr);
3133     EXPECT_EQ(kvStoreImpl->Close(), OK);
3134 
3135     Query query;
3136     EXPECT_EQ(kvStoreImpl->SubscribeRemoteQuery({}, nullptr, query, true), DB_ERROR);
3137     EXPECT_EQ(kvStoreImpl->UnSubscribeRemoteQuery({}, nullptr, query, true), DB_ERROR);
3138     EXPECT_EQ(kvStoreImpl->RemoveDeviceData(), DB_ERROR);
3139     const Key key = {0};
3140     std::vector<Key> keys;
3141     EXPECT_EQ(kvStoreImpl->GetKeys(key, keys), DB_ERROR);
3142     uint32_t expectedVal = 0;
3143     EXPECT_EQ(kvStoreImpl->GetSyncDataSize(""), expectedVal);
3144     EXPECT_EQ(kvStoreImpl->UpdateKey(nullptr), DB_ERROR);
3145     const std::string device = "test";
3146     std::pair<DBStatus, WatermarkInfo> info = kvStoreImpl->GetWatermarkInfo(device);
3147     EXPECT_EQ(info.first, DB_ERROR);
3148     EXPECT_EQ(kvStoreImpl->GetTaskCount(), DB_ERROR);
3149     EXPECT_EQ(kvStoreImpl->SetReceiveDataInterceptor(nullptr), DB_ERROR);
3150     CloudSyncConfig config;
3151     EXPECT_EQ(kvStoreImpl->SetCloudSyncConfig(config), DB_ERROR);
3152     const IOption iOption;
3153     std::vector<Entry> entries;
3154     EXPECT_EQ(kvStoreImpl->GetEntries(key, entries), DB_ERROR);
3155 
3156     /**
3157      * @tc.steps: step3. close kvStore.
3158      * @tc.expected: step3. Success.
3159      */
3160     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
3161     EXPECT_EQ(g_mgr.DeleteKvStore("AbnormalKvStoreTest002"), OK);
3162     g_kvNbDelegatePtr = nullptr;
3163 }
3164 
3165 /**
3166  * @tc.name: AbnormalKvStoreResultSetTest
3167  * @tc.desc: Test KvStoreResultSetImpl interface when class para is nullptr.
3168  * @tc.type: FUNC
3169  * @tc.require: DTS2024073106613
3170  * @tc.author: suyue
3171  */
3172 HWTEST_F(DistributedDBInterfacesNBDelegateTest, AbnormalKvStoreResultSetTest, TestSize.Level1)
3173 {
3174     /**
3175      * @tc.steps: step1. Call interfaces when calss para is null.
3176      * @tc.expected: step1. return failInfo.
3177      */
3178     KvStoreResultSetImpl kvStoreObj(nullptr);
3179     EXPECT_EQ(kvStoreObj.GetCount(), 0);
3180     EXPECT_EQ(kvStoreObj.GetPosition(), INIT_POSITION);
3181     EXPECT_EQ(kvStoreObj.Move(0), false);
3182     EXPECT_EQ(kvStoreObj.MoveToPosition(0), false);
3183     EXPECT_EQ(kvStoreObj.MoveToFirst(), false);
3184     EXPECT_EQ(kvStoreObj.MoveToLast(), false);
3185     EXPECT_EQ(kvStoreObj.IsFirst(), false);
3186     EXPECT_EQ(kvStoreObj.IsLast(), false);
3187     EXPECT_EQ(kvStoreObj.IsBeforeFirst(), false);
3188     EXPECT_EQ(kvStoreObj.IsAfterLast(), false);
3189     std::vector<std::string> columnNames;
3190     kvStoreObj.GetColumnNames(columnNames);
3191     Entry entry;
3192     EXPECT_EQ(kvStoreObj.GetEntry(entry), DB_ERROR);
3193     EXPECT_EQ(kvStoreObj.IsClosed(), false);
3194     kvStoreObj.Close();
3195 
3196     /**
3197      * @tc.steps: step2. Call unsupported interfaces.
3198      * @tc.expected: step2. return NOT_SUPPORT.
3199      */
3200     std::string columnName;
3201     int columnIndex = 0;
3202     EXPECT_EQ(kvStoreObj.GetColumnIndex(columnName, columnIndex), NOT_SUPPORT);
3203     EXPECT_EQ(kvStoreObj.GetColumnName(columnIndex, columnName), NOT_SUPPORT);
3204     std::vector<uint8_t> vecVal;
3205     EXPECT_EQ(kvStoreObj.Get(columnIndex, vecVal), NOT_SUPPORT);
3206     std::string strVal;
3207     EXPECT_EQ(kvStoreObj.Get(columnIndex, strVal), NOT_SUPPORT);
3208     int64_t intVal;
3209     EXPECT_EQ(kvStoreObj.Get(columnIndex, intVal), NOT_SUPPORT);
3210     double doubleVal;
3211     EXPECT_EQ(kvStoreObj.Get(columnIndex, doubleVal), NOT_SUPPORT);
3212     bool isNull;
3213     EXPECT_EQ(kvStoreObj.IsColumnNull(columnIndex, isNull), NOT_SUPPORT);
3214     std::map<std::string, VariantData> data;
3215     EXPECT_EQ(kvStoreObj.GetRow(data), NOT_SUPPORT);
3216 }
3217 }