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 <fstream>
17 #include <gtest/gtest.h>
18 #include <unistd.h>
19 
20 #include "db_common.h"
21 #include "distributeddb_data_generate_unit_test.h"
22 #include "distributeddb_tools_unit_test.h"
23 #include "kvdb_manager.h"
24 #include "kv_store_changed_data_impl.h"
25 #include "platform_specific.h"
26 #include "process_system_api_adapter_impl.h"
27 #include "relational_store_changed_data_impl.h"
28 #include "runtime_context.h"
29 
30 using namespace testing::ext;
31 using namespace DistributedDB;
32 using namespace DistributedDBUnitTest;
33 using namespace std;
34 
35 namespace {
36     enum {
37         SCHEMA_TYPE1 = 1,
38         SCHEMA_TYPE2
39     };
40     static int g_conflictCount = 0;
41     // define some variables to init a KvStoreDelegateManager object.
42     KvStoreDelegateManager g_mgr(APP_ID, USER_ID);
43     string g_testDir;
44     KvStoreConfig g_config;
45 
46     DBStatus g_kvDelegateStatus = INVALID_ARGS;
47 #ifndef OMIT_MULTI_VER
48     // define the g_kvDelegateCallback, used to get some information when open a kv store.
49     KvStoreDelegate *g_kvDelegatePtr = nullptr;
50     // the type of g_kvDelegateCallback is function<void(DBStatus, KvStoreDelegate*)>
51     auto g_kvDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1,
52         placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvDelegatePtr));
53 #endif // OMIT_MULTI_VER
54 
55     KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr;
56     auto g_kvNbDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback,
57         placeholders::_1, placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvNbDelegatePtr));
58 #ifndef OMIT_JSON
59     const int PASSWD_LEN = 10;
60     const int PASSWD_VAL = 45;
GenerateValidSchemaString(std::string & string,int num=SCHEMA_TYPE1)61     void GenerateValidSchemaString(std::string &string, int num = SCHEMA_TYPE1)
62     {
63         switch (num) {
64             case SCHEMA_TYPE1:
65                 string = "{\"SCHEMA_VERSION\":\"1.0\","
66                     "\"SCHEMA_MODE\":\"STRICT\","
67                     "\"SCHEMA_DEFINE\":{"
68                         "\"field_name1\":\"BOOL\","
69                         "\"field_name2\":{"
70                             "\"field_name3\":\"INTEGER, NOT NULL\","
71                             "\"field_name4\":\"LONG, DEFAULT 100\","
72                             "\"field_name5\":\"DOUBLE, NOT NULL, DEFAULT 3.14\","
73                             "\"field_name6\":\"STRING, NOT NULL, DEFAULT '3.1415'\","
74                             "\"field_name7\":[],"
75                             "\"field_name8\":{}"
76                         "}"
77                     "},"
78                     "\"SCHEMA_INDEXES\":[\"$.field_name1\", \"$.field_name2.field_name6\"]}";
79                 break;
80             case SCHEMA_TYPE2:
81                 string = "{\"SCHEMA_VERSION\":\"1.0\","
82                     "\"SCHEMA_MODE\":\"STRICT\","
83                     "\"SCHEMA_DEFINE\":{"
84                         "\"field_name1\":\"LONG, DEFAULT 100\","
85                         "\"field_name2\":{"
86                             "\"field_name3\":\"INTEGER, NOT NULL\","
87                             "\"field_name4\":\"LONG, DEFAULT 100\","
88                             "\"field_name5\":\"DOUBLE, NOT NULL, DEFAULT 3.14\","
89                             "\"field_name6\":\"STRING, NOT NULL, DEFAULT '3.1415'\""
90                         "}"
91                     "},"
92                     "\"SCHEMA_INDEXES\":[\"$.field_name1\", \"$.field_name2.field_name6\"]}";
93                 break;
94             default:
95                 return;
96         }
97     }
98 
GenerateInvalidSchemaString(std::string & string)99     void GenerateInvalidSchemaString(std::string &string)
100     {
101         string = "123";
102     }
103 
GenerateEmptySchemaString(std::string & string)104     void GenerateEmptySchemaString(std::string &string)
105     {
106         string.clear();
107     }
108 
WriteValidDataIntoKvStore()109     int WriteValidDataIntoKvStore()
110     {
111         return OK;
112     }
113 
OpenOpenedKvstoreWithSchema(const std::string & storeId,bool isEncrypt)114     void OpenOpenedKvstoreWithSchema(const std::string &storeId, bool isEncrypt)
115     {
116         /**
117          * @tc.steps: step1. create a new db(non-memory, encrypt), with schema;
118          * @tc.expected: step1. Returns a non-null kvstore and error code is OK.
119          */
120         KvStoreNbDelegate::Option option = {true, false, isEncrypt};
121         if (isEncrypt) {
122             CipherPassword passwd;
123             vector<uint8_t> passwdBuffer(PASSWD_LEN, PASSWD_VAL);
124             passwd.SetValue(passwdBuffer.data(), passwdBuffer.size());
125             option.passwd = passwd;
126         }
127         GenerateValidSchemaString(option.schema);
128         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
129         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
130         EXPECT_TRUE(g_kvDelegateStatus == OK);
131         KvStoreNbDelegate *kvNbDelegatePtr1 = g_kvNbDelegatePtr;
132         /**
133          * @tc.steps: step2. open an opened db, with same schema;
134          * @tc.expected: step2. Returns a non-null kvstore and error code is OK.
135          */
136         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
137         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
138         EXPECT_TRUE(g_kvDelegateStatus == OK);
139         KvStoreNbDelegate *kvNbDelegatePtr2 = g_kvNbDelegatePtr;
140         /**
141          * @tc.steps: step3. open an opened db, with valid but different schema;
142          * @tc.expected: step3. Returns a null kvstore and error code is SCHEMA_MISMATCH.
143          */
144         GenerateValidSchemaString(option.schema, SCHEMA_TYPE2);
145         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
146         ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
147         EXPECT_TRUE(g_kvDelegateStatus == SCHEMA_MISMATCH);
148 
149         /**
150          * @tc.steps: step4. open an opened db, with invalid schema;
151          * @tc.expected: step4. Returns a null kvstore and error code is INVALID_SCHEMA.
152          */
153         GenerateInvalidSchemaString(option.schema);
154         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
155         ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
156         EXPECT_TRUE(g_kvDelegateStatus == INVALID_SCHEMA);
157 
158         /**
159          * @tc.steps: step5. open an opened db, with empty schema;
160          * @tc.expected: step5. Returns a null kvstore and error code is INVALID_SCHEMA.
161          */
162         std::string emptySchema;
163         option.schema = emptySchema;
164         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
165         ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
166         EXPECT_TRUE(g_kvDelegateStatus == SCHEMA_MISMATCH);
167 
168         EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr1), OK);
169         EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr2), OK);
170         g_kvNbDelegatePtr = nullptr;
171         EXPECT_TRUE(g_mgr.DeleteKvStore(storeId) == OK);
172     }
173 
OpenClosedSchemaKvStore(const std::string & storeId,bool isEncrypt,const std::string & inSchema)174     void OpenClosedSchemaKvStore(const std::string &storeId, bool isEncrypt, const std::string &inSchema)
175     {
176         /**
177          * @tc.steps: step1. create a new db(non-memory), with input schema;
178          * @tc.expected: step1. Returns a non-null kvstore and error code is OK.
179          */
180         KvStoreNbDelegate::Option option = {true, false, isEncrypt};
181         option.schema = inSchema;
182         if (isEncrypt) {
183             CipherPassword passwd;
184             vector<uint8_t> passwdBuffer(PASSWD_LEN, PASSWD_VAL);
185             passwd.SetValue(passwdBuffer.data(), passwdBuffer.size());
186             option.passwd = passwd;
187         }
188         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
189         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
190         EXPECT_TRUE(g_kvDelegateStatus == OK);
191         EXPECT_TRUE(WriteValidDataIntoKvStore() == OK);
192         /**
193          * @tc.steps: step2. close the created kvstore;
194          * @tc.expected: step2. Return OK.
195          */
196         EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
197         g_kvNbDelegatePtr = nullptr;
198 
199         /**
200          * @tc.steps: step3. reopen the kvstore with same schema;
201          * @tc.expected: step3. Return OK.
202          */
203         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
204         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
205         EXPECT_TRUE(g_kvDelegateStatus == OK);
206         EXPECT_TRUE(WriteValidDataIntoKvStore() == OK);
207         EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
208         g_kvNbDelegatePtr = nullptr;
209 
210         /**
211          * @tc.steps: step4. reopen the kvstore with valid schema, but the schema is not equal to inSchema;
212          * @tc.expected: step4. Return a null kvstore and retCode is SCHEMA_MISMATCH.
213          */
214         GenerateValidSchemaString(option.schema, SCHEMA_TYPE2);
215         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
216         ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
217         EXPECT_TRUE(g_kvDelegateStatus == SCHEMA_MISMATCH);
218         /**
219          * @tc.steps: step5. reopen the kvstore with invalid schema;
220          * @tc.expected: step5. Return a null kvstore and retCode is INVALID_SCHEMA.
221          */
222         GenerateInvalidSchemaString(option.schema);
223         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
224         ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
225         EXPECT_TRUE(g_kvDelegateStatus == INVALID_SCHEMA);
226         /**
227          * @tc.steps: step6. reopen the kvstore with empty schema;
228          * @tc.expected: step6. Return a read-only kvstore and retCode is READ_ONLY.
229          */
230         GenerateEmptySchemaString(option.schema);
231         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
232         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
233         EXPECT_TRUE(g_kvDelegateStatus == OK);
234         // here should return READ_ONLY
235         EXPECT_TRUE(WriteValidDataIntoKvStore() == OK);
236         KvStoreNbDelegate *kvNbDelegatePtr1 = g_kvNbDelegatePtr;
237 
238         // Open another kvstore with empty schema
239         GenerateEmptySchemaString(option.schema);
240         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
241         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
242         EXPECT_TRUE(g_kvDelegateStatus == OK);
243         KvStoreNbDelegate *kvNbDelegatePtr2 = g_kvNbDelegatePtr;
244         // here should return READ_ONLY
245         EXPECT_TRUE(WriteValidDataIntoKvStore() == OK);
246 
247         // Open another kvstore with origin schema
248         option.schema = inSchema;
249         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
250         ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
251         EXPECT_TRUE(g_kvDelegateStatus == SCHEMA_MISMATCH);
252 
253         EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr1), OK);
254         EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr2), OK);
255         EXPECT_TRUE(g_mgr.DeleteKvStore(storeId) == OK);
256     }
257 
OpenClosedNormalKvStore(const std::string & storeId,bool isEncrypt)258     void OpenClosedNormalKvStore(const std::string &storeId, bool isEncrypt)
259     {
260         /**
261          * @tc.steps: step1. create a new db(non-memory), without schema;
262          * @tc.expected: step1. Returns a non-null kvstore and error code is OK.
263          */
264         KvStoreNbDelegate::Option option = {true, false, isEncrypt};
265         if (isEncrypt) {
266             CipherPassword passwd;
267             vector<uint8_t> passwdBuffer(PASSWD_LEN, PASSWD_VAL);
268             passwd.SetValue(passwdBuffer.data(), passwdBuffer.size());
269             option.passwd = passwd;
270         }
271         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
272         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
273         EXPECT_TRUE(g_kvDelegateStatus == OK);
274         EXPECT_TRUE(WriteValidDataIntoKvStore() == OK);
275         /**
276          * @tc.steps: step2. close the created kvstore;
277          * @tc.expected: step2. Return OK.
278          */
279         EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
280         g_kvNbDelegatePtr = nullptr;
281 
282         /**
283          * @tc.steps: step3. reopen the kvstore with empty schema;
284          * @tc.expected: step3. Return a kvstore and retCode is OK.
285          */
286         GenerateEmptySchemaString(option.schema);
287         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
288         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
289         EXPECT_TRUE(g_kvDelegateStatus == OK);
290         EXPECT_TRUE(WriteValidDataIntoKvStore() == OK);
291         EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
292         g_kvNbDelegatePtr = nullptr;
293         /**
294          * @tc.steps: step4. reopen the kvstore with valid schema;
295          * @tc.expected: step4. Return OK.
296          */
297         GenerateValidSchemaString(option.schema);
298         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
299         ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
300         EXPECT_TRUE(g_kvDelegateStatus == OK);
301         EXPECT_TRUE(WriteValidDataIntoKvStore() == OK);
302         EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
303         g_kvNbDelegatePtr = nullptr;
304 
305         /**
306          * @tc.steps: step5. reopen the kvstore with invalid schema;
307          * @tc.expected: step5. Return a null kvstore and retCode is SCHEMA_MISMATCH.
308          */
309         GenerateInvalidSchemaString(option.schema);
310         g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
311         ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
312         EXPECT_TRUE(g_kvDelegateStatus == INVALID_SCHEMA);
313         EXPECT_TRUE(g_mgr.DeleteKvStore(storeId) == OK);
314     }
315 #endif
316 }
317 
318 class DistributedDBInterfacesDatabaseTest : public testing::Test {
319 public:
320     static void SetUpTestCase(void);
321     static void TearDownTestCase(void);
322     void SetUp();
323     void TearDown();
324 };
325 
SetUpTestCase(void)326 void DistributedDBInterfacesDatabaseTest::SetUpTestCase(void)
327 {
328     DistributedDBToolsUnitTest::TestDirInit(g_testDir);
329     g_config.dataDir = g_testDir;
330     g_mgr.SetKvStoreConfig(g_config);
331     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(nullptr);
332 }
333 
TearDownTestCase(void)334 void DistributedDBInterfacesDatabaseTest::TearDownTestCase(void)
335 {
336     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(nullptr);
337 }
338 
SetUp(void)339 void DistributedDBInterfacesDatabaseTest::SetUp(void)
340 {
341     DistributedDBToolsUnitTest::PrintTestCaseInfo();
342 #ifndef OMIT_MULTI_VER
343     g_kvDelegateStatus = INVALID_ARGS;
344     g_kvDelegatePtr = nullptr;
345 #endif // OMIT_MULTI_VER
346 }
347 
TearDown(void)348 void DistributedDBInterfacesDatabaseTest::TearDown(void)
349 {
350     if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) {
351         LOGE("rm test db files error!");
352     }
353 }
354 
355 #ifndef OMIT_MULTI_VER
356 /**
357   * @tc.name: GetKvStore001
358   * @tc.desc: Get kv store through different parameters.
359   * @tc.type: FUNC
360   * @tc.require: AR000CQDV4 AR000CQS3P
361   * @tc.author: huangnaigu
362   */
363 HWTEST_F(DistributedDBInterfacesDatabaseTest, GetKvStore001, TestSize.Level1)
364 {
365     /**
366      * @tc.steps: step1. Obtain the kvStore through the GetKvStore interface of the delegate manager
367      *  using the parameter the normal storId, createIfNecessary(true) and isLocal(true).
368      * @tc.steps: step2. Close the kvStore through the CloseKvStore interface of the delegate manager.
369      * @tc.expected: step1. Returns a non-null kvstore.
370      * @tc.expected: step2. Returns OK.
371      */
372     KvStoreDelegate::Option option = {true, true, false};
373     g_mgr.GetKvStore("distributed_db_test1", option, g_kvDelegateCallback);
374     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
375     EXPECT_TRUE(g_kvDelegateStatus == OK);
376     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
377 
378     /**
379      * @tc.steps: step3. Obtain the kvStore through the GetKvStore interface of the delegate manager
380      *  using the parameter the normal storId, createIfNecessary(true) and isLocal(false).
381      * @tc.steps: step4. Close the kvStore through the CloseKvStore interface of the delegate manager.
382      * @tc.expected: step3. Returns a non-null kvstore.
383      * @tc.expected: step4. Returns OK.
384      */
385     option = {true, false, false};
386     g_mgr.GetKvStore("distributed_db_test2", option, g_kvDelegateCallback);
387     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
388     EXPECT_TRUE(g_kvDelegateStatus == OK);
389     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
390 
391     /**
392      * @tc.steps: step5. Obtain the kvStore through the GetKvStore interface of the delegate manager
393      *  using the parameter the normal storId, createIfNecessary(false) and isLocal(true).
394      * @tc.expected: step5. Returns a non-null kvstore and error code is ERROR.
395      */
396     option = {false, true, false};
397     g_mgr.GetKvStore("distributed_db_test3", option, g_kvDelegateCallback);
398     ASSERT_TRUE(g_kvDelegatePtr == nullptr);
399     EXPECT_NE(g_kvDelegateStatus, OK);
400 
401     /**
402      * @tc.steps: step6. Obtain the kvStore through the GetKvStore interface of the delegate manager
403      *  using the parameter the normal storId, createIfNecessary(false) and isLocal(false).
404      * @tc.expected: step6. Returns a non-null kvstore and error code is ERROR.
405      */
406     option = {false, false, false};
407     g_mgr.GetKvStore("distributed_db_test4", option, g_kvDelegateCallback);
408     ASSERT_TRUE(g_kvDelegatePtr == nullptr);
409     EXPECT_NE(g_kvDelegateStatus, OK);
410 
411     /**
412      * @tc.steps: step7. Obtain the kvStore through the GetKvStore interface of the delegate manager
413      *  which is initialized with the empty appid.
414      * @tc.expected: step7. Returns a non-null kvstore and error code is INVALID_ARGS.
415      */
416     KvStoreDelegateManager invalidMgrFirst("", USER_ID);
417     invalidMgrFirst.SetKvStoreConfig(g_config);
418     option = {true, true, false};
419     invalidMgrFirst.GetKvStore("distributed_db_test5", option, g_kvDelegateCallback);
420     ASSERT_TRUE(g_kvDelegatePtr == nullptr);
421     EXPECT_TRUE(g_kvDelegateStatus == INVALID_ARGS);
422 
423     /**
424      * @tc.steps: step8. Obtain the kvStore through the GetKvStore interface of the delegate manager
425      *  which is initialized with the empty userid.
426      * @tc.expected: step8. Returns a non-null kvstore and error code is INVALID_ARGS.
427      */
428     KvStoreDelegateManager invalidMgrSecond(APP_ID, "");
429     invalidMgrSecond.SetKvStoreConfig(g_config);
430     invalidMgrSecond.GetKvStore("distributed_db_test6", option, g_kvDelegateCallback);
431     ASSERT_TRUE(g_kvDelegatePtr == nullptr);
432     EXPECT_TRUE(g_kvDelegateStatus == INVALID_ARGS);
433 
434     /**
435      * @tc.steps: step9. Obtain the kvStore through the GetKvStore interface of the delegate manager
436      *  using the parameter the empty storId, createIfNecessary(true) and isLocal(true).
437      * @tc.expected: step9. Returns a non-null kvstore and error code is INVALID_ARGS.
438      */
439     g_mgr.GetKvStore("", option, g_kvDelegateCallback);
440     ASSERT_TRUE(g_kvDelegatePtr == nullptr);
441     EXPECT_TRUE(g_kvDelegateStatus == INVALID_ARGS);
442 
443     /**
444      * @tc.steps: step10. Obtain the kvStore through the GetKvStore interface of the delegate manager
445      *  using the parameter the invalid storId, createIfNecessary(true) and isLocal(true).
446      * @tc.expected: step10. Returns a non-null kvstore and error code is INVALID_ARGS.
447      */
448     g_mgr.GetKvStore("$@.test", option, g_kvDelegateCallback);
449     ASSERT_TRUE(g_kvDelegatePtr == nullptr);
450     EXPECT_TRUE(g_kvDelegateStatus == INVALID_ARGS);
451 
452     /**
453      * @tc.steps: step11. Obtain the kvStore through the GetKvStore interface of the delegate manager
454      *  using the parameter: all alphabet string storId, createIfNecessary(true) and isLocal(true).
455      * @tc.expected: step11. Returns a non-null kvstore and error code is OK.
456      */
457     g_mgr.GetKvStore("TEST", option, g_kvDelegateCallback);
458     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
459     EXPECT_TRUE(g_kvDelegateStatus == OK);
460     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
461 
462     /**
463      * @tc.steps: step12. Obtain the kvStore through the GetKvStore interface of the delegate manager
464      *  using the parameter: digital string storId, createIfNecessary(true) and isLocal(true).
465      * @tc.expected: step12. Returns a non-null kvstore and error code is OK.
466      */
467     g_mgr.GetKvStore("123", option, g_kvDelegateCallback);
468     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
469     EXPECT_TRUE(g_kvDelegateStatus == OK);
470     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
471 
472     /**
473      * @tc.steps: step13. Obtain the kvStore through the GetKvStore interface of the delegate manager
474      *  using the parmater: digital and alphabet combined string storId, createIfNecessary(true) and isLocal(true).
475      * @tc.expected: step13. Returns a non-null kvstore and error code is OK.
476      */
477     g_mgr.GetKvStore("TEST_test_123", option, g_kvDelegateCallback);
478     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
479     EXPECT_TRUE(g_kvDelegateStatus == OK);
480     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
481 }
482 
483 /**
484   * @tc.name: GetKvStore002
485   * @tc.desc: Get kv store through different parameters for the same storeID.
486   * @tc.type: FUNC
487   * @tc.require: AR000CQDV5 AR000CQS3P
488   * @tc.author: huangnaigu
489   */
490 HWTEST_F(DistributedDBInterfacesDatabaseTest, GetKvStore002, TestSize.Level1)
491 {
492     /**
493      * @tc.steps: step1. Obtain the kvStore through the GetKvStore interface of the delegate manager
494      *  using the parameter createIfNecessary(true) and isLocal(true).
495      * @tc.expected: step1. Returns a non-null kvstore and error code is OK.
496      */
497     CipherPassword passwd;
498     KvStoreDelegate::Option option = {true, true, false};
499     g_mgr.GetKvStore("distributed_getkvstore_002", option, g_kvDelegateCallback);
500     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
501     EXPECT_TRUE(g_kvDelegateStatus == OK);
502     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
503 
504     /**
505      * @tc.steps: step2. Re-Obtain the kvStore through the GetKvStore interface of the delegate manager
506      *  using the parameter createIfNecessary(true) and isLocal(false).
507      * @tc.expected: step2. Returns a non-null kvstore and error code is OK.
508      */
509     option.localOnly = false;
510     g_mgr.GetKvStore("distributed_getkvstore_002", option, g_kvDelegateCallback);
511     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
512     EXPECT_TRUE(g_kvDelegateStatus == OK);
513     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
514 
515     /**
516      * @tc.steps: step3. Re-Obtain the kvStore through the GetKvStore interface of the delegate manager
517      *  using the parameter createIfNecessary(false) and isLocal(true).
518      * @tc.expected: step3. Returns a non-null kvstore and error code is OK.
519      */
520     option = {false, true, false};
521     g_mgr.GetKvStore("distributed_getkvstore_002", option, g_kvDelegateCallback);
522     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
523     EXPECT_TRUE(g_kvDelegateStatus == OK);
524     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
525 
526     /**
527      * @tc.steps: step4. Re-Obtain the kvStore through the GetKvStore interface of the delegate manager
528      *  using the parameter createIfNecessary(false) and isLocal(false).
529      * @tc.expected: step4. Returns a non-null kvstore and error code is OK.
530      */
531     option = {false, false, false};
532     g_mgr.GetKvStore("distributed_getkvstore_002", option, g_kvDelegateCallback);
533     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
534     EXPECT_TRUE(g_kvDelegateStatus == OK);
535     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
536 
537     /**
538      * @tc.steps: step5. Re-Obtain the kvStore through the GetKvStore interface of the delegate manager
539      *  using the parameter createIfNecessary(false) and isLocal(false).
540      * @tc.expected: step5. Returns a non-null kvstore and error code is OK.
541      */
542     option = {true, true, false};
543     g_mgr.GetKvStore("distributed_getkvstore_002", option, g_kvDelegateCallback);
544     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
545     EXPECT_TRUE(g_kvDelegateStatus == OK);
546     string retStoreId = g_kvDelegatePtr->GetStoreId();
547     EXPECT_TRUE(retStoreId.compare("distributed_getkvstore_002") == 0);
548     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
549 }
550 #endif // OMIT_MULTI_VER
551 
552 /**
553   * @tc.name: GetKvStore003
554   * @tc.desc: Get kv store through different SecurityOption, abnormal or normal.
555   * @tc.type: FUNC
556   * @tc.require: AR000EV1G2
557   * @tc.author: liuwenkai
558   */
559 HWTEST_F(DistributedDBInterfacesDatabaseTest, GetKvStore003, TestSize.Level1)
560 {
561     /**
562      * @tc.steps: step1. Obtain the kvStore through the GetKvStore interface of the delegate manager
563      *  using the parameter secOption(abnormal).
564      * @tc.expected: step1. Returns a null kvstore and error code is not OK.
565      */
566     std::shared_ptr<IProcessSystemApiAdapter> g_adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
567     RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(g_adapter);
568     KvStoreNbDelegate::Option option = {true, false, false};
569     int abnormalNum = -100;
570     option.secOption.securityLabel = abnormalNum;
571     option.secOption.securityFlag = abnormalNum;
572     g_mgr.GetKvStore("distributed_getkvstore_003", option, g_kvNbDelegateCallback);
573     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
574     EXPECT_TRUE(g_kvDelegateStatus != OK);
575 
576     /**
577      * @tc.steps: step2. Obtain the kvStore through the GetKvStore interface of the delegate manager
578      *  using the parameter secOption(normal).
579      * @tc.expected: step2. Returns a non-null kvstore and error code is OK.
580      */
581     option.secOption.securityLabel = S3;
582     option.secOption.securityFlag = 0;
583     g_mgr.GetKvStore("distributed_getkvstore_003", option, g_kvNbDelegateCallback);
584     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
585     EXPECT_TRUE(g_kvDelegateStatus == OK);
586     KvStoreNbDelegate *kvNbDelegatePtr1 = g_kvNbDelegatePtr;
587 
588     /**
589      * @tc.steps: step3. Obtain the kvStore through the GetKvStore interface of the delegate manager
590      *  using the parameter secOption(normal but not same as last).
591      * @tc.expected: step3. Returns a null kvstore and error code is not OK.
592      */
593     option.secOption.securityLabel = S3;
594     option.secOption.securityFlag = 1;
595     g_mgr.GetKvStore("distributed_getkvstore_003", option, g_kvNbDelegateCallback);
596     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
597     EXPECT_TRUE(g_kvDelegateStatus != OK);
598 
599     /**
600     * @tc.steps: step4. Obtain the kvStore through the GetKvStore interface of the delegate manager
601     *  using the parameter secOption(normal and same as last).
602     * @tc.expected: step4. Returns a non-null kvstore and error code is OK.
603     */
604     option.secOption.securityLabel = S3;
605     option.secOption.securityFlag = 0;
606     g_mgr.GetKvStore("distributed_getkvstore_003", option, g_kvNbDelegateCallback);
607     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
608     EXPECT_TRUE(g_kvDelegateStatus == OK);
609 
610     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
611     EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr1), OK);
612     g_kvNbDelegatePtr = nullptr;
613     EXPECT_TRUE(g_mgr.DeleteKvStore("distributed_getkvstore_003") == OK);
614 }
615 
NotifierCallback(const KvStoreNbConflictData & data)616 static void NotifierCallback(const KvStoreNbConflictData &data)
617 {
618     LOGE("Trigger conflict callback!");
619     g_conflictCount++;
620 }
621 
622 /**
623   * @tc.name: GetKvStore004
624   * @tc.desc: Get kv store parameters with Observer and Notifier, then trigger callback.
625   * @tc.type: FUNC
626   * @tc.require: AR000EV1G2
627   * @tc.author: liuwenkai
628   */
629 HWTEST_F(DistributedDBInterfacesDatabaseTest, GetKvStore004, TestSize.Level1)
630 {
631     /**
632      * @tc.steps: step1. Obtain the kvStore through the GetKvStore interface of the delegate manager
633      *  using the parameter observer, notifier, key.
634      * @tc.expected: step1. Returns a non-null kvstore and error code is OK.
635      */
636     KvStoreNbDelegate::Option option = {true, false, false};
637     KvStoreObserverUnitTest *observer = new (std::nothrow) KvStoreObserverUnitTest;
638     ASSERT_NE(observer, nullptr);
639     Key key;
640     Value value1;
641     Value value2;
642     key.push_back(1);
643     value1.push_back(1);
644     value2.push_back(2);
645     option.conflictType = CONFLICT_NATIVE_ALL;
646     option.notifier = NotifierCallback;
647     option.key = key;
648     option.observer = observer;
649     option.mode = OBSERVER_CHANGES_NATIVE;
650     g_conflictCount = 0;
651     int sleepTime = 100;
652     g_mgr.GetKvStore("distributed_getkvstore_004", option, g_kvNbDelegateCallback);
653     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
654     EXPECT_TRUE(g_kvDelegateStatus == OK);
655 
656     /**
657      * @tc.steps: step2. Put(k1,v1) to db and check the observer info.
658      * @tc.expected: step2. Put successfully and trigger notifier callback.
659      */
660     EXPECT_TRUE(g_kvNbDelegatePtr->Put(key, value1) == OK);
661     std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
662     LOGI("observer count:%lu", observer->GetCallCount());
663     EXPECT_TRUE(observer->GetCallCount() == 1);
664 
665     /**
666      * @tc.steps: step3. put(k1,v2) to db and check the observer info.
667      * @tc.expected: step3. put successfully and trigger conflict callback.
668      */
669     EXPECT_TRUE(g_kvNbDelegatePtr->Put(key, value2) == OK);
670     std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
671     LOGI("observer count:%lu", observer->GetCallCount());
672     EXPECT_TRUE(observer->GetCallCount() == 2);
673     LOGI("call conflictNotifier count:%d, 1 means trigger success.", g_conflictCount);
674     EXPECT_EQ(g_conflictCount, 1);
675 
676     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
677     g_kvNbDelegatePtr = nullptr;
678     delete observer;
679     observer = nullptr;
680     EXPECT_TRUE(g_mgr.DeleteKvStore("distributed_getkvstore_004") == OK);
681 }
682 
683 #ifndef OMIT_MULTI_VER
684 /**
685   * @tc.name: CloseKvStore001
686   * @tc.desc: Test the CloseKvStore Interface and check whether the database file can be closed.
687   * @tc.type: FUNC
688   * @tc.require: AR000CQDV6 AR000CQS3P
689   * @tc.author: huangnaigu
690   */
691 HWTEST_F(DistributedDBInterfacesDatabaseTest, CloseKvStore001, TestSize.Level1)
692 {
693     /**
694      * @tc.steps: step1. Obtain the kvStore of the non-existed database through the GetKvStore interface of
695      *  the delegate manager using the parameter createdIfNecessary(true)
696      * @tc.steps: step2. Close the valid kvStore.
697      * @tc.expected: step1. Returns a non-null kvstore and error code is OK.
698      * @tc.expected: step2. Returns OK.
699      */
700     CipherPassword passwd;
701     KvStoreDelegate::Option option = {true, true, false};
702     g_mgr.GetKvStore("CloseKvStore_001", option, g_kvDelegateCallback);
703     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
704     EXPECT_TRUE(g_kvDelegateStatus == OK);
705     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
706     g_kvDelegatePtr = nullptr;
707 
708     /**
709      * @tc.steps: step3. Obtain the kvStore of the existed database through the GetKvStore interface of
710      *  the delegate manager using the parameter createIfNecessary(false)
711      * @tc.steps: step4. Close the valid kvStore.
712      * @tc.expected: step3. Returns a non-null kvstore and error code is OK.
713      * @tc.expected: step4. Returns OK.
714      */
715     option = {false, true, false};
716     g_mgr.GetKvStore("CloseKvStore_001", option, g_kvDelegateCallback);
717     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
718     EXPECT_TRUE(g_kvDelegateStatus == OK);
719     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
720     g_kvDelegatePtr = nullptr;
721 
722     /**
723      * @tc.steps: step5. Close the invalid kvStore which is nullptr.
724      * @tc.expected: step5. Returns INVALID_ARGS.
725      */
726     KvStoreDelegate *storeDelegate = nullptr;
727     EXPECT_EQ(g_mgr.CloseKvStore(storeDelegate), INVALID_ARGS);
728 }
729 
730 /**
731   * @tc.name: DeleteKvStore001
732   * @tc.desc: Test the DeleteKvStore Interface and check whether the database files can be removed.
733   * @tc.type: FUNC
734   * @tc.require: AR000C2F0C AR000CQDV7
735   * @tc.author: huangnaigu
736   */
737 HWTEST_F(DistributedDBInterfacesDatabaseTest, DeleteKvStore001, TestSize.Level1)
738 {
739     /**
740      * @tc.steps: step1. Obtain the kvStore through the GetKvStore interface of
741      *  the delegate manager using the parameter createIfNecessary(true)
742      * @tc.steps: step2. Close the kvStore.
743      * @tc.expected: step1. Returns a non-null kvstore and error code is OK.
744      * @tc.expected: step2. Returns OK.
745      */
746     CipherPassword passwd;
747     KvStoreDelegate::Option option = {true, true, false};
748     const std::string storeId("DeleteKvStore_001");
749     g_mgr.GetKvStore(storeId, option, g_kvDelegateCallback);
750     std::string origIdentifierName = USER_ID + "-" + APP_ID + "-" + storeId;
751     std::string hashIdentifierName = DBCommon::TransferHashString(origIdentifierName);
752     std::string identifierName = DBCommon::TransferStringToHex(hashIdentifierName);
753     ASSERT_TRUE(g_kvDelegatePtr != nullptr);
754     EXPECT_TRUE(g_kvDelegateStatus == OK);
755     EXPECT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK);
756     g_kvDelegatePtr = nullptr;
757 
758     /**
759      * @tc.steps: step3. Check the database file
760      * @tc.expected: step3. the database file are existed.
761      */
762     string dbFileName = g_testDir + "/" + identifierName + "/local/local.db";
763     ifstream dbFile(dbFileName);
764     EXPECT_TRUE(dbFile);
765     dbFile.close();
766     string walFileName = g_testDir + "/" + identifierName + "/local/local.db-wal";
767     fstream walFile(walFileName, fstream::out);
768     EXPECT_TRUE(walFile.is_open());
769     walFile.close();
770     string shmFileName = g_testDir + "/" + identifierName + "/local/local.db-shm";
771     fstream shmFile(shmFileName, fstream::out);
772     EXPECT_TRUE(shmFile.is_open());
773     shmFile.close();
774 
775     std::string dataBaseDir = g_testDir + "/" + identifierName;
776     EXPECT_GE(access(dataBaseDir.c_str(), F_OK), 0);
777 
778     /**
779      * @tc.steps: step4. Delete the kvStore through the DeleteKvStore interface of
780      *  the delegate manager
781      * @tc.steps: step5. Check the database files and the storage paths.
782      * @tc.expected: step4. Returns OK.
783      * @tc.expected: step5. The database files  and the storage paths are not existed.
784      */
785     EXPECT_TRUE(g_mgr.DeleteKvStore(storeId) == OK);
786     ifstream dbFileAfter(dbFileName);
787     ifstream walFileAfter(walFileName);
788     ifstream shmFileAfter(shmFileName);
789     EXPECT_FALSE(dbFileAfter);
790     EXPECT_FALSE(walFileAfter);
791     EXPECT_FALSE(shmFileAfter);
792     ASSERT_EQ(OS::CheckPathExistence(dataBaseDir), false);
793     std::string storeIdOnlyIdentifier = DBCommon::TransferHashString(storeId);
794     std::string storeIdOnlyIdentifierName = DBCommon::TransferStringToHex(storeIdOnlyIdentifier);
795     std::string storeIdOnlyIdDataBaseDir = g_testDir + "/" + storeIdOnlyIdentifierName;
796     ASSERT_EQ(OS::CheckPathExistence(storeIdOnlyIdDataBaseDir), false);
797 
798     /**
799      * @tc.steps: step6. Re-Delete the kvStore through the DeleteKvStore interface of
800      *  the delegate manager
801      * @tc.expected: step6. Returns NOT_FOUND.
802      */
803     EXPECT_TRUE(g_mgr.DeleteKvStore(storeId) == NOT_FOUND);
804 }
805 #endif // OMIT_MULTI_VER
806 
807 /**
808   * @tc.name: RepeatCloseKvStore001
809   * @tc.desc: Close the kv store repeatedly and check the database.
810   * @tc.type: FUNC
811   * @tc.require: AR000C2F0C AR000CQDV7
812   * @tc.author: wangbingquan
813   */
814 HWTEST_F(DistributedDBInterfacesDatabaseTest, RepeatCloseKvStore001, TestSize.Level2)
815 {
816     /**
817      * @tc.steps: step1. Obtain the kvStore through the GetKvStore interface of
818      *  the delegate manager using the parameter createIfNecessary(true)
819      * @tc.expected: step1. Returns a non-null kvstore and error code is OK.
820      */
821     CipherPassword passwd;
822     KvStoreNbDelegate::Option option = {true, false, false};
823     g_mgr.GetKvStore("RepeatCloseKvStore_001", option, g_kvNbDelegateCallback);
824     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
825     EXPECT_TRUE(g_kvDelegateStatus == OK);
826     static const size_t totalSize = 50;
827 
828     /**
829      * @tc.steps: step2. Put into the database some data.
830      * @tc.expected: step2. Put returns OK.
831      */
832     std::vector<Key> keys;
833     for (size_t i = 0; i < totalSize; i++) {
834         Entry entry;
835         DistributedDBToolsUnitTest::GetRandomKeyValue(entry.key, static_cast<uint32_t>(i + 1));
836         DistributedDBToolsUnitTest::GetRandomKeyValue(entry.value);
837         EXPECT_EQ(g_kvNbDelegatePtr->Put(entry.key, entry.value), OK);
838         keys.push_back(entry.key);
839     }
840 
841     /**
842      * @tc.steps: step3. Delete the data from the database, and close the database, reopen the database and
843      *  get the data.
844      * @tc.expected: step3. Delete returns OK, Close returns OK and Get returns NOT_FOUND.
845      */
846     for (size_t i = 0; i < keys.size(); i++) {
847         Value value;
848         EXPECT_EQ(g_kvNbDelegatePtr->Delete(keys[i]), OK);
849         EXPECT_EQ(g_kvNbDelegatePtr->Get(keys[i], value), NOT_FOUND);
850         EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
851         g_mgr.GetKvStore("RepeatCloseKvStore_001", option, g_kvNbDelegateCallback);
852         EXPECT_EQ(g_kvNbDelegatePtr->Get(keys[i], value), NOT_FOUND);
853     }
854     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
855     /**
856      * @tc.steps: step4. Delete the kvstore created before.
857      * @tc.expected: step4. Delete returns OK.
858      */
859     EXPECT_EQ(g_mgr.DeleteKvStore("RepeatCloseKvStore_001"), OK);
860 }
861 #ifndef OMIT_JSON
862 /**
863   * @tc.name: CreatKvStoreWithSchema001
864   * @tc.desc: Create non-memory KvStore with schema, check if create success.
865   * @tc.type: FUNC
866   * @tc.require: AR000DR9K2
867   * @tc.author: weifeng
868   */
869 HWTEST_F(DistributedDBInterfacesDatabaseTest, CreatKvStoreWithSchema001, TestSize.Level1)
870 {
871     /**
872      * @tc.steps: step1. create a new db(non-memory, non-encrypt), with valid schema;
873      * @tc.expected: step1. Returns a non-null kvstore and error code is OK.
874      */
875     KvStoreNbDelegate::Option option = {true, false, false};
876     GenerateValidSchemaString(option.schema);
877     g_mgr.GetKvStore("CreatKvStoreWithSchema_001", option, g_kvNbDelegateCallback);
878     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
879     EXPECT_TRUE(g_kvDelegateStatus == OK);
880     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
881     g_kvNbDelegatePtr = nullptr;
882     EXPECT_TRUE(g_mgr.DeleteKvStore("CreatKvStoreWithSchema_001") == OK);
883     /**
884      * @tc.steps: step2. create a new db(non-memory, non-encrypt), with invalid schema;
885      * @tc.expected: step2. Returns null kvstore and error code is INVALID_SCHEMA.
886      */
887     option = {true, false, false};
888     GenerateInvalidSchemaString(option.schema);
889     g_mgr.GetKvStore("CreatKvStoreWithSchema_001_invalid_schema", option, g_kvNbDelegateCallback);
890     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
891     EXPECT_TRUE(g_kvDelegateStatus == INVALID_SCHEMA);
892     EXPECT_TRUE(g_mgr.DeleteKvStore("CreatKvStoreWithSchema_001_invalid_schema") == NOT_FOUND);
893 #ifndef OMIT_ENCRYPT
894     /**
895      * @tc.steps: step3. create a new db(non-memory, encrypt), with valid schema;
896      * @tc.expected: step3. Returns a non-null kvstore and error code is OK.
897      */
898     CipherPassword passwd;
899     vector<uint8_t> passwdBuffer(10, 45);
900     passwd.SetValue(passwdBuffer.data(), passwdBuffer.size());
901     option = {true, false, true};
902     GenerateValidSchemaString(option.schema);
903     option.passwd = passwd;
904     g_mgr.GetKvStore("CreatKvStoreWithSchema_001_002", option, g_kvNbDelegateCallback);
905     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
906     EXPECT_TRUE(g_kvDelegateStatus == OK);
907     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
908     g_kvNbDelegatePtr = nullptr;
909     EXPECT_TRUE(g_mgr.DeleteKvStore("CreatKvStoreWithSchema_001_002") == OK);
910 
911     /**
912      * @tc.steps: step4. create a new db(non-memory, non-encrypt), with invalid schema;
913      * @tc.expected: step2. Returns null kvstore and error code is INVALID_SCHEMA.
914      */
915     option = {true, false, false};
916     GenerateInvalidSchemaString(option.schema);
917     g_mgr.GetKvStore("CreatKvStoreWithSchema_002_invalid_schema", option, g_kvNbDelegateCallback);
918     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
919     EXPECT_TRUE(g_kvDelegateStatus == INVALID_SCHEMA);
920     EXPECT_TRUE(g_mgr.DeleteKvStore("CreatKvStoreWithSchema_002_invalid_schema") == NOT_FOUND);
921 #endif
922 }
923 
924 /**
925   * @tc.name: CreatKvStoreWithSchema002
926   * @tc.desc: Create memory KvStore with schema, check if create success.
927   * @tc.type: FUNC
928   * @tc.require: AR000DR9K2
929   * @tc.author: weifeng
930   */
931 HWTEST_F(DistributedDBInterfacesDatabaseTest, CreatKvStoreWithSchema002, TestSize.Level1)
932 {
933     /**
934      * @tc.steps: step1. create a new db(memory, non-encrypt), with valid schema;
935      * @tc.expected: step1. Returns a null kvstore and error code is NOT_SUPPORT.
936      */
937     KvStoreNbDelegate::Option option = {true, true, false};
938     GenerateValidSchemaString(option.schema);
939     g_mgr.GetKvStore("CreatKvStoreWithSchema_002", option, g_kvNbDelegateCallback);
940     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
941     EXPECT_TRUE(g_kvDelegateStatus == NOT_SUPPORT);
942 
943     /**
944      * @tc.steps: step2. create a new db(memory, non-encrypt), with invalid schema;
945      * @tc.expected: step2. Returns null kvstore and error code is NOT_SUPPORT.
946      */
947     option = {true, true, false};
948     GenerateInvalidSchemaString(option.schema);
949     g_mgr.GetKvStore("CreatKvStoreWithSchema_002_invalid", option, g_kvNbDelegateCallback);
950     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
951     EXPECT_TRUE(g_kvDelegateStatus == NOT_SUPPORT);
952 }
953 #ifndef OMIT_ENCRYPT
954 /**
955   * @tc.name: OpenKvStoreWithSchema001
956   * @tc.desc: open an opened kvstore(non-memory, no-schema) with schema, check if open success.
957   * @tc.type: FUNC
958   * @tc.require: AR000DR9K2
959   * @tc.author: weifeng
960   */
961 HWTEST_F(DistributedDBInterfacesDatabaseTest, OpenKvStoreWithSchema001, TestSize.Level1)
962 {
963     /**
964      * @tc.steps: step1. create a new db(non-memory, non-encrypt), without schema;
965      * @tc.expected: step1. Returns a non-null kvstore and error code is OK.
966      */
967     KvStoreNbDelegate::Option option = {true, false, false};
968     g_mgr.GetKvStore("OpenKvStoreWithSchema_001", option, g_kvNbDelegateCallback);
969     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
970     EXPECT_TRUE(g_kvDelegateStatus == OK);
971     KvStoreNbDelegate *kvNbDelegatePtr = g_kvNbDelegatePtr;
972     /**
973      * @tc.steps: step2. open the db with valid schema;
974      * @tc.expected: step2. Returns a null kvstore and error code is SCHEMA_MISMATCH.
975      */
976     GenerateValidSchemaString(option.schema);
977     g_mgr.GetKvStore("OpenKvStoreWithSchema_001", option, g_kvNbDelegateCallback);
978     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
979     EXPECT_TRUE(g_kvDelegateStatus == SCHEMA_MISMATCH);
980 
981     /**
982      * @tc.steps: step3. open the db with invalid schema;
983      * @tc.expected: step3. Returns a null kvstore and error code is SCHEMA_MISMATCH.
984      */
985     GenerateInvalidSchemaString(option.schema);
986     g_mgr.GetKvStore("OpenKvStoreWithSchema_001", option, g_kvNbDelegateCallback);
987     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
988     EXPECT_TRUE(g_kvDelegateStatus == INVALID_SCHEMA);
989 
990     EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr), OK);
991     g_kvNbDelegatePtr = nullptr;
992     EXPECT_TRUE(g_mgr.DeleteKvStore("OpenKvStoreWithSchema_001") == OK);
993     /**
994      * @tc.steps: step4. create a new db(non-memory, encrypt), without schema;
995      * @tc.expected: step4. Returns a non-null kvstore and error code is OK.
996      */
997     option = {true, false, true};
998     CipherPassword passwd;
999     vector<uint8_t> passwdBuffer(10, 45);
1000     passwd.SetValue(passwdBuffer.data(), passwdBuffer.size());
1001     option.passwd = passwd;
1002     g_mgr.GetKvStore("OpenKvStoreWithSchema_001_encrypt", option, g_kvNbDelegateCallback);
1003     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1004     EXPECT_TRUE(g_kvDelegateStatus == OK);
1005     kvNbDelegatePtr = g_kvNbDelegatePtr;
1006     /**
1007      * @tc.steps: step5. open the db with valid schema;
1008      * @tc.expected: step5. Returns a null kvstore and error code is SCHEMA_MISMATCH.
1009      */
1010     GenerateValidSchemaString(option.schema);
1011     g_mgr.GetKvStore("OpenKvStoreWithSchema_001_encrypt", option, g_kvNbDelegateCallback);
1012     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
1013     EXPECT_TRUE(g_kvDelegateStatus == SCHEMA_MISMATCH);
1014 
1015     /**
1016      * @tc.steps: step6. open the db with invalid schema;
1017      * @tc.expected: step6. Returns a null kvstore and error code is SCHEMA_MISMATCH.
1018      */
1019     GenerateInvalidSchemaString(option.schema);
1020     g_mgr.GetKvStore("OpenKvStoreWithSchema_001_encrypt", option, g_kvNbDelegateCallback);
1021     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
1022     EXPECT_TRUE(g_kvDelegateStatus == INVALID_SCHEMA);
1023 
1024     EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr), OK);
1025     g_kvNbDelegatePtr = nullptr;
1026     EXPECT_TRUE(g_mgr.DeleteKvStore("OpenKvStoreWithSchema_001_encrypt") == OK);
1027 }
1028 #endif
1029 /**
1030   * @tc.name: OpenKvStoreWithSchema002
1031   * @tc.desc: open an opened kvstore(non-memory, schema) with schema, check if open success.
1032   * @tc.type: FUNC
1033   * @tc.require: AR000DR9K2
1034   * @tc.author: weifeng
1035   */
1036 HWTEST_F(DistributedDBInterfacesDatabaseTest, OpenKvStoreWithSchema002, TestSize.Level1)
1037 {
1038 #ifndef OMIT_ENCRYPT
1039     /**
1040      * @tc.steps: step1. open an opened kvstore(non-memory, non-encrypt), with different schemas;
1041      */
1042     OpenOpenedKvstoreWithSchema("OpenKvStoreWithSchema_002", true);
1043 #endif
1044     /**
1045      * @tc.steps: step2. open an opened kvstore(non-memory, encrypt), with different schemas;
1046      */
1047     OpenOpenedKvstoreWithSchema("OpenKvStoreWithSchema_002_encrypt", false);
1048 }
1049 
1050 /**
1051   * @tc.name: OpenKvStoreWithSchema003
1052   * @tc.desc: open an opened kvstore(memory) with different schemas, check if open success.
1053   * @tc.type: FUNC
1054   * @tc.require: AR000DR9K2
1055   * @tc.author: weifeng
1056   */
1057 HWTEST_F(DistributedDBInterfacesDatabaseTest, OpenKvStoreWithSchema003, TestSize.Level1)
1058 {
1059     /**
1060      * @tc.steps: step1. create a new db(memory, non-encrypt), without schema;
1061      * @tc.expected: step1. Returns a non-null kvstore and error code is OK.
1062      */
1063     KvStoreNbDelegate::Option option = {true, true, false};
1064     g_mgr.GetKvStore("OpenKvStoreWithSchema_003", option, g_kvNbDelegateCallback);
1065     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1066     EXPECT_TRUE(g_kvDelegateStatus == OK);
1067     KvStoreNbDelegate *kvNbDelegatePtr1 = g_kvNbDelegatePtr;
1068     /**
1069      * @tc.steps: step2. open a new db(memory, non-encrypt), without schema;
1070      * @tc.expected: step2. Returns a non-null kvstore and error code is OK.
1071      */
1072     g_mgr.GetKvStore("OpenKvStoreWithSchema_003", option, g_kvNbDelegateCallback);
1073     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1074     EXPECT_TRUE(g_kvDelegateStatus == OK);
1075     KvStoreNbDelegate *kvNbDelegatePtr2 = g_kvNbDelegatePtr;
1076     /**
1077      * @tc.steps: step3. open a new db(memory, non-encrypt), with valid schema;
1078      * @tc.expected: step3. Returns a null kvstore and error code is NOT_SUPPORT.
1079      */
1080     GenerateValidSchemaString(option.schema);
1081     g_mgr.GetKvStore("OpenKvStoreWithSchema_003", option, g_kvNbDelegateCallback);
1082     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
1083     EXPECT_TRUE(g_kvDelegateStatus == NOT_SUPPORT);
1084 
1085     /**
1086      * @tc.steps: step4. open a new db(memory, non-encrypt), with invalid schema;
1087      * @tc.expected: step4. Returns a null kvstore and error code is NOT_SUPPORT.
1088      */
1089     GenerateInvalidSchemaString(option.schema);
1090     g_mgr.GetKvStore("OpenKvStoreWithSchema_003", option, g_kvNbDelegateCallback);
1091     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
1092     EXPECT_TRUE(g_kvDelegateStatus == NOT_SUPPORT);
1093     EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr1), OK);
1094     EXPECT_EQ(g_mgr.CloseKvStore(kvNbDelegatePtr2), OK);
1095 }
1096 
1097 /**
1098   * @tc.name: OpenKvStoreWithSchema004
1099   * @tc.desc: open a totally closed schema-kvstore(non-memory) with different schemas, check if open success.
1100   * @tc.type: FUNC
1101   * @tc.require: AR000DR9K2
1102   * @tc.author: weifeng
1103   */
1104 HWTEST_F(DistributedDBInterfacesDatabaseTest, OpenKvStoreWithSchema004, TestSize.Level1)
1105 {
1106     /**
1107      * @tc.steps: step1. open a new db(non-memory, non-encrypt), with different schemas;
1108      * @tc.expected: step1. Returns a null kvstore and error code is NOT_SUPPORT.
1109      */
1110     std::string schema;
1111     GenerateValidSchemaString(schema);
1112     OpenClosedSchemaKvStore("OpenKvStoreWithSchema_004", false, schema);
1113 #ifndef OMIT_ENCRYPT
1114     /**
1115      * @tc.steps: step2. open a new db(non-memory, encrypt), with different schemas;
1116      * @tc.expected: step2. Returns a null kvstore and error code is NOT_SUPPORT.
1117      */
1118     OpenClosedSchemaKvStore("OpenKvStoreWithSchema_004_encrypt", true, schema);
1119 #endif
1120 }
1121 
1122 /**
1123   * @tc.name: OpenKvStoreWithSchema005
1124   * @tc.desc: open a totally closed non-schema-kvstore(non-memory) with different schemas, check if open success.
1125   * @tc.type: FUNC
1126   * @tc.require: AR000DR9K2
1127   * @tc.author: weifeng
1128   */
1129 HWTEST_F(DistributedDBInterfacesDatabaseTest, OpenKvStoreWithSchema005, TestSize.Level1)
1130 {
1131     /**
1132      * @tc.steps: step1. open a new db(non-memory, non-encrypt, non-schema), with different schemas;
1133      * @tc.expected: step1. Returns a different result.
1134      */
1135     OpenClosedNormalKvStore("OpenKvStoreWithSchema_005", false);
1136 #ifndef OMIT_ENCRYPT
1137     /**
1138      * @tc.steps: step2. open a new db(non-memory, encrypt, non-schema), with different schemas;
1139      * @tc.expected: step2. Returns a different result.
1140      */
1141     OpenClosedNormalKvStore("OpenKvStoreWithSchema_005", true);
1142 #endif
1143 }
1144 
1145 /**
1146   * @tc.name: OpenKvStoreWithSchema006
1147   * @tc.desc: open a memory non-schema-kvstore with different schemas, check if open success.
1148   * @tc.type: FUNC
1149   * @tc.require: AR000DR9K2
1150   * @tc.author: weifeng
1151   */
1152 HWTEST_F(DistributedDBInterfacesDatabaseTest, OpenKvStoreWithSchema006, TestSize.Level1)
1153 {
1154     /**
1155      * @tc.steps: step1. open a new db(memory, non-encrypt, non-schema), without schema;
1156      * @tc.expected: step1. Returns OK.
1157      */
1158     KvStoreNbDelegate::Option option = {true, true, false};
1159     g_mgr.GetKvStore("OpenKvStoreWithSchema_006", option, g_kvNbDelegateCallback);
1160     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1161     EXPECT_TRUE(g_kvDelegateStatus == OK);
1162     /**
1163      * @tc.steps: step2. close the kvstore;
1164      * @tc.expected: step2. Returns OK.
1165      */
1166     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1167     g_kvNbDelegatePtr = nullptr;
1168 
1169     /**
1170      * @tc.steps: step3. reopen the kvstore without schema;
1171      * @tc.expected: step3. Returns OK.
1172      */
1173     g_mgr.GetKvStore("OpenKvStoreWithSchema_006", option, g_kvNbDelegateCallback);
1174     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1175     EXPECT_TRUE(g_kvDelegateStatus == OK);
1176     EXPECT_TRUE(WriteValidDataIntoKvStore() == OK);
1177     EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1178     g_kvNbDelegatePtr = nullptr;
1179 
1180     /**
1181      * @tc.steps: step4. reopen the kvstore with valid schema;
1182      * @tc.expected: step4. Returns OK.
1183      */
1184     GenerateValidSchemaString(option.schema);
1185     g_mgr.GetKvStore("OpenKvStoreWithSchema_006", option, g_kvNbDelegateCallback);
1186     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
1187     EXPECT_TRUE(g_kvDelegateStatus == NOT_SUPPORT);
1188 
1189     /**
1190      * @tc.steps: step4. reopen the kvstore with invalid schema;
1191      * @tc.expected: step4. Returns OK.
1192      */
1193     GenerateInvalidSchemaString(option.schema);
1194     g_mgr.GetKvStore("OpenKvStoreWithSchema_006", option, g_kvNbDelegateCallback);
1195     ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
1196     EXPECT_TRUE(g_kvDelegateStatus == NOT_SUPPORT);
1197 }
1198 #endif
1199 /**
1200   * @tc.name: OpenKvStoreWithStoreOnly001
1201   * @tc.desc: open the kv store with the option that createDirByStoreIdOnly is true.
1202   * @tc.type: FUNC
1203   * @tc.require: AR000DR9K2
1204   * @tc.author: wangbingquan
1205   */
1206 HWTEST_F(DistributedDBInterfacesDatabaseTest, OpenKvStoreWithStoreOnly001, TestSize.Level1)
1207 {
1208     /**
1209      * @tc.steps: step1. open the kv store with the option that createDirByStoreIdOnly is true.
1210      * @tc.expected: step1. Returns OK.
1211      */
1212     KvStoreNbDelegate::Option option;
1213     option.createDirByStoreIdOnly = true;
1214     g_mgr.GetKvStore("StoreOnly001", option, g_kvNbDelegateCallback);
1215     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1216     EXPECT_TRUE(g_kvDelegateStatus == OK);
1217     auto kvStorePtr = g_kvNbDelegatePtr;
1218     /**
1219      * @tc.steps: step2. open the same store with the option that createDirByStoreIdOnly is false.
1220      * @tc.expected: step2. Returns NOT OK.
1221      */
1222     option.createDirByStoreIdOnly = false;
1223     g_kvNbDelegatePtr = nullptr;
1224     g_mgr.GetKvStore("StoreOnly001", option, g_kvNbDelegateCallback);
1225     EXPECT_EQ(g_kvDelegateStatus, INVALID_ARGS);
1226     /**
1227      * @tc.steps: step3. close the kvstore and delete the kv store;
1228      * @tc.expected: step3. Returns OK.
1229      */
1230     EXPECT_EQ(g_mgr.CloseKvStore(kvStorePtr), OK);
1231     kvStorePtr = nullptr;
1232     EXPECT_EQ(g_mgr.DeleteKvStore("StoreOnly001"), OK);
1233 }
1234 
1235 /**
1236   * @tc.name: GetDBWhileOpened001
1237   * @tc.desc: open the kv store with the option that createDirByStoreIdOnly is true.
1238   * @tc.type: FUNC
1239   * @tc.require: AR000E8S2V
1240   * @tc.author: wangbingquan
1241   */
1242 HWTEST_F(DistributedDBInterfacesDatabaseTest, GetDBWhileOpened001, TestSize.Level1)
1243 {
1244     /**
1245      * @tc.steps: step1. Get the connection.
1246      * @tc.expected: step1. Returns OK.
1247      */
1248     KvDBProperties property;
1249     std::string storeId = "openTest";
1250     std::string origId = USER_ID + "-" + APP_ID + "-" + storeId;
1251     std::string identifier = DBCommon::TransferHashString(origId);
1252     std::string hexDir = DBCommon::TransferStringToHex(identifier);
1253     property.SetStringProp(KvDBProperties::IDENTIFIER_DATA, identifier);
1254     property.SetStringProp(KvDBProperties::IDENTIFIER_DIR, hexDir);
1255     property.SetStringProp(KvDBProperties::DATA_DIR, g_testDir);
1256     property.SetBoolProp(KvDBProperties::CREATE_IF_NECESSARY, true);
1257     property.SetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::SINGLE_VER_TYPE_SQLITE);
1258     property.SetBoolProp(KvDBProperties::MEMORY_MODE, false);
1259     property.SetBoolProp(KvDBProperties::ENCRYPTED_MODE, false);
1260     property.SetBoolProp(KvDBProperties::CREATE_DIR_BY_STORE_ID_ONLY, true);
1261     property.SetStringProp(KvDBProperties::APP_ID, APP_ID);
1262     property.SetStringProp(KvDBProperties::USER_ID, USER_ID);
1263     property.SetStringProp(KvDBProperties::APP_ID, storeId);
1264 
1265     int errCode = E_OK;
1266     auto connection1 = KvDBManager::GetDatabaseConnection(property, errCode, false);
1267     EXPECT_EQ(errCode, E_OK);
1268     /**
1269      * @tc.steps: step2. Get the connection with the para: isNeedIfOpened is false.
1270      * @tc.expected: step2. Returns -E_ALREADY_OPENED.
1271      */
1272     auto connection2 = KvDBManager::GetDatabaseConnection(property, errCode, false);
1273     EXPECT_EQ(errCode, -E_ALREADY_OPENED);
1274     EXPECT_EQ(connection2, nullptr);
1275 
1276     /**
1277      * @tc.steps: step3. Get the connection with the para: isNeedIfOpened is true.
1278      * @tc.expected: step3. Returns E_OK.
1279      */
1280     auto connection3 = KvDBManager::GetDatabaseConnection(property, errCode, true);
1281     EXPECT_EQ(errCode, E_OK);
1282     EXPECT_NE(connection3, nullptr);
1283 
1284     KvDBManager::ReleaseDatabaseConnection(connection1);
1285     KvDBManager::ReleaseDatabaseConnection(connection3);
1286     EXPECT_EQ(g_mgr.DeleteKvStore(storeId), OK);
1287 }
1288 namespace {
OpenCloseDatabase(const std::string & storeId)1289     void OpenCloseDatabase(const std::string &storeId)
1290     {
1291         KvStoreNbDelegate::Option option;
1292         DBStatus status;
1293         KvStoreNbDelegate *delegate = nullptr;
1294         auto nbDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback,
1295             placeholders::_1, placeholders::_2, std::ref(status), std::ref(delegate));
1296         int totalNum = 0;
1297         for (size_t i = 0; i < 100; i++) { // cycle 100 times.
1298             g_mgr.GetKvStore(storeId, option, nbDelegateCallback);
1299             if (delegate != nullptr) {
1300                 totalNum++;
1301             }
1302             g_mgr.CloseKvStore(delegate);
1303             delegate = nullptr;
1304             std::this_thread::sleep_for(std::chrono::milliseconds(1));
1305         }
1306         LOGD("Succeed %d times", totalNum);
1307     }
1308 
FreqOpenClose001()1309     void FreqOpenClose001()
1310     {
1311         std::string storeId = "FrqOpenClose001";
1312         std::thread t1(OpenCloseDatabase, storeId);
1313         std::thread t2(OpenCloseDatabase, storeId);
1314         std::thread t3(OpenCloseDatabase, storeId);
1315         std::thread t4(OpenCloseDatabase, storeId);
1316         t1.join();
1317         t2.join();
1318         t3.join();
1319         t4.join();
1320         EXPECT_EQ(g_mgr.DeleteKvStore(storeId), OK);
1321     }
1322 
FreqOpenCloseDel001()1323     void FreqOpenCloseDel001()
1324     {
1325         std::string storeId = "FrqOpenCloseDelete001";
1326         std::thread t1(OpenCloseDatabase, storeId);
1327         std::thread t2([&]() {
1328             for (int i = 0; i < 10000; i++) { // loop 10000 times
1329                 DBStatus status = g_mgr.DeleteKvStore(storeId);
1330                 LOGI("delete res %d", status);
1331                 EXPECT_TRUE(status == OK || status == BUSY || status == NOT_FOUND);
1332             }
1333         });
1334         t1.join();
1335         t2.join();
1336     }
1337 }
1338 
1339 /**
1340   * @tc.name: FreqOpenCloseDel001
1341   * @tc.desc: Open/close/delete the kv store concurrently.
1342   * @tc.type: FUNC
1343   * @tc.require: AR000DR9K2
1344   * @tc.author: wangbingquan
1345   */
1346 HWTEST_F(DistributedDBInterfacesDatabaseTest, FreqOpenCloseDel001, TestSize.Level2)
1347 {
1348     ASSERT_NO_FATAL_FAILURE(FreqOpenCloseDel001());
1349 }
1350 
1351 /**
1352   * @tc.name: FreqOpenClose001
1353   * @tc.desc: Open and close the kv store concurrently.
1354   * @tc.type: FUNC
1355   * @tc.require: AR000DR9K2
1356   * @tc.author: wangbingquan
1357   */
1358 HWTEST_F(DistributedDBInterfacesDatabaseTest, FreqOpenClose001, TestSize.Level2)
1359 {
1360     ASSERT_NO_FATAL_FAILURE(FreqOpenClose001());
1361 }
1362 
1363 /**
1364   * @tc.name: CheckKvStoreDir001
1365   * @tc.desc: Delete the kv store with the option that createDirByStoreIdOnly is true.
1366   * @tc.type: FUNC
1367   * @tc.require: AR000CQDV7
1368   * @tc.author: wangbingquan
1369   */
1370 HWTEST_F(DistributedDBInterfacesDatabaseTest, CheckKvStoreDir001, TestSize.Level1)
1371 {
1372     /**
1373      * @tc.steps: step1. open the kv store with the option that createDirByStoreIdOnly is true.
1374      * @tc.expected: step1. Returns OK.
1375      */
1376     KvStoreNbDelegate::Option option;
1377     option.createDirByStoreIdOnly = true;
1378     const std::string storeId("StoreOnly002");
1379     g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
1380     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1381     EXPECT_TRUE(g_kvDelegateStatus == OK);
1382     std::string testSubDir;
1383     EXPECT_EQ(KvStoreDelegateManager::GetDatabaseDir(storeId, testSubDir), OK);
1384     std::string dataBaseDir = g_testDir + "/" + testSubDir;
1385     EXPECT_GE(access(dataBaseDir.c_str(), F_OK), 0);
1386 
1387     /**
1388      * @tc.steps: step2. delete the kv store, and check the directory.
1389      * @tc.expected: step2. the directory is removed.
1390      */
1391     g_mgr.CloseKvStore(g_kvNbDelegatePtr);
1392     g_kvNbDelegatePtr = nullptr;
1393     EXPECT_EQ(g_mgr.DeleteKvStore(storeId), OK);
1394     LOGI("[%s]", dataBaseDir.c_str());
1395     ASSERT_EQ(OS::CheckPathExistence(dataBaseDir), false);
1396 }
1397 
1398 /**
1399  * @tc.name: CompressionRate1
1400  * @tc.desc: Open the kv store with invalid compressionRate and open successfully.
1401  * @tc.type: FUNC
1402  * @tc.require: AR000G3QTT
1403  * @tc.author: lidongwei
1404  */
1405 HWTEST_F(DistributedDBInterfacesDatabaseTest, CompressionRate1, TestSize.Level1)
1406 {
1407     /**
1408      * @tc.steps: step1. Open the kv store with the option that comressionRate is invalid.
1409      * @tc.expected: step1. Open kv store successfully. Returns OK.
1410      */
1411     KvStoreNbDelegate::Option option;
1412     option.isNeedCompressOnSync = true;
1413     option.compressionRate = 0; // 0 is invalid.
1414     const std::string storeId("CompressionRate1");
1415     g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
1416     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1417     EXPECT_TRUE(g_kvDelegateStatus == OK);
1418 
1419     g_mgr.CloseKvStore(g_kvNbDelegatePtr);
1420     g_kvNbDelegatePtr = nullptr;
1421     EXPECT_EQ(g_mgr.DeleteKvStore(storeId), OK);
1422 }
1423 
1424 /**
1425  * @tc.name: CompressionRate2
1426  * @tc.desc: Open the kv store with again with different compression option.
1427  * @tc.type: FUNC
1428  * @tc.require:
1429  * @tc.author: lianhuix
1430  */
1431 HWTEST_F(DistributedDBInterfacesDatabaseTest, CompressionRate2, TestSize.Level1)
1432 {
1433     /**
1434      * @tc.steps: step1. Open the kv store with the option that comressionRate is invalid.
1435      * @tc.expected: step1. Open kv store successfully. Returns OK.
1436      */
1437     KvStoreNbDelegate::Option option;
1438     option.isNeedCompressOnSync = true;
1439     option.compressionRate = 70; // 70 compression rate.
1440     const std::string storeId("CompressionRate1");
1441     g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
1442     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1443     EXPECT_TRUE(g_kvDelegateStatus == OK);
1444 
1445     /**
1446      * @tc.steps: step2. Open again with different compression option
1447      * @tc.expected: step2. Open kv store failed. Returns INVALID_ARGS.
1448      */
1449     DBStatus status;
1450     KvStoreNbDelegate *delegate = nullptr;
1451     auto callback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback,
1452         placeholders::_1, placeholders::_2, std::ref(status), std::ref(delegate));
1453 
1454     option.compressionRate = 80; // 80 compression rate.
1455     g_mgr.GetKvStore(storeId, option, callback);
1456     ASSERT_TRUE(delegate == nullptr);
1457     EXPECT_TRUE(status == INVALID_ARGS);
1458 
1459     option.isNeedCompressOnSync = false;
1460     option.compressionRate = 70; // 70 compression rate.
1461     g_mgr.GetKvStore(storeId, option, callback);
1462     ASSERT_TRUE(delegate == nullptr);
1463     EXPECT_TRUE(status == INVALID_ARGS);
1464 
1465     /**
1466      * @tc.steps: step3. Close kv store
1467      * @tc.expected: step3. OK.
1468      */
1469     g_mgr.CloseKvStore(g_kvNbDelegatePtr);
1470     g_kvNbDelegatePtr = nullptr;
1471     EXPECT_EQ(g_mgr.DeleteKvStore(storeId), OK);
1472 }
1473 
1474 HWTEST_F(DistributedDBInterfacesDatabaseTest, DataInterceptor1, TestSize.Level1)
1475 {
1476     /**
1477      * @tc.steps: step1. Open the kv store with the option that comressionRate is invalid.
1478      * @tc.expected: step1. Open kv store successfully. Returns OK.
1479      */
1480     KvStoreNbDelegate::Option option;
1481     const std::string storeId("DataInterceptor1");
1482     g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
1483     ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1484     EXPECT_TRUE(g_kvDelegateStatus == OK);
1485 
1486     g_kvNbDelegatePtr->SetPushDataInterceptor(
__anonf9df31ef0502(InterceptedData &data, const std::string &sourceID, const std::string &targetID) 1487         [](InterceptedData &data, const std::string &sourceID, const std::string &targetID) {
1488             int errCode = OK;
1489             auto entries = data.GetEntries();
1490             for (size_t i = 0; i < entries.size(); i++) {
1491                 if (entries[i].key.empty() || entries[i].key.at(0) != 'A') {
1492                     continue;
1493                 }
1494                 auto newKey = entries[i].key;
1495                 newKey[0] = 'B';
1496                 errCode = data.ModifyKey(i, newKey);
1497                 if (errCode != OK) {
1498                     break;
1499                 }
1500             }
1501             return errCode;
1502         }
1503     );
1504 
1505     g_mgr.CloseKvStore(g_kvNbDelegatePtr);
1506     g_kvNbDelegatePtr = nullptr;
1507     EXPECT_EQ(g_mgr.DeleteKvStore(storeId), OK);
1508 }
1509 
1510 HWTEST_F(DistributedDBInterfacesDatabaseTest, KvObserver001, TestSize.Level0)
1511 {
1512     KvStoreObserverUnitTest observer;
1513     KvStoreChangedDataImpl changedData(nullptr);
1514     EXPECT_FALSE(changedData.IsCleared());
1515     observer.OnChange(changedData);
1516     RelationalStoreChangedDataImpl storeChangedData("");
1517     observer.OnChange(storeChangedData);
1518     StoreObserver::StoreChangedInfo info;
1519     observer.OnChange(std::move(info));
1520     ChangedData simpleData;
1521     observer.OnChange(Origin::ORIGIN_ALL, "", std::move(simpleData));
1522 }