1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <gtest/gtest.h>
17 #include <thread>
18
19 #include "db_common.h"
20 #include "db_constant.h"
21 #include "db_errno.h"
22 #include "distributeddb_data_generate_unit_test.h"
23 #include "distributeddb_tools_unit_test.h"
24 #include "log_print.h"
25 #include "platform_specific.h"
26 #include "process_system_api_adapter_impl.h"
27 #include "runtime_context.h"
28 #include "sqlite_single_ver_natural_store.h"
29 #include "storage_engine_manager.h"
30 #ifdef DB_DEBUG_ENV
31 #include "system_time.h"
32 #endif // DB_DEBUG_ENV
33 #include "kv_store_result_set_impl.h"
34 #include "kv_store_nb_delegate_impl.h"
35 #include "kv_virtual_device.h"
36 #include "virtual_communicator_aggregator.h"
37
38 using namespace testing::ext;
39 using namespace DistributedDB;
40 using namespace DistributedDBUnitTest;
41 using namespace std;
42
43 namespace {
44 // define some variables to init a KvStoreDelegateManager object.
45 KvStoreDelegateManager g_mgr(APP_ID, USER_ID);
46 string g_testDir;
47 KvStoreConfig g_config;
48 Key g_keyPrefix = {'A', 'B', 'C'};
49 const int RESULT_SET_COUNT = 9;
50 const int RESULT_SET_INIT_POS = -1;
51 uint8_t g_testDict[RESULT_SET_COUNT] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
52
53 // define the g_kvNbDelegateCallback, used to get some information when open a kv store.
54 DBStatus g_kvDelegateStatus = INVALID_ARGS;
55 KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr;
56 #ifndef OMIT_MULTI_VER
57 KvStoreDelegate *g_kvDelegatePtr = nullptr;
58
59 // the type of g_kvDelegateCallback is function<void(DBStatus, KvStoreDelegate*)>
60 auto g_kvDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreDelegateCallback, placeholders::_1,
61 placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvDelegatePtr));
62 #endif // OMIT_MULTI_VER
63 const int OBSERVER_SLEEP_TIME = 100;
64 const int BATCH_PRESET_SIZE_TEST = 10;
65 const int DIVIDE_BATCH_PRESET_SIZE = 5;
66 const int VALUE_OFFSET = 5;
67
68 const int DEFAULT_KEY_VALUE_SIZE = 10;
69
70 const int CON_PUT_THREAD_NUM = 4;
71 const int PER_THREAD_PUT_NUM = 100;
72
73 const std::string DEVICE_B = "deviceB";
74 VirtualCommunicatorAggregator* g_communicatorAggregator = nullptr;
75 KvVirtualDevice *g_deviceB = nullptr;
76 VirtualSingleVerSyncDBInterface *g_syncInterfaceB = nullptr;
77
78 // the type of g_kvNbDelegateCallback is function<void(DBStatus, KvStoreDelegate*)>
79 auto g_kvNbDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, placeholders::_1,
80 placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvNbDelegatePtr));
81
82 enum LockState {
83 UNLOCKED = 0,
84 LOCKED
85 };
86
InitResultSet()87 void InitResultSet()
88 {
89 Key testKey;
90 Value testValue;
91 for (int i = 0; i < RESULT_SET_COUNT; i++) {
92 testKey.clear();
93 testValue.clear();
94 // set key
95 testKey = g_keyPrefix;
96 testKey.push_back(g_testDict[i]);
97 // set value
98 testValue.push_back(g_testDict[i]);
99 // insert entry
100 EXPECT_EQ(g_kvNbDelegatePtr->Put(testKey, testValue), OK);
101 }
102 }
103
InitVirtualDevice(const std::string & devId,KvVirtualDevice * & devices,VirtualSingleVerSyncDBInterface * & syncInterface)104 void InitVirtualDevice(const std::string &devId, KvVirtualDevice *&devices,
105 VirtualSingleVerSyncDBInterface *&syncInterface)
106 {
107 devices = new (std::nothrow) KvVirtualDevice(devId);
108 ASSERT_TRUE(devices != nullptr);
109 syncInterface = new (std::nothrow) VirtualSingleVerSyncDBInterface();
110 ASSERT_TRUE(syncInterface != nullptr);
111 ASSERT_EQ(devices->Initialize(g_communicatorAggregator, syncInterface), E_OK);
112 }
113
114 class DistributedDBInterfacesNBDelegateExtendTest : public testing::Test {
115 public:
116 static void SetUpTestCase(void);
117 static void TearDownTestCase(void);
118 void SetUp();
119 void TearDown();
120 };
121
SetUpTestCase(void)122 void DistributedDBInterfacesNBDelegateExtendTest::SetUpTestCase(void)
123 {
124 DistributedDBToolsUnitTest::TestDirInit(g_testDir);
125 g_config.dataDir = g_testDir;
126 g_mgr.SetKvStoreConfig(g_config);
127 if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) {
128 LOGE("rm test db files error!");
129 }
130
131 g_communicatorAggregator = new (std::nothrow) VirtualCommunicatorAggregator();
132 ASSERT_TRUE(g_communicatorAggregator != nullptr);
133 RuntimeContext::GetInstance()->SetCommunicatorAggregator(g_communicatorAggregator);
134 }
135
TearDownTestCase(void)136 void DistributedDBInterfacesNBDelegateExtendTest::TearDownTestCase(void)
137 {
138 RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(nullptr);
139
140 RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
141 }
142
SetUp(void)143 void DistributedDBInterfacesNBDelegateExtendTest::SetUp(void)
144 {
145 DistributedDBToolsUnitTest::PrintTestCaseInfo();
146 g_kvDelegateStatus = INVALID_ARGS;
147 g_kvNbDelegatePtr = nullptr;
148 #ifndef OMIT_MULTI_VER
149 g_kvDelegatePtr = nullptr;
150 #endif // OMIT_MULTI_VER
151 }
152
TearDown(void)153 void DistributedDBInterfacesNBDelegateExtendTest::TearDown(void)
154 {
155 if (g_kvNbDelegatePtr != nullptr) {
156 g_mgr.CloseKvStore(g_kvNbDelegatePtr);
157 g_kvNbDelegatePtr = nullptr;
158 }
159 RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(nullptr);
160 }
161
162 #ifdef DB_DEBUG_ENV
163 /**
164 * @tc.name: TimeChangeWithCloseStoreTest001
165 * @tc.desc: Test close store with time changed
166 * @tc.type: FUNC
167 * @tc.require:
168 * @tc.author: lianhuix
169 */
170 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, TimeChangeWithCloseStoreTest001, TestSize.Level3)
171 {
172 KvStoreDelegateManager mgr(APP_ID, USER_ID);
173 mgr.SetKvStoreConfig(g_config);
174
175 std::atomic<bool> isFinished(false);
176
177 std::vector<std::thread> slowThreads;
178 for (int i = 0; i < 10; i++) { // 10: thread to slow donw system
__anon230238950202() 179 std::thread th([&isFinished]() {
180 while (!isFinished) {
181 // pass
182 }
183 });
184 slowThreads.emplace_back(std::move(th));
185 }
186
__anon230238950302() 187 std::thread th([&isFinished]() {
188 int timeChangedCnt = 0;
189 while (!isFinished.load()) {
190 OS::SetOffsetBySecond(100 - timeChangedCnt++ * 2); // 100 2 : fake system time change
191 std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 100: wait for a while
192 }
193 });
194
195 for (int i = 0; i < 100; i++) { // run 100 times
196 const KvStoreNbDelegate::Option option = {true, false, false};
197 mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
198 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
199 EXPECT_EQ(g_kvDelegateStatus, OK);
200 EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
201 g_kvNbDelegatePtr = nullptr;
202 }
203
204 std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // 1000: wait for a while
205 isFinished.store(true);
206 th.join();
207 for (auto &it : slowThreads) {
208 it.join();
209 }
210 EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
211 }
212
213 /**
214 * @tc.name: TimeChangeWithCloseStoreTest002
215 * @tc.desc: Test close store with time changed
216 * @tc.type: FUNC
217 * @tc.require:
218 * @tc.author: zhangqiquan
219 */
220 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, TimeChangeWithCloseStoreTest002, TestSize.Level3)
221 {
222 KvStoreDelegateManager mgr(APP_ID, USER_ID);
223 mgr.SetKvStoreConfig(g_config);
224
225 const KvStoreNbDelegate::Option option = {true, false, false};
226 mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
227 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
228 EXPECT_EQ(g_kvDelegateStatus, OK);
229 const int threadPoolMax = 10;
230 for (int i = 0; i < threadPoolMax; ++i) {
__anon230238950402() 231 (void) RuntimeContext::GetInstance()->ScheduleTask([]() {
232 std::this_thread::sleep_for(std::chrono::seconds(10)); // sleep 10s for block thread pool
233 });
234 }
235 OS::SetOffsetBySecond(100); // 100 2 : fake system time change
236 std::this_thread::sleep_for(std::chrono::seconds(1)); // sleep 1s for time tick
237
238 EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
239 g_kvNbDelegatePtr = nullptr;
240
241 EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
242 RuntimeContext::GetInstance()->StopTaskPool(); // stop all async task
243 }
244
245 /**
246 * @tc.name: TimeChangeWithCloseStoreTest003
247 * @tc.desc: Test store close with timechange listener
248 * @tc.type: FUNC
249 * @tc.require:
250 * @tc.author: zhangqiquan
251 */
252 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, TimeChangeWithCloseStoreTest003, TestSize.Level3)
253 {
254 /**
255 * @tc.steps:step1. Create database.
256 * @tc.expected: step1. Returns a non-null kvstore.
257 */
258 KvStoreNbDelegate::Option option;
259 g_mgr.GetKvStore("TimeChangeWithCloseStoreTest003", option, g_kvNbDelegateCallback);
260 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
261 EXPECT_TRUE(g_kvDelegateStatus == OK);
262 std::shared_ptr<bool> timeChange = std::make_shared<bool>(false);
263 int errCode = E_OK;
__anon230238950502(void *) 264 auto *listener = RuntimeContext::GetInstance()->RegisterTimeChangedLister([timeChange](void *) {
265 std::this_thread::sleep_for(std::chrono::seconds(10)); // block close store 10s
266 *timeChange = true;
267 }, nullptr, errCode);
268 /**
269 * @tc.steps:step2. Block time change 10s and trigger time change.
270 * @tc.expected: step2. close store cost time > 5s.
271 */
272 ASSERT_EQ(errCode, E_OK);
273 OS::SetOffsetBySecond(100); // 100 : fake system time change
274 std::this_thread::sleep_for(std::chrono::seconds(1)); // wait 1s for time change
275 Timestamp beginTime;
276 (void)OS::GetCurrentSysTimeInMicrosecond(beginTime);
277 ASSERT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
278 Timestamp endTime;
279 (void)OS::GetCurrentSysTimeInMicrosecond(endTime);
280 if (*timeChange) {
281 EXPECT_GE(static_cast<int>(endTime - beginTime), 5 * 1000 * 1000); // 5 * 1000 * 1000 = 5s
282 }
283 listener->Drop(true);
284 OS::SetOffsetBySecond(-100); // -100 : fake system time change
285 g_kvNbDelegatePtr = nullptr;
286 EXPECT_EQ(g_mgr.DeleteKvStore("TimeChangeWithCloseStoreTest003"), OK);
287 }
288
289 /**
290 * @tc.name: TimeChangeWithDataChangeTest001
291 * @tc.desc: Test change data and change time
292 * @tc.type: FUNC
293 * @tc.require:
294 * @tc.author: liaoyonghuang
295 */
296 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, TimeChangeWithDataChangeTest001, TestSize.Level0)
297 {
298 /**
299 * @tc.steps:step1. Create local database.
300 * @tc.expected: step1. Returns a non-null kvstore.
301 */
302 KvStoreNbDelegate::Option option;
303 option.localOnly = true;
304 g_mgr.GetKvStore("TimeChangeWithDataChangeTest001", option, g_kvNbDelegateCallback);
305 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
306 EXPECT_TRUE(g_kvDelegateStatus == OK);
307 /**
308 * @tc.steps:step2. Set 100s time offset, put{k1, v1}. Then Set 0s time offset, put {k1, v2}.
309 * @tc.expected: step2. Get {k1, v2} form DB.
310 */
311 OS::SetOffsetBySecond(100); // 100 : fake system time change
312 g_kvNbDelegatePtr->Put(KEY_1, VALUE_1);
313 OS::SetOffsetBySecond(0);
314 g_kvNbDelegatePtr->Put(KEY_1, VALUE_2);
315 Value expectValue = VALUE_2;
316 Value actualValue;
317 g_kvNbDelegatePtr->Get(KEY_1, actualValue);
318 EXPECT_EQ(expectValue, actualValue);
319
320 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
321 g_kvNbDelegatePtr = nullptr;
322 EXPECT_EQ(g_mgr.DeleteKvStore("TimeChangeWithDataChangeTest001"), OK);
323 }
324 #endif // DB_DEBUG_ENV
325
326 /**
327 * @tc.name: ResultSetLimitTest001
328 * @tc.desc: Get result set over limit
329 * @tc.type: FUNC
330 * @tc.require:
331 * @tc.author: lianhuix
332 */
333 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, ResultSetLimitTest001, TestSize.Level0)
334 {
335 /**
336 * @tc.steps:step1. Create database.
337 * @tc.expected: step1. Returns a non-null kvstore.
338 */
339 KvStoreNbDelegate::Option option;
340 g_mgr.GetKvStore("ResultSetLimitTest001", option, g_kvNbDelegateCallback);
341 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
342 EXPECT_TRUE(g_kvDelegateStatus == OK);
343
344 /**
345 * @tc.steps:step2. Put the random entry into the database.
346 * @tc.expected: step2. Returns OK.
347 */
348 EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_1, VALUE_1), OK);
349 EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_2, VALUE_2), OK);
350 EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_3, VALUE_3), OK);
351
352 /**
353 * @tc.steps:step3. Get the resultset overlimit.
354 * @tc.expected: step3. In limit returns OK, else return OVER_MAX_LIMITS.
355 */
356 std::vector<KvStoreResultSet *> dataResultSet;
357 for (int i = 0; i < 8; i++) { // 8: max result set count
358 KvStoreResultSet *resultSet = nullptr;
359 EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(Key{}, resultSet), OK);
360 dataResultSet.push_back(resultSet);
361 EXPECT_NE(resultSet, nullptr);
362 }
363
364 KvStoreResultSet *resultSet = nullptr;
365 EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(Key{}, resultSet), OVER_MAX_LIMITS);
366 EXPECT_EQ(resultSet, nullptr);
367 if (resultSet != nullptr) {
368 EXPECT_EQ(g_kvNbDelegatePtr->CloseResultSet(resultSet), OK);
369 }
370
371 /**
372 * @tc.steps:step4. Close result set and store.
373 * @tc.expected: step4. Returns OK.
374 */
375 for (auto it : dataResultSet) {
376 EXPECT_EQ(g_kvNbDelegatePtr->CloseResultSet(it), OK);
377 }
378
379 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
380 EXPECT_EQ(g_mgr.DeleteKvStore("ResultSetLimitTest001"), OK);
381 g_kvNbDelegatePtr = nullptr;
382 }
383
384 /**
385 * @tc.name: LocalStore001
386 * @tc.desc: Test get kv store with localOnly
387 * @tc.type: FUNC
388 * @tc.require:
389 * @tc.author: zhangqiquan
390 */
391 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, LocalStore001, TestSize.Level1)
392 {
393 KvStoreDelegateManager mgr(APP_ID, USER_ID);
394 mgr.SetKvStoreConfig(g_config);
395
396 /**
397 * @tc.steps:step1. Create database with localOnly.
398 * @tc.expected: step1. Returns a non-null store.
399 */
400 KvStoreNbDelegate::Option option = {true, false, false};
401 option.localOnly = true;
402 DBStatus openStatus = DBStatus::DB_ERROR;
403 KvStoreNbDelegate *openDelegate = nullptr;
__anon230238950602(DBStatus status, KvStoreNbDelegate *delegate) 404 mgr.GetKvStore(STORE_ID_1, option, [&openStatus, &openDelegate](DBStatus status, KvStoreNbDelegate *delegate) {
405 openStatus = status;
406 openDelegate = delegate;
407 });
408 ASSERT_TRUE(openDelegate != nullptr);
409 EXPECT_EQ(openStatus, OK);
410 /**
411 * @tc.steps:step2. call sync and put/get interface.
412 * @tc.expected: step2. sync return NOT_ACTIVE.
413 */
414 DBStatus actionStatus = openDelegate->Sync({}, SyncMode::SYNC_MODE_PUSH_ONLY, nullptr);
415 EXPECT_EQ(actionStatus, DBStatus::NOT_ACTIVE);
416 Key key = {'k'};
417 Value expectValue = {'v'};
418 EXPECT_EQ(openDelegate->Put(key, expectValue), OK);
419 Value actualValue;
420 EXPECT_EQ(openDelegate->Get(key, actualValue), OK);
421 EXPECT_EQ(actualValue, expectValue);
422
423 int pragmaData = 1;
424 auto input = static_cast<PragmaData>(&pragmaData);
425 EXPECT_EQ(openDelegate->Pragma(SET_SYNC_RETRY, input), NOT_SUPPORT);
426
427 EXPECT_EQ(mgr.CloseKvStore(openDelegate), OK);
428 EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
429 openDelegate = nullptr;
430 }
431
432 /**
433 * @tc.name: LocalStore002
434 * @tc.desc: Test get kv store different local mode
435 * @tc.type: FUNC
436 * @tc.require:
437 * @tc.author: zhangqiquan
438 */
439 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, LocalStore002, TestSize.Level1)
440 {
441 KvStoreDelegateManager mgr(APP_ID, USER_ID);
442 mgr.SetKvStoreConfig(g_config);
443
444 /**
445 * @tc.steps:step1. Create database with localOnly.
446 * @tc.expected: step1. Returns a non-null store.
447 */
448 KvStoreNbDelegate::Option option = {true, false, false};
449 option.localOnly = true;
450 DBStatus openStatus = DBStatus::DB_ERROR;
451 KvStoreNbDelegate *localDelegate = nullptr;
__anon230238950702(DBStatus status, KvStoreNbDelegate *delegate) 452 mgr.GetKvStore(STORE_ID_1, option, [&openStatus, &localDelegate](DBStatus status, KvStoreNbDelegate *delegate) {
453 openStatus = status;
454 localDelegate = delegate;
455 });
456 ASSERT_TRUE(localDelegate != nullptr);
457 EXPECT_EQ(openStatus, OK);
458 /**
459 * @tc.steps:step2. Create database without localOnly.
460 * @tc.expected: step2. Returns a null store.
461 */
462 option.localOnly = false;
463 KvStoreNbDelegate *syncDelegate = nullptr;
__anon230238950802(DBStatus status, KvStoreNbDelegate *delegate) 464 mgr.GetKvStore(STORE_ID_1, option, [&openStatus, &syncDelegate](DBStatus status, KvStoreNbDelegate *delegate) {
465 openStatus = status;
466 syncDelegate = delegate;
467 });
468 EXPECT_EQ(syncDelegate, nullptr);
469 EXPECT_EQ(openStatus, INVALID_ARGS);
470 EXPECT_EQ(mgr.CloseKvStore(localDelegate), OK);
471 EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
472 localDelegate = nullptr;
473 }
474
475 /**
476 * @tc.name: PutSync001
477 * @tc.desc: put data and sync at same time
478 * @tc.type: FUNC
479 * @tc.require:
480 * @tc.author: zhangqiquan
481 */
482 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, PutSync001, TestSize.Level3)
483 {
484 /**
485 * @tc.steps:step1. Create database with localOnly.
486 * @tc.expected: step1. Returns a non-null store.
487 */
488 KvStoreDelegateManager mgr(APP_ID, USER_ID);
489 mgr.SetKvStoreConfig(g_config);
490 const KvStoreNbDelegate::Option option = {true, false, false};
491 mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
492 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
493 EXPECT_EQ(g_kvDelegateStatus, OK);
494 /**
495 * @tc.steps:step2. Put data async.
496 * @tc.expected: step2. Always returns OK.
497 */
498 std::atomic<bool> finish = false;
__anon230238950902() 499 std::thread putThread([&finish]() {
500 while (!finish) {
501 EXPECT_EQ(g_kvNbDelegatePtr->Put(KEY_1, VALUE_1), OK);
502 }
503 });
504 /**
505 * @tc.steps:step3. Call sync async.
506 * @tc.expected: step3. Always returns OK.
507 */
__anon230238950a02() 508 std::thread syncThread([]() {
509 std::vector<std::string> devices;
510 devices.emplace_back("");
511 Key key = {'k'};
512 for (int i = 0; i < 100; ++i) { // sync 100 times
513 Query query = Query::Select().PrefixKey(key);
514 DBStatus status = g_kvNbDelegatePtr->Sync(devices, SYNC_MODE_PULL_ONLY, nullptr, query, true);
515 EXPECT_EQ(status, OK);
516 }
517 });
518 syncThread.join();
519 finish = true;
520 putThread.join();
521 EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
522 g_kvNbDelegatePtr = nullptr;
523 EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
524 }
525
526 /**
527 * @tc.name: UpdateKey001
528 * @tc.desc: Test update key
529 * @tc.type: FUNC
530 * @tc.require:
531 * @tc.author: zhangqiquan
532 */
533 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, UpdateKey001, TestSize.Level0)
534 {
535 /**
536 * @tc.steps:step1. Create database.
537 * @tc.expected: step1. Returns a non-null kvstore.
538 */
539 KvStoreNbDelegate::Option option;
540 g_mgr.GetKvStore("UpdateKey001", option, g_kvNbDelegateCallback);
541 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
542 EXPECT_TRUE(g_kvDelegateStatus == OK);
543 /**
544 * @tc.steps:step2. Put (k1, v1) into the database.
545 * @tc.expected: step2. Returns OK.
546 */
547 Key k1 = {'k', '1'};
548 EXPECT_EQ(g_kvNbDelegatePtr->Put(k1, VALUE_1), OK);
549 /**
550 * @tc.steps:step3. Update (k1, v1) to (k10, v1).
551 * @tc.expected: step3. Returns OK and get k1 return not found.
552 */
__anon230238950b02(const Key &originKey, Key &newKey) 553 g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
554 newKey = originKey;
555 newKey.push_back('0');
556 });
557 Value actualValue;
558 EXPECT_EQ(g_kvNbDelegatePtr->Get(k1, actualValue), NOT_FOUND);
559 k1.push_back('0');
560 EXPECT_EQ(g_kvNbDelegatePtr->Get(k1, actualValue), OK);
561 EXPECT_EQ(actualValue, VALUE_1);
562 /**
563 * @tc.steps:step4. Close store.
564 * @tc.expected: step4. Returns OK.
565 */
566 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
567 EXPECT_EQ(g_mgr.DeleteKvStore("UpdateKey001"), OK);
568 g_kvNbDelegatePtr = nullptr;
569 }
570
571 /**
572 * @tc.name: UpdateKey002
573 * @tc.desc: Test update key with transaction
574 * @tc.type: FUNC
575 * @tc.require:
576 * @tc.author: zhangqiquan
577 */
578 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, UpdateKey002, TestSize.Level0)
579 {
580 /**
581 * @tc.steps:step1. Create database.
582 * @tc.expected: step1. Returns a non-null kvstore.
583 */
584 KvStoreNbDelegate::Option option;
585 g_mgr.GetKvStore("UpdateKey002", option, g_kvNbDelegateCallback);
586 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
587 EXPECT_TRUE(g_kvDelegateStatus == OK);
588 /**
589 * @tc.steps:step2. Put (k1, v1) into the database .
590 * @tc.expected: step2. Returns OK.
591 */
592 Key k1 = {'k', '1'};
593 EXPECT_EQ(g_kvNbDelegatePtr->Put(k1, VALUE_1), OK);
594 g_kvNbDelegatePtr->StartTransaction();
595 /**
596 * @tc.steps:step3. Update (k1, v1) to (k10, v1).
597 * @tc.expected: step3. Returns OK and get k1 return not found.
598 */
__anon230238950c02(const Key &originKey, Key &newKey) 599 g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
600 newKey = originKey;
601 newKey.push_back('0');
602 });
603 Value actualValue;
604 EXPECT_EQ(g_kvNbDelegatePtr->Get(k1, actualValue), NOT_FOUND);
605 Key k10 = {'k', '1', '0'};
606 EXPECT_EQ(g_kvNbDelegatePtr->Get(k10, actualValue), OK);
607 EXPECT_EQ(actualValue, VALUE_1);
608 /**
609 * @tc.steps:step5. Rollback Transaction.
610 * @tc.expected: step5. k10 not exist in db.
611 */
612 g_kvNbDelegatePtr->Rollback();
613 EXPECT_EQ(g_kvNbDelegatePtr->Get(k10, actualValue), NOT_FOUND);
614 EXPECT_EQ(g_kvNbDelegatePtr->Get(k1, actualValue), OK);
615 /**
616 * @tc.steps:step5. Commit transaction.
617 * @tc.expected: step5. data exist in db.
618 */
619 g_kvNbDelegatePtr->StartTransaction();
__anon230238950d02(const Key &originKey, Key &newKey) 620 g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
621 newKey = originKey;
622 newKey.push_back('0');
623 });
624 g_kvNbDelegatePtr->Commit();
625 EXPECT_EQ(g_kvNbDelegatePtr->Get(k10, actualValue), OK);
626 /**
627 * @tc.steps:step6. Close store.
628 * @tc.expected: step6. Returns OK.
629 */
630 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
631 EXPECT_EQ(g_mgr.DeleteKvStore("UpdateKey002"), OK);
632 g_kvNbDelegatePtr = nullptr;
633 }
634
635 /**
636 * @tc.name: UpdateKey003
637 * @tc.desc: Test update key with invalid args
638 * @tc.type: FUNC
639 * @tc.require:
640 * @tc.author: zhangqiquan
641 */
642 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, UpdateKey003, TestSize.Level0)
643 {
644 /**
645 * @tc.steps:step1. Create database.
646 * @tc.expected: step1. Returns a non-null kvstore.
647 */
648 KvStoreNbDelegate::Option option;
649 g_mgr.GetKvStore("UpdateKey003", option, g_kvNbDelegateCallback);
650 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
651 EXPECT_TRUE(g_kvDelegateStatus == OK);
652 /**
653 * @tc.steps:step2. Put (k1, v1) into the database .
654 * @tc.expected: step2. Returns OK.
655 */
656 Key k1 = {'k', '1'};
657 Key k2 = {'k', '2'};
658 EXPECT_EQ(g_kvNbDelegatePtr->Put(k1, VALUE_1), OK);
659 EXPECT_EQ(g_kvNbDelegatePtr->Put(k2, VALUE_1), OK);
660 /**
661 * @tc.steps:step3. Update key with nullptr or invalid key.
662 * @tc.expected: step3. Returns INVALID_ARGS.
663 */
664 EXPECT_EQ(g_kvNbDelegatePtr->UpdateKey(nullptr), INVALID_ARGS);
__anon230238950e02(const Key &originKey, Key &newKey) 665 DBStatus status = g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
666 newKey.clear();
667 });
668 EXPECT_EQ(status, INVALID_ARGS);
__anon230238950f02(const Key &originKey, Key &newKey) 669 status = g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
670 newKey.assign(2048u, '0'); // 2048 is invalid len
671 });
672 EXPECT_EQ(status, INVALID_ARGS);
__anon230238951002(const Key &originKey, Key &newKey) 673 status = g_kvNbDelegatePtr->UpdateKey([](const Key &originKey, Key &newKey) {
674 newKey = {'k', '3'};
675 });
676 EXPECT_EQ(status, CONSTRAINT);
677 /**
678 * @tc.steps:step4. Close store.
679 * @tc.expected: step4. Returns OK.
680 */
681 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
682 EXPECT_EQ(g_mgr.DeleteKvStore("UpdateKey003"), OK);
683 g_kvNbDelegatePtr = nullptr;
684 }
685
686 /**
687 * @tc.name: BlockTimer001
688 * @tc.desc: Test open close function with block timer
689 * @tc.type: FUNC
690 * @tc.require:
691 * @tc.author: zhangqiquan
692 */
693 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, BlockTimer001, TestSize.Level1)
694 {
695 /**
696 * @tc.steps:step1. Create database.
697 * @tc.expected: step1. Returns a non-null store.
698 */
699 KvStoreNbDelegate::Option option;
700 g_mgr.GetKvStore("BlockTimer001", option, g_kvNbDelegateCallback);
701 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
702 EXPECT_TRUE(g_kvDelegateStatus == OK);
703 /**
704 * @tc.steps:step2. Create block timer.
705 * @tc.expected: step2. create ok.
706 */
707 TimerId timerId = 0u;
708 bool timerFinalize = false;
709 std::condition_variable cv;
710 std::mutex finalizeMutex;
711 bool triggerTimer = false;
712 std::condition_variable triggerCv;
713 std::mutex triggerMutex;
__anon230238951102(TimerId id) 714 int errCode = RuntimeContext::GetInstance()->SetTimer(1, [&triggerTimer, &triggerCv, &triggerMutex](TimerId id) {
715 {
716 std::lock_guard<std::mutex> autoLock(triggerMutex);
717 triggerTimer = true;
718 }
719 triggerCv.notify_all();
720 std::this_thread::sleep_for(std::chrono::seconds(5));
721 return -E_END_TIMER;
722 }, [&timerFinalize, &finalizeMutex, &cv]() {
723 {
724 std::lock_guard<std::mutex> autoLock(finalizeMutex);
725 timerFinalize = true;
726 }
727 cv.notify_all();
728 }, timerId);
729 ASSERT_EQ(errCode, E_OK);
730 {
731 std::unique_lock<std::mutex> uniqueLock(triggerMutex);
__anon230238951302() 732 triggerCv.wait(uniqueLock, [&triggerTimer]() {
733 return triggerTimer;
734 });
735 }
736 /**
737 * @tc.steps:step3. Close store.
738 * @tc.expected: step3. Returns OK.
739 */
740 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
741 std::unique_lock<std::mutex> uniqueLock(finalizeMutex);
742 EXPECT_TRUE(timerFinalize);
__anon230238951402() 743 cv.wait(uniqueLock, [&timerFinalize]() {
744 return timerFinalize;
745 });
746 EXPECT_EQ(g_mgr.DeleteKvStore("BlockTimer001"), OK);
747 g_kvNbDelegatePtr = nullptr;
748 }
749
750 /**
751 * @tc.name: MigrateDeadLockTest0011
752 * @tc.desc: Test the will not be deadlock in migration.
753 * @tc.type: FUNC
754 * @tc.require:
755 * @tc.author: zhangshijie
756 */
757 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, MigrateDeadLockTest001, TestSize.Level2)
758 {
759 std::shared_ptr<ProcessSystemApiAdapterImpl> g_adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
760 RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(g_adapter);
761 /**
762 * @tc.steps:step1. Get the nb delegate.
763 * @tc.expected: step1. Get results OK and non-null delegate.
764 */
765 KvStoreNbDelegate::Option option = {true, false, false};
766 option.secOption = {S3, SECE};
767 std::string storeId = "distributed_nb_delegate_test";
768 g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
769 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
770 EXPECT_TRUE(g_kvDelegateStatus == OK);
771
772 KvDBProperties property;
773 property.SetStringProp(KvDBProperties::DATA_DIR, g_testDir);
774 property.SetStringProp(KvDBProperties::STORE_ID, storeId);
775 property.SetIntProp(KvDBProperties::SECURITY_LABEL, S3);
776 property.SetIntProp(KvDBProperties::SECURITY_FLAG, SECE);
777
778 std::string identifier = DBCommon::GenerateIdentifierId(storeId, APP_ID, USER_ID);
779 property.SetStringProp(KvDBProperties::IDENTIFIER_DATA, DBCommon::TransferHashString(identifier));
780 property.SetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::SINGLE_VER_TYPE_SQLITE);
781
782 int errCode;
783 SQLiteSingleVerStorageEngine *storageEngine =
784 static_cast<SQLiteSingleVerStorageEngine *>(StorageEngineManager::GetStorageEngine(property, errCode));
785 ASSERT_EQ(errCode, E_OK);
786 ASSERT_NE(storageEngine, nullptr);
787 storageEngine->SetEngineState(EngineState::CACHEDB);
788
789 /**
790 * @tc.steps:step2. create cache db
791 * @tc.expected: step2. operation ok
792 */
793 std::string cacheDir = g_testDir + "/" + DBCommon::TransferStringToHex(DBCommon::TransferHashString(identifier)) +
794 "/" + DBConstant::SINGLE_SUB_DIR + "/" + DBConstant::CACHEDB_DIR;
795 std::string cacheDB = cacheDir + "/" + DBConstant::SINGLE_VER_CACHE_STORE + DBConstant::DB_EXTENSION;
796 EXPECT_EQ(OS::CreateFileByFileName(cacheDB), E_OK);
797
798 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
799 g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
800 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
801 EXPECT_TRUE(g_kvDelegateStatus == OK);
802
803 std::this_thread::sleep_for(std::chrono::seconds(3)); // 3 is sleep seconds
804 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
805 EXPECT_EQ(g_mgr.DeleteKvStore(storeId), OK);
806 g_kvNbDelegatePtr = nullptr;
807 if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) {
808 LOGE("rm test db files error!");
809 }
810 }
811
812 /**
813 * @tc.name: InvalidQueryTest001
814 * @tc.desc: Test GetEntries with range query filter by sqlite
815 * @tc.type: FUNC
816 * @tc.require:
817 * @tc.author: mazhao
818 */
819 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, InvalidQueryTest001, TestSize.Level1)
820 {
821 /**
822 * @tc.steps:step1. Get the nb delegate.
823 * @tc.expected: step1. Get results OK and non-null delegate.
824 */
825 KvStoreNbDelegate::Option option;
826 g_mgr.GetKvStore("InvalidQueryTest001", option, g_kvNbDelegateCallback);
827 std::vector<Entry> entries;
828 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
829 EXPECT_TRUE(g_kvDelegateStatus == OK);
830
831 /**
832 * @tc.steps: step2. Use range query conditions to obtain the resultset when use sqlite engine.
833 * @tc.expected: step2. return NOT_SUPPORT.
834 */
835 KvStoreResultSet *resultSet = nullptr;
836 Query inValidQuery = Query::Select().Range({}, {});
837 EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(inValidQuery, resultSet), NOT_SUPPORT);
838 EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(inValidQuery, entries), NOT_SUPPORT);
839 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
840 EXPECT_EQ(g_mgr.DeleteKvStore("InvalidQueryTest001"), OK);
841 g_kvNbDelegatePtr = nullptr;
842 }
843
844 /**
845 * @tc.name: InvalidQueryTest002
846 * @tc.desc: Test GetEntries with range query filter by sqlite while conn is nullptr.
847 * @tc.type: FUNC
848 * @tc.require:
849 * @tc.author: caihaoting
850 */
851 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, InvalidQueryTest002, TestSize.Level1)
852 {
853 /**
854 * @tc.steps: step1. initialize result set.
855 * @tc.expected: step1. Success.
856 */
857 KvStoreNbDelegate::Option option = {true, false, false};
858 g_mgr.GetKvStore("InvalidQueryTest002", option, g_kvNbDelegateCallback);
859 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
860 EXPECT_TRUE(g_kvDelegateStatus == OK);
861 InitResultSet();
862
863 /**
864 * @tc.steps: step2. get entries using result set while conn is nullptr.
865 * @tc.expected: step2. DB_ERROR.
866 */
867 KvStoreResultSet *readResultSet = nullptr;
868 auto kvStoreImpl = static_cast<KvStoreNbDelegateImpl *>(g_kvNbDelegatePtr);
869 EXPECT_EQ(kvStoreImpl->Close(), OK);
870 EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(g_keyPrefix, readResultSet), DB_ERROR);
871 ASSERT_TRUE(readResultSet == nullptr);
872
873 std::vector<Entry> entries;
874 Query query = Query::Select().PrefixKey({'a', 'c'});
875 EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(query, entries), DB_ERROR);
876 EXPECT_EQ(entries.size(), 0UL);
877
878 EXPECT_EQ(g_kvNbDelegatePtr->GetEntries(query, readResultSet), DB_ERROR);
879 ASSERT_TRUE(readResultSet == nullptr);
880
881 int count = -1;
882 EXPECT_EQ(g_kvNbDelegatePtr->GetCount(query, count), DB_ERROR);
883 EXPECT_EQ(count, -1);
884
885 /**
886 * @tc.steps: step3. close kvStore.
887 * @tc.expected: step3. Success.
888 */
889 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
890 EXPECT_EQ(g_mgr.DeleteKvStore("InvalidQueryTest002"), OK);
891 g_kvNbDelegatePtr = nullptr;
892 }
893
894 /**
895 * @tc.name: SyncRangeQuery001
896 * @tc.desc: test sync query with range
897 * @tc.type: FUNC
898 * @tc.require:
899 * @tc.author: mazhao
900 */
901 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, SyncRangeQuery001, TestSize.Level3)
902 {
903 /**
904 * @tc.steps:step1. Create database with localOnly.
905 * @tc.expected: step1. Returns a non-null store.
906 */
907 InitVirtualDevice(DEVICE_B, g_deviceB, g_syncInterfaceB);
908 KvStoreDelegateManager mgr(APP_ID, USER_ID);
909 mgr.SetKvStoreConfig(g_config);
910 const KvStoreNbDelegate::Option option = {true, false, false};
911 mgr.GetKvStore(STORE_ID_1, option, g_kvNbDelegateCallback);
912 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
913 EXPECT_EQ(g_kvDelegateStatus, OK);
914 /**
915 * @tc.steps:step2. Construct invalid query with range, Call sync async.
916 * @tc.expected: step2. returns NOT_SUPPORT.
917 */
918 std::vector<std::string> devices;
919 devices.emplace_back(DEVICE_B);
920 Query inValidQuery = Query::Select().Range({}, {});
921 DBStatus status = g_kvNbDelegatePtr->Sync(devices, SYNC_MODE_PULL_ONLY, nullptr, inValidQuery, true);
922 EXPECT_EQ(status, NOT_SUPPORT);
923 EXPECT_EQ(mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
924 g_kvNbDelegatePtr = nullptr;
925 EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK);
926 }
927
928 /**
929 * @tc.name: OptionValidCheck001
930 * @tc.desc: test validation of option mode
931 * @tc.type: FUNC
932 * @tc.require:
933 * @tc.author: zhangshijie
934 */
935 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, OptionModeValidCheck001, TestSize.Level1)
936 {
937 /**
938 * @tc.steps:step1. Get the nb delegate.
939 * @tc.expected: step1. Get results OK and non-null delegate.
940 */
941 KvStoreNbDelegate::Option option = {true, false, false};
942 KvStoreObserverUnitTest *observer = new KvStoreObserverUnitTest();
943 ASSERT_TRUE(observer != nullptr);
944 option.observer = observer;
945 std::vector<int> invalidModeVec = {0, 5, 6, 7, 9, 16};
946 std::string storeId = "OptionModeValidCheck001";
947 for (size_t i = 0; i < invalidModeVec.size(); i++) {
948 option.mode = invalidModeVec.at(i);
949 g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
950 ASSERT_TRUE(g_kvNbDelegatePtr == nullptr);
951 EXPECT_EQ(g_kvDelegateStatus, INVALID_ARGS);
952 }
953
954 std::vector<int> validModeVec = {1, 2, 3, 4, 8};
955 for (size_t i = 0; i < validModeVec.size(); i++) {
956 option.mode = validModeVec.at(i);
957 g_mgr.GetKvStore(storeId, option, g_kvNbDelegateCallback);
958 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
959 EXPECT_EQ(g_kvDelegateStatus, OK);
960 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
961 EXPECT_EQ(g_mgr.DeleteKvStore(storeId), OK);
962 g_kvNbDelegatePtr = nullptr;
963 }
964
965 delete observer;
966 }
967
968 /**
969 * @tc.name: AbnormalKvStoreTest001
970 * @tc.desc: Test KvStoreNbDelegateImpl interface while conn is nullptr.
971 * @tc.type: FUNC
972 * @tc.require:
973 * @tc.author: suyue
974 */
975 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, AbnormalKvStoreTest001, TestSize.Level1)
976 {
977 /**
978 * @tc.steps: step1. GetKvStore for initialize g_kvNbDelegatePtr.
979 * @tc.expected: step1. Success.
980 */
981 KvStoreNbDelegate::Option option = {true, false, false};
982 g_mgr.GetKvStore("AbnormalKvStoreTest001", option, g_kvNbDelegateCallback);
983 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
984 EXPECT_TRUE(g_kvDelegateStatus == OK);
985 InitResultSet();
986
987 /**
988 * @tc.steps: step2. test KvStoreNbDelegateImpl interface while conn is nullptr.
989 * @tc.expected: step2. return DB_ERROR.
990 */
991 auto kvStoreImpl = static_cast<KvStoreNbDelegateImpl *>(g_kvNbDelegatePtr);
992 EXPECT_EQ(kvStoreImpl->Close(), OK);
993
994 const Key key = {0};
995 EXPECT_EQ(kvStoreImpl->PublishLocal(key, true, true, nullptr), DB_ERROR);
996 EXPECT_EQ(kvStoreImpl->UnpublishToLocal(key, true, true), DB_ERROR);
997 EXPECT_EQ(kvStoreImpl->UnpublishToLocal({}, true, true), INVALID_ARGS);
998 EXPECT_EQ(kvStoreImpl->RemoveDeviceData(""), DB_ERROR);
999 EXPECT_EQ(kvStoreImpl->CancelSync(0), DB_ERROR);
1000 bool autoSync = true;
1001 PragmaData data = static_cast<PragmaData>(&autoSync);
1002 EXPECT_EQ(kvStoreImpl->Pragma(AUTO_SYNC, data), DB_ERROR);
1003 EXPECT_EQ(kvStoreImpl->SetConflictNotifier(0, nullptr), DB_ERROR);
1004 CipherPassword password;
1005 EXPECT_EQ(kvStoreImpl->Rekey(password), DB_ERROR);
1006 EXPECT_EQ(kvStoreImpl->Export("", password, true), DB_ERROR);
1007 EXPECT_EQ(kvStoreImpl->Import("", password), DB_ERROR);
1008 EXPECT_EQ(kvStoreImpl->StartTransaction(), DB_ERROR);
1009 EXPECT_EQ(kvStoreImpl->Commit(), DB_ERROR);
1010 EXPECT_EQ(kvStoreImpl->Rollback(), DB_ERROR);
1011 EXPECT_EQ(kvStoreImpl->CheckIntegrity(), DB_ERROR);
1012 SecurityOption securityOption;
1013 EXPECT_EQ(kvStoreImpl->GetSecurityOption(securityOption), DB_ERROR);
1014 EXPECT_EQ(kvStoreImpl->SetRemotePushFinishedNotify(nullptr), DB_ERROR);
1015 EXPECT_EQ(kvStoreImpl->SetEqualIdentifier("", {}), DB_ERROR);
1016 EXPECT_EQ(kvStoreImpl->SetPushDataInterceptor(nullptr), DB_ERROR);
1017
1018 /**
1019 * @tc.steps: step3. close kvStore.
1020 * @tc.expected: step3. Success.
1021 */
1022 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1023 EXPECT_EQ(g_mgr.DeleteKvStore("AbnormalKvStoreTest001"), OK);
1024 g_kvNbDelegatePtr = nullptr;
1025 }
1026
1027 /**
1028 * @tc.name: AbnormalKvStoreTest002
1029 * @tc.desc: Test KvStoreNbDelegateImpl interface while conn is nullptr.
1030 * @tc.type: FUNC
1031 * @tc.require:
1032 * @tc.author: suyue
1033 */
1034 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, AbnormalKvStoreTest002, TestSize.Level1)
1035 {
1036 /**
1037 * @tc.steps: step1. GetKvStore for initialize g_kvNbDelegatePtr.
1038 * @tc.expected: step1. Success.
1039 */
1040 KvStoreNbDelegate::Option option = {true, false, false};
1041 g_mgr.GetKvStore("AbnormalKvStoreTest002", option, g_kvNbDelegateCallback);
1042 ASSERT_TRUE(g_kvNbDelegatePtr != nullptr);
1043 EXPECT_TRUE(g_kvDelegateStatus == OK);
1044 InitResultSet();
1045
1046 /**
1047 * @tc.steps: step2. test KvStoreNbDelegateImpl interface while conn is nullptr.
1048 * @tc.expected: step2. return DB_ERROR.
1049 */
1050 auto kvStoreImpl = static_cast<KvStoreNbDelegateImpl *>(g_kvNbDelegatePtr);
1051 EXPECT_EQ(kvStoreImpl->Close(), OK);
1052
1053 Query query;
1054 EXPECT_EQ(kvStoreImpl->SubscribeRemoteQuery({}, nullptr, query, true), DB_ERROR);
1055 EXPECT_EQ(kvStoreImpl->UnSubscribeRemoteQuery({}, nullptr, query, true), DB_ERROR);
1056 EXPECT_EQ(kvStoreImpl->RemoveDeviceData(), DB_ERROR);
1057 const Key key = {0};
1058 std::vector<Key> keys;
1059 EXPECT_EQ(kvStoreImpl->GetKeys(key, keys), DB_ERROR);
1060 uint32_t expectedVal = 0;
1061 EXPECT_EQ(kvStoreImpl->GetSyncDataSize(""), expectedVal);
1062 EXPECT_EQ(kvStoreImpl->UpdateKey(nullptr), DB_ERROR);
1063 const std::string device = "test";
1064 std::pair<DBStatus, WatermarkInfo> info = kvStoreImpl->GetWatermarkInfo(device);
1065 EXPECT_EQ(info.first, DB_ERROR);
1066 EXPECT_EQ(kvStoreImpl->GetTaskCount(), DB_ERROR);
1067 EXPECT_EQ(kvStoreImpl->SetReceiveDataInterceptor(nullptr), DB_ERROR);
1068 CloudSyncConfig config;
1069 EXPECT_EQ(kvStoreImpl->SetCloudSyncConfig(config), DB_ERROR);
1070 const IOption iOption;
1071 std::vector<Entry> entries;
1072 EXPECT_EQ(kvStoreImpl->GetEntries(key, entries), DB_ERROR);
1073
1074 /**
1075 * @tc.steps: step3. close kvStore.
1076 * @tc.expected: step3. Success.
1077 */
1078 EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK);
1079 EXPECT_EQ(g_mgr.DeleteKvStore("AbnormalKvStoreTest002"), OK);
1080 g_kvNbDelegatePtr = nullptr;
1081 }
1082
1083 /**
1084 * @tc.name: AbnormalKvStoreResultSetTest
1085 * @tc.desc: Test KvStoreResultSetImpl interface when class para is nullptr.
1086 * @tc.type: FUNC
1087 * @tc.require:
1088 * @tc.author: suyue
1089 */
1090 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, AbnormalKvStoreResultSetTest, TestSize.Level1)
1091 {
1092 /**
1093 * @tc.steps: step1. Call interfaces when class para is null.
1094 * @tc.expected: step1. return failInfo.
1095 */
1096 KvStoreResultSetImpl kvStoreObj(nullptr);
1097 EXPECT_EQ(kvStoreObj.GetCount(), 0);
1098 EXPECT_EQ(kvStoreObj.GetPosition(), INIT_POSITION);
1099 EXPECT_EQ(kvStoreObj.Move(0), false);
1100 EXPECT_EQ(kvStoreObj.MoveToPosition(0), false);
1101 EXPECT_EQ(kvStoreObj.MoveToFirst(), false);
1102 EXPECT_EQ(kvStoreObj.MoveToLast(), false);
1103 EXPECT_EQ(kvStoreObj.IsFirst(), false);
1104 EXPECT_EQ(kvStoreObj.IsLast(), false);
1105 EXPECT_EQ(kvStoreObj.IsBeforeFirst(), false);
1106 EXPECT_EQ(kvStoreObj.IsAfterLast(), false);
1107 std::vector<std::string> columnNames;
1108 kvStoreObj.GetColumnNames(columnNames);
1109 Entry entry;
1110 EXPECT_EQ(kvStoreObj.GetEntry(entry), DB_ERROR);
1111 EXPECT_EQ(kvStoreObj.IsClosed(), false);
1112 kvStoreObj.Close();
1113
1114 /**
1115 * @tc.steps: step2. Call unsupported interfaces.
1116 * @tc.expected: step2. return NOT_SUPPORT.
1117 */
1118 std::string columnName;
1119 int columnIndex = 0;
1120 EXPECT_EQ(kvStoreObj.GetColumnIndex(columnName, columnIndex), NOT_SUPPORT);
1121 EXPECT_EQ(kvStoreObj.GetColumnName(columnIndex, columnName), NOT_SUPPORT);
1122 std::vector<uint8_t> vecVal;
1123 EXPECT_EQ(kvStoreObj.Get(columnIndex, vecVal), NOT_SUPPORT);
1124 std::string strVal;
1125 EXPECT_EQ(kvStoreObj.Get(columnIndex, strVal), NOT_SUPPORT);
1126 int64_t intVal;
1127 EXPECT_EQ(kvStoreObj.Get(columnIndex, intVal), NOT_SUPPORT);
1128 double doubleVal;
1129 EXPECT_EQ(kvStoreObj.Get(columnIndex, doubleVal), NOT_SUPPORT);
1130 bool isNull;
1131 EXPECT_EQ(kvStoreObj.IsColumnNull(columnIndex, isNull), NOT_SUPPORT);
1132 std::map<std::string, VariantData> data;
1133 EXPECT_EQ(kvStoreObj.GetRow(data), NOT_SUPPORT);
1134 }
1135
1136 /**
1137 * @tc.name: AbnormalKvStoreTest003
1138 * @tc.desc: Test SqliteCloudKvStore interface when para is invalid.
1139 * @tc.type: FUNC
1140 * @tc.require:
1141 * @tc.author: suyue
1142 */
1143 HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, AbnormalKvStoreTest003, TestSize.Level1)
1144 {
1145 /**
1146 * @tc.steps: step1. Call defaule interfaces.
1147 * @tc.expected: step1. return E_OK.
1148 */
1149 SqliteCloudKvStore kvStoreObj(nullptr);
1150 DataBaseSchema schema;
1151 EXPECT_EQ(kvStoreObj.SetCloudDbSchema(schema), E_OK);
1152 EXPECT_EQ(kvStoreObj.Commit(), E_OK);
1153 EXPECT_EQ(kvStoreObj.Rollback(), E_OK);
1154 const TableName tableName = "test";
1155 VBucket vBucket;
1156 EXPECT_EQ(kvStoreObj.FillCloudAssetForDownload(tableName, vBucket, true), E_OK);
1157 EXPECT_EQ(kvStoreObj.SetLogTriggerStatus(true), E_OK);
1158 QuerySyncObject query;
1159 EXPECT_EQ(kvStoreObj.CheckQueryValid(query), E_OK);
1160 ContinueToken continueStmtToken = nullptr;
1161 EXPECT_EQ(kvStoreObj.ReleaseCloudDataToken(continueStmtToken), E_OK);
1162 std::vector<QuerySyncObject> syncQuery;
1163 std::vector<std::string> users;
1164 EXPECT_EQ(kvStoreObj.GetCompensatedSyncQuery(syncQuery, users, true), E_OK);
1165
1166 /**
1167 * @tc.steps: step2. Get and set Schema with different para when class para is null.
1168 * @tc.expected: step2. return failInfo.
1169 */
1170 TableSchema tableSchema;
1171 EXPECT_EQ(kvStoreObj.GetCloudTableSchema(tableName, tableSchema), -E_NOT_FOUND);
1172 CloudSyncData cloudDataResult;
1173 EXPECT_EQ(kvStoreObj.GetCloudDataNext(continueStmtToken, cloudDataResult), -E_INVALID_ARGS);
1174 std::map<std::string, DataBaseSchema> schemaMap;
1175 EXPECT_EQ(kvStoreObj.SetCloudDbSchema(schemaMap), -E_INVALID_SCHEMA);
1176 schema.tables = {tableSchema, tableSchema};
1177 schemaMap.insert(std::pair<std::string, DataBaseSchema>(tableName, schema));
1178 EXPECT_EQ(kvStoreObj.SetCloudDbSchema(schemaMap), -E_INVALID_SCHEMA);
1179 const std::string user = "user1";
1180 kvStoreObj.SetUser(user);
1181 EXPECT_EQ(kvStoreObj.GetCloudTableSchema(tableName, tableSchema), -E_SCHEMA_MISMATCH);
1182 }
1183 }
1184