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