1 /*
2 * Copyright (c) 2022 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 #include <gtest/gtest.h>
16 #include <gmock/gmock.h>
17 #ifdef RUN_AS_ROOT
18 #include <sys/time.h>
19 #endif
20 #include <thread>
21
22 #include "db_common.h"
23 #include "distributeddb_tools_unit_test.h"
24 #include "generic_single_ver_kv_entry.h"
25 #include "message.h"
26 #include "mock_auto_launch.h"
27 #include "mock_communicator.h"
28 #include "mock_kv_sync_interface.h"
29 #include "mock_meta_data.h"
30 #include "mock_remote_executor.h"
31 #include "mock_single_ver_data_sync.h"
32 #include "mock_single_ver_kv_syncer.h"
33 #include "mock_single_ver_state_machine.h"
34 #include "mock_sync_engine.h"
35 #include "mock_sync_task_context.h"
36 #include "mock_time_sync.h"
37 #include "remote_executor_packet.h"
38 #include "single_ver_data_sync_utils.h"
39 #include "single_ver_kv_syncer.h"
40 #include "single_ver_relational_sync_task_context.h"
41 #include "virtual_communicator_aggregator.h"
42 #include "virtual_single_ver_sync_db_Interface.h"
43 #ifdef DATA_SYNC_CHECK_003
44 #include "virtual_relational_ver_sync_db_interface.h"
45 #endif
46
47 using namespace testing::ext;
48 using namespace testing;
49 using namespace DistributedDB;
50 using namespace DistributedDBUnitTest;
51 class TestKvDb {
52 public:
~TestKvDb()53 ~TestKvDb()
54 {
55 LOGI("~TestKvDb");
56 }
Initialize(ISyncInterface * syncInterface)57 void Initialize(ISyncInterface *syncInterface)
58 {
59 syncer_.Initialize(syncInterface, true);
60 syncer_.EnableAutoSync(true);
61 }
LocalChange()62 void LocalChange()
63 {
64 syncer_.LocalDataChanged(static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_PUT_EVENT));
65 }
Close()66 int Close()
67 {
68 return syncer_.Close(true);
69 }
70 private:
71 SyncerProxy syncer_;
72 };
73 class TestInterface : public TestKvDb, public VirtualSingleVerSyncDBInterface, public RefObject {
74 public:
TestInterface()75 TestInterface() {}
~TestInterface()76 ~TestInterface()
77 {
78 TestKvDb::Close();
79 }
Initialize()80 void Initialize()
81 {
82 TestKvDb::Initialize(this);
83 }
TestLocalChange()84 void TestLocalChange()
85 {
86 TestKvDb::LocalChange();
87 }
TestSetIdentifier(std::vector<uint8_t> & identifierVec)88 void TestSetIdentifier(std::vector<uint8_t> &identifierVec)
89 {
90 VirtualSingleVerSyncDBInterface::SetIdentifier(identifierVec);
91 }
92
IncRefCount()93 void IncRefCount() override
94 {
95 RefObject::IncObjRef(this);
96 }
97
DecRefCount()98 void DecRefCount() override
99 {
100 RefObject::DecObjRef(this);
101 }
102 };
103
104 namespace {
105 using State = SingleVerSyncStateMachine::State;
106 const uint32_t MESSAGE_COUNT = 10u;
107 const uint32_t EXECUTE_COUNT = 2u;
Init(MockSingleVerStateMachine & stateMachine,MockSyncTaskContext & syncTaskContext,MockCommunicator & communicator,VirtualSingleVerSyncDBInterface & dbSyncInterface)108 void Init(MockSingleVerStateMachine &stateMachine, MockSyncTaskContext &syncTaskContext, MockCommunicator &communicator,
109 VirtualSingleVerSyncDBInterface &dbSyncInterface)
110 {
111 std::shared_ptr<Metadata> metadata = std::make_shared<Metadata>();
112 ASSERT_EQ(metadata->Initialize(&dbSyncInterface), E_OK);
113 (void)syncTaskContext.Initialize("device", &dbSyncInterface, metadata, &communicator);
114 (void)stateMachine.Initialize(&syncTaskContext, &dbSyncInterface, metadata, &communicator);
115 }
116
Init(MockSingleVerStateMachine & stateMachine,MockSyncTaskContext * syncTaskContext,MockCommunicator & communicator,VirtualSingleVerSyncDBInterface * dbSyncInterface)117 void Init(MockSingleVerStateMachine &stateMachine, MockSyncTaskContext *syncTaskContext,
118 MockCommunicator &communicator, VirtualSingleVerSyncDBInterface *dbSyncInterface)
119 {
120 std::shared_ptr<Metadata> metadata = std::make_shared<Metadata>();
121 ASSERT_EQ(metadata->Initialize(dbSyncInterface), E_OK);
122 (void)syncTaskContext->Initialize("device", dbSyncInterface, metadata, &communicator);
123 (void)stateMachine.Initialize(syncTaskContext, dbSyncInterface, metadata, &communicator);
124 }
125
126 #ifdef RUN_AS_ROOT
ChangeTime(int sec)127 void ChangeTime(int sec)
128 {
129 timeval time;
130 gettimeofday(&time, nullptr);
131 time.tv_sec += sec;
132 settimeofday(&time, nullptr);
133 }
134 #endif
135
BuildRemoteQueryMsg(DistributedDB::Message * & message)136 int BuildRemoteQueryMsg(DistributedDB::Message *&message)
137 {
138 auto packet = RemoteExecutorRequestPacket::Create();
139 if (packet == nullptr) {
140 return -E_OUT_OF_MEMORY;
141 }
142 message = new (std::nothrow) DistributedDB::Message(static_cast<uint32_t>(MessageId::REMOTE_EXECUTE_MESSAGE));
143 if (message == nullptr) {
144 RemoteExecutorRequestPacket::Release(packet);
145 return -E_OUT_OF_MEMORY;
146 }
147 message->SetMessageType(TYPE_REQUEST);
148 packet->SetNeedResponse();
149 message->SetExternalObject(packet);
150 return E_OK;
151 }
152
ConstructPacel(Parcel & parcel,uint32_t conditionCount,const std::string & key,const std::string & value)153 void ConstructPacel(Parcel &parcel, uint32_t conditionCount, const std::string &key, const std::string &value)
154 {
155 parcel.WriteUInt32(RemoteExecutorRequestPacket::REQUEST_PACKET_VERSION_V2); // version
156 parcel.WriteUInt32(1); // flag
157 parcel.WriteInt(1); // current_version
158 parcel.WriteInt(1); // opcode
159 parcel.WriteString("sql"); // sql
160 parcel.WriteInt(1); // bandArgs_
161 parcel.WriteString("condition");
162 parcel.EightByteAlign();
163
164 parcel.WriteUInt32(conditionCount);
165 if (key.empty()) {
166 return;
167 }
168 parcel.WriteString(key);
169 parcel.WriteString(value);
170 }
171
StateMachineCheck013()172 void StateMachineCheck013()
173 {
174 MockSingleVerStateMachine stateMachine;
175 auto *syncTaskContext = new (std::nothrow) MockSyncTaskContext();
176 auto *dbSyncInterface = new (std::nothrow) VirtualSingleVerSyncDBInterface();
177 ASSERT_NE(syncTaskContext, nullptr);
178 EXPECT_NE(dbSyncInterface, nullptr);
179 if (dbSyncInterface == nullptr) {
180 RefObject::KillAndDecObjRef(syncTaskContext);
181 return;
182 }
183 MockCommunicator communicator;
184 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
185 int count = 0;
186 EXPECT_CALL(*syncTaskContext, Clear()).WillRepeatedly([&count]() {
187 count++;
188 });
189 syncTaskContext->RegForkGetDeviceIdFunc([]() {
190 std::this_thread::sleep_for(std::chrono::seconds(2)); // sleep 2s
191 });
192 auto token = new VirtualContinueToken();
193 syncTaskContext->SetContinueToken(static_cast<void *>(token));
194 RefObject::KillAndDecObjRef(syncTaskContext);
195 delete dbSyncInterface;
196 std::this_thread::sleep_for(std::chrono::seconds(5)); // sleep 5s and wait for task exist
197 EXPECT_EQ(count, 1);
198 }
199
AutoLaunchCheck001()200 void AutoLaunchCheck001()
201 {
202 MockAutoLaunch mockAutoLaunch;
203 /**
204 * @tc.steps: step1. put AutoLaunchItem in cache to simulate a connection was auto launched
205 */
206 std::string id = "TestAutoLaunch";
207 std::string userId = "userId";
208 AutoLaunchItem item;
209 mockAutoLaunch.SetAutoLaunchItem(id, userId, item);
210 EXPECT_CALL(mockAutoLaunch, TryCloseConnection(_)).WillOnce(Return());
211 /**
212 * @tc.steps: step2. send close signal to simulate a connection was unused in 1 min
213 * @tc.expected: 10 thread try to close the connection and one thread close success
214 */
215 const int loopCount = 10;
216 int finishCount = 0;
217 std::mutex mutex;
218 std::unique_lock<std::mutex> lock(mutex);
219 std::condition_variable cv;
220 for (int i = 0; i < loopCount; i++) {
221 std::thread t = std::thread([&finishCount, &mockAutoLaunch, &id, &userId, &mutex, &cv] {
222 mockAutoLaunch.CallExtConnectionLifeCycleCallbackTask(id, userId);
223 finishCount++;
224 if (finishCount == loopCount) {
225 std::unique_lock<std::mutex> lockInner(mutex);
226 cv.notify_one();
227 }
228 });
229 t.detach();
230 }
231 cv.wait(lock, [&finishCount, &loopCount]() { return finishCount == loopCount; });
232 }
233
AbilitySync004()234 void AbilitySync004()
235 {
236 /**
237 * @tc.steps: step1. set table TEST is permitSync
238 */
239 auto *context = new (std::nothrow) SingleVerKvSyncTaskContext();
240 ASSERT_NE(context, nullptr);
241 /**
242 * @tc.steps: step2. test context recv dbAbility in diff thread
243 */
244 const int loopCount = 1000;
245 std::atomic<int> finishCount = 0;
246 std::mutex mutex;
247 std::unique_lock<std::mutex> lock(mutex);
248 std::condition_variable cv;
249 for (int i = 0; i < loopCount; i++) {
250 std::thread t = std::thread([&] {
251 DbAbility dbAbility;
252 context->SetDbAbility(dbAbility);
253 finishCount++;
254 if (finishCount == loopCount) {
255 cv.notify_one();
256 }
257 });
258 t.detach();
259 }
260 cv.wait(lock, [&]() { return finishCount == loopCount; });
261 EXPECT_EQ(context->GetRemoteCompressAlgoStr(), "none");
262 RefObject::KillAndDecObjRef(context);
263 }
264
SyncLifeTest001()265 void SyncLifeTest001()
266 {
267 std::shared_ptr<SingleVerKVSyncer> syncer = std::make_shared<SingleVerKVSyncer>();
268 VirtualCommunicatorAggregator *virtualCommunicatorAggregator = new VirtualCommunicatorAggregator();
269 ASSERT_NE(virtualCommunicatorAggregator, nullptr);
270 RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator);
271 VirtualSingleVerSyncDBInterface *syncDBInterface = new VirtualSingleVerSyncDBInterface();
272 ASSERT_NE(syncDBInterface, nullptr);
273 EXPECT_EQ(syncer->Initialize(syncDBInterface, true), -E_INVALID_ARGS);
274 syncer->EnableAutoSync(true);
275 for (int i = 0; i < 1000; i++) { // trigger 1000 times auto sync check
276 syncer->LocalDataChanged(static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_PUT_EVENT));
277 }
278 EXPECT_EQ(virtualCommunicatorAggregator->GetOnlineDevices().size(), 0u);
279 syncer = nullptr;
280 RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
281 delete syncDBInterface;
282 }
283
SyncLifeTest002()284 void SyncLifeTest002()
285 {
286 std::shared_ptr<SingleVerKVSyncer> syncer = std::make_shared<SingleVerKVSyncer>();
287 VirtualCommunicatorAggregator *virtualCommunicatorAggregator = new VirtualCommunicatorAggregator();
288 ASSERT_NE(virtualCommunicatorAggregator, nullptr);
289 RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator);
290 const std::string DEVICE_B = "deviceB";
291 VirtualSingleVerSyncDBInterface *syncDBInterface = new VirtualSingleVerSyncDBInterface();
292 ASSERT_NE(syncDBInterface, nullptr);
293 std::string userId = "userid_0";
294 std::string storeId = "storeId_0";
295 std::string appId = "appid_0";
296 std::string identifier = KvStoreDelegateManager::GetKvStoreIdentifier(userId, appId, storeId);
297 std::vector<uint8_t> identifierVec(identifier.begin(), identifier.end());
298 syncDBInterface->SetIdentifier(identifierVec);
299 for (int i = 0; i < 100; i++) { // run 100 times
300 EXPECT_EQ(syncer->Initialize(syncDBInterface, true), E_OK);
301 syncer->EnableAutoSync(true);
302 virtualCommunicatorAggregator->OnlineDevice(DEVICE_B);
303 std::thread writeThread([syncer]() {
304 syncer->LocalDataChanged(
305 static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_PUT_EVENT));
306 });
307 std::thread closeThread([syncer, &syncDBInterface]() {
308 std::this_thread::sleep_for(std::chrono::milliseconds(1));
309 EXPECT_EQ(syncer->Close(true), E_OK);
310 });
311 closeThread.join();
312 writeThread.join();
313 }
314 syncer = nullptr;
315 std::this_thread::sleep_for(std::chrono::seconds(1));
316 RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
317 delete syncDBInterface;
318 }
319
SyncLifeTest003()320 void SyncLifeTest003()
321 {
322 VirtualCommunicatorAggregator *virtualCommunicatorAggregator = new VirtualCommunicatorAggregator();
323 ASSERT_NE(virtualCommunicatorAggregator, nullptr);
324 RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator);
325 TestInterface *syncDBInterface = new TestInterface();
326 ASSERT_NE(syncDBInterface, nullptr);
327 const std::string DEVICE_B = "deviceB";
328 std::string userId = "userId_0";
329 std::string storeId = "storeId_0";
330 std::string appId = "appId_0";
331 std::string identifier = KvStoreDelegateManager::GetKvStoreIdentifier(userId, appId, storeId);
332 std::vector<uint8_t> identifierVec(identifier.begin(), identifier.end());
333 syncDBInterface->TestSetIdentifier(identifierVec);
334 syncDBInterface->Initialize();
335 virtualCommunicatorAggregator->OnlineDevice(DEVICE_B);
336 syncDBInterface->TestLocalChange();
337 virtualCommunicatorAggregator->OfflineDevice(DEVICE_B);
338 EXPECT_EQ(syncDBInterface->Close(), E_OK);
339 RefObject::KillAndDecObjRef(syncDBInterface);
340 RuntimeContext::GetInstance()->StopTaskPool();
341 std::this_thread::sleep_for(std::chrono::seconds(1));
342 RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
343 }
344
MockRemoteQuery002()345 void MockRemoteQuery002()
346 {
347 MockRemoteExecutor *executor = new (std::nothrow) MockRemoteExecutor();
348 ASSERT_NE(executor, nullptr);
349 EXPECT_EQ(executor->CallResponseFailed(0, 0, 0, "DEVICE"), -E_BUSY);
350 RefObject::KillAndDecObjRef(executor);
351 }
352
SyncerCheck001()353 void SyncerCheck001()
354 {
355 std::shared_ptr<SingleVerKVSyncer> syncer = std::make_shared<SingleVerKVSyncer>();
356 EXPECT_EQ(syncer->SetSyncRetry(true), -E_NOT_INIT);
357 syncer = nullptr;
358 }
359
TimeSync001()360 void TimeSync001()
361 {
362 auto *communicator = new(std::nothrow) MockCommunicator();
363 ASSERT_NE(communicator, nullptr);
364 auto *storage = new(std::nothrow) VirtualSingleVerSyncDBInterface();
365 ASSERT_NE(storage, nullptr);
366 std::shared_ptr<Metadata> metadata = std::make_shared<Metadata>();
367
368 EXPECT_CALL(*communicator, SendMessage(_, _, _, _)).WillRepeatedly(Return(DB_ERROR));
369 const int loopCount = 100;
370 const int timeDriverMs = 100;
371 for (int i = 0; i < loopCount; ++i) {
372 MockTimeSync timeSync;
373 EXPECT_EQ(timeSync.Initialize(communicator, metadata, storage, "DEVICES_A"), E_OK);
374 EXPECT_CALL(timeSync, SyncStart).WillRepeatedly(Return(E_OK));
375 timeSync.ModifyTimer(timeDriverMs);
376 std::this_thread::sleep_for(std::chrono::milliseconds(timeDriverMs));
377 timeSync.Close();
378 }
379 std::this_thread::sleep_for(std::chrono::seconds(1));
380 metadata = nullptr;
381 delete storage;
382 delete communicator;
383 }
384
385 class DistributedDBMockSyncModuleTest : public testing::Test {
386 public:
387 static void SetUpTestCase(void);
388 static void TearDownTestCase(void);
389 void SetUp();
390 void TearDown();
391 };
392
SetUpTestCase(void)393 void DistributedDBMockSyncModuleTest::SetUpTestCase(void)
394 {
395 }
396
TearDownTestCase(void)397 void DistributedDBMockSyncModuleTest::TearDownTestCase(void)
398 {
399 }
400
SetUp(void)401 void DistributedDBMockSyncModuleTest::SetUp(void)
402 {
403 DistributedDBToolsUnitTest::PrintTestCaseInfo();
404 }
405
TearDown(void)406 void DistributedDBMockSyncModuleTest::TearDown(void)
407 {
408 }
409
410 /**
411 * @tc.name: StateMachineCheck001
412 * @tc.desc: Test machine do timeout when has same timerId.
413 * @tc.type: FUNC
414 * @tc.require: AR000CCPOM
415 * @tc.author: zhangqiquan
416 */
417 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck001, TestSize.Level1)
418 {
419 MockSingleVerStateMachine stateMachine;
420 MockSyncTaskContext syncTaskContext;
421 MockCommunicator communicator;
422 VirtualSingleVerSyncDBInterface dbSyncInterface;
423 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
424
425 TimerId expectId = 0;
426 TimerId actualId = expectId;
427 EXPECT_CALL(syncTaskContext, GetTimerId()).WillOnce(Return(expectId));
428 EXPECT_CALL(stateMachine, SwitchStateAndStep(_)).WillOnce(Return());
429
430 stateMachine.CallStepToTimeout(actualId);
431 }
432
433 /**
434 * @tc.name: StateMachineCheck002
435 * @tc.desc: Test machine do timeout when has diff timerId.
436 * @tc.type: FUNC
437 * @tc.require: AR000CCPOM
438 * @tc.author: zhangqiquan
439 */
440 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck002, TestSize.Level1)
441 {
442 MockSingleVerStateMachine stateMachine;
443 MockSyncTaskContext syncTaskContext;
444 MockCommunicator communicator;
445 VirtualSingleVerSyncDBInterface dbSyncInterface;
446 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
447
448 TimerId expectId = 0;
449 TimerId actualId = 1;
450 EXPECT_CALL(syncTaskContext, GetTimerId()).WillOnce(Return(expectId));
451 EXPECT_CALL(stateMachine, SwitchStateAndStep(_)).Times(0);
452
453 stateMachine.CallStepToTimeout(actualId);
454 }
455
456 /**
457 * @tc.name: StateMachineCheck003
458 * @tc.desc: Test machine exec next task when queue not empty.
459 * @tc.type: FUNC
460 * @tc.require: AR000CCPOM
461 * @tc.author: zhangqiquan
462 */
463 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck003, TestSize.Level1)
464 {
465 MockSingleVerStateMachine stateMachine;
466 MockSyncTaskContext syncTaskContext;
467 MockCommunicator communicator;
468 VirtualSingleVerSyncDBInterface dbSyncInterface;
469 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
470
471 syncTaskContext.SetLastRequestSessionId(1u);
472 EXPECT_CALL(syncTaskContext, IsTargetQueueEmpty()).WillRepeatedly(Return(false));
__anon44dd37990a02() 473 EXPECT_CALL(syncTaskContext, Clear()).WillRepeatedly([&syncTaskContext]() {
474 syncTaskContext.SetLastRequestSessionId(0u);
475 });
476 EXPECT_CALL(syncTaskContext, MoveToNextTarget()).WillRepeatedly(Return());
477 EXPECT_CALL(syncTaskContext, IsCurrentSyncTaskCanBeSkipped()).WillOnce(Return(true)).WillOnce(Return(false));
478 // we expect machine don't change context status when queue not empty
479 EXPECT_CALL(syncTaskContext, SetOperationStatus(_)).WillOnce(Return());
480 EXPECT_CALL(stateMachine, PrepareNextSyncTask()).WillOnce(Return(E_OK));
481 EXPECT_CALL(syncTaskContext, SetTaskExecStatus(_)).Times(0);
482
483 EXPECT_EQ(stateMachine.CallExecNextTask(), E_OK);
484 EXPECT_EQ(syncTaskContext.GetLastRequestSessionId(), 0u);
485 }
486
487 /**
488 * @tc.name: StateMachineCheck004
489 * @tc.desc: Test machine deal time sync ack failed.
490 * @tc.type: FUNC
491 * @tc.require: AR000CCPOM
492 * @tc.author: zhangqiquan
493 */
494 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck004, TestSize.Level1)
495 {
496 MockSingleVerStateMachine stateMachine;
497 MockSyncTaskContext syncTaskContext;
498 MockCommunicator communicator;
499 VirtualSingleVerSyncDBInterface dbSyncInterface;
500 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
501
502 DistributedDB::Message *message = new (std::nothrow) DistributedDB::Message();
503 ASSERT_NE(message, nullptr);
504 message->SetMessageType(TYPE_RESPONSE);
505 message->SetSessionId(1u);
506 EXPECT_CALL(syncTaskContext, GetRequestSessionId()).WillRepeatedly(Return(1u));
507 EXPECT_EQ(stateMachine.CallTimeMarkSyncRecv(message), -E_INVALID_ARGS);
508 EXPECT_EQ(syncTaskContext.GetTaskErrCode(), -E_INVALID_ARGS);
509 delete message;
510 }
511
512 /**
513 * @tc.name: StateMachineCheck005
514 * @tc.desc: Test machine recv errCode.
515 * @tc.type: FUNC
516 * @tc.require: AR000CCPOM
517 * @tc.author: zhangqiquan
518 */
519 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck005, TestSize.Level1)
520 {
521 MockSingleVerStateMachine stateMachine;
522 MockSyncTaskContext syncTaskContext;
523 MockCommunicator communicator;
524 VirtualSingleVerSyncDBInterface dbSyncInterface;
525 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
526 EXPECT_CALL(stateMachine, SwitchStateAndStep(_)).WillRepeatedly(Return());
527 EXPECT_CALL(syncTaskContext, GetRequestSessionId()).WillRepeatedly(Return(0u));
528
529 std::initializer_list<int> testCode = {-E_DISTRIBUTED_SCHEMA_CHANGED, -E_DISTRIBUTED_SCHEMA_NOT_FOUND};
530 for (int errCode : testCode) {
531 stateMachine.DataRecvErrCodeHandle(0, errCode);
532 EXPECT_EQ(syncTaskContext.GetTaskErrCode(), errCode);
533 stateMachine.CallDataAckRecvErrCodeHandle(errCode, true);
534 EXPECT_EQ(syncTaskContext.GetTaskErrCode(), errCode);
535 }
536 EXPECT_CALL(syncTaskContext, SetOperationStatus(_)).WillOnce(Return());
537 stateMachine.DataRecvErrCodeHandle(0, -E_NOT_PERMIT);
538 }
539
540 /**
541 * @tc.name: StateMachineCheck006
542 * @tc.desc: Test machine exec next task when queue not empty to empty.
543 * @tc.type: FUNC
544 * @tc.require: AR000CCPOM
545 * @tc.author: zhangqiquan
546 */
547 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck006, TestSize.Level1)
548 {
549 MockSingleVerStateMachine stateMachine;
550 MockSyncTaskContext syncTaskContext;
551 MockCommunicator communicator;
552 VirtualSingleVerSyncDBInterface dbSyncInterface;
553 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
554
555 syncTaskContext.CallSetSyncMode(QUERY_PUSH);
556 EXPECT_CALL(syncTaskContext, IsTargetQueueEmpty())
557 .WillOnce(Return(false))
558 .WillOnce(Return(true));
559 EXPECT_CALL(syncTaskContext, IsCurrentSyncTaskCanBeSkipped())
560 .WillRepeatedly(Return(syncTaskContext.CallIsCurrentSyncTaskCanBeSkipped()));
561 EXPECT_CALL(syncTaskContext, MoveToNextTarget()).WillOnce(Return());
562 // we expect machine don't change context status when queue not empty
563 EXPECT_CALL(syncTaskContext, SetOperationStatus(_)).WillOnce(Return());
564 EXPECT_CALL(syncTaskContext, SetTaskExecStatus(_)).WillOnce(Return());
565 EXPECT_CALL(syncTaskContext, Clear()).WillRepeatedly(Return());
566
567 EXPECT_EQ(stateMachine.CallExecNextTask(), -E_NO_SYNC_TASK);
568 }
569
570 /**
571 * @tc.name: StateMachineCheck007
572 * @tc.desc: Test machine DoSaveDataNotify in another thread.
573 * @tc.type: FUNC
574 * @tc.require: AR000CCPOM
575 * @tc.author: zhangqiquan
576 */
577 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck007, TestSize.Level3)
578 {
579 MockSingleVerStateMachine stateMachine;
580 uint8_t callCount = 0;
581 EXPECT_CALL(stateMachine, DoSaveDataNotify(_, _, _))
__anon44dd37990b02(uint32_t sessionId, uint32_t sequenceId, uint32_t inMsgId) 582 .WillRepeatedly([&callCount](uint32_t sessionId, uint32_t sequenceId, uint32_t inMsgId) {
583 (void) sessionId;
584 (void) sequenceId;
585 (void) inMsgId;
586 callCount++;
587 std::this_thread::sleep_for(std::chrono::seconds(4)); // sleep 4s
588 });
589 stateMachine.CallStartSaveDataNotify(0, 0, 0);
590 std::this_thread::sleep_for(std::chrono::seconds(5)); // sleep 5s
591 stateMachine.CallStopSaveDataNotify();
592 // timer is called once in 2s, we sleep 5s timer call twice
593 EXPECT_EQ(callCount, 2);
594 std::this_thread::sleep_for(std::chrono::seconds(10)); // sleep 10s to wait all thread exit
595 }
596
597 /**
598 * @tc.name: StateMachineCheck008
599 * @tc.desc: test machine process when last sync task send packet failed.
600 * @tc.type: FUNC
601 * @tc.require: AR000CCPOM
602 * @tc.author: zhuwentao
603 */
604 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck008, TestSize.Level1)
605 {
606 MockSingleVerStateMachine stateMachine;
607 MockSyncTaskContext syncTaskContext;
608 MockCommunicator communicator;
609 VirtualSingleVerSyncDBInterface dbSyncInterface;
610 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
611 syncTaskContext.CallCommErrHandlerFuncInner(-E_PERIPHERAL_INTERFACE_FAIL, 1u);
612 EXPECT_EQ(syncTaskContext.IsCommNormal(), true);
613 }
614
615 /**
616 * @tc.name: StateMachineCheck009
617 * @tc.desc: test machine process when last sync task send packet failed.
618 * @tc.type: FUNC
619 * @tc.require: AR000CCPOM
620 * @tc.author: zhuwentao
621 */
622 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck009, TestSize.Level1)
623 {
624 MockSingleVerStateMachine stateMachine;
625 MockSyncTaskContext syncTaskContext;
626 MockCommunicator communicator;
627 VirtualSingleVerSyncDBInterface dbSyncInterface;
628 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
629 stateMachine.CallSwitchMachineState(SingleVerSyncStateMachine::Event::START_SYNC_EVENT); // START_SYNC_EVENT
630 stateMachine.CommErrAbort(1u);
631 EXPECT_EQ(stateMachine.GetCurrentState(), State::TIME_SYNC);
632 }
633
634 /**
635 * @tc.name: StateMachineCheck010
636 * @tc.desc: test machine process when error happened in response pull.
637 * @tc.type: FUNC
638 * @tc.require: AR000CCPOM
639 * @tc.author: zhangqiquan
640 */
641 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck010, TestSize.Level1)
642 {
643 MockSingleVerStateMachine stateMachine;
644 MockSyncTaskContext syncTaskContext;
645 MockCommunicator communicator;
646 VirtualSingleVerSyncDBInterface dbSyncInterface;
647 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
648 EXPECT_CALL(stateMachine, SwitchStateAndStep(_)).WillOnce(Return());
649 stateMachine.CallResponsePullError(-E_BUSY, false);
650 EXPECT_EQ(syncTaskContext.GetTaskErrCode(), -E_BUSY);
651 }
652
653 /**
654 * @tc.name: StateMachineCheck011
655 * @tc.desc: test machine process when error happened in response pull.
656 * @tc.type: FUNC
657 * @tc.require: AR000CCPOM
658 * @tc.author: zhangqiquan
659 */
660 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck011, TestSize.Level1)
661 {
662 MockSingleVerStateMachine stateMachine;
663 MockSyncTaskContext syncTaskContext;
664 MockCommunicator communicator;
665 VirtualSingleVerSyncDBInterface dbSyncInterface;
666 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
667 syncTaskContext.CallSetTaskExecStatus(SyncTaskContext::RUNNING);
668 EXPECT_CALL(syncTaskContext, GetRequestSessionId()).WillOnce(Return(1u));
669 syncTaskContext.ClearAllSyncTask();
670 EXPECT_EQ(syncTaskContext.IsCommNormal(), false);
671 }
672
673 /**
674 * @tc.name: StateMachineCheck012
675 * @tc.desc: Verify Ability LastNotify AckReceive callback.
676 * @tc.type: FUNC
677 * @tc.require: AR000DR9K4
678 * @tc.author: zhangqiquan
679 */
680 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck012, TestSize.Level1)
681 {
682 MockSingleVerStateMachine stateMachine;
683 MockSyncTaskContext syncTaskContext;
684 MockCommunicator communicator;
685 VirtualSingleVerSyncDBInterface dbSyncInterface;
686 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
687 EXPECT_CALL(stateMachine, SwitchStateAndStep(_)).WillOnce(Return());
688 DistributedDB::Message msg(ABILITY_SYNC_MESSAGE);
689 msg.SetMessageType(TYPE_NOTIFY);
690 AbilitySyncAckPacket packet;
691 packet.SetProtocolVersion(ABILITY_SYNC_VERSION_V1);
692 packet.SetSoftwareVersion(SOFTWARE_VERSION_CURRENT);
693 packet.SetAckCode(-E_BUSY);
694 msg.SetCopiedObject(packet);
695 EXPECT_EQ(stateMachine.ReceiveMessageCallback(&msg), E_OK);
696 EXPECT_EQ(syncTaskContext.GetTaskErrCode(), -E_BUSY);
697 }
698
699 /**
700 * @tc.name: StateMachineCheck013
701 * @tc.desc: test kill syncTaskContext.
702 * @tc.type: FUNC
703 * @tc.require: AR000CCPOM
704 * @tc.author: zhangqiquan
705 */
706 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck013, TestSize.Level1)
707 {
708 ASSERT_NO_FATAL_FAILURE(StateMachineCheck013());
709 }
710
711 /**
712 * @tc.name: StateMachineCheck014
713 * @tc.desc: test machine stop save notify without start.
714 * @tc.type: FUNC
715 * @tc.require: AR000CCPOM
716 * @tc.author: zhangqiquan
717 */
718 HWTEST_F(DistributedDBMockSyncModuleTest, StateMachineCheck014, TestSize.Level1)
719 {
720 MockSingleVerStateMachine stateMachine;
721 stateMachine.CallStopSaveDataNotify();
722 EXPECT_EQ(stateMachine.GetSaveDataNotifyRefCount(), 0);
723 }
724
725 /**
726 * @tc.name: DataSyncCheck001
727 * @tc.desc: Test dataSync recv error ack.
728 * @tc.type: FUNC
729 * @tc.require: AR000CCPOM
730 * @tc.author: zhangqiquan
731 */
732 HWTEST_F(DistributedDBMockSyncModuleTest, DataSyncCheck001, TestSize.Level1)
733 {
734 SingleVerDataSync dataSync;
735 DistributedDB::Message *message = new (std::nothrow) DistributedDB::Message();
736 ASSERT_TRUE(message != nullptr);
737 message->SetErrorNo(E_FEEDBACK_COMMUNICATOR_NOT_FOUND);
738 EXPECT_EQ(dataSync.AckPacketIdCheck(message), true);
739 delete message;
740 }
741
742 /**
743 * @tc.name: DataSyncCheck002
744 * @tc.desc: Test dataSync recv notify ack.
745 * @tc.type: FUNC
746 * @tc.require: AR000CCPOM
747 * @tc.author: zhangqiquan
748 */
749 HWTEST_F(DistributedDBMockSyncModuleTest, DataSyncCheck002, TestSize.Level1)
750 {
751 SingleVerDataSync dataSync;
752 DistributedDB::Message *message = new (std::nothrow) DistributedDB::Message();
753 ASSERT_TRUE(message != nullptr);
754 message->SetMessageType(TYPE_NOTIFY);
755 EXPECT_EQ(dataSync.AckPacketIdCheck(message), true);
756 delete message;
757 }
758 #ifdef DATA_SYNC_CHECK_003
759 /**
760 * @tc.name: DataSyncCheck003
761 * @tc.desc: Test dataSync recv notify ack.
762 * @tc.type: FUNC
763 * @tc.require: AR000CCPOM
764 * @tc.author: zhangqiquan
765 */
766 HWTEST_F(DistributedDBMockSyncModuleTest, DataSyncCheck003, TestSize.Level1)
767 {
768 MockSingleVerDataSync mockDataSync;
769 MockSyncTaskContext mockSyncTaskContext;
770 auto mockMetadata = std::make_shared<MockMetadata>();
771 SyncTimeRange dataTimeRange = {1, 0, 1, 0};
772 mockDataSync.CallUpdateSendInfo(dataTimeRange, &mockSyncTaskContext);
773
774 VirtualRelationalVerSyncDBInterface storage;
775 MockCommunicator communicator;
776 std::shared_ptr<Metadata> metadata = std::static_pointer_cast<Metadata>(mockMetadata);
777 mockDataSync.Initialize(&storage, &communicator, metadata, "deviceId");
778
779 DistributedDB::Message *message = new (std::nothrow) DistributedDB::Message();
780 ASSERT_TRUE(message != nullptr);
781 DataAckPacket packet;
782 message->SetSequenceId(1);
783 message->SetCopiedObject(packet);
784 mockSyncTaskContext.SetQuerySync(true);
785
786 EXPECT_CALL(*mockMetadata, GetLastQueryTime(_, _, _)).WillOnce(Return(E_OK));
787 EXPECT_CALL(*mockMetadata, SetLastQueryTime(_, _, _))
788 .WillOnce([&dataTimeRange](
__anon44dd37990c02( const std::string &queryIdentify, const std::string &deviceId, const Timestamp ×tamp) 789 const std::string &queryIdentify, const std::string &deviceId, const Timestamp ×tamp) {
790 EXPECT_EQ(timestamp, dataTimeRange.endTime);
791 return E_OK;
792 });
793 EXPECT_CALL(mockSyncTaskContext, SetOperationStatus(_)).WillOnce(Return());
794 EXPECT_EQ(mockDataSync.TryContinueSync(&mockSyncTaskContext, message), -E_FINISHED);
795 delete message;
796 }
797 #endif
798
799 /**
800 * @tc.name: DataSyncCheck004
801 * @tc.desc: Test dataSync do ability sync.
802 * @tc.type: FUNC
803 * @tc.require:
804 * @tc.author: zhangqiquan
805 */
806 HWTEST_F(DistributedDBMockSyncModuleTest, DataSyncCheck004, TestSize.Level1)
807 {
808 MockSingleVerDataSync dataSync;
809 auto *message = new (std::nothrow) DistributedDB::Message();
810 ASSERT_TRUE(message != nullptr);
811 message->SetMessageType(TYPE_NOTIFY);
812 auto *context = new (std::nothrow) SingleVerKvSyncTaskContext();
813 ASSERT_NE(context, nullptr);
814 auto *communicator = new (std::nothrow) VirtualCommunicator("DEVICE", nullptr);
815 ASSERT_NE(communicator, nullptr);
816 dataSync.SetCommunicatorHandle(communicator);
817 EXPECT_EQ(dataSync.CallDoAbilitySyncIfNeed(context, message, false), -E_NEED_ABILITY_SYNC);
818 delete message;
819 RefObject::KillAndDecObjRef(context);
820 dataSync.SetCommunicatorHandle(nullptr);
821 RefObject::KillAndDecObjRef(communicator);
822 }
823
824 /**
825 * @tc.name: AutoLaunchCheck001
826 * @tc.desc: Test autoLaunch close connection.
827 * @tc.type: FUNC
828 * @tc.require: AR000CCPOM
829 * @tc.author: zhangqiquan
830 */
831 HWTEST_F(DistributedDBMockSyncModuleTest, AutoLaunchCheck001, TestSize.Level1)
832 {
833 ASSERT_NO_FATAL_FAILURE(AutoLaunchCheck001());
834 }
835
836 /**
837 * @tc.name: AutoLaunchCheck002
838 * @tc.desc: Test autoLaunch receive diff userId.
839 * @tc.type: FUNC
840 * @tc.require: AR000CCPOM
841 * @tc.author: zhangqiquan
842 */
843 HWTEST_F(DistributedDBMockSyncModuleTest, AutoLaunchCheck002, TestSize.Level1)
844 {
845 MockAutoLaunch mockAutoLaunch;
846 std::string id = "identify";
847 std::string userId0 = "USER0";
848 std::string userId1 = "USER1";
849 AutoLaunchItem item;
850 item.propertiesPtr = std::make_shared<KvDBProperties>();
851 mockAutoLaunch.SetWhiteListItem(id, userId0, item);
852 bool ext = false;
853 EXPECT_EQ(mockAutoLaunch.CallGetAutoLaunchItemUid(id, userId1, ext), userId0);
854 EXPECT_EQ(ext, false);
855 mockAutoLaunch.ClearWhiteList();
856 }
857
858 /**
859 * @tc.name: SyncDataSync001
860 * @tc.desc: Test request start when RemoveDeviceDataIfNeed failed.
861 * @tc.type: FUNC
862 * @tc.require: AR000CCPOM
863 * @tc.author: zhangqiquan
864 */
865 HWTEST_F(DistributedDBMockSyncModuleTest, SyncDataSync001, TestSize.Level1)
866 {
867 MockSyncTaskContext syncTaskContext;
868 MockSingleVerDataSync dataSync;
869
870 EXPECT_CALL(dataSync, RemoveDeviceDataIfNeed(_)).WillRepeatedly(Return(-E_BUSY));
871 EXPECT_EQ(dataSync.CallRequestStart(&syncTaskContext, PUSH), -E_BUSY);
872 EXPECT_EQ(syncTaskContext.GetTaskErrCode(), -E_BUSY);
873 }
874
875 /**
876 * @tc.name: SyncDataSync002
877 * @tc.desc: Test pull request start when RemoveDeviceDataIfNeed failed.
878 * @tc.type: FUNC
879 * @tc.require: AR000CCPOM
880 * @tc.author: zhangqiquan
881 */
882 HWTEST_F(DistributedDBMockSyncModuleTest, SyncDataSync002, TestSize.Level1)
883 {
884 MockSyncTaskContext syncTaskContext;
885 MockSingleVerDataSync dataSync;
886
887 EXPECT_CALL(dataSync, RemoveDeviceDataIfNeed(_)).WillRepeatedly(Return(-E_BUSY));
888 EXPECT_EQ(dataSync.CallPullRequestStart(&syncTaskContext), -E_BUSY);
889 EXPECT_EQ(syncTaskContext.GetTaskErrCode(), -E_BUSY);
890 }
891
892 /**
893 * @tc.name: SyncDataSync003
894 * @tc.desc: Test call RemoveDeviceDataIfNeed in diff thread.
895 * @tc.type: FUNC
896 * @tc.require: AR000CCPOM
897 * @tc.author: zhangqiquan
898 */
899 HWTEST_F(DistributedDBMockSyncModuleTest, SyncDataSync003, TestSize.Level1)
900 {
901 MockSyncTaskContext syncTaskContext;
902 MockSingleVerDataSync dataSync;
903
904 VirtualSingleVerSyncDBInterface storage;
905 MockCommunicator communicator;
906 std::shared_ptr<MockMetadata> mockMetadata = std::make_shared<MockMetadata>();
907 std::shared_ptr<Metadata> metadata = std::static_pointer_cast<Metadata>(mockMetadata);
908 metadata->Initialize(&storage);
909 const std::string deviceId = "deviceId";
910 dataSync.Initialize(&storage, &communicator, metadata, deviceId);
911 syncTaskContext.SetRemoteSoftwareVersion(SOFTWARE_VERSION_CURRENT);
912 syncTaskContext.Initialize(deviceId, &storage, metadata, &communicator);
913 syncTaskContext.EnableClearRemoteStaleData(true);
914
915 /**
916 * @tc.steps: step1. set diff db createtime for rebuild label in meta
917 */
918 metadata->SetDbCreateTime(deviceId, 1, true); // 1 is old db createTime
919 metadata->SetDbCreateTime(deviceId, 2, true); // 1 is new db createTime
920
921 DistributedDB::Key k1 = {'k', '1'};
922 DistributedDB::Value v1 = {'v', '1'};
923 DistributedDB::Key k2 = {'k', '2'};
924 DistributedDB::Value v2 = {'v', '2'};
925
926 /**
927 * @tc.steps: step2. call RemoveDeviceDataIfNeed in diff thread and then put data
928 */
__anon44dd37990d02() 929 std::thread thread1([&]() {
930 (void)dataSync.CallRemoveDeviceDataIfNeed(&syncTaskContext);
931 storage.PutDeviceData(deviceId, k1, v1);
932 LOGD("PUT FINISH");
933 });
__anon44dd37990e02() 934 std::thread thread2([&]() {
935 (void)dataSync.CallRemoveDeviceDataIfNeed(&syncTaskContext);
936 storage.PutDeviceData(deviceId, k2, v2);
937 LOGD("PUT FINISH");
938 });
939 thread1.join();
940 thread2.join();
941
942 DistributedDB::Value actualValue;
943 storage.GetDeviceData(deviceId, k1, actualValue);
944 EXPECT_EQ(v1, actualValue);
945 storage.GetDeviceData(deviceId, k2, actualValue);
946 EXPECT_EQ(v2, actualValue);
947 }
948
949 /**
950 * @tc.name: AbilitySync001
951 * @tc.desc: Test abilitySync abort when recv error.
952 * @tc.type: FUNC
953 * @tc.require: AR000CCPOM
954 * @tc.author: zhangqiquan
955 */
956 HWTEST_F(DistributedDBMockSyncModuleTest, AbilitySync001, TestSize.Level1)
957 {
958 MockSyncTaskContext syncTaskContext;
959 AbilitySync abilitySync;
960
961 DistributedDB::Message *message = new (std::nothrow) DistributedDB::Message();
962 ASSERT_TRUE(message != nullptr);
963 AbilitySyncAckPacket packet;
964 packet.SetAckCode(-E_BUSY);
965 message->SetCopiedObject(packet);
966 EXPECT_EQ(abilitySync.AckRecv(message, &syncTaskContext), -E_BUSY);
967 delete message;
968 EXPECT_EQ(syncTaskContext.GetTaskErrCode(), -E_BUSY);
969 }
970
971 /**
972 * @tc.name: AbilitySync002
973 * @tc.desc: Test abilitySync abort when save meta failed.
974 * @tc.type: FUNC
975 * @tc.require: AR000CCPOM
976 * @tc.author: zhangqiquan
977 */
978 HWTEST_F(DistributedDBMockSyncModuleTest, AbilitySync002, TestSize.Level1)
979 {
980 MockSyncTaskContext syncTaskContext;
981 AbilitySync abilitySync;
982 MockCommunicator comunicator;
983 VirtualSingleVerSyncDBInterface syncDBInterface;
984 std::shared_ptr<Metadata> metaData = std::make_shared<Metadata>();
985 metaData->Initialize(&syncDBInterface);
986 abilitySync.Initialize(&comunicator, &syncDBInterface, metaData, "deviceId");
987
988 /**
989 * @tc.steps: step1. set AbilitySyncAckPacket ackCode is E_OK for pass the ack check
990 */
991 DistributedDB::Message *message = new (std::nothrow) DistributedDB::Message();
992 ASSERT_TRUE(message != nullptr);
993 AbilitySyncAckPacket packet;
994 packet.SetAckCode(E_OK);
995 packet.SetSoftwareVersion(SOFTWARE_VERSION_CURRENT);
996 message->SetCopiedObject(packet);
997 /**
998 * @tc.steps: step2. set syncDBInterface busy for save data return -E_BUSY
999 */
1000 syncDBInterface.SetBusy(true);
1001 EXPECT_CALL(syncTaskContext, GetSchemaSyncStatus(_)).Times(0);
1002 EXPECT_EQ(abilitySync.AckRecv(message, &syncTaskContext), -E_BUSY);
1003 delete message;
1004 EXPECT_EQ(syncTaskContext.GetTaskErrCode(), -E_BUSY);
1005 }
1006
1007 /**
1008 * @tc.name: AbilitySync002
1009 * @tc.desc: Test abilitySync when offline.
1010 * @tc.type: FUNC
1011 * @tc.require: AR000CCPOM
1012 * @tc.author: zhangqiquan
1013 */
1014 HWTEST_F(DistributedDBMockSyncModuleTest, AbilitySync003, TestSize.Level1)
1015 {
1016 /**
1017 * @tc.steps: step1. set table TEST is permitSync
1018 */
1019 SingleVerRelationalSyncTaskContext *context = new (std::nothrow) SingleVerRelationalSyncTaskContext();
1020 ASSERT_NE(context, nullptr);
1021 RelationalSyncStrategy strategy;
1022 const std::string tableName = "TEST";
1023 strategy[tableName] = {true, true, true};
1024 context->SetRelationalSyncStrategy(strategy, true);
1025 QuerySyncObject query;
1026 query.SetTableName(tableName);
1027 /**
1028 * @tc.steps: step2. set table is need reset ability sync but it still permit sync
1029 */
1030 context->SetIsNeedResetAbilitySync(true);
1031 EXPECT_EQ(context->GetSchemaSyncStatus(query).first, true);
1032 /**
1033 * @tc.steps: step3. set table is schema change now it don't permit sync
1034 */
1035 context->SchemaChange();
1036 EXPECT_EQ(context->GetSchemaSyncStatus(query).first, false);
1037 RefObject::KillAndDecObjRef(context);
1038 }
1039
1040 /**
1041 * @tc.name: AbilitySync004
1042 * @tc.desc: Test abilitySync when offline.
1043 * @tc.type: FUNC
1044 * @tc.require: AR000CCPOM
1045 * @tc.author: zhangqiquan
1046 */
1047 HWTEST_F(DistributedDBMockSyncModuleTest, AbilitySync004, TestSize.Level1)
1048 {
1049 ASSERT_NO_FATAL_FAILURE(AbilitySync004());
1050 }
1051
1052 /**
1053 * @tc.name: SyncLifeTest001
1054 * @tc.desc: Test syncer alive when thread still exist.
1055 * @tc.type: FUNC
1056 * @tc.require: AR000CCPOM
1057 * @tc.author: zhangqiquan
1058 */
1059 HWTEST_F(DistributedDBMockSyncModuleTest, SyncLifeTest001, TestSize.Level3)
1060 {
1061 ASSERT_NO_FATAL_FAILURE(SyncLifeTest001());
1062 }
1063
1064 /**
1065 * @tc.name: SyncLifeTest002
1066 * @tc.desc: Test autosync when thread still exist.
1067 * @tc.type: FUNC
1068 * @tc.require: AR000CCPOM
1069 * @tc.author: zhuwentao
1070 */
1071 HWTEST_F(DistributedDBMockSyncModuleTest, SyncLifeTest002, TestSize.Level3)
1072 {
1073 ASSERT_NO_FATAL_FAILURE(SyncLifeTest002());
1074 }
1075
1076 /**
1077 * @tc.name: SyncLifeTest003
1078 * @tc.desc: Test syncer localdatachange when store is destructor
1079 * @tc.type: FUNC
1080 * @tc.require: AR000CCPOM
1081 * @tc.author: zhangqiquan
1082 */
1083 HWTEST_F(DistributedDBMockSyncModuleTest, SyncLifeTest003, TestSize.Level3)
1084 {
1085 ASSERT_NO_FATAL_FAILURE(SyncLifeTest003());
1086 }
1087
1088 /**
1089 * @tc.name: SyncLifeTest004
1090 * @tc.desc: Test syncer remote data change.
1091 * @tc.type: FUNC
1092 * @tc.require: AR000CCPOM
1093 * @tc.author: zhangqiquan
1094 */
1095 HWTEST_F(DistributedDBMockSyncModuleTest, SyncLifeTest004, TestSize.Level3)
1096 {
1097 std::shared_ptr<SingleVerKVSyncer> syncer = std::make_shared<SingleVerKVSyncer>();
1098 VirtualCommunicatorAggregator *virtualCommunicatorAggregator = new VirtualCommunicatorAggregator();
1099 RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator);
1100 auto syncDBInterface = new MockKvSyncInterface();
1101 int incRefCount = 0;
__anon44dd37990f02() 1102 EXPECT_CALL(*syncDBInterface, IncRefCount()).WillRepeatedly([&incRefCount]() {
1103 incRefCount++;
1104 });
1105 EXPECT_CALL(*syncDBInterface, DecRefCount()).WillRepeatedly(Return());
1106 std::vector<uint8_t> identifier(COMM_LABEL_LENGTH, 1u);
1107 syncDBInterface->SetIdentifier(identifier);
1108 syncer->Initialize(syncDBInterface, true);
1109 syncer->EnableAutoSync(true);
1110 incRefCount = 0;
1111 syncer->RemoteDataChanged("");
1112 std::this_thread::sleep_for(std::chrono::seconds(1));
1113 EXPECT_EQ(incRefCount, 2); // refCount is 2
1114 syncer = nullptr;
1115 RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
1116 delete syncDBInterface;
1117 RuntimeContext::GetInstance()->StopTaskPool();
1118 }
1119
1120 /**
1121 * @tc.name: SyncLifeTest005
1122 * @tc.desc: Test syncer remote device offline.
1123 * @tc.type: FUNC
1124 * @tc.require: AR000CCPOM
1125 * @tc.author: zhangqiquan
1126 */
1127 HWTEST_F(DistributedDBMockSyncModuleTest, SyncLifeTest005, TestSize.Level3)
1128 {
1129 std::shared_ptr<SingleVerKVSyncer> syncer = std::make_shared<SingleVerKVSyncer>();
1130 VirtualCommunicatorAggregator *virtualCommunicatorAggregator = new VirtualCommunicatorAggregator();
1131 RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator);
1132 auto syncDBInterface = new MockKvSyncInterface();
1133 int incRefCount = 0;
__anon44dd37991002() 1134 EXPECT_CALL(*syncDBInterface, IncRefCount()).WillRepeatedly([&incRefCount]() {
1135 incRefCount++;
1136 });
1137 EXPECT_CALL(*syncDBInterface, DecRefCount()).WillRepeatedly(Return());
1138 std::vector<uint8_t> identifier(COMM_LABEL_LENGTH, 1u);
1139 syncDBInterface->SetIdentifier(identifier);
1140 syncer->Initialize(syncDBInterface, true);
1141 syncer->RemoteDeviceOffline("dev");
1142 std::this_thread::sleep_for(std::chrono::seconds(1));
1143 syncer = nullptr;
1144 RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
1145 delete syncDBInterface;
1146 EXPECT_EQ(incRefCount, 2); // refCount is 2
1147 }
1148
1149 /**
1150 * @tc.name: MessageScheduleTest001
1151 * @tc.desc: Test MessageSchedule stop timer when no message.
1152 * @tc.type: FUNC
1153 * @tc.require: AR000CCPOM
1154 * @tc.author: zhangqiquan
1155 */
1156 HWTEST_F(DistributedDBMockSyncModuleTest, MessageScheduleTest001, TestSize.Level1)
1157 {
1158 MockSyncTaskContext *context = new MockSyncTaskContext();
1159 ASSERT_NE(context, nullptr);
1160 context->SetRemoteSoftwareVersion(SOFTWARE_VERSION_CURRENT);
1161 bool last = false;
__anon44dd37991102() 1162 context->OnLastRef([&last]() {
1163 last = true;
1164 });
1165 SingleVerDataMessageSchedule schedule;
1166 bool isNeedHandle = false;
1167 bool isNeedContinue = false;
1168 schedule.MoveNextMsg(context, isNeedHandle, isNeedContinue);
1169 RefObject::KillAndDecObjRef(context);
1170 std::this_thread::sleep_for(std::chrono::seconds(1));
1171 EXPECT_TRUE(last);
1172 }
1173
1174 /**
1175 * @tc.name: SyncEngineTest001
1176 * @tc.desc: Test SyncEngine receive message when closing.
1177 * @tc.type: FUNC
1178 * @tc.require: AR000CCPOM
1179 * @tc.author: zhangqiquan
1180 */
1181 HWTEST_F(DistributedDBMockSyncModuleTest, SyncEngineTest001, TestSize.Level1)
1182 {
1183 std::unique_ptr<MockSyncEngine> enginePtr = std::make_unique<MockSyncEngine>();
1184 EXPECT_CALL(*enginePtr, CreateSyncTaskContext())
1185 .WillRepeatedly(Return(new (std::nothrow) SingleVerKvSyncTaskContext()));
1186 VirtualCommunicatorAggregator *virtualCommunicatorAggregator = new VirtualCommunicatorAggregator();
1187 MockKvSyncInterface syncDBInterface;
1188 EXPECT_CALL(syncDBInterface, IncRefCount()).WillRepeatedly(Return());
1189 EXPECT_CALL(syncDBInterface, DecRefCount()).WillRepeatedly(Return());
1190 std::vector<uint8_t> identifier(COMM_LABEL_LENGTH, 1u);
1191 syncDBInterface.SetIdentifier(identifier);
1192 std::shared_ptr<Metadata> metaData = std::make_shared<Metadata>();
1193 metaData->Initialize(&syncDBInterface);
1194 ASSERT_NE(virtualCommunicatorAggregator, nullptr);
1195 RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator);
1196 ISyncEngine::InitCallbackParam param = { nullptr, nullptr, nullptr };
1197 enginePtr->Initialize(&syncDBInterface, metaData, param);
1198 auto communicator =
1199 static_cast<VirtualCommunicator *>(virtualCommunicatorAggregator->GetCommunicator("real_device"));
1200 RefObject::IncObjRef(communicator);
__anon44dd37991202() 1201 std::thread thread1([&]() {
1202 if (communicator == nullptr) {
1203 return;
1204 }
1205 for (int count = 0; count < 100; count++) { // loop 100 times
1206 auto *message = new (std::nothrow) DistributedDB::Message();
1207 ASSERT_NE(message, nullptr);
1208 message->SetMessageId(LOCAL_DATA_CHANGED);
1209 message->SetErrorNo(E_FEEDBACK_UNKNOWN_MESSAGE);
1210 communicator->CallbackOnMessage("src", message);
1211 }
1212 });
__anon44dd37991302() 1213 std::thread thread2([&]() {
1214 std::this_thread::sleep_for(std::chrono::milliseconds(1));
1215 enginePtr->Close();
1216 });
1217 thread1.join();
1218 thread2.join();
1219
1220 LOGD("FINISHED");
1221 RefObject::KillAndDecObjRef(communicator);
1222 communicator = nullptr;
1223 enginePtr = nullptr;
1224 metaData = nullptr;
1225 RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
1226 virtualCommunicatorAggregator = nullptr;
1227 }
1228
1229 /**
1230 * @tc.name: SyncEngineTest002
1231 * @tc.desc: Test SyncEngine add sync operation.
1232 * @tc.type: FUNC
1233 * @tc.require: AR000CCPOM
1234 * @tc.author: zhangqiquan
1235 */
1236 HWTEST_F(DistributedDBMockSyncModuleTest, SyncEngineTest002, TestSize.Level1)
1237 {
1238 /**
1239 * @tc.steps: step1. prepare env
1240 */
1241 auto *enginePtr = new (std::nothrow) MockSyncEngine();
1242 ASSERT_NE(enginePtr, nullptr);
1243 EXPECT_CALL(*enginePtr, CreateSyncTaskContext())
__anon44dd37991402() 1244 .WillRepeatedly([]() {
1245 return new (std::nothrow) SingleVerKvSyncTaskContext();
1246 });
1247 VirtualCommunicatorAggregator *virtualCommunicatorAggregator = new VirtualCommunicatorAggregator();
1248 MockKvSyncInterface syncDBInterface;
1249 int syncInterfaceRefCount = 1;
__anon44dd37991502() 1250 EXPECT_CALL(syncDBInterface, IncRefCount()).WillRepeatedly([&syncInterfaceRefCount]() {
1251 syncInterfaceRefCount++;
1252 });
__anon44dd37991602() 1253 EXPECT_CALL(syncDBInterface, DecRefCount()).WillRepeatedly([&syncInterfaceRefCount]() {
1254 syncInterfaceRefCount--;
1255 });
1256 std::vector<uint8_t> identifier(COMM_LABEL_LENGTH, 1u);
1257 syncDBInterface.SetIdentifier(identifier);
1258 std::shared_ptr<Metadata> metaData = std::make_shared<Metadata>();
1259 ASSERT_NE(virtualCommunicatorAggregator, nullptr);
1260 RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator);
1261 ISyncEngine::InitCallbackParam param = { nullptr, nullptr, nullptr };
1262 enginePtr->Initialize(&syncDBInterface, metaData, param);
1263 /**
1264 * @tc.steps: step2. add sync operation for DEVICE_A and DEVICE_B. It will create two context for A and B
1265 */
1266 std::vector<std::string> devices = {
1267 "DEVICES_A", "DEVICES_B"
1268 };
1269 const int syncId = 1;
1270 auto operation = new (std::nothrow) SyncOperation(syncId, devices, 0, nullptr, false);
1271 if (operation != nullptr) {
1272 enginePtr->AddSyncOperation(operation);
1273 }
1274 /**
1275 * @tc.steps: step3. abort machine and both context will be released
1276 */
1277 syncInterfaceRefCount = 0;
1278 enginePtr->AbortMachineIfNeed(syncId);
1279 EXPECT_EQ(syncInterfaceRefCount, 0);
1280 enginePtr->Close();
1281
1282 RefObject::KillAndDecObjRef(enginePtr);
1283 enginePtr = nullptr;
1284 RefObject::KillAndDecObjRef(operation);
1285
1286 metaData = nullptr;
1287 RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
1288 virtualCommunicatorAggregator = nullptr;
1289 std::this_thread::sleep_for(std::chrono::seconds(1));
1290 RuntimeContext::GetInstance()->StopTaskPool();
1291 }
1292
1293 /**
1294 * @tc.name: SyncEngineTest003
1295 * @tc.desc: Test SyncEngine add block sync operation.
1296 * @tc.type: FUNC
1297 * @tc.require: AR000CCPOM
1298 * @tc.author: zhangqiquan
1299 */
1300 HWTEST_F(DistributedDBMockSyncModuleTest, SyncEngineTest003, TestSize.Level1)
1301 {
1302 auto *enginePtr = new (std::nothrow) MockSyncEngine();
1303 ASSERT_NE(enginePtr, nullptr);
1304 std::vector<std::string> devices = {
1305 "DEVICES_A", "DEVICES_B"
1306 };
1307 const int syncId = 1;
1308 auto operation = new (std::nothrow) SyncOperation(syncId, devices, 0, nullptr, true);
1309 ASSERT_NE(operation, nullptr);
1310 operation->Initialize();
1311 enginePtr->AddSyncOperation(operation);
1312 for (const auto &device: devices) {
1313 EXPECT_EQ(operation->GetStatus(device), static_cast<int>(SyncOperation::OP_BUSY_FAILURE));
1314 }
1315 RefObject::KillAndDecObjRef(operation);
1316 RefObject::KillAndDecObjRef(enginePtr);
1317 }
1318
1319 /**
1320 * @tc.name: remote query packet 001
1321 * @tc.desc: Test RemoteExecutorRequestPacket Serialization And DeSerialization
1322 * @tc.type: FUNC
1323 * @tc.require: AR000GK58G
1324 * @tc.author: zhangqiquan
1325 */
1326 HWTEST_F(DistributedDBMockSyncModuleTest, RemoteQueryPacket001, TestSize.Level1)
1327 {
1328 /**
1329 * @tc.steps: step1. create remoteExecutorRequestPacket
1330 */
1331 RemoteExecutorRequestPacket packet;
1332 std::map<std::string, std::string> extraCondition = { { "test", "testsql" } };
1333 packet.SetExtraConditions(extraCondition);
1334 packet.SetNeedResponse();
1335 packet.SetVersion(SOFTWARE_VERSION_RELEASE_6_0);
1336
1337 /**
1338 * @tc.steps: step2. serialization to parcel
1339 */
1340 std::vector<uint8_t> buffer(packet.CalculateLen());
1341 Parcel parcel(buffer.data(), buffer.size());
1342 ASSERT_EQ(packet.Serialization(parcel), E_OK);
1343 ASSERT_FALSE(parcel.IsError());
1344
1345 /**
1346 * @tc.steps: step3. deserialization from parcel
1347 */
1348 RemoteExecutorRequestPacket targetPacket;
1349 Parcel targetParcel(buffer.data(), buffer.size());
1350 ASSERT_EQ(targetPacket.DeSerialization(targetParcel), E_OK);
1351 ASSERT_FALSE(parcel.IsError());
1352
1353 /**
1354 * @tc.steps: step4. check packet is equal
1355 */
1356 EXPECT_EQ(packet.GetVersion(), targetPacket.GetVersion());
1357 EXPECT_EQ(packet.GetFlag(), targetPacket.GetFlag());
1358 }
1359
1360 /**
1361 * @tc.name: remote query packet 002
1362 * @tc.desc: Test RemoteExecutorAckPacket Serialization And DeSerialization
1363 * @tc.type: FUNC
1364 * @tc.require: AR000GK58G
1365 * @tc.author: zhangqiquan
1366 */
1367 HWTEST_F(DistributedDBMockSyncModuleTest, RemoteQueryPacket002, TestSize.Level1)
1368 {
1369 /**
1370 * @tc.steps: step1. create remoteExecutorRequestPacket
1371 */
1372 RemoteExecutorAckPacket packet;
1373 packet.SetLastAck();
1374 packet.SetAckCode(-E_INTERNAL_ERROR);
1375 packet.SetVersion(SOFTWARE_VERSION_RELEASE_6_0);
1376
1377 /**
1378 * @tc.steps: step2. serialization to parcel
1379 */
1380 std::vector<uint8_t> buffer(packet.CalculateLen());
1381 Parcel parcel(buffer.data(), buffer.size());
1382 ASSERT_EQ(packet.Serialization(parcel), E_OK);
1383 ASSERT_FALSE(parcel.IsError());
1384
1385 /**
1386 * @tc.steps: step3. deserialization from parcel
1387 */
1388 RemoteExecutorAckPacket targetPacket;
1389 Parcel targetParcel(buffer.data(), buffer.size());
1390 ASSERT_EQ(targetPacket.DeSerialization(targetParcel), E_OK);
1391 ASSERT_FALSE(parcel.IsError());
1392
1393 /**
1394 * @tc.steps: step4. check packet is equal
1395 */
1396 EXPECT_EQ(packet.GetVersion(), targetPacket.GetVersion());
1397 EXPECT_EQ(packet.GetFlag(), targetPacket.GetFlag());
1398 EXPECT_EQ(packet.GetAckCode(), targetPacket.GetAckCode());
1399 }
1400
1401 /**
1402 * @tc.name: remote query packet 003
1403 * @tc.desc: Test RemoteExecutorRequestPacket Serialization with invalid args
1404 * @tc.type: FUNC
1405 * @tc.require: AR000GK58G
1406 * @tc.author: zhangshijie
1407 */
1408 HWTEST_F(DistributedDBMockSyncModuleTest, RemoteQueryPacket003, TestSize.Level1)
1409 {
1410 /**
1411 * @tc.steps: step1. check E_INVALID_ARGS
1412 */
1413 RemoteExecutorRequestPacket packet;
1414 packet.SetNeedResponse();
1415 packet.SetVersion(SOFTWARE_VERSION_RELEASE_6_0);
1416
1417 std::vector<uint8_t> buffer(packet.CalculateLen());
1418 Parcel parcel(buffer.data(), buffer.size());
1419
1420 ASSERT_EQ(packet.Serialization(parcel), E_OK);
1421 std::map<std::string, std::string> extraCondition = { { "test", "testsql" } };
1422 packet.SetExtraConditions(extraCondition);
1423 EXPECT_EQ(packet.Serialization(parcel), -E_INVALID_ARGS);
1424
1425 std::string sql = "testsql";
1426 for (uint32_t i = 0; i < DBConstant::MAX_CONDITION_COUNT; i++) {
1427 extraCondition[std::to_string(i)] = sql;
1428 }
1429 packet.SetExtraConditions(extraCondition);
1430
1431 std::vector<uint8_t> buffer2(packet.CalculateLen());
1432 Parcel parcel2(buffer2.data(), buffer2.size());
1433 Parcel targetParcel2(buffer2.data(), buffer2.size());
1434 EXPECT_EQ(packet.Serialization(parcel2), -E_INVALID_ARGS);
1435
1436 extraCondition.erase("0");
1437 extraCondition.erase("1");
1438 extraCondition.erase("2");
1439 std::string bigKey(DBConstant::MAX_CONDITION_KEY_LEN + 1, 'a');
1440 extraCondition[bigKey] = sql;
1441 packet.SetExtraConditions(extraCondition);
1442 std::vector<uint8_t> buffer3(packet.CalculateLen());
1443 Parcel parcel3(buffer3.data(), buffer3.size());
1444 EXPECT_EQ(packet.Serialization(parcel3), -E_INVALID_ARGS);
1445
1446 std::string bigValue(DBConstant::MAX_CONDITION_VALUE_LEN + 1, 'a');
1447 extraCondition["1"] = bigValue;
1448 packet.SetExtraConditions(extraCondition);
1449 std::vector<uint8_t> buffer4(packet.CalculateLen());
1450 Parcel parcel4(buffer4.data(), buffer4.size());
1451 EXPECT_EQ(packet.Serialization(parcel4), -E_INVALID_ARGS);
1452 }
1453
1454 /**
1455 * @tc.name: remote query packet 004
1456 * @tc.desc: Test RemoteExecutorRequestPacket Deserialization with invalid args
1457 * @tc.type: FUNC
1458 * @tc.require: AR000GK58G
1459 * @tc.author: zhangshijie
1460 */
1461 HWTEST_F(DistributedDBMockSyncModuleTest, RemoteQueryPacket004, TestSize.Level1)
1462 {
1463 RemoteExecutorRequestPacket packet;
1464 packet.SetNeedResponse();
1465 packet.SetVersion(SOFTWARE_VERSION_RELEASE_6_0);
1466
1467 std::vector<uint8_t> buffer(packet.CalculateLen());
1468 RemoteExecutorRequestPacket targetPacket;
1469 Parcel targetParcel(buffer.data(), 3); // 3 is invalid len for deserialization
1470 EXPECT_EQ(targetPacket.DeSerialization(targetParcel), -E_INVALID_ARGS);
1471
1472 std::vector<uint8_t> buffer1(1024); // 1024 is buffer len for serialization
1473 Parcel parcel(buffer1.data(), buffer1.size());
1474 ConstructPacel(parcel, DBConstant::MAX_CONDITION_COUNT + 1, "", "");
1475 Parcel desParcel(buffer1.data(), buffer1.size());
1476 EXPECT_EQ(targetPacket.DeSerialization(desParcel), -E_INVALID_ARGS);
1477
1478 Parcel parcel2(buffer1.data(), buffer1.size());
1479 std::string bigKey(DBConstant::MAX_CONDITION_KEY_LEN + 1, 'a');
1480 ConstructPacel(parcel2, 1, bigKey, "");
1481 Parcel desParcel2(buffer1.data(), buffer1.size());
1482 EXPECT_EQ(targetPacket.DeSerialization(desParcel2), -E_INVALID_ARGS);
1483
1484 Parcel parcel3(buffer1.data(), buffer1.size());
1485 std::string bigValue(DBConstant::MAX_CONDITION_VALUE_LEN + 1, 'a');
1486 ConstructPacel(parcel3, 1, "1", bigValue);
1487 Parcel desParcel3(buffer1.data(), buffer1.size());
1488 EXPECT_EQ(targetPacket.DeSerialization(desParcel3), -E_INVALID_ARGS);
1489
1490 Parcel parcel4(buffer1.data(), buffer1.size());
1491 ConstructPacel(parcel4, 1, "1", "1");
1492 Parcel desParcel4(buffer1.data(), buffer1.size());
1493 EXPECT_EQ(targetPacket.DeSerialization(desParcel4), E_OK);
1494
1495 Parcel parcel5(buffer1.data(), buffer1.size());
1496 ConstructPacel(parcel5, 0, "", "");
1497 Parcel desParcel5(buffer1.data(), buffer1.size());
1498 EXPECT_EQ(targetPacket.DeSerialization(desParcel5), E_OK);
1499 }
1500
1501 /**
1502 * @tc.name: SingleVerKvEntryTest001
1503 * @tc.desc: Test SingleVerKvEntry Serialize and DeSerialize.
1504 * @tc.type: FUNC
1505 * @tc.require: AR000CCPOM
1506 * @tc.author: zhangqiquan
1507 */
1508 HWTEST_F(DistributedDBMockSyncModuleTest, SingleVerKvEntryTest001, TestSize.Level1)
1509 {
1510 std::vector<SingleVerKvEntry *> kvEntries;
1511 size_t len = 0u;
1512 for (size_t i = 0; i < DBConstant::MAX_NORMAL_PACK_ITEM_SIZE + 1; ++i) {
1513 auto entryPtr = new GenericSingleVerKvEntry();
1514 kvEntries.push_back(entryPtr);
1515 len += entryPtr->CalculateLen(SOFTWARE_VERSION_CURRENT);
1516 len = BYTE_8_ALIGN(len);
1517 }
1518 std::vector<uint8_t> srcData(len, 0);
1519 Parcel parcel(srcData.data(), srcData.size());
1520 EXPECT_EQ(GenericSingleVerKvEntry::SerializeDatas(kvEntries, parcel, SOFTWARE_VERSION_CURRENT), E_OK);
1521 parcel = Parcel(srcData.data(), srcData.size());
1522 EXPECT_EQ(GenericSingleVerKvEntry::DeSerializeDatas(kvEntries, parcel), 0);
1523 SingleVerKvEntry::Release(kvEntries);
1524 }
1525
1526 /**
1527 * @tc.name: mock remote query 001
1528 * @tc.desc: Test RemoteExecutor receive msg when closing
1529 * @tc.type: FUNC
1530 * @tc.require: AR000GK58G
1531 * @tc.author: zhangqiquan
1532 */
1533 HWTEST_F(DistributedDBMockSyncModuleTest, MockRemoteQuery001, TestSize.Level3)
1534 {
1535 MockRemoteExecutor *executor = new (std::nothrow) MockRemoteExecutor();
1536 ASSERT_NE(executor, nullptr);
1537 uint32_t count = 0u;
1538 EXPECT_CALL(*executor, ParseOneRequestMessage).WillRepeatedly(
__anon44dd37991702(const std::string &device, DistributedDB::Message *inMsg) 1539 [&count](const std::string &device, DistributedDB::Message *inMsg) {
1540 std::this_thread::sleep_for(std::chrono::seconds(5)); // mock one msg execute 5 s
1541 count++;
1542 });
1543 EXPECT_CALL(*executor, IsPacketValid).WillRepeatedly(Return(true));
1544 for (uint32_t i = 0; i < MESSAGE_COUNT; i++) {
1545 DistributedDB::Message *message = nullptr;
1546 EXPECT_EQ(BuildRemoteQueryMsg(message), E_OK);
1547 executor->ReceiveMessage("DEVICE", message);
1548 }
1549 std::this_thread::sleep_for(std::chrono::seconds(1));
1550 executor->Close();
1551 EXPECT_EQ(count, EXECUTE_COUNT);
1552 RefObject::KillAndDecObjRef(executor);
1553 }
1554
1555 /**
1556 * @tc.name: mock remote query 002
1557 * @tc.desc: Test RemoteExecutor response failed when closing
1558 * @tc.type: FUNC
1559 * @tc.require: AR000GK58G
1560 * @tc.author: zhangqiquan
1561 */
1562 HWTEST_F(DistributedDBMockSyncModuleTest, MockRemoteQuery002, TestSize.Level3)
1563 {
1564 ASSERT_NO_FATAL_FAILURE(MockRemoteQuery002());
1565 }
1566
1567 /**
1568 * @tc.name: SyncTaskContextCheck001
1569 * @tc.desc: test context check task can be skipped in push mode.
1570 * @tc.type: FUNC
1571 * @tc.require: AR000CCPOM
1572 * @tc.author: zhangqiquan
1573 */
1574 HWTEST_F(DistributedDBMockSyncModuleTest, SyncTaskContextCheck001, TestSize.Level1)
1575 {
1576 MockSyncTaskContext syncTaskContext;
1577 MockCommunicator communicator;
1578 VirtualSingleVerSyncDBInterface dbSyncInterface;
1579 std::shared_ptr<Metadata> metadata = std::make_shared<Metadata>();
1580 (void)syncTaskContext.Initialize("device", &dbSyncInterface, metadata, &communicator);
1581 syncTaskContext.SetLastFullSyncTaskStatus(SyncOperation::Status::OP_FINISHED_ALL);
1582 syncTaskContext.CallSetSyncMode(static_cast<int>(SyncModeType::PUSH));
1583 EXPECT_EQ(syncTaskContext.CallIsCurrentSyncTaskCanBeSkipped(), true);
1584 }
1585
1586 /**
1587 * @tc.name: SyncTaskContextCheck002
1588 * @tc.desc: test context check task can be skipped in push mode.
1589 * @tc.type: FUNC
1590 * @tc.require: AR000CCPOM
1591 * @tc.author: zhangqiquan
1592 */
1593 HWTEST_F(DistributedDBMockSyncModuleTest, SyncTaskContextCheck002, TestSize.Level1)
1594 {
1595 /**
1596 * @tc.steps: step1. create context and operation
1597 */
1598 auto syncTaskContext = new(std::nothrow) MockSyncTaskContext();
1599 ASSERT_NE(syncTaskContext, nullptr);
1600 auto operation = new SyncOperation(1u, {}, static_cast<int>(SyncModeType::QUERY_PUSH), nullptr, false);
1601 ASSERT_NE(operation, nullptr);
1602 QuerySyncObject querySyncObject;
1603 operation->SetQuery(querySyncObject);
1604 syncTaskContext->SetSyncOperation(operation);
1605 syncTaskContext->SetLastFullSyncTaskStatus(SyncOperation::Status::OP_FAILED);
1606 syncTaskContext->CallSetSyncMode(static_cast<int>(SyncModeType::QUERY_PUSH));
1607 EXPECT_CALL(*syncTaskContext, IsTargetQueueEmpty()).WillRepeatedly(Return(false));
1608
1609 const int loopCount = 1000;
1610 /**
1611 * @tc.steps: step2. loop 1000 times for writing data into lastQuerySyncTaskStatusMap_ async
1612 */
__anon44dd37991802() 1613 std::thread writeThread([&syncTaskContext]() {
1614 for (int i = 0; i < loopCount; ++i) {
1615 syncTaskContext->SaveLastPushTaskExecStatus(static_cast<int>(SyncOperation::Status::OP_FAILED));
1616 }
1617 });
1618 /**
1619 * @tc.steps: step3. loop 100000 times for clear lastQuerySyncTaskStatusMap_ async
1620 */
__anon44dd37991902() 1621 std::thread clearThread([&syncTaskContext]() {
1622 for (int i = 0; i < 100000; ++i) { // loop 100000 times
1623 syncTaskContext->ResetLastPushTaskStatus();
1624 }
1625 });
1626 /**
1627 * @tc.steps: step4. loop 1000 times for read data from lastQuerySyncTaskStatusMap_ async
1628 */
__anon44dd37991a02() 1629 std::thread readThread([&syncTaskContext]() {
1630 for (int i = 0; i < loopCount; ++i) {
1631 EXPECT_EQ(syncTaskContext->CallIsCurrentSyncTaskCanBeSkipped(), false);
1632 }
1633 });
1634 writeThread.join();
1635 clearThread.join();
1636 readThread.join();
1637 RefObject::KillAndDecObjRef(operation);
1638 syncTaskContext->SetSyncOperation(nullptr);
1639 RefObject::KillAndDecObjRef(syncTaskContext);
1640 }
1641
1642 /**
1643 * @tc.name: SyncTaskContextCheck003
1644 * @tc.desc: test context call on sync task add.
1645 * @tc.type: FUNC
1646 * @tc.require: AR000CCPOM
1647 * @tc.author: zhangqiquan
1648 */
1649 HWTEST_F(DistributedDBMockSyncModuleTest, SyncTaskContextCheck003, TestSize.Level1)
1650 {
1651 auto *syncTaskContext = new (std::nothrow) MockSyncTaskContext();
1652 syncTaskContext->CallSetTaskExecStatus(DistributedDB::ISyncTaskContext::RUNNING);
1653 int callCount = 0;
1654 std::condition_variable cv;
1655 std::mutex countMutex;
__anon44dd37991b02() 1656 syncTaskContext->RegOnSyncTask([&callCount, &countMutex, &cv]() {
1657 {
1658 std::lock_guard<std::mutex> autoLock(countMutex);
1659 callCount++;
1660 }
1661 cv.notify_one();
1662 return E_OK;
1663 });
1664 EXPECT_EQ(syncTaskContext->AddSyncTarget(nullptr), -E_INVALID_ARGS);
1665 auto target = new (std::nothrow) SingleVerSyncTarget();
1666 ASSERT_NE(target, nullptr);
1667 target->SetTaskType(ISyncTarget::REQUEST);
1668 EXPECT_EQ(syncTaskContext->AddSyncTarget(target), E_OK);
1669 {
1670 std::unique_lock<std::mutex> lock(countMutex);
__anon44dd37991c02() 1671 cv.wait_for(lock, std::chrono::seconds(5), [&callCount]() { // wait 5s
1672 return callCount > 0;
1673 });
1674 }
1675 EXPECT_EQ(callCount, 1);
1676 RefObject::KillAndDecObjRef(syncTaskContext);
1677 RuntimeContext::GetInstance()->StopTaskPool();
1678 }
1679
1680 /**
1681 * @tc.name: SyncTaskContextCheck004
1682 * @tc.desc: test context add sync task should not cancel current task.
1683 * @tc.type: FUNC
1684 * @tc.require: AR000CCPOM
1685 * @tc.author: zhangqiquan
1686 */
1687 HWTEST_F(DistributedDBMockSyncModuleTest, SyncTaskContextCheck004, TestSize.Level1)
1688 {
1689 /**
1690 * @tc.steps: step1. create context and target
1691 */
1692 auto *syncTaskContext = new (std::nothrow) MockSyncTaskContext();
1693 ASSERT_NE(syncTaskContext, nullptr);
1694 int beforeRetryTime = syncTaskContext->GetRetryTime();
1695 auto target = new (std::nothrow) SingleVerSyncTarget();
1696 ASSERT_NE(target, nullptr);
1697 target->SetTaskType(ISyncTarget::REQUEST);
1698 syncTaskContext->SetAutoSync(true);
1699 /**
1700 * @tc.steps: step2. add target
1701 * @tc.expected: retry time should not be changed
1702 */
1703 EXPECT_EQ(syncTaskContext->AddSyncTarget(target), E_OK);
1704 std::this_thread::sleep_for(std::chrono::seconds(1));
1705 int afterRetryTime = syncTaskContext->GetRetryTime();
1706 EXPECT_EQ(beforeRetryTime, afterRetryTime);
1707 /**
1708 * @tc.steps: step3. release resource
1709 */
1710 RefObject::KillAndDecObjRef(syncTaskContext);
1711 RuntimeContext::GetInstance()->StopTaskPool();
1712 }
1713
1714 /**
1715 * @tc.name: SyncTaskContextCheck005
1716 * @tc.desc: test context call get query id async.
1717 * @tc.type: FUNC
1718 * @tc.require: AR000CCPOM
1719 * @tc.author: zhangqiquan
1720 */
1721 HWTEST_F(DistributedDBMockSyncModuleTest, SyncTaskContextCheck005, TestSize.Level1)
1722 {
1723 /**
1724 * @tc.steps: step1. prepare context
1725 */
1726 auto context = new (std::nothrow) SingleVerRelationalSyncTaskContext();
1727 ASSERT_NE(context, nullptr);
1728 SingleVerSyncStateMachine stateMachine;
1729 VirtualCommunicator communicator("device", nullptr);
1730 VirtualSingleVerSyncDBInterface dbSyncInterface;
1731 std::shared_ptr<Metadata> metadata = std::make_shared<Metadata>();
1732 ASSERT_EQ(metadata->Initialize(&dbSyncInterface), E_OK);
1733 (void)context->Initialize("device", &dbSyncInterface, metadata, &communicator);
1734 (void)stateMachine.Initialize(context, &dbSyncInterface, metadata, &communicator);
1735
1736 for (int i = 0; i < 100; ++i) { // 100 sync target
1737 auto target = new (std::nothrow) SingleVerSyncTarget();
1738 ASSERT_NE(target, nullptr);
1739 target->SetTaskType(ISyncTarget::RESPONSE);
1740 EXPECT_EQ(context->AddSyncTarget(target), E_OK);
1741 }
__anon44dd37991d02() 1742 std::thread clearThread([context]() {
1743 for (int i = 0; i < 100; ++i) { // clear 100 times
1744 context->Clear();
1745 std::this_thread::sleep_for(std::chrono::milliseconds(1));
1746 }
1747 });
__anon44dd37991e02() 1748 std::thread getThread([context]() {
1749 for (int i = 0; i < 100; ++i) { // get 100 times
1750 (void) context->GetDeleteSyncId();
1751 (void) context->GetQuerySyncId();
1752 std::this_thread::sleep_for(std::chrono::milliseconds(1));
1753 }
1754 });
__anon44dd37991f02() 1755 std::thread copyThread([context]() {
1756 for (int i = 0; i < 100; ++i) { // move 100 times
1757 (void) context->MoveToNextTarget();
1758 std::this_thread::sleep_for(std::chrono::milliseconds(1));
1759 }
1760 });
1761 clearThread.join();
1762 getThread.join();
1763 copyThread.join();
1764 context->Clear();
1765 EXPECT_EQ(context->GetDeleteSyncId(), "");
1766 EXPECT_EQ(context->GetQuerySyncId(), "");
1767 RefObject::KillAndDecObjRef(context);
1768 }
1769
1770 /**
1771 * @tc.name: SyncTaskContextCheck006
1772 * @tc.desc: test context call get query id async.
1773 * @tc.type: FUNC
1774 * @tc.require: AR000CCPOM
1775 * @tc.author: zhangqiquan
1776 */
1777 HWTEST_F(DistributedDBMockSyncModuleTest, SyncTaskContextCheck006, TestSize.Level1)
1778 {
1779 /**
1780 * @tc.steps: step1. prepare context
1781 */
1782 auto context = new (std::nothrow) SingleVerRelationalSyncTaskContext();
1783 ASSERT_NE(context, nullptr);
1784 auto communicator = new (std::nothrow) VirtualCommunicator("device", nullptr);
1785 ASSERT_NE(communicator, nullptr);
1786 VirtualSingleVerSyncDBInterface dbSyncInterface;
1787 std::shared_ptr<Metadata> metadata = std::make_shared<Metadata>();
1788 ASSERT_EQ(metadata->Initialize(&dbSyncInterface), E_OK);
1789 (void)context->Initialize("device", &dbSyncInterface, metadata, communicator);
1790 /**
1791 * @tc.steps: step2. add sync target into context
1792 */
1793 auto target = new (std::nothrow) SingleVerSyncTarget();
1794 ASSERT_NE(target, nullptr);
1795 target->SetTaskType(ISyncTarget::RESPONSE);
1796 EXPECT_EQ(context->AddSyncTarget(target), E_OK);
1797 /**
1798 * @tc.steps: step3. move to next target
1799 * @tc.expected: retry time will be reset to zero
1800 */
1801 context->SetRetryTime(AUTO_RETRY_TIMES);
1802 context->MoveToNextTarget();
1803 EXPECT_EQ(context->GetRetryTime(), 0);
1804 context->Clear();
1805 RefObject::KillAndDecObjRef(context);
1806 RefObject::KillAndDecObjRef(communicator);
1807 }
1808 #ifdef RUN_AS_ROOT
1809 /**
1810 * @tc.name: TimeChangeListenerTest001
1811 * @tc.desc: Test RegisterTimeChangedLister.
1812 * @tc.type: FUNC
1813 * @tc.require: AR000CCPOM
1814 * @tc.author: zhangqiquan
1815 */
1816 HWTEST_F(DistributedDBMockSyncModuleTest, TimeChangeListenerTest001, TestSize.Level1)
1817 {
1818 SingleVerKVSyncer syncer;
1819 VirtualSingleVerSyncDBInterface syncDBInterface;
1820 KvDBProperties dbProperties;
1821 dbProperties.SetBoolProp(DBProperties::SYNC_DUAL_TUPLE_MODE, true);
1822 syncDBInterface.SetDbProperties(dbProperties);
1823 EXPECT_EQ(syncer.Initialize(&syncDBInterface, false), -E_NO_NEED_ACTIVE);
1824 std::this_thread::sleep_for(std::chrono::seconds(1)); // sleep 1s wait for time tick
1825 const std::string LOCAL_TIME_OFFSET_KEY = "localTimeOffset";
1826 std::vector<uint8_t> key;
1827 DBCommon::StringToVector(LOCAL_TIME_OFFSET_KEY, key);
1828 std::vector<uint8_t> beforeOffset;
1829 EXPECT_EQ(syncDBInterface.GetMetaData(key, beforeOffset), E_OK);
1830 ChangeTime(2); // increase 2s
1831 std::this_thread::sleep_for(std::chrono::seconds(1)); // sleep 1s wait for time tick
1832 std::vector<uint8_t> afterOffset;
1833 EXPECT_EQ(syncDBInterface.GetMetaData(key, afterOffset), E_OK);
1834 EXPECT_NE(beforeOffset, afterOffset);
1835 ChangeTime(-2); // decrease 2s
1836 }
1837 #endif
1838
1839 /**
1840 * @tc.name: TimeChangeListenerTest002
1841 * @tc.desc: Test TimeChange.
1842 * @tc.type: FUNC
1843 * @tc.require: AR000CCPOM
1844 * @tc.author: zhangqiquan
1845 */
1846 HWTEST_F(DistributedDBMockSyncModuleTest, TimeChangeListenerTest002, TestSize.Level1)
1847 {
1848 /**
1849 * @tc.steps: step1. create syncer without activation
1850 */
1851 MockSingleVerKVSyncer syncer;
1852 VirtualSingleVerSyncDBInterface syncDBInterface;
1853 KvDBProperties dbProperties;
1854 dbProperties.SetBoolProp(DBProperties::SYNC_DUAL_TUPLE_MODE, true);
1855 syncDBInterface.SetDbProperties(dbProperties);
1856 /**
1857 * @tc.steps: step2. trigger time change logic and reopen syncer at the same time
1858 * @tc.expected: no crash here
1859 */
1860 const int loopCount = 100;
__anon44dd37992002() 1861 std::thread timeChangeThread([&syncer]() {
1862 for (int i = 0; i < loopCount; ++i) {
1863 int64_t changeOffset = 1;
1864 syncer.CallRecordTimeChangeOffset(&changeOffset);
1865 }
1866 });
1867 for (int i = 0; i < loopCount; ++i) {
1868 EXPECT_EQ(syncer.Initialize(&syncDBInterface, false), -E_NO_NEED_ACTIVE);
1869 EXPECT_EQ(syncer.Close(true), -E_NOT_INIT);
1870 }
1871 timeChangeThread.join();
1872 }
1873
1874 /**
1875 * @tc.name: SyncerCheck001
1876 * @tc.desc: Test syncer call set sync retry before init.
1877 * @tc.type: FUNC
1878 * @tc.require: AR000CCPOM
1879 * @tc.author: zhangqiquan
1880 */
1881 HWTEST_F(DistributedDBMockSyncModuleTest, SyncerCheck001, TestSize.Level1)
1882 {
1883 ASSERT_NO_FATAL_FAILURE(SyncerCheck001());
1884 }
1885
1886 /**
1887 * @tc.name: SyncerCheck002
1888 * @tc.desc: Test syncer call get timestamp with close and open.
1889 * @tc.type: FUNC
1890 * @tc.require: AR000CCPOM
1891 * @tc.author: zhangqiquan
1892 */
1893 HWTEST_F(DistributedDBMockSyncModuleTest, SyncerCheck002, TestSize.Level1)
1894 {
1895 /**
1896 * @tc.steps: step1. create context and syncer
1897 */
1898 std::shared_ptr<SingleVerKVSyncer> syncer = std::make_shared<SingleVerKVSyncer>();
1899 auto virtualCommunicatorAggregator = new(std::nothrow) VirtualCommunicatorAggregator();
1900 ASSERT_NE(virtualCommunicatorAggregator, nullptr);
1901 auto syncDBInterface = new VirtualSingleVerSyncDBInterface();
1902 ASSERT_NE(syncDBInterface, nullptr);
1903 std::vector<uint8_t> identifier(COMM_LABEL_LENGTH, 1u);
1904 syncDBInterface->SetIdentifier(identifier);
1905 RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator);
1906 /**
1907 * @tc.steps: step2. get timestamp by syncer over and over again
1908 */
1909 std::atomic<bool> finish = false;
__anon44dd37992102() 1910 std::thread t([&finish, &syncer]() {
1911 while (!finish) {
1912 (void) syncer->GetTimestamp();
1913 }
1914 });
1915 /**
1916 * @tc.steps: step3. re init syncer over and over again
1917 * @tc.expected: step3. dont crash here.
1918 */
1919 for (int i = 0; i < 100; ++i) { // loop 100 times
1920 syncer->Initialize(syncDBInterface, false);
1921 syncer->Close(true);
1922 }
1923 finish = true;
1924 t.join();
1925 delete syncDBInterface;
1926 syncer = nullptr;
1927 RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
1928 RuntimeContext::GetInstance()->StopTaskPool();
1929 }
1930
1931 /**
1932 * @tc.name: SyncerCheck003
1933 * @tc.desc: Test syncer query auto sync.
1934 * @tc.type: FUNC
1935 * @tc.require: AR000CCPOM
1936 * @tc.author: zhangqiquan
1937 */
1938 HWTEST_F(DistributedDBMockSyncModuleTest, SyncerCheck003, TestSize.Level1)
1939 {
1940 MockSingleVerKVSyncer syncer;
1941 InternalSyncParma param;
1942 auto *engine = new(std::nothrow) MockSyncEngine();
1943 ASSERT_NE(engine, nullptr);
1944 auto *storage = new(std::nothrow) MockKvSyncInterface();
1945 ASSERT_NE(storage, nullptr);
1946 int incCount = 0;
1947 int decCount = 0;
__anon44dd37992202() 1948 EXPECT_CALL(*storage, IncRefCount).WillRepeatedly([&incCount]() {
1949 incCount++;
1950 });
__anon44dd37992302() 1951 EXPECT_CALL(*storage, DecRefCount).WillRepeatedly([&decCount]() {
1952 decCount++;
1953 });
1954 syncer.Init(engine, storage, true);
1955 syncer.CallQueryAutoSync(param);
1956 std::this_thread::sleep_for(std::chrono::seconds(1)); // sleep 1s
1957 RuntimeContext::GetInstance()->StopTaskPool();
1958 EXPECT_EQ(incCount, 1);
1959 EXPECT_EQ(decCount, 1);
1960 RefObject::KillAndDecObjRef(engine);
1961 delete storage;
1962 syncer.Init(nullptr, nullptr, false);
1963 }
1964
1965 /**
1966 * @tc.name: SyncerCheck004
1967 * @tc.desc: Test syncer call status check.
1968 * @tc.type: FUNC
1969 * @tc.require: AR000CCPOM
1970 * @tc.author: zhangqiquan
1971 */
1972 HWTEST_F(DistributedDBMockSyncModuleTest, SyncerCheck004, TestSize.Level1)
1973 {
1974 MockSingleVerKVSyncer syncer;
1975 EXPECT_EQ(syncer.CallStatusCheck(), -E_BUSY);
1976 }
1977
1978 /**
1979 * @tc.name: SyncerCheck005
1980 * @tc.desc: Test syncer call erase watermark without storage.
1981 * @tc.type: FUNC
1982 * @tc.require: AR000CCPOM
1983 * @tc.author: zhangqiquan
1984 */
1985 HWTEST_F(DistributedDBMockSyncModuleTest, SyncerCheck005, TestSize.Level1)
1986 {
1987 MockSingleVerKVSyncer syncer;
1988 std::shared_ptr<Metadata> metadata = std::make_shared<Metadata>();
1989 syncer.SetMetadata(metadata);
1990 EXPECT_EQ(syncer.EraseDeviceWaterMark("", true), -E_NOT_INIT);
1991 syncer.SetMetadata(nullptr);
1992 }
1993
1994 /**
1995 * @tc.name: SyncerCheck006
1996 * @tc.desc: Test syncer call init with busy.
1997 * @tc.type: FUNC
1998 * @tc.require: AR000CCPOM
1999 * @tc.author: zhangqiquan
2000 */
2001 HWTEST_F(DistributedDBMockSyncModuleTest, SyncerCheck006, TestSize.Level1)
2002 {
2003 std::shared_ptr<SingleVerKVSyncer> syncer = std::make_shared<SingleVerKVSyncer>();
2004 auto syncDBInterface = new VirtualSingleVerSyncDBInterface();
2005 ASSERT_NE(syncDBInterface, nullptr);
2006 syncDBInterface->SetBusy(true);
2007 EXPECT_EQ(syncer->Initialize(syncDBInterface, false), -E_BUSY);
2008 syncDBInterface->SetBusy(true);
2009 syncer = nullptr;
2010 delete syncDBInterface;
2011 }
2012
2013 /**
2014 * @tc.name: SyncerCheck007
2015 * @tc.desc: Test syncer get sync data size without syncer lock.
2016 * @tc.type: FUNC
2017 * @tc.require: AR000CCPOM
2018 * @tc.author: zhangqiquan
2019 */
2020 HWTEST_F(DistributedDBMockSyncModuleTest, SyncerCheck007, TestSize.Level1)
2021 {
2022 MockSingleVerKVSyncer syncer;
2023 auto mockMeta = std::make_shared<MockMetadata>();
2024 auto metadata = std::static_pointer_cast<Metadata>(mockMeta);
__anon44dd37992402(const DeviceID &, uint64_t &) 2025 EXPECT_CALL(*mockMeta, GetLocalWaterMark).WillRepeatedly([&syncer](const DeviceID &, uint64_t &) {
2026 syncer.TestSyncerLock();
2027 });
2028 syncer.SetMetadata(metadata);
2029 auto syncDBInterface = new VirtualSingleVerSyncDBInterface();
2030 ASSERT_NE(syncDBInterface, nullptr);
2031 syncer.Init(nullptr, syncDBInterface, true);
2032 size_t size = 0u;
2033 EXPECT_EQ(syncer.GetSyncDataSize("device", size), E_OK);
2034 syncer.SetMetadata(nullptr);
2035 delete syncDBInterface;
2036 }
2037
2038 /**
2039 * @tc.name: SessionId001
2040 * @tc.desc: Test syncer call set sync retry before init.
2041 * @tc.type: FUNC
2042 * @tc.require: AR000CCPOM
2043 * @tc.author: zhangqiquan
2044 */
2045 HWTEST_F(DistributedDBMockSyncModuleTest, SessionId001, TestSize.Level1)
2046 {
2047 auto context = new(std::nothrow) MockSyncTaskContext();
2048 ASSERT_NE(context, nullptr);
2049 const uint32_t sessionIdMaxValue = 0x8fffffffu;
2050 context->SetLastRequestSessionId(sessionIdMaxValue);
2051 EXPECT_LE(context->CallGenerateRequestSessionId(), sessionIdMaxValue);
2052 RefObject::KillAndDecObjRef(context);
2053 }
2054
2055 /**
2056 * @tc.name: TimeSync001
2057 * @tc.desc: Test syncer call set sync retry before init.
2058 * @tc.type: FUNC
2059 * @tc.require: AR000CCPOM
2060 * @tc.author: zhangqiquan
2061 */
2062 HWTEST_F(DistributedDBMockSyncModuleTest, TimeSync001, TestSize.Level1)
2063 {
2064 ASSERT_NO_FATAL_FAILURE(TimeSync001());
2065 }
2066
2067 /**
2068 * @tc.name: TimeSync002
2069 * @tc.desc: Test syncer call set sync retry before init.
2070 * @tc.type: FUNC
2071 * @tc.require:
2072 * @tc.author: zhangqiquan
2073 */
2074 HWTEST_F(DistributedDBMockSyncModuleTest, TimeSync002, TestSize.Level1)
2075 {
2076 auto *storage = new(std::nothrow) VirtualSingleVerSyncDBInterface();
2077 ASSERT_NE(storage, nullptr);
2078 auto *communicator = new(std::nothrow) MockCommunicator();
2079 ASSERT_NE(communicator, nullptr);
2080 std::shared_ptr<Metadata> metadata = std::make_shared<Metadata>();
2081
2082 MockTimeSync timeSync;
2083 EXPECT_CALL(timeSync, SyncStart).WillRepeatedly(Return(E_OK));
2084 EXPECT_EQ(timeSync.Initialize(communicator, metadata, storage, "DEVICES_A"), E_OK);
2085 const int loopCount = 100;
2086 const int timeDriverMs = 10;
2087 for (int i = 0; i < loopCount; ++i) {
2088 timeSync.ModifyTimer(timeDriverMs);
2089 std::this_thread::sleep_for(std::chrono::milliseconds(timeDriverMs));
2090 timeSync.CallResetTimer();
2091 }
2092 timeSync.Close();
2093 EXPECT_EQ(timeSync.CallIsClosed(), true);
2094 metadata = nullptr;
2095 delete storage;
2096 RefObject::KillAndDecObjRef(communicator);
2097 }
2098
2099 /**
2100 * @tc.name: SyncContextCheck001
2101 * @tc.desc: Test context time out logic.
2102 * @tc.type: FUNC
2103 * @tc.require: AR000CCPOM
2104 * @tc.author: zhangqiquan
2105 */
2106 HWTEST_F(DistributedDBMockSyncModuleTest, SyncContextCheck001, TestSize.Level1)
2107 {
2108 auto context = new (std::nothrow) MockSyncTaskContext();
2109 ASSERT_NE(context, nullptr);
__anon44dd37992502(TimerId id) 2110 context->SetTimeoutCallback([context](TimerId id) {
2111 EXPECT_EQ(id, 1u);
2112 EXPECT_EQ(context->GetUseCount(), 0);
2113 return E_OK;
2114 });
2115 EXPECT_EQ(context->CallTimeout(1u), E_OK);
2116 RefObject::KillAndDecObjRef(context);
2117 }
2118
2119 /**
2120 * @tc.name: SingleVerDataSyncUtils001
2121 * @tc.desc: Test translate item got diff timestamp.
2122 * @tc.type: FUNC
2123 * @tc.require: AR000CCPOM
2124 * @tc.author: zhangqiquan
2125 */
2126 HWTEST_F(DistributedDBMockSyncModuleTest, SingleVerDataSyncUtils001, TestSize.Level1)
2127 {
2128 MockSyncTaskContext context;
2129 MockCommunicator communicator;
2130 VirtualSingleVerSyncDBInterface dbSyncInterface;
2131 std::shared_ptr<Metadata> metadata = std::make_shared<Metadata>();
2132 (void)context.Initialize("device", &dbSyncInterface, metadata, &communicator);
2133
2134 std::vector<SendDataItem> data;
2135 for (int i = 0; i < 2; ++i) { // loop 2 times
2136 data.push_back(new(std::nothrow) GenericSingleVerKvEntry());
2137 data[i]->SetTimestamp(UINT64_MAX);
2138 }
2139 SingleVerDataSyncUtils::TransSendDataItemToLocal(&context, "", data);
2140 EXPECT_NE(data[0]->GetTimestamp(), data[1]->GetTimestamp());
2141 SingleVerKvEntry::Release(data);
2142 }
2143
2144 /**
2145 * @tc.name: SyncTimerResetTest001
2146 * @tc.desc: Test it will retrurn ok when sync with a timer already exists.
2147 * @tc.type: FUNC
2148 * @tc.require:
2149 * @tc.author: zhangshijie
2150 */
2151 HWTEST_F(DistributedDBMockSyncModuleTest, SyncTimerResetTest001, TestSize.Level1) {
2152 MockSingleVerStateMachine stateMachine;
2153 MockSyncTaskContext syncTaskContext;
2154 MockCommunicator communicator;
2155 VirtualSingleVerSyncDBInterface dbSyncInterface;
2156 Init(stateMachine, syncTaskContext, communicator, dbSyncInterface);
2157
2158 EXPECT_EQ(stateMachine.CallStartWatchDog(), E_OK);
2159 EXPECT_EQ(stateMachine.CallPrepareNextSyncTask(), E_OK);
2160 stateMachine.CallStopWatchDog();
2161 }
2162 }