• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "system_timer.h"
30 
31 using namespace testing::ext;
32 using namespace DistributedDB;
33 using namespace DistributedDBUnitTest;
34 using namespace std;
35 
36 namespace {
37     // define some variables to init a KvStoreDelegateManager object.
38     KvStoreDelegateManager g_mgr(APP_ID, USER_ID);
39     string g_testDir;
40     KvStoreConfig g_config;
41     Key g_keyPrefix = {'A', 'B', 'C'};
42     const int RESULT_SET_COUNT = 9;
43     const int RESULT_SET_INIT_POS = -1;
44     uint8_t g_testDict[RESULT_SET_COUNT] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
45 
46     // define the g_kvNbDelegateCallback, used to get some information when open a kv store.
47     DBStatus g_kvDelegateStatus = INVALID_ARGS;
48     KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr;
49     KvStoreDelegate *g_kvDelegatePtr = nullptr;
50     const int OBSERVER_SLEEP_TIME = 100;
51     const int BATCH_PRESET_SIZE_TEST = 10;
52     const int DIVIDE_BATCH_PRESET_SIZE = 5;
53     const int VALUE_OFFSET = 5;
54 
55     const int DEFAULT_KEY_VALUE_SIZE = 10;
56 
57     const int CON_PUT_THREAD_NUM = 4;
58     const int PER_THREAD_PUT_NUM = 100;
59 
60     // the type of g_kvNbDelegateCallback is function<void(DBStatus, KvStoreDelegate*)>
61     auto g_kvNbDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1,
62         placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvNbDelegatePtr));
63 
64     // the type of g_kvDelegateCallback is function<void(DBStatus, KvStoreDelegate*)>
65     auto g_kvDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1,
66         placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvDelegatePtr));
67 
68     enum LockState {
69         UNLOCKED = 0,
70         LOCKED
71     };
72 
InitResultSet()73     void InitResultSet()
74     {
75         Key testKey;
76         Value testValue;
77         for (int i = 0; i < RESULT_SET_COUNT; i++) {
78             testKey.clear();
79             testValue.clear();
80             // set key
81             testKey = g_keyPrefix;
82             testKey.push_back(g_testDict[i]);
83             // set value
84             testValue.push_back(g_testDict[i]);
85             // insert entry
86             EXPECT_EQ(g_kvNbDelegatePtr->Put(testKey, testValue), OK);
87         }
88     }
89 
ReadResultSet(KvStoreResultSet * readResultSet)90     void ReadResultSet(KvStoreResultSet *readResultSet)
91     {
92         if (readResultSet == nullptr) {
93             return;
94         }
95         // index from 0 to 8(first to last)
96         for (int i = 0; i < RESULT_SET_COUNT; i++) {
97             Entry entry;
98             std::vector<uint8_t> cursorKey = g_keyPrefix;
99             cursorKey.push_back(g_testDict[i]);
100             std::vector<uint8_t> cursorValue;
101             cursorValue.push_back(g_testDict[i]);
102             EXPECT_TRUE(readResultSet->MoveToNext());
103             EXPECT_EQ(readResultSet->GetEntry(entry), OK);
104             EXPECT_EQ(entry.key, cursorKey);
105             EXPECT_EQ(entry.value, cursorValue);
106             EXPECT_TRUE(!readResultSet->IsBeforeFirst());
107             EXPECT_TRUE(!readResultSet->IsAfterLast());
108         }
109         // change index to 8(last)
110         EXPECT_EQ(readResultSet->GetPosition(), RESULT_SET_COUNT - 1);
111         EXPECT_TRUE(!readResultSet->IsFirst());
112         EXPECT_TRUE(readResultSet->IsLast());
113         EXPECT_TRUE(!readResultSet->IsBeforeFirst());
114         EXPECT_TRUE(!readResultSet->IsAfterLast());
115     }
116 
CheckResultSetValue(KvStoreResultSet * readResultSet,DBStatus errCode,int position)117     void CheckResultSetValue(KvStoreResultSet *readResultSet, DBStatus errCode, int position)
118     {
119         if (readResultSet == nullptr) {
120             return;
121         }
122         Entry entry;
123         EXPECT_EQ(readResultSet->GetPosition(), position);
124         EXPECT_EQ(readResultSet->GetEntry(entry), errCode);
125         if (errCode == OK) {
126             std::vector<uint8_t> cursorKey;
127             std::vector<uint8_t> cursorValue;
128             if (position > RESULT_SET_INIT_POS && position < RESULT_SET_COUNT) {
129                 uint8_t keyPostfix = g_testDict[position];
130                 // set key
131                 cursorKey = g_keyPrefix;
132                 cursorKey.push_back(keyPostfix);
133                 // set value
134                 cursorValue.push_back(keyPostfix);
135             }
136             // check key and value
137             EXPECT_EQ(entry.key, cursorKey);
138             EXPECT_EQ(entry.value, cursorValue);
139         }
140     }
141 
142     std::vector<Entry> g_entriesForConcurrency;
PutData(KvStoreNbDelegate * kvStore,int flag)143     void PutData(KvStoreNbDelegate *kvStore, int flag)
144     {
145         for (int i = 0; i < PER_THREAD_PUT_NUM; i++) {
146             int index = flag * PER_THREAD_PUT_NUM + i;
147             kvStore->Put(g_entriesForConcurrency[index].key, g_entriesForConcurrency[index].value);
148         }
149         LOGD("%dth put has been finished", flag);
150     }
151 
CheckDataTimestamp(const std::string & storeId)152     bool CheckDataTimestamp(const std::string &storeId)
153     {
154         std::string identifier = USER_ID + "-" + APP_ID + "-" + storeId;
155         std::string hashIdentifier = DBCommon::TransferHashString(identifier);
156         std::string identifierName = DBCommon::TransferStringToHex(hashIdentifier);
157         std::string storeDir = g_testDir + "/" + identifierName + "/" + DBConstant::SINGLE_SUB_DIR + "/" +
158             DBConstant::MAINDB_DIR + "/" + DBConstant::SINGLE_VER_DATA_STORE + DBConstant::SQLITE_DB_EXTENSION;
159         sqlite3 *db = nullptr;
160         EXPECT_EQ(sqlite3_open_v2(storeDir.c_str(), &db, SQLITE_OPEN_READWRITE, nullptr), SQLITE_OK);
161         if (db == nullptr) {
162             return false;
163         }
164 
165         std::string selectSQL = "select timestamp from sync_data order by rowid;";
166         sqlite3_stmt *statement = nullptr;
167         EXPECT_EQ(sqlite3_prepare(db, selectSQL.c_str(), -1, &statement, NULL), SQLITE_OK);
168         std::vector<int64_t> timeVect;
169         while (sqlite3_step(statement) == SQLITE_ROW) {
170             timeVect.push_back(sqlite3_column_int64(statement, 0));
171         }
172 
173         sqlite3_finalize(statement);
174         statement = nullptr;
175         (void)sqlite3_close_v2(db);
176         db = nullptr;
177         EXPECT_EQ(timeVect.size(), g_entriesForConcurrency.size());
178         bool resultCheck = true;
179         if (g_entriesForConcurrency.size() > 1) {
180             for (size_t i = 1; i < timeVect.size(); i++) {
181                 if (timeVect[i] <= timeVect[i - 1]) {
182                     resultCheck = false;
183                     break;
184                 }
185             }
186         }
187 
188         return resultCheck;
189     }
190 }
191 class DistributedDBInterfacesNBDelegateTest : public testing::Test {
192 public:
193     static void SetUpTestCase(void);
194     static void TearDownTestCase(void);
195     void SetUp();
196     void TearDown();
197 };
198 
SetUpTestCase(void)199 void DistributedDBInterfacesNBDelegateTest::SetUpTestCase(void)
200 {
201     DistributedDBToolsUnitTest::TestDirInit(g_testDir);
202     g_config.dataDir = g_testDir;
203     g_mgr.SetKvStoreConfig(g_config);
204 }
205 
TearDownTestCase(void)206 void DistributedDBInterfacesNBDelegateTest::TearDownTestCase(void)
207 {
208     if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) {
209         LOGE("rm test db files error!");
210     }
211     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(nullptr);
212 }
213 
SetUp(void)214 void DistributedDBInterfacesNBDelegateTest::SetUp(void)
215 {
216     DistributedDBToolsUnitTest::PrintTestCaseInfo();
217     g_kvDelegateStatus = INVALID_ARGS;
218     g_kvNbDelegatePtr = nullptr;
219     g_kvDelegatePtr = nullptr;
220 }
221 
TearDown(void)222 void DistributedDBInterfacesNBDelegateTest::TearDown(void)
223 {
224     if (g_kvDelegatePtr != nullptr) {
225         g_mgr.CloseKvStore(g_kvNbDelegatePtr);
226         g_kvNbDelegatePtr = nullptr;
227     }
228     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(nullptr);
229 }
230 
231 /**
232   * @tc.name: CombineTest001
233   * @tc.desc: Test the NbDelegate for combined operation.
234   * @tc.type: FUNC
235   * @tc.require: AR000CCPOM
236   * @tc.author: huangnaigu
237   */
238 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CombineTest001, TestSize.Level1)
239 {
240     /**
241      * @tc.steps:step1. Get the nb delegate.
242      * @tc.expected: step1. Get results OK and non-null delegate.
243      */
244     KvStoreNbDelegate::Option option = {true, false, false};
245     g_mgr.GetKvStore("distributed_nb_delegate_test", option, g_kvNbDelegateCallback);
246     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
247     EXPECT_TRUE(g_kvDelegateStatus == OK);
248     Key key;
249     key = {'A', 'C', 'Q'};
250     Value value;
251     value = {'G', 'D', 'O'};
252     Value valueRead;
253     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
254     ASSERT_TRUE(observer != nullptr);
255     /**
256      * @tc.steps:step2. Register the non-null observer for the special key.
257      * @tc.expected: step2. Register results OK.
258      */
259     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_LOCAL_ONLY, observer), OK);
260     /**
261      * @tc.steps:step3. Put the local data.
262      * @tc.expected: step3. Put returns OK.
263      */
264     EXPECT_EQ(g_kvNbDelegatePtr->PutLocal(key, value), OK);
265     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
266     /**
267      * @tc.steps:step4. Check the local data.
268      * @tc.expected: step4. The get data is equal to the put data.
269      */
270     EXPECT_EQ(g_kvNbDelegatePtr->GetLocal(key, valueRead), OK);
271     /**
272      * @tc.steps:step5. Delete the local data.
273      * @tc.expected: step5. Delete returns OK.
274      */
275     EXPECT_EQ(g_kvNbDelegatePtr->DeleteLocal(key), OK);
276     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
277     /**
278      * @tc.steps:step6. Check the local data.
279      * @tc.expected: step6. Couldn't find the deleted data.
280      */
281     EXPECT_EQ(g_kvNbDelegatePtr->GetLocal(key, valueRead), NOT_FOUND);
282     /**
283      * @tc.steps:step7. UnRegister the observer.
284      * @tc.expected: step7. Returns OK.
285      */
286     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
287     delete observer;
288     observer = nullptr;
289     Key key1;
290     key1 = {'D', 'B', 'N'};
291     Value value1;
292     value1 = {'P', 'D', 'G'};
293 
294     Key key2 = key1;
295     Value value2;
296     key2.push_back('U');
297     value2 = {'C'};
298     /**
299      * @tc.steps:step8. Put the data.
300      * @tc.expected: step8. Put returns OK.
301      */
302     EXPECT_EQ(g_kvNbDelegatePtr->Put(key1, value1), OK);
303     Value valueRead2;
304     /**
305      * @tc.steps:step9. Check the data.
306      * @tc.expected: step9. Getting the put data returns OK.
307      */
308     EXPECT_EQ(g_kvNbDelegatePtr->Get(key1, valueRead2), OK);
309     /**
310      * @tc.steps:step10. Put another data.
311      * @tc.expected: step10. Returns OK.
312      */
313     EXPECT_EQ(g_kvNbDelegatePtr->Put(key2, value2), OK);
314     std::vector<Entry> vect;
315     /**
316      * @tc.steps:step10. Get the batch data using the prefix key.
317      * @tc.expected: step10. Results OK and the batch data size is equal to the put data size.
318      */
319     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(key1, vect), OK);
320     EXPECT_EQ(vect.size(), 2UL);
321     /**
322      * @tc.steps:step11. Delete one data.
323      * @tc.expected: step11. Results OK and couldn't get the deleted data.
324      */
325     EXPECT_EQ(g_kvNbDelegatePtr->Delete(key1), OK);
326     EXPECT_EQ(g_kvNbDelegatePtr->Get(key1, valueRead2), NOT_FOUND);
327 
328     LOGD("Close store");
329     /**
330      * @tc.steps:step12. Close the kv store.
331      * @tc.expected: step12. Results OK and delete successfully.
332      */
333     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
334     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_nb_delegate_test"), OK);
335     g_kvNbDelegatePtr = nullptr;
336 }
337 
338 /**
339   * @tc.name: CreateMemoryDb001
340   * @tc.desc: Create memory database after.
341   * @tc.type: FUNC
342   * @tc.require: AR000CRAKN
343   * @tc.author: sunpeng
344   */
345 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDb001, TestSize.Level1)
346 {
347     /**
348      * @tc.steps: step1. Create Memory database by GetKvStore.
349      * @tc.expected: step1. Create successfully.
350      */
351     const KvStoreNbDelegate::Option option = {true, true};
352     g_mgr.SetKvStoreConfig(g_config);
353     g_mgr.GetKvStore("distributed_Memorykvstore_001", option, g_kvNbDelegateCallback);
354     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
355     EXPECT_TRUE(g_kvDelegateStatus == OK);
356     KvStoreNbDelegate *kvNbDelegatePtr001 = g_kvNbDelegatePtr;
357 
358     /**
359      * @tc.steps: step2. Duplicate create Memory database by GetKvStore.
360      * @tc.expected: step2. Duplicate create successfully.
361      */
362     g_mgr.GetKvStore("distributed_Memorykvstore_001", option, g_kvNbDelegateCallback);
363     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
364     EXPECT_TRUE(g_kvDelegateStatus == OK);
365     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
366 
367     /**
368      * @tc.steps: step3. Duplicate create Memory database by GetKvStore.
369      * @tc.expected: step3. Duplicate create successfully.
370      */
371     g_mgr.GetKvStore("distributed_Memorykvstore_002", option, g_kvNbDelegateCallback);
372     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
373     EXPECT_TRUE(g_kvDelegateStatus == OK);
374     KvStoreNbDelegate *kvNbDelegatePtr002 = g_kvNbDelegatePtr;
375 
376     g_mgr.CloseKvStore(kvNbDelegatePtr001);
377     g_mgr.CloseKvStore(kvNbDelegatePtr002);
378 }
379 
380 /**
381   * @tc.name: CreateMemoryDb002
382   * @tc.desc: The MemoryDB cannot be created or open, when the physical database has been opened
383   * @tc.type: FUNC
384   * @tc.require: AR000CRAKN
385   * @tc.author: sunpeng
386   */
387 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDb002, TestSize.Level1)
388 {
389     KvStoreNbDelegate::Option option = {true, true};
390     /**
391      * @tc.steps: step1. Create SingleVer database by GetKvStore.
392      * @tc.expected: step1. Create database success.
393      */
394     g_mgr.GetKvStore("distributed_Memorykvstore_002", option, g_kvNbDelegateCallback);
395     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
396     EXPECT_TRUE(g_kvDelegateStatus == OK);
397     KvStoreNbDelegate *delegate1 = g_kvNbDelegatePtr;
398     g_kvNbDelegatePtr = nullptr;
399 
400     /**
401      * @tc.steps: step2. Create Memory database by GetKvStore.
402      * @tc.expected: step2. Create Memory database fail.
403      */
404     option.isMemoryDb = false;
405     g_mgr.GetKvStore("distributed_Memorykvstore_002", option, g_kvNbDelegateCallback);
406     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
407     EXPECT_TRUE(g_kvDelegateStatus != OK);
408     g_mgr.CloseKvStore(delegate1);
409     delegate1 = nullptr;
410 }
411 
412 /**
413   * @tc.name: CreateMemoryDb003
414   * @tc.desc: The physical database cannot be created or open, when the MemoryDB has been opened.
415   * @tc.type: FUNC
416   * @tc.require: AR000CRAKN
417   * @tc.author: sunpeng
418   */
419 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDb003, TestSize.Level1)
420 {
421     /**
422      * @tc.steps: step1. Get singleVer kvStore by GetKvStore.
423      * @tc.expected: step1. Get database success.
424      */
425     KvStoreDelegate::Option option;
426     g_mgr.GetKvStore("distributed_Memorykvstore_003", option, g_kvDelegateCallback);
427     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
428     EXPECT_TRUE(g_kvDelegateStatus == OK);
429 
430     /**
431      * @tc.steps: step2. Create Memory database by GetKvStore.
432      * @tc.expected: step2. Create Memory database fail.
433      */
434     KvStoreNbDelegate::Option nbOption = {true, true};
435     g_mgr.GetKvStore("distributed_Memorykvstore_003", nbOption, g_kvNbDelegateCallback);
436     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
437     EXPECT_TRUE(g_kvDelegateStatus != OK);
438     g_mgr.CloseKvStore(g_kvDelegatePtr);
439     g_kvDelegatePtr = nullptr;
440 }
441 
442 /**
443   * @tc.name: OperMemoryDbData001
444   * @tc.desc: Operate memory database
445   * @tc.type: FUNC
446   * @tc.require: AR000CRAKN
447   * @tc.author: sunpeng
448   */
449 HWTEST_F(DistributedDBInterfacesNBDelegateTest, OperMemoryDbData001, TestSize.Level1)
450 {
451     /**
452      * @tc.steps: step1. Create Memory database by GetKvStore.
453      */
454     const KvStoreNbDelegate::Option option = {true, true};
455     g_mgr.GetKvStore("distributed_OperMemorykvstore_001", option, g_kvNbDelegateCallback);
456     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
457     EXPECT_TRUE(g_kvDelegateStatus == OK);
458 
459     /**
460      * @tc.steps: step2. Put (KEY_1,VALUE_1)(KEY_2,VALUE_2) to Memory database.
461      * @tc.expected: step2. Success.
462      */
463     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_1, VALUE_1), OK);
464     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_2, VALUE_2), OK);
465 
466     /**
467      * @tc.steps: step3. Get (KEY_1,VALUE_1)(KEY_2,VALUE_2) to Memory database.
468      * @tc.expected: step3. Success.
469      */
470     Value readValueKey1;
471     Value readValueKey2;
472     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_1, readValueKey1), OK);
473     EXPECT_EQ(readValueKey1, VALUE_1);
474 
475     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_2, readValueKey2), OK);
476     EXPECT_EQ(readValueKey2, VALUE_2);
477 
478     /**
479      * @tc.steps: step4. Delete K1 from Memory database.
480      * @tc.expected: step4. Success.
481      */
482     EXPECT_EQ(g_kvNbDelegatePtr->Delete(KEY_1), OK);
483 
484     /**
485      * @tc.steps: step5. Get K1 from Memory database.
486      * @tc.expected: step5. NOT_FOUND.
487      */
488     readValueKey1.clear();
489     readValueKey2.clear();
490     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_1, readValueKey1), NOT_FOUND);
491 
492     /**
493      * @tc.steps: step6. Update K2 value from Memory database.
494      * @tc.expected: step6. Get the right value after the update.
495      */
496     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_2, VALUE_3), OK);
497     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_2, readValueKey2), OK);
498     EXPECT_EQ(readValueKey2, VALUE_3);
499     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
500 }
501 
502 /**
503   * @tc.name: CloseMemoryDb001
504   * @tc.desc: Operate memory database after reopen memory database
505   * @tc.type: FUNC
506   * @tc.require: AR000CRAKN
507   * @tc.author: sunpeng
508   */
509 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CloseMemoryDb001, TestSize.Level1)
510 {
511     /**
512      * @tc.steps: step1. Create Memory database by GetKvStore.
513      */
514     const KvStoreNbDelegate::Option option = {true, true};
515     g_mgr.SetKvStoreConfig(g_config);
516     g_mgr.GetKvStore("distributed_CloseMemorykvstore_001", option, g_kvNbDelegateCallback);
517     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
518     EXPECT_TRUE(g_kvDelegateStatus == OK);
519 
520     /**
521      * @tc.steps: step2/3. Put and get to Memory database.
522      * @tc.expected: step2/3. Success and the value is right.
523      */
524     Value readValue;
525     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_1, VALUE_1), OK);
526     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_1, readValue), OK);
527     EXPECT_EQ(readValue, VALUE_1);
528 
529     /**
530      * @tc.steps: step4. Close the Memory database.
531      * @tc.expected: step4. Success.
532      */
533     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
534 
535     /**
536      * @tc.steps: step5. Reopen the Memory database.
537      * @tc.expected: step5. Success.
538      */
539     g_mgr.GetKvStore("distributed_CloseMemorykvstore_001", option, g_kvNbDelegateCallback);
540     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
541     EXPECT_TRUE(g_kvDelegateStatus == OK);
542 
543     /**
544      * @tc.steps: step6. Get the key1 which has been put into the Memory database.
545      * @tc.expected: step6. Return NOT_FOUND.
546      */
547     readValue.clear();
548     EXPECT_EQ(g_kvNbDelegatePtr->Get(KEY_1, readValue), NOT_FOUND);
549     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
550 }
551 
552 /**
553   * @tc.name: ResultSetTest001
554   * @tc.desc: Test the NbDelegate for result set function.
555   * @tc.type: FUNC
556   * @tc.require: AR000D08KT
557   * @tc.author: wumin
558   */
559 HWTEST_F(DistributedDBInterfacesNBDelegateTest, ResultSetTest001, TestSize.Level1)
560 {
561     /**
562      * @tc.steps: step1. initialize result set.
563      * @tc.expected: step1. Success.
564      */
565     KvStoreNbDelegate::Option option = {true, false, false};
566     g_mgr.GetKvStore("distributed_nb_delegate_result_set_test", option, g_kvNbDelegateCallback);
567     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
568     EXPECT_TRUE(g_kvDelegateStatus == OK);
569     InitResultSet();
570 
571     /**
572      * @tc.steps: step2. get entries using result set.
573      * @tc.expected: step2. Success.
574      */
575     KvStoreResultSet *readResultSet = nullptr;
576     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(g_keyPrefix, readResultSet), OK);
577     ASSERT_TRUE(readResultSet != nullptr);
578     EXPECT_EQ(readResultSet->GetCount(), RESULT_SET_COUNT);
579 
580     /**
581      * @tc.steps: step3. result function check.
582      * @tc.expected: step3. Success.
583      */
584     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_INIT_POS);
585     // index from 0 to 8(first to last)
586     ReadResultSet(readResultSet);
587     // change index to 9(after last)
588     EXPECT_TRUE(!readResultSet->MoveToNext());
589     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_COUNT);
590     // change index to 8(last)
591     EXPECT_TRUE(readResultSet->MoveToPrevious());
592     CheckResultSetValue(readResultSet, OK, RESULT_SET_COUNT - 1);
593     // change index to 0(first)
594     EXPECT_TRUE(readResultSet->MoveToFirst());
595     CheckResultSetValue(readResultSet, OK, RESULT_SET_INIT_POS + 1);
596     // change index to 8(last)
597     EXPECT_TRUE(readResultSet->MoveToLast());
598     CheckResultSetValue(readResultSet, OK, RESULT_SET_COUNT - 1);
599     // move to -4: change index to -1
600     EXPECT_TRUE(!readResultSet->MoveToPosition(RESULT_SET_INIT_POS - 3));
601     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_INIT_POS);
602     // move to 10: change index to 9
603     EXPECT_TRUE(!readResultSet->MoveToPosition(RESULT_SET_COUNT + 1));
604     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_COUNT);
605     // change index to 2
606     EXPECT_TRUE(readResultSet->MoveToPosition(RESULT_SET_INIT_POS + 3));
607     CheckResultSetValue(readResultSet, OK, RESULT_SET_INIT_POS + 3);
608     // move 0: change index to 2
609     EXPECT_TRUE(readResultSet->Move(0));
610     CheckResultSetValue(readResultSet, OK, RESULT_SET_INIT_POS + 3);
611     // change index to 6
612     EXPECT_TRUE(readResultSet->Move(RESULT_SET_INIT_POS + 5));
613     CheckResultSetValue(readResultSet, OK, RESULT_SET_INIT_POS + 7);
614     // change index to 3
615     EXPECT_TRUE(readResultSet->Move(RESULT_SET_INIT_POS - 2));
616     CheckResultSetValue(readResultSet, OK, RESULT_SET_INIT_POS + 4);
617     // move -5: change index to -1
618     EXPECT_TRUE(!readResultSet->Move(-5));
619     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_INIT_POS);
620 
621     // move INT_MIN: change index to -1
622     EXPECT_TRUE(!readResultSet->Move(INT_MIN));
623     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_INIT_POS);
624 
625     EXPECT_TRUE(readResultSet->Move(5));
626     EXPECT_TRUE(!readResultSet->Move(INT_MAX));
627     CheckResultSetValue(readResultSet, NOT_FOUND, RESULT_SET_COUNT);
628 
629     /**
630      * @tc.steps: step4. clear the result set resource.
631      * @tc.expected: step4. Success.
632      */
633     EXPECT_EQ(g_kvNbDelegatePtr->CloseResultSet(readResultSet), OK);
634     EXPECT_TRUE(readResultSet == nullptr);
635     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
636     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_nb_delegate_result_set_test"), OK);
637     g_kvNbDelegatePtr = nullptr;
638 }
639 
640 /**
641   * @tc.name: PutBatchVerify001
642   * @tc.desc: This test case use to verify the putBatch interface function
643   * @tc.type: FUNC
644   * @tc.require: AR000CCPOM
645   * @tc.author: wumin
646   */
647 HWTEST_F(DistributedDBInterfacesNBDelegateTest, PutBatchVerify001, TestSize.Level1)
648 {
649     /**
650      * @tc.steps: step1. Get singleVer kvStore by GetKvStore.
651      * @tc.expected: step1. Get database success.
652      */
653     const KvStoreNbDelegate::Option option = {true, true};
654     g_mgr.SetKvStoreConfig(g_config);
655     g_mgr.GetKvStore("distributed_PutBatchVerify_001", option, g_kvNbDelegateCallback);
656     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
657     EXPECT_TRUE(g_kvDelegateStatus == OK);
658 
659     /**
660      * @tc.steps: step2. Insert 10 records into database.
661      * @tc.expected: step2. Insert successfully.
662      */
663     vector<Entry> entries;
664     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
665         Entry entry;
666         entry.key.push_back(i);
667         entry.value.push_back(i);
668         entries.push_back(entry);
669     }
670 
671     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), OK);
672 
673     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
674         Key key;
675         key.push_back(i);
676         Value value;
677         g_kvNbDelegatePtr->Get(key, value);
678         EXPECT_EQ(key, value);
679     }
680 
681     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
682     g_kvNbDelegatePtr = nullptr;
683 }
684 
685 /**
686   * @tc.name: SingleVerPutBatch001
687   * @tc.desc: Check for illegal parameters
688   * @tc.type: FUNC
689   * @tc.require: AR000DPTQ8
690   * @tc.author: sunpeng
691   */
692 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatch001, TestSize.Level1)
693 {
694     /**
695      * @tc.steps: step1.
696      *  Create and construct three sets of vector <Entry>, each set of three data contains records:
697      *  (K1, V1) It is illegal for K1 to be greater than 1K, and V1 is 1K in size
698      *  (K2, V2) K2 is legal, V2 is greater than 4M
699      *  (K3, V3) are not legal.
700      */
701     Key illegalKey;
702     DistributedDBToolsUnitTest::GetRandomKeyValue(illegalKey, DBConstant::MAX_KEY_SIZE + 1); // 1K + 1
703     Value illegalValue;
704     DistributedDBToolsUnitTest::GetRandomKeyValue(illegalValue, DBConstant::MAX_VALUE_SIZE + 1); // 4M + 1
705     vector<Entry> entrysKeyIllegal = {KV_ENTRY_1, KV_ENTRY_2, {illegalKey, VALUE_3}};
706     vector<Entry> entrysValueIllegal = {KV_ENTRY_1, KV_ENTRY_2, {KEY_3, illegalValue}};
707     vector<Entry> entrysIllegal = {KV_ENTRY_1, KV_ENTRY_2, {illegalKey, illegalValue}};
708 
709     const KvStoreNbDelegate::Option option = {true, false};
710     g_mgr.SetKvStoreConfig(g_config);
711     g_mgr.GetKvStore("distributed_SingleVerPutBatch_001", option, g_kvNbDelegateCallback);
712     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
713     EXPECT_TRUE(g_kvDelegateStatus == OK);
714     /**
715      * @tc.steps: step2. PutBatch operates on three sets of data.
716      * @tc.expected: step2. All three operations return INVALID_ARGS.
717      */
718     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysKeyIllegal), INVALID_ARGS);
719     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysValueIllegal), INVALID_ARGS);
720     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysIllegal), INVALID_ARGS);
721 
722     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
723     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_001"), OK);
724     g_kvNbDelegatePtr = nullptr;
725 }
726 
727 /**
728   * @tc.name: SingleVerPutBatch002
729   * @tc.desc: PutBatch normal insert function test.
730   * @tc.type: FUNC
731   * @tc.require: AR000DPTQ8
732   * @tc.author: sunpeng
733   */
734 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatch002, TestSize.Level1)
735 {
736     const KvStoreNbDelegate::Option option = {true, false};
737     g_mgr.SetKvStoreConfig(g_config);
738     g_mgr.GetKvStore("distributed_SingleVerPutBatch_002", option, g_kvNbDelegateCallback);
739     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
740     EXPECT_TRUE(g_kvDelegateStatus == OK);
741     /**
742      * @tc.steps: step1.
743      *  Create and build 4 groups of vector <Entry>, which are:
744      *  Vect of empty objects;
745      *  Vect1 of a legal Entry record;
746      *  128 legal Entry records Vect2;
747      *  129 legal Entry records Vect3;
748      */
749     vector<Entry> entrysMaxNumber;
750     for (size_t i = 0; i < DBConstant::MAX_BATCH_SIZE; i++) {
751         Entry entry;
752         entry.key.push_back(i);
753         entry.value.push_back(i);
754         entrysMaxNumber.push_back(entry);
755     }
756     Key keyTemp = {'1', '1'};
757     Value valueTemp;
758     Entry entryTemp = {keyTemp, VALUE_1};
759     vector<Entry> entrysOneRecord = {entryTemp};
760     vector<Entry> entrysOverSize = entrysMaxNumber;
761     entrysOverSize.push_back(entryTemp);
762     /**
763      * @tc.steps: step2. PutBatch operates on four sets of data. and use get check the result of Vect3.
764      * @tc.expected: step2. Returns INVALID_ARGS for 129 records, and returns OK for the rest. all get return NOT_FOUND.
765      */
766     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysOverSize), INVALID_ARGS);
767     for (size_t i = 0; i < entrysOverSize.size(); i++) {
768         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysOverSize[i].key, valueTemp), NOT_FOUND);
769     }
770     /**
771      * @tc.steps: step3. Use get check the result of Vect2.
772      * @tc.expected: step3. Return OK and get the correct value.
773      */
774     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysOneRecord), OK);
775     EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueTemp), OK);
776     EXPECT_EQ(valueTemp, VALUE_1);
777     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysMaxNumber), OK);
778      /**
779      * @tc.steps: step4. Use get check the result of Vect3.
780      * @tc.expected: step4. Return OK and get the correct value.
781      */
782     for (size_t i = 0; i < entrysMaxNumber.size(); i++) {
783         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysMaxNumber[i].key, valueTemp), OK);
784         EXPECT_EQ(valueTemp, entrysMaxNumber[i].value);
785     }
786 
787     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
788     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_002"), OK);
789     g_kvNbDelegatePtr = nullptr;
790 }
791 
792 /**
793   * @tc.name: SingleVerPutBatch003
794   * @tc.desc: Check interface atomicity
795   * @tc.type: FUNC
796   * @tc.require: AR000DPTQ8
797   * @tc.author: sunpeng
798   */
799 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatch003, TestSize.Level1)
800 {
801     const KvStoreNbDelegate::Option option = {true, false};
802     g_mgr.SetKvStoreConfig(g_config);
803     g_mgr.GetKvStore("distributed_SingleVerPutBatch_003", option, g_kvNbDelegateCallback);
804     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
805     EXPECT_TRUE(g_kvDelegateStatus == OK);
806     /**
807      * @tc.steps: step1. Create and construct a set of vector <Entry> with a total of 128 data,
808      * including one illegal data. And call PutBatch interface to insert.
809      */
810     vector<Entry> entrysMaxNumber;
811     for (size_t i = 0; i < DBConstant::MAX_BATCH_SIZE; i++) {
812         Entry entry;
813         entry.key.push_back(i);
814         entry.value.push_back(i);
815         entrysMaxNumber.push_back(entry);
816     }
817     Key illegalKey;
818     Value valueTemp;
819     DistributedDBToolsUnitTest::GetRandomKeyValue(illegalKey, DBConstant::MAX_KEY_SIZE + 1); // 1K + 1
820     entrysMaxNumber[0].key = illegalKey;
821 
822     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysMaxNumber), INVALID_ARGS);
823     /**
824      * @tc.steps: step2. Use Get interface to query 128 corresponding key values.
825      * @tc.expected: step2. All Get interface return NOT_FOUND.
826      */
827     EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysMaxNumber[0].key, valueTemp), INVALID_ARGS);
828     for (size_t i = 1; i < entrysMaxNumber.size(); i++) {
829         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysMaxNumber[i].key, valueTemp), NOT_FOUND);
830     }
831     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
832     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_003"), OK);
833     g_kvNbDelegatePtr = nullptr;
834 }
835 
PreparePutBatch004(vector<Entry> & entrys1,vector<Entry> & entrys2,vector<Entry> & entrys3)836 static void PreparePutBatch004(vector<Entry> &entrys1, vector<Entry> &entrys2, vector<Entry> &entrys3)
837 {
838     const KvStoreNbDelegate::Option option = {true, false};
839     g_mgr.SetKvStoreConfig(g_config);
840     g_mgr.GetKvStore("distributed_SingleVerPutBatch_004", option, g_kvNbDelegateCallback);
841     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
842     EXPECT_TRUE(g_kvDelegateStatus == OK);
843 
844     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
845         Entry entry;
846         entry.key.push_back(i);
847         entry.value.push_back(i);
848         entrys1.push_back(entry);
849     }
850 
851     for (int i = 0; i < DIVIDE_BATCH_PRESET_SIZE; i++) {
852         Entry entry;
853         entry.key.push_back(i);
854         entry.value.push_back(i + VALUE_OFFSET);
855         entrys2.push_back(entry);
856     }
857 
858     for (int i = DIVIDE_BATCH_PRESET_SIZE; i < BATCH_PRESET_SIZE_TEST; i++) {
859         Entry entry;
860         entry.key.push_back(i);
861         entry.value.push_back(i - VALUE_OFFSET);
862         entrys3.push_back(entry);
863     }
864 }
865 
866 /**
867   * @tc.name: SingleVerPutBatch004
868   * @tc.desc: Check interface data insertion and update functions.
869   * @tc.type: FUNC
870   * @tc.require: AR000DPTQ8
871   * @tc.author: sunpeng
872   */
873 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatch004, TestSize.Level1)
874 {
875     /**
876      * @tc.steps: step1.
877      *  Construct three groups of three vector <Entry>:
878      *  (1) entrys1: key1 ~ 10, corresponding to Value1 ~ 10;
879      *  (2) entrys2: key1 ~ 5, corresponding to Value6 ~ 10;
880      *  (3) entrys3: key6 ~ 10, corresponding to Value1 ~ 5;
881      */
882     vector<Entry> entrys1;
883     vector<Entry> entrys2;
884     vector<Entry> entrys3;
885     PreparePutBatch004(entrys1, entrys2, entrys3);
886     /**
887      * @tc.steps: step2. PutBatch entrys2.
888      * @tc.expected: step2. PutBatch return OK.
889      */
890     Value valueRead;
891     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys2), OK);
892     /**
893      * @tc.steps: step3. Check PutBatch result.
894      * @tc.expected: step3. Get correct value of key1~5. Key6~10 return NOT_FOUND.
895      */
896     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
897         Key keyTemp;
898         keyTemp.push_back(i);
899         if (i < DIVIDE_BATCH_PRESET_SIZE) {
900             Value valueTemp;
901             valueTemp.push_back(i + VALUE_OFFSET);
902             EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), OK);
903             EXPECT_EQ(valueRead, valueTemp);
904             continue;
905         }
906         EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), NOT_FOUND);
907     }
908     /**
909      * @tc.steps: step4. PutBatch entrys1.
910      * @tc.expected: step4. PutBatch return OK.
911      */
912     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys1), OK);
913     /**
914      * @tc.steps: step5. Check PutBatch result.
915      * @tc.expected: step5. Update and insert value of key1~10 to value1~10.
916      */
917     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
918         Key keyTemp;
919         keyTemp.push_back(i);
920         if (i < DIVIDE_BATCH_PRESET_SIZE) {
921             EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), OK);
922             EXPECT_EQ(valueRead, keyTemp);
923             continue;
924         }
925         EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), OK);
926         EXPECT_EQ(valueRead, keyTemp);
927     }
928     /**
929      * @tc.steps: step6. PutBatch entrys3.
930      * @tc.expected: step6. PutBatch return OK.
931      */
932     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys3), OK);
933     /**
934      * @tc.steps: step7. Check PutBatch result of key1~10.
935      * @tc.expected: step7. Update value of key5~10 to value1~5.
936      */
937     for (int i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
938         Key keyTemp;
939         keyTemp.push_back(i);
940         if (i < DIVIDE_BATCH_PRESET_SIZE) {
941             EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), OK);
942             EXPECT_EQ(valueRead, keyTemp);
943             continue;
944         }
945         Value valueTemp;
946         valueTemp.push_back(i - VALUE_OFFSET);
947         EXPECT_EQ(g_kvNbDelegatePtr->Get(keyTemp, valueRead), OK);
948         EXPECT_EQ(valueRead, valueTemp);
949     }
950 
951     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
952     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_004"), OK);
953     g_kvNbDelegatePtr = nullptr;
954 }
955 
CreatEntrys(int recordSize,vector<Key> & keys,vector<Value> & values,vector<Entry> & entries)956 static void CreatEntrys(int recordSize, vector<Key> &keys, vector<Value> &values, vector<Entry> &entries)
957 {
958     keys.clear();
959     values.clear();
960     entries.clear();
961     for (int i = 0; i < recordSize; i++) {
962         string temp = to_string(i);
963         Entry entry;
964         Key keyTemp;
965         Value valueTemp;
966         for (auto &iter : temp) {
967             entry.key.push_back(iter);
968             entry.value.push_back(iter);
969             keyTemp.push_back(iter);
970             valueTemp.push_back(iter);
971         }
972         keys.push_back(keyTemp);
973         values.push_back(valueTemp);
974         entries.push_back(entry);
975     }
976 }
977 
978 /**
979   * @tc.name: SingleVerDeleteBatch001
980   * @tc.desc: Check for illegal parameters.
981   * @tc.type: FUNC
982   * @tc.require: AR000DPTQ8
983   * @tc.author: sunpeng
984   */
985 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerDeleteBatch001, TestSize.Level1)
986 {
987     const KvStoreNbDelegate::Option option = {true, false};
988     g_mgr.SetKvStoreConfig(g_config);
989     g_mgr.GetKvStore("distributed_SingleVerPutBatch_001", option, g_kvNbDelegateCallback);
990     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
991     EXPECT_TRUE(g_kvDelegateStatus == OK);
992     /**
993      * @tc.steps: step1. Create and construct a set of vector <Entry>, containing a total of 10 data keys1 ~ 10,
994      *  Value1 ~ 10, and call Putbatch interface to insert data.
995      * @tc.expected: step1. PutBatch successfully.
996      */
997     vector<Entry> entries;
998     vector<Key> keys;
999     vector<Value> values;
1000     Value valueRead;
1001     CreatEntrys(BATCH_PRESET_SIZE_TEST, keys, values, entries);
1002     vector<Entry> entrysBase = entries;
1003     vector<Key> keysBase = keys;
1004     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysBase), OK);
1005     /**
1006      * @tc.steps: step2. Use Get to check data in database.
1007      * @tc.expected: step2. Get value1~10 by key1~10 successfully.
1008      */
1009     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1010         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysBase[i].key, valueRead), OK);
1011     }
1012     /**
1013      * @tc.steps: step3. Use DeleteBatch interface to transfer 10 + 119 extra keys (total 129).
1014      * @tc.expected: step3. Return INVALID_ARGS.
1015      */
1016     CreatEntrys(DBConstant::MAX_BATCH_SIZE + 1, keys, values, entries);
1017     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keys), INVALID_ARGS);
1018     /**
1019      * @tc.steps: step4. Use Get to check data in database.
1020      * @tc.expected: step4. Key1~10 still in database.
1021      */
1022     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1023         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysBase[i].key, valueRead), OK);
1024     }
1025     /**
1026      * @tc.steps: step5. Use the DeleteBatch interface to pass in 10 included
1027      *  keys6 ~ 10 + 123 additional key values ​​(128 in total).
1028      * @tc.expected: step5. DeleteBatch OK.
1029      */
1030     CreatEntrys(DBConstant::MAX_BATCH_SIZE + DIVIDE_BATCH_PRESET_SIZE, keys, values, entries);
1031     keys.erase(keys.begin(), keys.begin() + DIVIDE_BATCH_PRESET_SIZE);
1032     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keys), OK);
1033     /**
1034      * @tc.steps: step6. Use Get to check key1~10 in database.
1035      * @tc.expected: step6. Key1~5 in database, key6~10 have been deleted.
1036      */
1037     for (size_t i = 0; i < DIVIDE_BATCH_PRESET_SIZE; i++) {
1038         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysBase[i].key, valueRead), OK);
1039     }
1040     for (size_t i = DIVIDE_BATCH_PRESET_SIZE; i < BATCH_PRESET_SIZE_TEST; i++) {
1041         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysBase[i].key, valueRead), NOT_FOUND);
1042     }
1043     /**
1044      * @tc.steps: step7. Repeat Putbatch key1~10, value1~10.
1045      * @tc.expected: step7. Return OK.
1046      */
1047     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysBase), OK);
1048 
1049     Key illegalKey;
1050     DistributedDBToolsUnitTest::GetRandomKeyValue(illegalKey, DBConstant::MAX_KEY_SIZE + 1); // 1K + 1
1051     keysBase.push_back(illegalKey);
1052     /**
1053      * @tc.steps: step8. Use DeleteBatch interface to pass in 10 + 1(larger than 1K) keys.
1054      * @tc.expected: step8. Return INVALID_ARGS.
1055      */
1056     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keysBase), INVALID_ARGS);
1057     /**
1058      * @tc.steps: step9. Use Get to check key1~10 in database.
1059      * @tc.expected: step9. Delete those data failed.
1060      */
1061     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1062         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysBase[i].key, valueRead), OK);
1063     }
1064     /**
1065      * @tc.steps: step10. Use DeleteBatch interface to pass in 10(in database) + 1 valid keys.
1066      * @tc.expected: step10. Delete those data successfully.
1067      */
1068     keysBase.back().erase(keysBase.back().begin(), keysBase.back().begin() + 1);
1069     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keysBase), OK);
1070     /**
1071      * @tc.steps: step11. Check data.
1072      * @tc.expected: step11. DeleteBatch successfully.
1073      */
1074     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1075         EXPECT_EQ(g_kvNbDelegatePtr->Get(entrysBase[i].key, valueRead), NOT_FOUND);
1076     }
1077 
1078     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1079     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_001"), OK);
1080     g_kvNbDelegatePtr = nullptr;
1081 }
1082 
1083 /**
1084   * @tc.name: SingleVerDeleteBatch002
1085   * @tc.desc: Check normal delete batch ability.
1086   * @tc.type: FUNC
1087   * @tc.require: AR000DPTQ8
1088   * @tc.author: sunpeng
1089   */
1090 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerDeleteBatch002, TestSize.Level1)
1091 {
1092     const KvStoreNbDelegate::Option option = {true, false};
1093     g_mgr.SetKvStoreConfig(g_config);
1094     g_mgr.GetKvStore("distributed_SingleVerPutBatch_002", option, g_kvNbDelegateCallback);
1095     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1096     EXPECT_TRUE(g_kvDelegateStatus == OK);
1097     /**
1098      * @tc.steps: step1. Create a group of vector <Entry>, containing a total of 10 data keys1 ~ 10, Value1 ~ 10,
1099      *  call the Putbatch interface to insert data.
1100      * @tc.expected: step1. Insert to database successfully.
1101      */
1102     vector<Entry> entries;
1103     vector<Key> keysBase;
1104     vector<Value> values;
1105     CreatEntrys(BATCH_PRESET_SIZE_TEST, keysBase, values, entries);
1106 
1107     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), OK);
1108     /**
1109      * @tc.steps: step2. Check data.
1110      * @tc.expected: step2. Get key1~10 successfully.
1111      */
1112     Value valueRead;
1113     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1114         EXPECT_EQ(g_kvNbDelegatePtr->Get(keysBase[i], valueRead), OK);
1115     }
1116     /**
1117      * @tc.steps: step3. DeleteBatch key1~5.
1118      * @tc.expected: step3. Return OK.
1119      */
1120     vector<Key> keys(keysBase.begin(), keysBase.begin() + DIVIDE_BATCH_PRESET_SIZE);
1121     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keys), OK);
1122     /**
1123      * @tc.steps: step4. Check key1~10.
1124      * @tc.expected: step4. Key1~5 deleted, key6~10 existed.
1125      */
1126     for (size_t i = 0; i < DIVIDE_BATCH_PRESET_SIZE; i++) {
1127         EXPECT_EQ(g_kvNbDelegatePtr->Get(keysBase[i], valueRead), NOT_FOUND);
1128     }
1129     for (size_t i = DIVIDE_BATCH_PRESET_SIZE; i < BATCH_PRESET_SIZE_TEST; i++) {
1130         EXPECT_EQ(g_kvNbDelegatePtr->Get(keysBase[i], valueRead), OK);
1131     }
1132     /**
1133      * @tc.steps: step5. DeleteBatch key1~10.
1134      * @tc.expected: step5. Return OK.
1135      */
1136     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keysBase), OK);
1137     /**
1138      * @tc.steps: step6. Check key1~10.
1139      * @tc.expected: step6. Key1~10 deleted successfully.
1140      */
1141     for (size_t i = 0; i < BATCH_PRESET_SIZE_TEST; i++) {
1142         EXPECT_EQ(g_kvNbDelegatePtr->Get(keysBase[i], valueRead), NOT_FOUND);
1143     }
1144     /**
1145      * @tc.steps: step7. DeleteBatch key1~10 once again.
1146      * @tc.expected: step7. Return OK.
1147      */
1148     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keysBase), OK);
1149 
1150     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1151     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatch_002"), OK);
1152     g_kvNbDelegatePtr = nullptr;
1153 }
1154 
1155 /**
1156   * @tc.name: SingleVerPutBatchObserver001
1157   * @tc.desc: Test the observer function of PutBatch() interface.
1158   * @tc.type: FUNC
1159   * @tc.require: AR000DPTTA
1160   * @tc.author: wumin
1161   */
1162 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatchObserver001, TestSize.Level1)
1163 {
1164     /**
1165      * @tc.steps:step1. Get the nb delegate.
1166      * @tc.expected: step1. Get results OK and non-null delegate.
1167      */
1168     KvStoreNbDelegate::Option option = {true, false, false};
1169     g_mgr.GetKvStore("distributed_SingleVerPutBatchObserver_001", option, g_kvNbDelegateCallback);
1170     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1171     EXPECT_TRUE(g_kvDelegateStatus == OK);
1172 
1173     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
1174     ASSERT_TRUE(observer != nullptr);
1175     /**
1176      * @tc.steps:step2. Register the non-null observer for the special key.
1177      * @tc.expected: step2. Register results OK.
1178      */
1179     Key key;
1180     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_NATIVE, observer), OK);
1181     /**
1182      * @tc.steps:step3. Put batch data.
1183      * @tc.expected: step3. Returns OK.
1184      */
1185     vector<Entry> entrysBase;
1186     vector<Key> keysBase;
1187     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST + 1, entrysBase, keysBase);
1188 
1189     vector<Entry> entries(entrysBase.begin(), entrysBase.end() - 1);
1190     EXPECT_EQ(entries.size(), 10UL);
1191     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), OK);
1192     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1193     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entries, observer->GetEntriesInserted()));
1194     /**
1195      * @tc.steps:step4. Delete the batch data.
1196      * @tc.expected: step4. Returns OK.
1197      */
1198     vector<Key> keys(keysBase.begin() + 5, keysBase.end());
1199     EXPECT_EQ(keys.size(), 6UL);
1200     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keys), OK);
1201     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1202     vector<Entry> entrysDel(entrysBase.begin() + 5, entrysBase.end() - 1);
1203     EXPECT_EQ(entrysDel.size(), 5UL);
1204     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrysDel, observer->GetEntriesDeleted()));
1205     /**
1206      * @tc.steps:step5. UnRegister the observer.
1207      * @tc.expected: step5. Returns OK.
1208      */
1209     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
1210     delete observer;
1211     observer = nullptr;
1212     /**
1213      * @tc.steps:step6. Close the kv store.
1214      * @tc.expected: step6. Results OK and delete successfully.
1215      */
1216     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1217     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatchObserver_001"), OK);
1218     g_kvNbDelegatePtr = nullptr;
1219 }
1220 
1221 /**
1222   * @tc.name: SingleVerPutBatchObserver002
1223   * @tc.desc: Test the observer function of PutBatch() for invalid input.
1224   * @tc.type: FUNC
1225   * @tc.require: AR000DPTTA
1226   * @tc.author: wumin
1227   */
1228 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatchObserver002, TestSize.Level4)
1229 {
1230     /**
1231      * @tc.steps:step1. Get the nb delegate.
1232      * @tc.expected: step1. Get results OK and non-null delegate.
1233      */
1234     KvStoreNbDelegate::Option option = {true, false, false};
1235     g_mgr.GetKvStore("distributed_SingleVerPutBatchObserver_002", option, g_kvNbDelegateCallback);
1236     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1237     EXPECT_TRUE(g_kvDelegateStatus == OK);
1238 
1239     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
1240     ASSERT_TRUE(observer != nullptr);
1241     /**
1242      * @tc.steps:step2. Register the non-null observer for the special key.
1243      * @tc.expected: step2. Register results OK.
1244      */
1245     Key key;
1246     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_NATIVE, observer), OK);
1247     /**
1248      * @tc.steps:step3. Put 129 batch data.
1249      * @tc.expected: step3. Returns INVALID_ARGS.
1250      */
1251     vector<Entry> entrys1;
1252     vector<Key> keys1;
1253     DistributedDBUnitTest::GenerateRecords(DBConstant::MAX_BATCH_SIZE + 1, entrys1, keys1);
1254 
1255     EXPECT_EQ(entrys1.size(), 129UL);
1256     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys1), INVALID_ARGS);
1257     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1258     EXPECT_TRUE(observer->GetEntriesInserted().empty());
1259     /**
1260      * @tc.steps:step4. Put invalid batch data.
1261      * @tc.expected: step4. Returns INVALID_ARGS.
1262      */
1263     vector<Entry> entrys2;
1264     vector<Key> keys2;
1265     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrys2, keys2);
1266     EXPECT_EQ(entrys2.size(), 10UL);
1267 
1268     vector<Entry> entrysInvalid;
1269     vector<Key> keysInvalid;
1270     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrysInvalid, keysInvalid,
1271         DBConstant::MAX_KEY_SIZE + 10);
1272     EXPECT_EQ(entrysInvalid.size(), 10UL);
1273     entrys2[0].key = entrysInvalid[0].key;
1274 
1275     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys2), INVALID_ARGS);
1276     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1277     EXPECT_TRUE(observer->GetEntriesInserted().empty());
1278     /**
1279      * @tc.steps:step5. Put MAX valid value batch data.
1280      * @tc.expected: step5. Returns OK.
1281      */
1282     vector<Entry> entrys3;
1283     vector<Key> keys3;
1284 
1285     DistributedDBUnitTest::GenerateRecords(DBConstant::MAX_BATCH_SIZE, entrys3, keys3);
1286     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys3), OK);
1287     LOGD("sleep begin");
1288     // sleep 20 seconds
1289     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME * 10));
1290     LOGD("sleep end");
1291     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrys3, observer->GetEntriesInserted()));
1292     /**
1293      * @tc.steps:step6. UnRegister the observer.
1294      * @tc.expected: step6. Returns OK.
1295      */
1296     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
1297     delete observer;
1298     observer = nullptr;
1299     /**
1300      * @tc.steps:step7. Close the kv store.
1301      * @tc.expected: step7. Results OK and delete successfully.
1302      */
1303     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1304     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatchObserver_002"), OK);
1305     g_kvNbDelegatePtr = nullptr;
1306 }
1307 
1308 /**
1309   * @tc.name: SingleVerPutBatchObserver003
1310   * @tc.desc: Test the observer function of PutBatch() update function.
1311   * @tc.type: FUNC
1312   * @tc.require: AR000DPTTA
1313   * @tc.author: wumin
1314   */
1315 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatchObserver003, TestSize.Level1)
1316 {
1317     /**
1318      * @tc.steps:step1. Get the nb delegate.
1319      * @tc.expected: step1. Get results OK and non-null delegate.
1320      */
1321     KvStoreNbDelegate::Option option = {true, false, false};
1322     g_mgr.GetKvStore("distributed_SingleVerPutBatchObserver_003", option, g_kvNbDelegateCallback);
1323     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1324     EXPECT_TRUE(g_kvDelegateStatus == OK);
1325 
1326     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
1327     ASSERT_TRUE(observer != nullptr);
1328     /**
1329      * @tc.steps:step2. Register the non-null observer for the special key.
1330      * @tc.expected: step2. Register results OK.
1331      */
1332     Key key;
1333     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_NATIVE, observer), OK);
1334     /**
1335      * @tc.steps:step3. Put batch data.
1336      * @tc.expected: step3. Returns OK.
1337      */
1338     vector<Entry> entrysAdd;
1339     vector<Key> keysAdd;
1340     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrysAdd, keysAdd);
1341 
1342     EXPECT_EQ(entrysAdd.size(), 10UL);
1343     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysAdd), OK);
1344     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1345     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrysAdd, observer->GetEntriesInserted()));
1346     /**
1347      * @tc.steps:step4. Update the batch data.
1348      * @tc.expected: step4. Returns OK.
1349      */
1350     vector<Entry> entrysUpdate;
1351     vector<Key> keysUpdate;
1352     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrysUpdate, keysUpdate, DEFAULT_KEY_VALUE_SIZE,
1353         DEFAULT_KEY_VALUE_SIZE + 10);
1354 
1355     EXPECT_EQ(entrysUpdate.size(), 10UL);
1356     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrysUpdate), OK);
1357     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1358     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrysUpdate, observer->GetEntriesUpdated()));
1359     /**
1360      * @tc.steps:step5. UnRegister the observer.
1361      * @tc.expected: step5. Returns OK.
1362      */
1363     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
1364     delete observer;
1365     observer = nullptr;
1366     /**
1367      * @tc.steps:step6. Close the kv store.
1368      * @tc.expected: step6. Results OK and delete successfully.
1369      */
1370     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1371     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatchObserver_003"), OK);
1372     g_kvNbDelegatePtr = nullptr;
1373 }
1374 
1375 /**
1376   * @tc.name: SingleVerPutBatchObserver004
1377   * @tc.desc: Test the observer function of PutBatch(), same keys handle.
1378   * @tc.type: FUNC
1379   * @tc.require: AR000DPTTA
1380   * @tc.author: wumin
1381   */
1382 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerPutBatchObserver004, TestSize.Level1)
1383 {
1384     /**
1385      * @tc.steps:step1. Get the nb delegate.
1386      * @tc.expected: step1. Get results OK and non-null delegate.
1387      */
1388     KvStoreNbDelegate::Option option = {true, false, false};
1389     g_mgr.GetKvStore("distributed_SingleVerPutBatchObserver_004", option, g_kvNbDelegateCallback);
1390     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1391     EXPECT_TRUE(g_kvDelegateStatus == OK);
1392 
1393     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
1394     ASSERT_TRUE(observer != nullptr);
1395     /**
1396      * @tc.steps:step2. Register the non-null observer for the special key.
1397      * @tc.expected: step2. Register results OK.
1398      */
1399     Key key;
1400     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_NATIVE, observer), OK);
1401     /**
1402      * @tc.steps:step3. Put batch data.
1403      * @tc.expected: step3. Returns OK.
1404      */
1405     vector<Entry> entrys1;
1406     vector<Key> keys1;
1407     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrys1, keys1);
1408     vector<Entry> entrys2;
1409     vector<Key> keys2;
1410     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrys2, keys2, DEFAULT_KEY_VALUE_SIZE,
1411         DEFAULT_KEY_VALUE_SIZE + 10);
1412     entrys1.insert(entrys1.end(), entrys2.begin(), entrys2.end());
1413 
1414     EXPECT_EQ(entrys1.size(), 20UL);
1415     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys1), OK);
1416     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1417     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrys2, observer->GetEntriesInserted()));
1418     EXPECT_EQ(observer->GetEntriesUpdated().size(), 0UL);
1419 
1420     vector<Entry> entrys3;
1421     vector<Key> keys3;
1422     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrys3, keys3, DEFAULT_KEY_VALUE_SIZE,
1423         DEFAULT_KEY_VALUE_SIZE + 20);
1424     vector<Entry> entrys4;
1425     vector<Key> keys4;
1426     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entrys4, keys4, DEFAULT_KEY_VALUE_SIZE,
1427         DEFAULT_KEY_VALUE_SIZE + 30);
1428     entrys3.insert(entrys3.end(), entrys4.begin(), entrys4.end());
1429     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entrys3), OK);
1430     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1431     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entrys4, observer->GetEntriesUpdated()));
1432     EXPECT_EQ(observer->GetEntriesInserted().size(), 0UL);
1433 
1434     /**
1435      * @tc.steps:step4. UnRegister the observer.
1436      * @tc.expected: step4. Returns OK.
1437      */
1438     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
1439     delete observer;
1440     observer = nullptr;
1441     /**
1442      * @tc.steps:step5. Close the kv store.
1443      * @tc.expected: step5. Results OK and delete successfully.
1444      */
1445     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1446     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerPutBatchObserver_004"), OK);
1447     g_kvNbDelegatePtr = nullptr;
1448 }
1449 
1450 /**
1451   * @tc.name: SingleVerDeleteBatchObserver001
1452   * @tc.desc: Test the observer function of DeleteBatch() interface.
1453   * @tc.type: FUNC
1454   * @tc.require: AR000DPTTA
1455   * @tc.author: wumin
1456   */
1457 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerDeleteBatchObserver001, TestSize.Level1)
1458 {
1459     /**
1460      * @tc.steps:step1. Get the nb delegate.
1461      * @tc.expected: step1. Get results OK and non-null delegate.
1462      */
1463     KvStoreNbDelegate::Option option = {true, false, false};
1464     g_mgr.GetKvStore("distributed_SingleVerDeleteBatchObserver_001", option, g_kvNbDelegateCallback);
1465     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1466     EXPECT_TRUE(g_kvDelegateStatus == OK);
1467 
1468     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
1469     ASSERT_TRUE(observer != nullptr);
1470     /**
1471      * @tc.steps:step2. Register the non-null observer for the special key.
1472      * @tc.expected: step2. Register results OK.
1473      */
1474     Key key;
1475     EXPECT_EQ(g_kvNbDelegatePtr->RegisterObserver(key, OBSERVER_CHANGES_NATIVE, observer), OK);
1476     /**
1477      * @tc.steps:step3. Put batch data.
1478      * @tc.expected: step3. Returns OK.
1479      */
1480     vector<Entry> entries;
1481     vector<Key> keys;
1482     DistributedDBUnitTest::GenerateRecords(BATCH_PRESET_SIZE_TEST, entries, keys);
1483     EXPECT_EQ(entries.size(), 10UL);
1484 
1485     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), OK);
1486     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1487     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entries, observer->GetEntriesInserted()));
1488     /**
1489      * @tc.steps:step4. Delete the batch data.
1490      * @tc.expected: step4. Returns OK.
1491      */
1492     EXPECT_EQ(g_kvNbDelegatePtr->DeleteBatch(keys), OK);
1493     std::this_thread::sleep_for(std::chrono::milliseconds(OBSERVER_SLEEP_TIME));
1494     EXPECT_TRUE(DistributedDBToolsUnitTest::CheckObserverResult(entries, observer->GetEntriesDeleted()));
1495     /**
1496      * @tc.steps:step5. UnRegister the observer.
1497      * @tc.expected: step5. Returns OK.
1498      */
1499     EXPECT_EQ(g_kvNbDelegatePtr->UnRegisterObserver(observer), OK);
1500     delete observer;
1501     observer = nullptr;
1502     /**
1503      * @tc.steps:step6. Close the kv store.
1504      * @tc.expected: step6. Results OK and delete successfully.
1505      */
1506     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1507     EXPECT_EQ(g_mgr.DeleteKvStore("distributed_SingleVerDeleteBatchObserver_001"), OK);
1508     g_kvNbDelegatePtr = nullptr;
1509 }
1510 
1511 /**
1512   * @tc.name: SingleVerConcurrentPut001
1513   * @tc.desc: Test put the data concurrently, and check the timestamp.
1514   * @tc.type: FUNC
1515   * @tc.require: AR000DPTTA
1516   * @tc.author: wangbingquan
1517   */
1518 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerConcurrentPut001, TestSize.Level4)
1519 {
1520     /**
1521      * @tc.steps:step1. Get the nb delegate.
1522      * @tc.expected: step1. Get results OK and non-null delegate.
1523      */
1524     KvStoreNbDelegate::Option option = {true, false, false};
1525     g_mgr.GetKvStore("concurrentPutTest", option, g_kvNbDelegateCallback);
1526     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1527     EXPECT_TRUE(g_kvDelegateStatus == OK);
1528 
1529     for (size_t i = 0; i < CON_PUT_THREAD_NUM * PER_THREAD_PUT_NUM; i++) {
1530         Entry entry;
1531         DistributedDBToolsUnitTest::GetRandomKeyValue(entry.key, DEFAULT_KEY_VALUE_SIZE);
1532         DistributedDBToolsUnitTest::GetRandomKeyValue(entry.value);
1533         g_entriesForConcurrency.push_back(std::move(entry));
1534     }
1535 
1536     /**
1537      * @tc.steps:step2. Put data concurrently in 4 threads.
1538      * @tc.expected: step2. Put OK, and the timestamp order is same with the rowid.
1539      */
1540     std::thread thread1(std::bind(PutData, g_kvNbDelegatePtr, 0)); // 0th thread.
1541     std::thread thread2(std::bind(PutData, g_kvNbDelegatePtr, 1)); // 1th thread.
1542     std::thread thread3(std::bind(PutData, g_kvNbDelegatePtr, 2)); // 2th thread.
1543     std::thread thread4(std::bind(PutData, g_kvNbDelegatePtr, 3)); // 3th thread.
1544 
1545     thread1.join();
1546     thread2.join();
1547     thread3.join();
1548     thread4.join();
1549 
1550     EXPECT_EQ(CheckDataTimestamp("concurrentPutTest"), true);
1551 
1552     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1553     EXPECT_EQ(g_mgr.DeleteKvStore("concurrentPutTest"), OK);
1554     g_kvNbDelegatePtr = nullptr;
1555 }
1556 
1557 /**
1558   * @tc.name: SingleVerGetLocalEntries001
1559   * @tc.desc: Test GetLocalEntries interface for the single ver database.
1560   * @tc.type: FUNC
1561   * @tc.require: AR000DPTTA
1562   * @tc.author: wangbingquan
1563   */
1564 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerGetLocalEntries001, TestSize.Level1)
1565 {
1566     /**
1567      * @tc.steps:step1. Get the nb delegate.
1568      * @tc.expected: step1. Get results OK and non-null delegate.
1569      */
1570     KvStoreNbDelegate::Option option = {true, false, false};
1571     g_mgr.GetKvStore("concurrentPutTest", option, g_kvNbDelegateCallback);
1572     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1573     EXPECT_TRUE(g_kvDelegateStatus == OK);
1574 
1575     /**
1576      * @tc.steps:step2. Put one data whose key has prefix 'p' into the local zone.
1577      */
1578     Entry entry1 = {{'p'}, {'q'}};
1579     EXPECT_EQ(g_kvNbDelegatePtr->PutLocal(entry1.key, entry1.value), OK);
1580 
1581     /**
1582      * @tc.steps:step3. Get batch data whose key has prefix 'k' from the local zone.
1583      * @tc.expected: step3. Get results NOT_FOUND.
1584      */
1585     std::vector<Entry> entries;
1586     EXPECT_EQ(g_kvNbDelegatePtr->GetLocalEntries({'k'}, entries), NOT_FOUND);
1587 
1588     /**
1589      * @tc.steps:step4. Put two data whose key have prefix 'k' into the local zone.
1590      */
1591     Entry entry2 = {{'k', '1'}, {'d'}};
1592     Entry entry3 = {{'k', '2'}, {'d'}};
1593     EXPECT_EQ(g_kvNbDelegatePtr->PutLocal(entry2.key, entry2.value), OK);
1594     EXPECT_EQ(g_kvNbDelegatePtr->PutLocal(entry3.key, entry3.value), OK);
1595 
1596     /**
1597      * @tc.steps:step5. Get batch data whose key has prefix 'k' from the local zone.
1598      * @tc.expected: step5. Get results OK, and the entries size is 2.
1599      */
1600     EXPECT_EQ(g_kvNbDelegatePtr->GetLocalEntries({'k'}, entries), OK);
1601     EXPECT_EQ(entries.size(), 2UL);
1602 
1603     /**
1604      * @tc.steps:step6. Get batch data whose key has empty prefix from the local zone.
1605      * @tc.expected: step6. Get results OK, and the entries size is 3.
1606      */
1607     EXPECT_EQ(g_kvNbDelegatePtr->GetLocalEntries({}, entries), OK);
1608     EXPECT_EQ(entries.size(), 3UL);
1609 
1610     /**
1611      * @tc.steps:step7. Delete one data whose key has prefix 'k' from the local zone.
1612      */
1613     EXPECT_EQ(g_kvNbDelegatePtr->DeleteLocal(entry3.key), OK);
1614 
1615     /**
1616      * @tc.steps:step8. Get batch data whose key has prefix 'k' from the local zone.
1617      * @tc.expected: step8. Get results OK, and the entries size is 1.
1618      */
1619     EXPECT_EQ(g_kvNbDelegatePtr->GetLocalEntries({'k'}, entries), OK);
1620     EXPECT_EQ(entries.size(), 1UL);
1621 
1622     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1623     EXPECT_EQ(g_mgr.DeleteKvStore("concurrentPutTest"), OK);
1624     g_kvNbDelegatePtr = nullptr;
1625 }
1626 
PreDataForQueryByPreFixKey()1627 static vector<Entry> PreDataForQueryByPreFixKey()
1628 {
1629     vector<Entry> res;
1630     for (int i = 0; i < 5; i++) { // Random 5 for test
1631         Key key = DistributedDBToolsUnitTest::GetRandPrefixKey({'a', 'b'}, 1024);
1632         std::string validData = "{\"field_name1\":null, \"field_name2\":" + std::to_string(rand()) + "}";
1633         Value value(validData.begin(), validData.end());
1634         res.push_back({key, value});
1635     }
1636 
1637     for (int i = 0; i < 5; i++) { // Random 5 for test
1638         Key key = DistributedDBToolsUnitTest::GetRandPrefixKey({'a', 'c'}, 1024);
1639         std::string validData = "{\"field_name1\":null, \"field_name2\":" + std::to_string(rand()) + "}";
1640         Value value(validData.begin(), validData.end());
1641         res.push_back({key, value});
1642     }
1643     return res;
1644 }
1645 
1646 /**
1647   * @tc.name: QueryPreFixKey002
1648   * @tc.desc: The query method without filtering the field can query non-schma databases
1649   * @tc.type: FUNC
1650   * @tc.require: AR000EPARK
1651   * @tc.author: sunpeng
1652   */
1653 HWTEST_F(DistributedDBInterfacesNBDelegateTest, QueryPreFixKey002, TestSize.Level1)
1654 {
1655     /**
1656      * @tc.steps:step1. Create non-schma databases
1657      */
1658     KvStoreNbDelegate::Option option = {true, false, false};
1659     g_mgr.GetKvStore("QueryPreFixKey002", option, g_kvNbDelegateCallback);
1660     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1661     EXPECT_TRUE(g_kvDelegateStatus == OK);
1662 
1663     vector<Entry> entries = PreDataForQueryByPreFixKey();
1664     EXPECT_EQ(g_kvNbDelegatePtr->PutBatch(entries), OK);
1665 
1666     /**
1667      * @tc.steps:step2. Get query object with prefixkey limit combination.
1668      * @tc.expected: step2. Get results OK, and the entries size right.
1669      */
1670     Query query = Query::Select().PrefixKey({'a', 'c'});
1671     std::vector<Entry> entriesRes;
1672     int errCode = g_kvNbDelegatePtr->GetEntries(query, entriesRes);
1673     EXPECT_EQ(errCode, OK);
1674     EXPECT_EQ(entriesRes.size(), 5ul);
1675     for (size_t i = 0; i < entriesRes.size(); i++) {
1676         EXPECT_EQ(entriesRes[i].key.front(), 'a');
1677         EXPECT_EQ(entriesRes[i].key[1], 'c');
1678     }
1679     int count = -1;
1680     g_kvNbDelegatePtr->GetCount(query, count);
1681     EXPECT_EQ(count, 5);
1682 
1683     Query query1 = Query::Select().PrefixKey({}).Limit(4, 0);
1684     errCode = g_kvNbDelegatePtr->GetEntries(query1, entriesRes);
1685     EXPECT_EQ(errCode, OK);
1686     EXPECT_EQ(entriesRes.size(), 4ul);
1687 
1688     Query query2 = Query::Select().PrefixKey(Key(1025, 'a'));
1689     errCode = g_kvNbDelegatePtr->GetEntries(query2, entriesRes);
1690     EXPECT_EQ(errCode, INVALID_ARGS);
1691 
1692     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1693     EXPECT_TRUE(g_mgr.DeleteKvStore("QueryPreFixKey002") == OK);
1694 }
1695 
1696 /**
1697   * @tc.name: SingleVerGetSecurityOption001
1698   * @tc.desc: Test GetSecurityOption interface for the single ver database.
1699   * @tc.type: FUNC
1700   * @tc.require: AR000EV1G2
1701   * @tc.author: liuwenkai
1702   */
1703 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerGetSecurityOption001, TestSize.Level1)
1704 {
1705     SecurityOption savedOption;
1706     std::shared_ptr<IProcessSystemApiAdapter> adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
1707     EXPECT_TRUE(adapter);
1708     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(adapter);
1709     KvStoreNbDelegate::Option option = {true, false, false};
1710 
1711     /**
1712      * @tc.steps:step1. Create databases without securityOption.
1713      * @tc.expected: step2. Returns a non-null kvstore but can not get SecurityOption.
1714      */
1715     g_mgr.GetKvStore("SingleVerGetSecurityOption001", option, g_kvNbDelegateCallback);
1716     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1717     EXPECT_TRUE(g_kvDelegateStatus == OK);
1718     EXPECT_TRUE(g_kvNbDelegatePtr->GetSecurityOption(savedOption) == OK);
1719     EXPECT_TRUE(savedOption.securityLabel == 0);
1720     EXPECT_TRUE(savedOption.securityFlag == 0);
1721     KvStoreNbDelegate *kvNbDelegatePtr1 = g_kvNbDelegatePtr;
1722 
1723     /**
1724      * @tc.steps:step2. Create databases with new securityOption(Check ignore the new option).
1725      * @tc.expected: step2. Returns non-null kvstore.
1726      */
1727     option.secOption.securityLabel = S3;
1728     option.secOption.securityFlag = 1;
1729     g_mgr.GetKvStore("SingleVerGetSecurityOption001", option, g_kvNbDelegateCallback);
1730     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1731     EXPECT_TRUE(g_kvDelegateStatus == OK);
1732     EXPECT_TRUE(g_kvNbDelegatePtr->GetSecurityOption(savedOption) == OK);
1733     EXPECT_TRUE(savedOption.securityLabel == 0);
1734     EXPECT_TRUE(savedOption.securityFlag == 0);
1735 
1736     EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr1), OK);
1737     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1738     g_kvNbDelegatePtr = nullptr;
1739     EXPECT_TRUE(g_mgr.DeleteKvStore("SingleVerGetSecurityOption001") == OK);
1740 }
1741 
1742 /**
1743   * @tc.name: SingleVerGetSecurityOption002
1744   * @tc.desc: Test GetSecurityOption interface for the single ver database.
1745   * @tc.type: FUNC
1746   * @tc.require: AR000EV1G2
1747   * @tc.author: liuwenkai
1748   */
1749 HWTEST_F(DistributedDBInterfacesNBDelegateTest, SingleVerGetSecurityOption002, TestSize.Level1)
1750 {
1751     SecurityOption savedOption;
1752     std::shared_ptr<IProcessSystemApiAdapter> adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
1753     EXPECT_TRUE(adapter != nullptr);
1754     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(adapter);
1755     KvStoreNbDelegate::Option option = {true, false, false};
1756 
1757     /**
1758      * @tc.steps:step1. Create databases with securityOption.
1759      * @tc.expected: step2. Returns a non-null kvstore and get right SecurityOption.
1760      */
1761     option.secOption.securityLabel = S3;
1762     option.secOption.securityFlag = 1;
1763     g_mgr.GetKvStore("SingleVerGetSecurityOption002", option, g_kvNbDelegateCallback);
1764     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1765     EXPECT_TRUE(g_kvDelegateStatus == OK);
1766     EXPECT_TRUE(g_kvNbDelegatePtr->GetSecurityOption(savedOption) == OK);
1767     EXPECT_TRUE(savedOption.securityLabel == S3);
1768     EXPECT_TRUE(savedOption.securityFlag == 1);
1769     KvStoreNbDelegate *kvNbDelegatePtr1 = g_kvNbDelegatePtr;
1770 
1771     /**
1772      * @tc.steps:step2. Create databases without securityOption.
1773      * @tc.expected: step2. Returns a non-null kvstore and get right SecurityOption.
1774      */
1775     option.secOption.securityLabel = 0;
1776     option.secOption.securityFlag = 0;
1777     g_mgr.GetKvStore("SingleVerGetSecurityOption002", option, g_kvNbDelegateCallback);
1778     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1779     EXPECT_TRUE(g_kvDelegateStatus == OK);
1780     EXPECT_TRUE(g_kvNbDelegatePtr->GetSecurityOption(savedOption) == OK);
1781     EXPECT_TRUE(savedOption.securityLabel == S3);
1782     EXPECT_TRUE(savedOption.securityFlag == 1);
1783 
1784     EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr1), OK);
1785     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1786     g_kvNbDelegatePtr = nullptr;
1787     EXPECT_TRUE(g_mgr.DeleteKvStore("SingleVerGetSecurityOption002") == OK);
1788 }
1789 
1790 /**
1791  * @tc.name: MaxLogSize001
1792  * @tc.desc: Test the pragma cmd of the max log size limit.
1793  * @tc.type: FUNC
1794  * @tc.require:
1795  * @tc.author: wangbingquan
1796  */
1797 HWTEST_F(DistributedDBInterfacesNBDelegateTest, MaxLogSize001, TestSize.Level2)
1798 {
1799     /**
1800      * @tc.steps:step1. Create database.
1801      * @tc.expected: step1. Returns a non-null kvstore.
1802      */
1803     KvStoreNbDelegate::Option option;
1804     g_mgr.GetKvStore("MaxLogSize001", option, g_kvNbDelegateCallback);
1805     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1806     EXPECT_TRUE(g_kvDelegateStatus == OK);
1807 
1808     /**
1809      * @tc.steps:step2. Setting the max log limit for the valid value.
1810      * @tc.expected: step2. Returns OK.
1811      */
1812     uint64_t logSize = DBConstant::MAX_LOG_SIZE_HIGH;
1813     PragmaData pragLimit = static_cast<PragmaData>(&logSize);
1814     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), OK);
1815 
1816     logSize = DBConstant::MAX_LOG_SIZE_LOW;
1817     pragLimit = static_cast<PragmaData>(&logSize);
1818     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), OK);
1819 
1820     logSize = 10 * 1024 * 1024; // 10M
1821     pragLimit = static_cast<PragmaData>(&logSize);
1822     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), OK);
1823 
1824     /**
1825      * @tc.steps:step3. Setting the max log limit for the invalid value.
1826      * @tc.expected: step3. Returns INLIVAD_ARGS.
1827      */
1828     logSize = DBConstant::MAX_LOG_SIZE_HIGH + 1;
1829     pragLimit = static_cast<PragmaData>(&logSize);
1830     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), INVALID_ARGS);
1831 
1832     logSize = DBConstant::MAX_LOG_SIZE_LOW - 1;
1833     pragLimit = static_cast<PragmaData>(&logSize);
1834     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), INVALID_ARGS);
1835     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1836     g_kvNbDelegatePtr = nullptr;
1837     EXPECT_TRUE(g_mgr.DeleteKvStore("MaxLogSize001") == OK);
1838 }
1839 
1840 /**
1841  * @tc.name: ForceCheckpoint002
1842  * @tc.desc: Test the checkpoint of the database.
1843  * @tc.type: FUNC
1844  * @tc.require:
1845  * @tc.author: wangbingquan
1846  */
1847 HWTEST_F(DistributedDBInterfacesNBDelegateTest, MaxLogSize002, TestSize.Level2)
1848 {
1849     /**
1850      * @tc.steps:step1. Create database.
1851      * @tc.expected: step1. Returns a non-null kvstore.
1852      */
1853     KvStoreNbDelegate::Option option;
1854     g_mgr.GetKvStore("MaxLogSize002", option, g_kvNbDelegateCallback);
1855     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1856     EXPECT_TRUE(g_kvDelegateStatus == OK);
1857 
1858     /**
1859      * @tc.steps:step2. Put the random entry into the database.
1860      * @tc.expected: step2. Returns OK.
1861      */
1862     Key key;
1863     Value value;
1864     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 30); // for 30B random key
1865     DistributedDBToolsUnitTest::GetRandomKeyValue(value, 3 * 1024 * 1024); // 3M value
1866     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
1867     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 40); // for 40B random key
1868     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
1869     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 20); // for 20B random key
1870     DistributedDBToolsUnitTest::GetRandomKeyValue(value, 1 * 1024 * 1024); // 1M value
1871     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
1872 
1873     /**
1874      * @tc.steps:step3. Get the resultset.
1875      * @tc.expected: step3. Returns OK.
1876      */
1877     KvStoreResultSet *resultSet = nullptr;
1878     EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(Key{}, resultSet), OK);
1879     ASSERT_NE(resultSet, nullptr);
1880     EXPECT_EQ(resultSet->GetCount(), 3); // size of all the entries is 3
1881     EXPECT_EQ(resultSet->MoveToFirst(), true);
1882 
1883     /**
1884      * @tc.steps:step4. Put more data into the database.
1885      * @tc.expected: step4. Returns OK.
1886      */
1887     uint64_t logSize = 6 * 1024 * 1024; // 6M for initial test.
1888     PragmaData pragLimit = static_cast<PragmaData>(&logSize);
1889     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), OK);
1890     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 10); // for 10B random key(different size)
1891     DistributedDBToolsUnitTest::GetRandomKeyValue(value, 3 * 1024 * 1024); // 3MB
1892     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
1893     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 15); // for 15B random key(different size)
1894     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
1895 
1896     /**
1897      * @tc.steps:step4. Put more data into the database while the log size is over the limit.
1898      * @tc.expected: step4. Returns LOG_OVER_LIMITS.
1899      */
1900     DistributedDBToolsUnitTest::GetRandomKeyValue(value, 25); // for 25B random key(different size)
1901     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), LOG_OVER_LIMITS);
1902     EXPECT_EQ(g_kvNbDelegatePtr->Delete(key), LOG_OVER_LIMITS);
1903     EXPECT_EQ(g_kvNbDelegatePtr->StartTransaction(), LOG_OVER_LIMITS);
1904     EXPECT_EQ(g_kvNbDelegatePtr->PutLocal(key, value), LOG_OVER_LIMITS);
1905     EXPECT_EQ(g_kvNbDelegatePtr->RemoveDeviceData("deviceA"), LOG_OVER_LIMITS);
1906     /**
1907      * @tc.steps:step4. Change the max log size limit, and put the data.
1908      * @tc.expected: step4. Returns OK.
1909      */
1910     logSize *= 10; // 10 multiple size
1911     pragLimit = static_cast<PragmaData>(&logSize);
1912     EXPECT_EQ(g_kvNbDelegatePtr->Pragma(SET_MAX_LOG_LIMIT, pragLimit), OK);
1913     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
1914     g_kvNbDelegatePtr->CloseResultSet(resultSet);
1915 
1916     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1917     EXPECT_EQ(g_mgr.DeleteKvStore("MaxLogSize002"), OK);
1918 }
1919 
1920 /**
1921  * @tc.name: MaxLogCheckPoint001
1922  * @tc.desc: Pragma the checkpoint command.
1923  * @tc.type: FUNC
1924  * @tc.require:
1925  * @tc.author: wangbingquan
1926  */
1927 HWTEST_F(DistributedDBInterfacesNBDelegateTest, MaxLogCheckPoint001, TestSize.Level2)
1928 {
1929     /**
1930      * @tc.steps:step1. Create database.
1931      * @tc.expected: step1. Returns a non-null kvstore.
1932      */
1933     KvStoreNbDelegate::Option option;
1934     g_mgr.GetKvStore("MaxLogCheckPoint001", option, g_kvNbDelegateCallback);
1935     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1936     EXPECT_TRUE(g_kvDelegateStatus == OK);
1937 
1938     /**
1939      * @tc.steps:step2. Put the random entry into the database.
1940      * @tc.expected: step2. Returns OK.
1941      */
1942     Key key;
1943     Value value;
1944     DistributedDBToolsUnitTest::GetRandomKeyValue(key, 30); // for 30B random key(different size)
1945     DistributedDBToolsUnitTest::GetRandomKeyValue(value, 1 * 1024 * 1024); // 1M
1946     EXPECT_EQ(g_kvNbDelegatePtr->Put(key, value), OK);
1947     EXPECT_EQ(g_kvNbDelegatePtr->Delete(key), OK);
1948 
1949     /**
1950      * @tc.steps:step3. Get the disk file size, execute the checkpoint and get the disk file size.
1951      * @tc.expected: step3. Returns OK and the file size is less than the size before checkpoint.
1952      */
1953     uint64_t sizeBeforeChk = 0;
1954     g_mgr.GetKvStoreDiskSize("MaxLogCheckPoint001", sizeBeforeChk);
1955     EXPECT_GT(sizeBeforeChk, 1 * 1024 * 1024ULL); // more than 1M
1956     int param = 0;
1957     PragmaData paraData = static_cast<PragmaData>(&param);
1958     g_kvNbDelegatePtr->Pragma(EXEC_CHECKPOINT, paraData);
1959     uint64_t sizeAfterChk = 0;
1960     g_mgr.GetKvStoreDiskSize("MaxLogCheckPoint001", sizeAfterChk);
1961     EXPECT_LT(sizeAfterChk, 100 * 1024ULL); // less than 100K
1962     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1963     EXPECT_EQ(g_mgr.DeleteKvStore("MaxLogCheckPoint001"), OK);
1964 }
1965 
1966 /**
1967   * @tc.name: CreateMemoryDbWithoutPath
1968   * @tc.desc: Create memory database without path.
1969   * @tc.type: FUNC
1970   * @tc.require: AR000CRAKN
1971   * @tc.author: sunpeng
1972   */
1973 HWTEST_F(DistributedDBInterfacesNBDelegateTest, CreateMemoryDbWithoutPath, TestSize.Level1)
1974 {
1975     /**
1976      * @tc.steps: step1. Create Memory database by GetKvStore without path.
1977      * @tc.expected: step1. Create successfully.
1978      */
1979     KvStoreDelegateManager mgr(APP_ID, USER_ID);
1980     const KvStoreNbDelegate::Option option = {true, true};
1981     mgr.GetKvStore("memory_without_path", option, g_kvNbDelegateCallback);
1982     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1983     EXPECT_TRUE(g_kvDelegateStatus == OK);
1984     EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1985 }
1986 
1987 /**
1988   * @tc.name: OpenStorePathCheckTest001
1989   * @tc.desc: Test open store with same label but different path.
1990   * @tc.type: FUNC
1991   * @tc.require: AR000GK58F
1992   * @tc.author: lianhuix
1993   */
1994 HWTEST_F(DistributedDBInterfacesNBDelegateTest, OpenStorePathCheckTest001, TestSize.Level1)
1995 {
1996     std::string dir1 = g_testDir + "/dbDir1";
1997     EXPECT_EQ(OS::MakeDBDirectory(dir1), E_OK);
1998     std::string dir2 = g_testDir + "/dbDir2";
1999     EXPECT_EQ(OS::MakeDBDirectory(dir2), E_OK);
2000 
2001     KvStoreDelegateManager mgr1(APP_ID, USER_ID);
2002     mgr1.SetKvStoreConfig({dir1});
2003 
2004     KvStoreNbDelegate *delegate1 = nullptr;
2005     auto callback1 = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1,
2006         placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(delegate1));
2007 
2008     KvStoreNbDelegate::Option option;
2009     mgr1.GetKvStore(STORE_ID_1, option, callback1);
2010     EXPECT_EQ(g_kvDelegateStatus, OK);
2011     ASSERT_NE(delegate1, nullptr);
2012 
2013     KvStoreNbDelegate *delegate2 = nullptr;
2014     auto callback2 = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1,
2015         placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(delegate2));
2016     KvStoreDelegateManager mgr2(APP_ID, USER_ID);
2017     mgr2.SetKvStoreConfig({dir2});
2018     mgr2.GetKvStore(STORE_ID_1, option, callback2);
2019     EXPECT_EQ(g_kvDelegateStatus, INVALID_ARGS);
2020     ASSERT_EQ(delegate2, nullptr);
2021 
2022     mgr1.CloseKvStore(delegate1);
2023     mgr1.DeleteKvStore(STORE_ID_1);
2024     mgr2.CloseKvStore(delegate2);
2025     mgr2.DeleteKvStore(STORE_ID_1);
2026 }
2027 
2028 namespace {
GetRealFileUrl(const std::string & dbPath,const std::string & appId,const std::string & userId,const std::string & storeId)2029 std::string GetRealFileUrl(const std::string &dbPath, const std::string &appId, const std::string &userId,
2030     const std::string &storeId)
2031 {
2032     std::string hashIdentifier = DBCommon::TransferHashString(
2033         DBCommon::GenerateIdentifierId(storeId, appId, userId));
2034     return dbPath + "/" + DBCommon::TransferStringToHex(hashIdentifier) + "/single_ver/main/gen_natural_store.db";
2035 }
2036 }
2037 
2038 /**
2039   * @tc.name: BusyTest001
2040   * @tc.desc: Test put kv data while another thread holds the transaction for one second
2041   * @tc.type: FUNC
2042   * @tc.require: AR000GK58F
2043   * @tc.author: lianhuix
2044   */
2045 HWTEST_F(DistributedDBInterfacesNBDelegateTest, BusyTest001, TestSize.Level1)
2046 {
2047     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2048     mgr.SetKvStoreConfig(g_config);
2049 
2050     const KvStoreNbDelegate::Option option = {true, false, false};
2051     mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
2052     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2053     EXPECT_TRUE(g_kvDelegateStatus == OK);
2054 
2055     std::string dbPath = GetRealFileUrl(g_config.dataDir, APP_ID, USER_ID, STORE_ID_1);
2056     sqlite3 *db = RelationalTestUtils::CreateDataBase(dbPath);
2057     RelationalTestUtils::ExecSql(db, "BEGIN IMMEDIATE;");
2058 
__anon8e1ef08c0302() 2059     std::thread th([db]() {
2060         std::this_thread::sleep_for(std::chrono::milliseconds(1000));
2061         RelationalTestUtils::ExecSql(db, "COMMIT");
2062     });
2063 
2064     EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_1, VALUE_1), OK);
2065 
2066     th.join();
2067     sqlite3_close_v2(db);
2068     EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2069     EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
2070 }
2071 
2072 #ifdef RUNNING_ON_SIMULATED_ENV
2073 /**
2074   * @tc.name: TimeChangeWithCloseStoreTest001
2075   * @tc.desc: Test close store with time changed
2076   * @tc.type: FUNC
2077   * @tc.require:
2078   * @tc.author: lianhuix
2079   */
2080 HWTEST_F(DistributedDBInterfacesNBDelegateTest, TimeChangeWithCloseStoreTest001, TestSize.Level3)
2081 {
2082     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2083     mgr.SetKvStoreConfig(g_config);
2084 
2085     std::atomic<bool> isFinished(false);
2086 
2087     std::vector<std::thread> slowThreads;
2088     for (int i = 0; i < 10; i++) { // 10: thread to slow donw system
__anon8e1ef08c0402() 2089         std::thread th([&isFinished]() {
2090             while (!isFinished) {
2091                 // pass
2092             }
2093         });
2094         slowThreads.emplace_back(std::move(th));
2095     }
2096 
__anon8e1ef08c0502() 2097     std::thread th([&isFinished]() {
2098         int timeChangedCnt = 0;
2099         while (!isFinished.load()) {
2100             OS::SetOffsetBySecond(100 - timeChangedCnt++ * 2); // 100 2 : fake system time change
2101             std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 100: wait for a while
2102         }
2103     });
2104 
2105     for (int i = 0; i < 100; i++) { // run 100 times
2106         const KvStoreNbDelegate::Option option = {true, false, false};
2107         mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
2108         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2109         EXPECT_EQ(g_kvDelegateStatus, OK);
2110         EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2111     }
2112 
2113     std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // 1000: wait for a while
2114     isFinished.store(true);
2115     th.join();
2116     for (auto &it : slowThreads) {
2117         it.join();
2118     }
2119     EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
2120 }
2121 
2122 /**
2123   * @tc.name: TimeChangeWithCloseStoreTest002
2124   * @tc.desc: Test close store with time changed
2125   * @tc.type: FUNC
2126   * @tc.require:
2127   * @tc.author: zhangqiquan
2128   */
2129 HWTEST_F(DistributedDBInterfacesNBDelegateTest, TimeChangeWithCloseStoreTest002, TestSize.Level3)
2130 {
2131     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2132     mgr.SetKvStoreConfig(g_config);
2133 
2134     const KvStoreNbDelegate::Option option = {true, false, false};
2135     mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
2136     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
2137     EXPECT_EQ(g_kvDelegateStatus, OK);
2138     const int threadPoolMax = 10;
2139     for (int i = 0; i < threadPoolMax; ++i) {
__anon8e1ef08c0602() 2140         (void) RuntimeContext::GetInstance()->ScheduleTask([]() {
2141             std::this_thread::sleep_for(std::chrono::seconds(10)); // sleep 10s for block thread pool
2142         });
2143     }
2144     OS::SetOffsetBySecond(100); // 100 2 : fake system time change
2145     std::this_thread::sleep_for(std::chrono::seconds(1)); // sleep 1s for time tick
2146 
2147     EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
2148     g_kvNbDelegatePtr = nullptr;
2149 
2150     EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
2151     RuntimeContext::GetInstance()->StopTaskPool(); // stop all async task
2152 }
2153 #endif // RUNNING_ON_SIMULATED_ENV
2154 
2155 /**
2156   * @tc.name: LocalStore001
2157   * @tc.desc: Test get kv store with localOnly
2158   * @tc.type: FUNC
2159   * @tc.require:
2160   * @tc.author: zhangqiquan
2161   */
2162 HWTEST_F(DistributedDBInterfacesNBDelegateTest, LocalStore001, TestSize.Level1)
2163 {
2164     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2165     mgr.SetKvStoreConfig(g_config);
2166 
2167     /**
2168      * @tc.steps:step1. Create database with localOnly.
2169      * @tc.expected: step1. Returns a non-null store.
2170      */
2171     KvStoreNbDelegate::Option option = {true, false, false};
2172     option.localOnly = true;
2173     DBStatus openStatus = DBStatus::DB_ERROR;
2174     KvStoreNbDelegate *openDelegate = nullptr;
__anon8e1ef08c0702(DBStatus status, KvStoreNbDelegate *delegate) 2175     mgr.GetKvStore(STORE_ID_1, option, [&openStatus, &openDelegate](DBStatus status, KvStoreNbDelegate *delegate) {
2176         openStatus = status;
2177         openDelegate = delegate;
2178     });
2179     ASSERT_TRUE(openDelegate != nullptr);
2180     EXPECT_EQ(openStatus, OK);
2181     /**
2182      * @tc.steps:step2. call sync and put/get interface.
2183      * @tc.expected: step2. sync return NOT_ACTIVE.
2184      */
2185     DBStatus actionStatus = openDelegate->Sync({}, SyncMode::SYNC_MODE_PUSH_ONLY, nullptr);
2186     EXPECT_EQ(actionStatus, DBStatus::NOT_ACTIVE);
2187     Key key = {'k'};
2188     Value expectValue = {'v'};
2189     EXPECT_EQ(openDelegate->Put(key, expectValue), OK);
2190     Value actualValue;
2191     EXPECT_EQ(openDelegate->Get(key, actualValue), OK);
2192     EXPECT_EQ(actualValue, expectValue);
2193     EXPECT_EQ(mgr.CloseKvStore(openDelegate), OK);
2194 }
2195 
2196 /**
2197   * @tc.name: LocalStore002
2198   * @tc.desc: Test get kv store different local mode
2199   * @tc.type: FUNC
2200   * @tc.require:
2201   * @tc.author: zhangqiquan
2202   */
2203 HWTEST_F(DistributedDBInterfacesNBDelegateTest, LocalStore002, TestSize.Level1)
2204 {
2205     KvStoreDelegateManager mgr(APP_ID, USER_ID);
2206     mgr.SetKvStoreConfig(g_config);
2207 
2208     /**
2209      * @tc.steps:step1. Create database with localOnly.
2210      * @tc.expected: step1. Returns a non-null store.
2211      */
2212     KvStoreNbDelegate::Option option = {true, false, false};
2213     option.localOnly = true;
2214     DBStatus openStatus = DBStatus::DB_ERROR;
2215     KvStoreNbDelegate *localDelegate = nullptr;
__anon8e1ef08c0802(DBStatus status, KvStoreNbDelegate *delegate) 2216     mgr.GetKvStore(STORE_ID_1, option, [&openStatus, &localDelegate](DBStatus status, KvStoreNbDelegate *delegate) {
2217         openStatus = status;
2218         localDelegate = delegate;
2219     });
2220     ASSERT_TRUE(localDelegate != nullptr);
2221     EXPECT_EQ(openStatus, OK);
2222     /**
2223      * @tc.steps:step2. Create database without localOnly.
2224      * @tc.expected: step2. Returns a null store.
2225      */
2226     option.localOnly = false;
2227     KvStoreNbDelegate *syncDelegate = nullptr;
__anon8e1ef08c0902(DBStatus status, KvStoreNbDelegate *delegate) 2228     mgr.GetKvStore(STORE_ID_1, option, [&openStatus, &syncDelegate](DBStatus status, KvStoreNbDelegate *delegate) {
2229         openStatus = status;
2230         syncDelegate = delegate;
2231     });
2232     EXPECT_EQ(syncDelegate, nullptr);
2233     EXPECT_EQ(openStatus, INVALID_ARGS);
2234     EXPECT_EQ(mgr.CloseKvStore(localDelegate), OK);
2235 }