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