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