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