1 /*
2 * Copyright (c) 2021 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 #ifdef RELATIONAL_STORE
16 #include <gtest/gtest.h>
17
18 #include "db_common.h"
19 #include "db_constant.h"
20 #include "distributeddb_data_generate_unit_test.h"
21 #include "distributeddb_tools_unit_test.h"
22 #include "isyncer.h"
23 #include "kv_virtual_device.h"
24 #include "platform_specific.h"
25 #include "process_system_api_adapter_impl.h"
26 #include "relational_schema_object.h"
27 #include "relational_store_manager.h"
28 #include "relational_virtual_device.h"
29 #include "runtime_config.h"
30 #include "virtual_relational_ver_sync_db_interface.h"
31
32 using namespace testing::ext;
33 using namespace DistributedDB;
34 using namespace DistributedDBUnitTest;
35
36 namespace {
37 const std::string DEVICE_A = "real_device";
38 const std::string DEVICE_B = "deviceB";
39 const std::string DEVICE_C = "deviceC";
40 const std::string DEVICE_D = "deviceD";
41 const std::string g_tableName = "TEST_TABLE";
42
43 #ifndef OMIT_ENCRYPT
44 bool g_isAfterRekey = false;
45 const string CORRECT_KEY = "a correct key";
46 CipherPassword g_correctPasswd;
47 const string REKEY_KEY = "a key after rekey";
48 CipherPassword g_rekeyPasswd;
49 const string INCORRECT_KEY = "a incorrect key";
50 CipherPassword g_incorrectPasswd;
51 const int DEFAULT_ITER = 5000;
52 #endif
53
54 const int ONE_HUNDERED = 100;
55 const char DEFAULT_CHAR = 'D';
56 const std::string DEFAULT_TEXT = "This is a text";
57 const std::vector<uint8_t> DEFAULT_BLOB(ONE_HUNDERED, DEFAULT_CHAR);
58 const std::string SHA1_ALGO_SQL = "PRAGMA codec_hmac_algo=SHA1";
59 const std::string SHA256_ALGO_SQL = "PRAGMA codec_hmac_algo=SHA256";
60 const std::string SHA256_ALGO_REKEY_SQL = "PRAGMA codec_rekey_hmac_algo=SHA256";
61
62 RelationalStoreManager g_mgr(APP_ID, USER_ID);
63 std::string g_testDir;
64 std::string g_dbDir;
65 std::string g_id;
66 std::vector<StorageType> g_storageType = {
67 StorageType::STORAGE_TYPE_INTEGER, StorageType::STORAGE_TYPE_REAL,
68 StorageType::STORAGE_TYPE_TEXT, StorageType::STORAGE_TYPE_BLOB
69 };
70 DistributedDBToolsUnitTest g_tool;
71 RelationalStoreDelegate* g_rdbDelegatePtr = nullptr;
72 VirtualCommunicatorAggregator* g_communicatorAggregator = nullptr;
73 RelationalVirtualDevice *g_deviceB = nullptr;
74 RelationalVirtualDevice *g_deviceC = nullptr;
75 KvVirtualDevice *g_deviceD = nullptr;
76 std::vector<FieldInfo> g_fieldInfoList;
77 RelationalStoreObserverUnitTest *g_observer = nullptr;
GetDeviceTableName(const std::string & tableName)78 std::string GetDeviceTableName(const std::string &tableName)
79 {
80 return "naturalbase_rdb_aux_" +
81 tableName + "_" + DBCommon::TransferStringToHex(DBCommon::TransferHashString(DEVICE_B));
82 }
83
OpenStore()84 void OpenStore()
85 {
86 if (g_observer == nullptr) {
87 g_observer = new (std::nothrow) RelationalStoreObserverUnitTest();
88 }
89 RelationalStoreDelegate::Option option;
90 option.observer = g_observer;
91 #ifndef OMIT_ENCRYPT
92 option.isEncryptedDb = true;
93 option.iterateTimes = DEFAULT_ITER;
94 option.passwd = g_isAfterRekey ? g_rekeyPasswd : g_correctPasswd;
95 option.cipher = CipherType::DEFAULT;
96 #endif
97 g_mgr.OpenStore(g_dbDir, STORE_ID_1, option, g_rdbDelegatePtr);
98 ASSERT_TRUE(g_rdbDelegatePtr != nullptr);
99 }
100
GetDB(sqlite3 * & db,bool isSha256Algo=true)101 int GetDB(sqlite3 *&db, bool isSha256Algo = true)
102 {
103 int flag = SQLITE_OPEN_URI | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
104 const auto &dbPath = g_dbDir;
105 int rc = sqlite3_open_v2(dbPath.c_str(), &db, flag, nullptr);
106 if (rc != SQLITE_OK) {
107 return rc;
108 }
109 #ifndef OMIT_ENCRYPT
110 string sql =
111 "PRAGMA key='" + (g_isAfterRekey ? REKEY_KEY : CORRECT_KEY) + "';"
112 "PRAGMA codec_kdf_iter=" + std::to_string(DEFAULT_ITER) + ";";
113 EXPECT_EQ(sqlite3_exec(db, sql.c_str(), nullptr, nullptr, nullptr), SQLITE_OK);
114 if (isSha256Algo) {
115 EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, SHA256_ALGO_SQL), E_OK);
116 } else {
117 EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, SHA1_ALGO_SQL), E_OK);
118 }
119 EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, SHA256_ALGO_REKEY_SQL), E_OK);
120 #endif
121 EXPECT_EQ(SQLiteUtils::RegisterCalcHash(db), E_OK);
122 EXPECT_EQ(SQLiteUtils::RegisterGetSysTime(db), E_OK);
123 EXPECT_EQ(sqlite3_exec(db, "PRAGMA journal_mode=WAL;", nullptr, nullptr, nullptr), SQLITE_OK);
124 return rc;
125 }
126
GetType(StorageType type)127 std::string GetType(StorageType type)
128 {
129 static std::map<StorageType, std::string> typeMap = {
130 {StorageType::STORAGE_TYPE_INTEGER, "INT"},
131 {StorageType::STORAGE_TYPE_REAL, "DOUBLE"},
132 {StorageType::STORAGE_TYPE_TEXT, "TEXT"},
133 {StorageType::STORAGE_TYPE_BLOB, "BLOB"}
134 };
135 if (typeMap.find(type) == typeMap.end()) {
136 type = StorageType::STORAGE_TYPE_INTEGER;
137 }
138 return typeMap[type];
139 }
140
DropTable(sqlite3 * db,const std::string & tableName)141 int DropTable(sqlite3 *db, const std::string &tableName)
142 {
143 std::string sql = "DROP TABLE " + tableName + ";";
144 return sqlite3_exec(db, sql.c_str(), nullptr, nullptr, nullptr);
145 }
146
CreateTable(sqlite3 * db,const std::vector<FieldInfo> & fieldInfoList,const std::string & tableName)147 int CreateTable(sqlite3 *db, const std::vector<FieldInfo> &fieldInfoList, const std::string &tableName)
148 {
149 std::string sql = "CREATE TABLE " + tableName + "(";
150 int index = 0;
151 for (const auto &field : fieldInfoList) {
152 if (index != 0) {
153 sql += ",";
154 }
155 sql += field.GetFieldName() + " ";
156 std::string type = GetType(field.GetStorageType());
157 sql += type + " ";
158 if (index == 0) {
159 sql += "PRIMARY KEY NOT NULL ";
160 }
161 index++;
162 }
163 sql += ");";
164 int rc = sqlite3_exec(db, sql.c_str(), nullptr, nullptr, nullptr);
165 return rc;
166 }
167
PrepareInsert(sqlite3 * db,sqlite3_stmt * & statement,std::vector<FieldInfo> fieldInfoList,const std::string & tableName)168 int PrepareInsert(sqlite3 *db, sqlite3_stmt *&statement,
169 std::vector<FieldInfo> fieldInfoList, const std::string &tableName)
170 {
171 std::string sql = "INSERT OR REPLACE INTO " + tableName + "(";
172 int index = 0;
173 for (const auto &fieldInfo : fieldInfoList) {
174 if (index != 0) {
175 sql += ",";
176 }
177 sql += fieldInfo.GetFieldName();
178 index++;
179 }
180 sql += ") VALUES (";
181 while (index > 0) {
182 sql += "?";
183 if (index != 1) {
184 sql += ", ";
185 }
186 index--;
187 }
188 sql += ");";
189 return sqlite3_prepare_v2(db, sql.c_str(), -1, &statement, nullptr);
190 }
191
SimulateCommitData(sqlite3 * db,sqlite3_stmt * & statement)192 int SimulateCommitData(sqlite3 *db, sqlite3_stmt *&statement)
193 {
194 sqlite3_exec(db, "BEGIN IMMEDIATE TRANSACTION", nullptr, nullptr, nullptr);
195
196 int rc = sqlite3_step(statement);
197
198 sqlite3_exec(db, "COMMIT TRANSACTION", nullptr, nullptr, nullptr);
199 return rc;
200 }
201
BindValue(const DataValue & item,sqlite3_stmt * stmt,int col)202 void BindValue(const DataValue &item, sqlite3_stmt *stmt, int col)
203 {
204 switch (item.GetType()) {
205 case StorageType::STORAGE_TYPE_INTEGER: {
206 int64_t intData = 0;
207 (void)item.GetInt64(intData);
208 EXPECT_EQ(sqlite3_bind_int64(stmt, col, intData), SQLITE_OK);
209 break;
210 }
211
212 case StorageType::STORAGE_TYPE_REAL: {
213 double doubleData = 0;
214 (void)item.GetDouble(doubleData);
215 EXPECT_EQ(sqlite3_bind_double(stmt, col, doubleData), SQLITE_OK);
216 break;
217 }
218
219 case StorageType::STORAGE_TYPE_TEXT: {
220 std::string strData;
221 (void)item.GetText(strData);
222 EXPECT_EQ(SQLiteUtils::BindTextToStatement(stmt, col, strData), E_OK);
223 break;
224 }
225
226 case StorageType::STORAGE_TYPE_BLOB: {
227 Blob blob;
228 (void)item.GetBlob(blob);
229 std::vector<uint8_t> blobData(blob.GetData(), blob.GetData() + blob.GetSize());
230 EXPECT_EQ(SQLiteUtils::BindBlobToStatement(stmt, col, blobData, true), E_OK);
231 break;
232 }
233
234 case StorageType::STORAGE_TYPE_NULL: {
235 EXPECT_EQ(SQLiteUtils::MapSQLiteErrno(sqlite3_bind_null(stmt, col)), E_OK);
236 break;
237 }
238
239 default:
240 break;
241 }
242 }
243
InsertValue(sqlite3 * db,std::map<std::string,DataValue> & dataMap,const std::vector<FieldInfo> & fieldInfoList,const std::string & tableName)244 void InsertValue(sqlite3 *db, std::map<std::string, DataValue> &dataMap,
245 const std::vector<FieldInfo> &fieldInfoList, const std::string &tableName)
246 {
247 sqlite3_stmt *stmt = nullptr;
248 EXPECT_EQ(PrepareInsert(db, stmt, fieldInfoList, tableName), SQLITE_OK);
249 for (int i = 0; i < static_cast<int>(fieldInfoList.size()); ++i) {
250 const auto &fieldName = fieldInfoList[i].GetFieldName();
251 ASSERT_TRUE(dataMap.find(fieldName) != dataMap.end());
252 const auto &item = dataMap[fieldName];
253 const int index = i + 1;
254 BindValue(item, stmt, index);
255 }
256 EXPECT_EQ(SimulateCommitData(db, stmt), SQLITE_DONE);
257 sqlite3_finalize(stmt);
258 }
259
InsertValue(sqlite3 * db,std::map<std::string,DataValue> & dataMap)260 void InsertValue(sqlite3 *db, std::map<std::string, DataValue> &dataMap)
261 {
262 InsertValue(db, dataMap, g_fieldInfoList, g_tableName);
263 }
264
SetNull(DataValue & dataValue)265 void SetNull(DataValue &dataValue)
266 {
267 dataValue.ResetValue();
268 }
269
SetInt64(DataValue & dataValue)270 void SetInt64(DataValue &dataValue)
271 {
272 dataValue = INT64_MAX;
273 }
274
SetDouble(DataValue & dataValue)275 void SetDouble(DataValue &dataValue)
276 {
277 dataValue = 1.0;
278 }
279
SetText(DataValue & dataValue)280 void SetText(DataValue &dataValue)
281 {
282 dataValue.SetText(DEFAULT_TEXT);
283 }
284
SetBlob(DataValue & dataValue)285 void SetBlob(DataValue &dataValue)
286 {
287 Blob blob;
288 blob.WriteBlob(DEFAULT_BLOB.data(), DEFAULT_BLOB.size());
289 dataValue.SetBlob(blob);
290 }
291
GenerateValue(std::map<std::string,DataValue> & dataMap,std::vector<FieldInfo> & fieldInfoList)292 void GenerateValue(std::map<std::string, DataValue> &dataMap, std::vector<FieldInfo> &fieldInfoList)
293 {
294 static std::map<StorageType, void(*)(DataValue&)> typeMapFunction = {
295 {StorageType::STORAGE_TYPE_NULL, &SetNull},
296 {StorageType::STORAGE_TYPE_INTEGER, &SetInt64},
297 {StorageType::STORAGE_TYPE_REAL, &SetDouble},
298 {StorageType::STORAGE_TYPE_TEXT, &SetText},
299 {StorageType::STORAGE_TYPE_BLOB, &SetBlob}
300 };
301 for (auto &fieldInfo : fieldInfoList) {
302 DataValue dataValue;
303 if (typeMapFunction.find(fieldInfo.GetStorageType()) == typeMapFunction.end()) {
304 fieldInfo.SetStorageType(StorageType::STORAGE_TYPE_NULL);
305 }
306 typeMapFunction[fieldInfo.GetStorageType()](dataValue);
307 dataMap[fieldInfo.GetFieldName()] = std::move(dataValue);
308 }
309 }
310
InsertFieldInfo(std::vector<FieldInfo> & fieldInfoList)311 void InsertFieldInfo(std::vector<FieldInfo> &fieldInfoList)
312 {
313 fieldInfoList.clear();
314 FieldInfo columnFirst;
315 columnFirst.SetFieldName("ID");
316 columnFirst.SetStorageType(StorageType::STORAGE_TYPE_INTEGER);
317 columnFirst.SetColumnId(0); // the first column
318 FieldInfo columnSecond;
319 columnSecond.SetFieldName("NAME");
320 columnSecond.SetStorageType(StorageType::STORAGE_TYPE_TEXT);
321 columnSecond.SetColumnId(1); // the 2nd column
322 FieldInfo columnThird;
323 columnThird.SetFieldName("AGE");
324 columnThird.SetStorageType(StorageType::STORAGE_TYPE_INTEGER);
325 columnThird.SetColumnId(2); // the 3rd column(index 2 base 0)
326 fieldInfoList.push_back(columnFirst);
327 fieldInfoList.push_back(columnSecond);
328 fieldInfoList.push_back(columnThird);
329 }
330
BlockSync(const Query & query,SyncMode syncMode,DBStatus exceptStatus,const std::vector<std::string> & devices)331 void BlockSync(const Query &query, SyncMode syncMode, DBStatus exceptStatus,
332 const std::vector<std::string> &devices)
333 {
334 std::map<std::string, std::vector<TableStatus>> statusMap;
335 SyncStatusCallback callBack = [&statusMap](
336 const std::map<std::string, std::vector<TableStatus>> &devicesMap) {
337 statusMap = devicesMap;
338 };
339 DBStatus callStatus = g_rdbDelegatePtr->Sync(devices, syncMode, query, callBack, true);
340 EXPECT_EQ(callStatus, OK);
341 for (const auto &tablesRes : statusMap) {
342 for (const auto &tableStatus : tablesRes.second) {
343 EXPECT_EQ(tableStatus.status, exceptStatus);
344 }
345 }
346 }
347
BlockSync(const std::string & tableName,SyncMode syncMode,DBStatus exceptStatus,const std::vector<std::string> & devices)348 void BlockSync(const std::string &tableName, SyncMode syncMode, DBStatus exceptStatus,
349 const std::vector<std::string> &devices)
350 {
351 Query query = Query::Select(tableName);
352 BlockSync(query, syncMode, exceptStatus, devices);
353 }
354
BlockSync(SyncMode syncMode,DBStatus exceptStatus,const std::vector<std::string> & devices)355 void BlockSync(SyncMode syncMode, DBStatus exceptStatus, const std::vector<std::string> &devices)
356 {
357 BlockSync(g_tableName, syncMode, exceptStatus, devices);
358 }
359
PrepareSelect(sqlite3 * db,sqlite3_stmt * & statement,const std::string & table)360 int PrepareSelect(sqlite3 *db, sqlite3_stmt *&statement, const std::string &table)
361 {
362 const std::string sql = "SELECT * FROM " + table;
363 return sqlite3_prepare_v2(db, sql.c_str(), -1, &statement, nullptr);
364 }
365
GetDataValue(sqlite3_stmt * statement,int col,DataValue & dataValue)366 void GetDataValue(sqlite3_stmt *statement, int col, DataValue &dataValue)
367 {
368 int type = sqlite3_column_type(statement, col);
369 switch (type) {
370 case SQLITE_INTEGER: {
371 dataValue = static_cast<int64_t>(sqlite3_column_int64(statement, col));
372 break;
373 }
374 case SQLITE_FLOAT: {
375 dataValue = sqlite3_column_double(statement, col);
376 break;
377 }
378 case SQLITE_TEXT: {
379 std::string str;
380 SQLiteUtils::GetColumnTextValue(statement, col, str);
381 dataValue.SetText(str);
382 break;
383 }
384 case SQLITE_BLOB: {
385 std::vector<uint8_t> blobValue;
386 (void)SQLiteUtils::GetColumnBlobValue(statement, col, blobValue);
387 Blob blob;
388 blob.WriteBlob(blobValue.data(), static_cast<uint32_t>(blobValue.size()));
389 dataValue.SetBlob(blob);
390 break;
391 }
392 case SQLITE_NULL:
393 break;
394 default:
395 LOGW("unknown type[%d] column[%d] ignore", type, col);
396 }
397 }
398
GetSyncDataStep(std::map<std::string,DataValue> & dataMap,sqlite3_stmt * statement,const std::vector<FieldInfo> & fieldInfoList)399 void GetSyncDataStep(std::map<std::string, DataValue> &dataMap, sqlite3_stmt *statement,
400 const std::vector<FieldInfo> &fieldInfoList)
401 {
402 int columnCount = sqlite3_column_count(statement);
403 ASSERT_EQ(static_cast<size_t>(columnCount), fieldInfoList.size());
404 for (int col = 0; col < columnCount; ++col) {
405 DataValue dataValue;
406 GetDataValue(statement, col, dataValue);
407 dataMap[fieldInfoList.at(col).GetFieldName()] = std::move(dataValue);
408 }
409 }
410
GetSyncData(sqlite3 * db,std::map<std::string,DataValue> & dataMap,const std::string & tableName,const std::vector<FieldInfo> & fieldInfoList)411 void GetSyncData(sqlite3 *db, std::map<std::string, DataValue> &dataMap, const std::string &tableName,
412 const std::vector<FieldInfo> &fieldInfoList)
413 {
414 sqlite3_stmt *statement = nullptr;
415 EXPECT_EQ(PrepareSelect(db, statement, GetDeviceTableName(tableName)), SQLITE_OK);
416 while (true) {
417 int rc = sqlite3_step(statement);
418 if (rc != SQLITE_ROW) {
419 LOGD("GetSyncData Exist by code[%d]", rc);
420 break;
421 }
422 GetSyncDataStep(dataMap, statement, fieldInfoList);
423 }
424 sqlite3_finalize(statement);
425 }
426
InsertValueToDB(std::map<std::string,DataValue> & dataMap)427 void InsertValueToDB(std::map<std::string, DataValue> &dataMap)
428 {
429 sqlite3 *db = nullptr;
430 EXPECT_EQ(GetDB(db), SQLITE_OK);
431 InsertValue(db, dataMap);
432 sqlite3_close(db);
433 }
434
PrepareBasicTable(const std::string & tableName,std::vector<FieldInfo> & fieldInfoList,const std::vector<RelationalVirtualDevice * > & remoteDeviceVec,bool createDistributedTable=true)435 void PrepareBasicTable(const std::string &tableName, std::vector<FieldInfo> &fieldInfoList,
436 const std::vector<RelationalVirtualDevice *> &remoteDeviceVec, bool createDistributedTable = true)
437 {
438 sqlite3 *db = nullptr;
439 EXPECT_EQ(GetDB(db), SQLITE_OK);
440 if (fieldInfoList.empty()) {
441 InsertFieldInfo(fieldInfoList);
442 }
443 for (auto &dev : remoteDeviceVec) {
444 dev->SetLocalFieldInfo(fieldInfoList);
445 }
446 EXPECT_EQ(CreateTable(db, fieldInfoList, tableName), SQLITE_OK);
447 TableInfo tableInfo;
448 SQLiteUtils::AnalysisSchema(db, tableName, tableInfo);
449 for (auto &dev : remoteDeviceVec) {
450 dev->SetTableInfo(tableInfo);
451 }
452 if (createDistributedTable) {
453 EXPECT_EQ(g_rdbDelegatePtr->CreateDistributedTable(tableName), OK);
454 }
455
456 sqlite3_close(db);
457 }
458
PrepareEnvironment(std::map<std::string,DataValue> & dataMap,std::vector<RelationalVirtualDevice * > remoteDeviceVec)459 void PrepareEnvironment(std::map<std::string, DataValue> &dataMap,
460 std::vector<RelationalVirtualDevice *> remoteDeviceVec)
461 {
462 PrepareBasicTable(g_tableName, g_fieldInfoList, remoteDeviceVec);
463 GenerateValue(dataMap, g_fieldInfoList);
464 InsertValueToDB(dataMap);
465 }
466
PrepareVirtualEnvironment(std::map<std::string,DataValue> & dataMap,const std::string & tableName,std::vector<FieldInfo> & fieldInfoList,const std::vector<RelationalVirtualDevice * > remoteDeviceVec,bool createDistributedTable=true)467 void PrepareVirtualEnvironment(std::map<std::string, DataValue> &dataMap, const std::string &tableName,
468 std::vector<FieldInfo> &fieldInfoList, const std::vector<RelationalVirtualDevice *> remoteDeviceVec,
469 bool createDistributedTable = true)
470 {
471 PrepareBasicTable(tableName, fieldInfoList, remoteDeviceVec, createDistributedTable);
472 GenerateValue(dataMap, fieldInfoList);
473 VirtualRowData virtualRowData;
474 for (const auto &item : dataMap) {
475 virtualRowData.objectData.PutDataValue(item.first, item.second);
476 }
477 virtualRowData.logInfo.timestamp = 1;
478 g_deviceB->PutData(tableName, {virtualRowData});
479 }
480
PrepareVirtualEnvironment(std::map<std::string,DataValue> & dataMap,const std::vector<RelationalVirtualDevice * > remoteDeviceVec,bool createDistributedTable=true)481 void PrepareVirtualEnvironment(std::map<std::string, DataValue> &dataMap,
482 const std::vector<RelationalVirtualDevice *> remoteDeviceVec, bool createDistributedTable = true)
483 {
484 PrepareVirtualEnvironment(dataMap, g_tableName, g_fieldInfoList, remoteDeviceVec, createDistributedTable);
485 }
486
CheckData(const std::map<std::string,DataValue> & targetMap,const std::string & tableName,const std::vector<FieldInfo> & fieldInfoList)487 void CheckData(const std::map<std::string, DataValue> &targetMap, const std::string &tableName,
488 const std::vector<FieldInfo> &fieldInfoList)
489 {
490 std::map<std::string, DataValue> dataMap;
491 sqlite3 *db = nullptr;
492 EXPECT_EQ(GetDB(db), SQLITE_OK);
493 GetSyncData(db, dataMap, tableName, fieldInfoList);
494 sqlite3_close(db);
495
496 for (const auto &[fieldName, dataValue] : targetMap) {
497 ASSERT_TRUE(dataMap.find(fieldName) != dataMap.end());
498 EXPECT_TRUE(dataMap[fieldName] == dataValue);
499 }
500 }
501
CheckData(const std::map<std::string,DataValue> & targetMap)502 void CheckData(const std::map<std::string, DataValue> &targetMap)
503 {
504 CheckData(targetMap, g_tableName, g_fieldInfoList);
505 }
506
CheckVirtualData(const std::string & tableName,std::map<std::string,DataValue> & data)507 void CheckVirtualData(const std::string &tableName, std::map<std::string, DataValue> &data)
508 {
509 std::vector<VirtualRowData> targetData;
510 g_deviceB->GetAllSyncData(tableName, targetData);
511
512 ASSERT_EQ(targetData.size(), 1u);
513 for (auto &[field, value] : data) {
514 DataValue target;
515 EXPECT_EQ(targetData[0].objectData.GetDataValue(field, target), E_OK);
516 LOGD("field %s actual_val[%s] except_val[%s]", field.c_str(), target.ToString().c_str(),
517 value.ToString().c_str());
518 EXPECT_TRUE(target == value);
519 }
520 }
521
CheckVirtualData(std::map<std::string,DataValue> & data)522 void CheckVirtualData(std::map<std::string, DataValue> &data)
523 {
524 CheckVirtualData(g_tableName, data);
525 }
526
GetFieldInfo(std::vector<FieldInfo> & fieldInfoList,std::vector<StorageType> typeList)527 void GetFieldInfo(std::vector<FieldInfo> &fieldInfoList, std::vector<StorageType> typeList)
528 {
529 fieldInfoList.clear();
530 for (size_t index = 0; index < typeList.size(); index++) {
531 const auto &type = typeList[index];
532 FieldInfo fieldInfo;
533 fieldInfo.SetFieldName("field_" + std::to_string(index));
534 fieldInfo.SetColumnId(index);
535 fieldInfo.SetStorageType(type);
536 fieldInfoList.push_back(fieldInfo);
537 }
538 }
539
InsertValueToDB(std::map<std::string,DataValue> & dataMap,std::vector<FieldInfo> fieldInfoList,const std::string & tableName)540 void InsertValueToDB(std::map<std::string, DataValue> &dataMap,
541 std::vector<FieldInfo> fieldInfoList, const std::string &tableName)
542 {
543 sqlite3 *db = nullptr;
544 EXPECT_EQ(GetDB(db), SQLITE_OK);
545 InsertValue(db, dataMap, fieldInfoList, tableName);
546 sqlite3_close(db);
547 }
548
PrepareEnvironment(std::map<std::string,DataValue> & dataMap,const std::string & tableName,std::vector<FieldInfo> & localFieldInfoList,std::vector<FieldInfo> & remoteFieldInfoList,std::vector<RelationalVirtualDevice * > remoteDeviceVec)549 void PrepareEnvironment(std::map<std::string, DataValue> &dataMap, const std::string &tableName,
550 std::vector<FieldInfo> &localFieldInfoList, std::vector<FieldInfo> &remoteFieldInfoList,
551 std::vector<RelationalVirtualDevice *> remoteDeviceVec)
552 {
553 sqlite3 *db = nullptr;
554 EXPECT_EQ(GetDB(db), SQLITE_OK);
555
556 EXPECT_EQ(CreateTable(db, remoteFieldInfoList, tableName), SQLITE_OK);
557 TableInfo tableInfo;
558 SQLiteUtils::AnalysisSchema(db, tableName, tableInfo);
559 for (auto &dev : remoteDeviceVec) {
560 dev->SetTableInfo(tableInfo);
561 }
562
563 EXPECT_EQ(DropTable(db, tableName), SQLITE_OK);
564 EXPECT_EQ(CreateTable(db, localFieldInfoList, tableName), SQLITE_OK);
565 EXPECT_EQ(g_rdbDelegatePtr->CreateDistributedTable(tableName), OK);
566
567 sqlite3_close(db);
568
569 GenerateValue(dataMap, localFieldInfoList);
570 InsertValueToDB(dataMap, localFieldInfoList, tableName);
571 for (auto &dev : remoteDeviceVec) {
572 dev->SetLocalFieldInfo(remoteFieldInfoList);
573 }
574 }
575
PrepareEnvironment(std::map<std::string,DataValue> & dataMap,std::vector<FieldInfo> & localFieldInfoList,std::vector<FieldInfo> & remoteFieldInfoList,const std::vector<RelationalVirtualDevice * > remoteDeviceVec)576 void PrepareEnvironment(std::map<std::string, DataValue> &dataMap,
577 std::vector<FieldInfo> &localFieldInfoList, std::vector<FieldInfo> &remoteFieldInfoList,
578 const std::vector<RelationalVirtualDevice *> remoteDeviceVec)
579 {
580 PrepareEnvironment(dataMap, g_tableName, localFieldInfoList, remoteFieldInfoList, remoteDeviceVec);
581 }
582
CheckIdentify(RelationalStoreObserverUnitTest * observer)583 void CheckIdentify(RelationalStoreObserverUnitTest *observer)
584 {
585 ASSERT_NE(observer, nullptr);
586 StoreProperty property = observer->GetStoreProperty();
587 EXPECT_EQ(property.appId, APP_ID);
588 EXPECT_EQ(property.storeId, STORE_ID_1);
589 EXPECT_EQ(property.userId, USER_ID);
590 }
591
CheckSearchData(std::shared_ptr<ResultSet> result,std::map<std::string,DataValue> & dataMap)592 void CheckSearchData(std::shared_ptr<ResultSet> result, std::map<std::string, DataValue> &dataMap)
593 {
594 ASSERT_NE(result, nullptr);
595 EXPECT_EQ(result->GetCount(), 1);
596 ASSERT_TRUE(result->MoveToFirst());
597 std::vector<string> columnNames;
598 result->GetColumnNames(columnNames);
599 ASSERT_EQ(columnNames.size(), dataMap.size());
600 int index = 0;
601 for (auto &column : columnNames) {
602 ASSERT_TRUE(dataMap.find(column) != dataMap.end());
603 LOGD("now check %s", column.c_str());
604 if (dataMap[column].GetType() == StorageType::STORAGE_TYPE_INTEGER) {
605 int64_t expectVal = 0;
606 dataMap[column].GetInt64(expectVal);
607 int64_t actualVal = 0;
608 ASSERT_EQ(result->Get(index, actualVal), OK);
609 EXPECT_EQ(expectVal, actualVal);
610 } else if (dataMap[column].GetType() == StorageType::STORAGE_TYPE_TEXT) {
611 std::string expectVal = "";
612 dataMap[column].GetText(expectVal);
613 std::string actualVal = "";
614 ASSERT_EQ(result->Get(index, actualVal), OK);
615 EXPECT_EQ(expectVal, actualVal);
616 } else if (dataMap[column].GetType() == StorageType::STORAGE_TYPE_REAL) {
617 double expectVal = 0;
618 dataMap[column].GetDouble(expectVal);
619 double actualVal = 0;
620 ASSERT_EQ(result->Get(index, actualVal), OK);
621 EXPECT_EQ(expectVal, actualVal);
622 }
623 index++;
624 }
625 }
626
GetCount(sqlite3 * db,const string & sql,size_t & count)627 int GetCount(sqlite3 *db, const string &sql, size_t &count)
628 {
629 sqlite3_stmt *stmt = nullptr;
630 int errCode = SQLiteUtils::GetStatement(db, sql, stmt);
631 if (errCode != E_OK) {
632 return errCode;
633 }
634 errCode = SQLiteUtils::StepWithRetry(stmt, false);
635 if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) {
636 count = static_cast<size_t>(sqlite3_column_int64(stmt, 0));
637 errCode = E_OK;
638 }
639 SQLiteUtils::ResetStatement(stmt, true, errCode);
640 return errCode;
641 }
642
GenerateSecurityData(std::vector<SecurityLabel> & labelList,std::vector<SecurityFlag> & flagList)643 void GenerateSecurityData(std::vector<SecurityLabel> &labelList, std::vector<SecurityFlag> &flagList)
644 {
645 labelList = {
646 SecurityLabel::NOT_SET, SecurityLabel::S0,
647 SecurityLabel::S1, SecurityLabel::S2,
648 SecurityLabel::S3, SecurityLabel::S4
649 };
650 flagList = {
651 SecurityFlag::ECE, SecurityFlag::SECE
652 };
653 }
654
SelectSecurityOption(int & labelIndex,int & flagIndex,const std::vector<SecurityLabel> & labelList,const std::vector<SecurityFlag> & flagList)655 SecurityOption SelectSecurityOption(int &labelIndex, int &flagIndex,
656 const std::vector<SecurityLabel> &labelList, const std::vector<SecurityFlag> &flagList)
657 {
658 SecurityOption option;
659 if (labelIndex >= static_cast<int>(labelList.size()) || flagIndex >= static_cast<int>(flagList.size())) {
660 return option;
661 }
662 option.securityLabel = labelList[labelIndex];
663 option.securityFlag = flagList[flagIndex];
664 labelIndex++;
665 if (labelIndex >= static_cast<int>(labelList.size())) {
666 labelIndex = 0;
667 flagIndex++;
668 }
669 return option;
670 }
671
SelectSecurityEnd(int flagIndex,const std::vector<SecurityFlag> & flagList)672 bool SelectSecurityEnd(int flagIndex, const std::vector<SecurityFlag> &flagList)
673 {
674 return flagIndex >= static_cast<int>(flagList.size());
675 }
676
GetSecurityRes(const SecurityOption & localOption,const SecurityOption & remoteOption,bool checkDeviceResult)677 DBStatus GetSecurityRes(const SecurityOption &localOption, const SecurityOption &remoteOption,
678 bool checkDeviceResult)
679 {
680 if (!checkDeviceResult) {
681 return SECURITY_OPTION_CHECK_ERROR;
682 }
683 if (localOption.securityLabel == static_cast<int>(SecurityLabel::NOT_SET) ||
684 remoteOption.securityLabel == static_cast<int>(SecurityLabel::NOT_SET)) {
685 return OK;
686 }
687 if (localOption.securityLabel != remoteOption.securityLabel) {
688 return SECURITY_OPTION_CHECK_ERROR;
689 }
690 return OK;
691 }
692
SyncWithSecurityCheck(const SecurityOption & localOption,const SecurityOption & remoteOption,bool remoteQuery,bool checkDeviceResult)693 void SyncWithSecurityCheck(const SecurityOption &localOption, const SecurityOption &remoteOption,
694 bool remoteQuery, bool checkDeviceResult)
695 {
696 std::shared_ptr<ProcessSystemApiAdapterImpl> adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
697 adapter->ForkCheckDeviceSecurityAbility(
698 [&localOption, &remoteOption, checkDeviceResult, remoteQuery](const std::string &devId,
699 const SecurityOption &option) {
700 if (remoteQuery) {
701 EXPECT_TRUE(remoteOption == option);
702 EXPECT_EQ(devId, DEVICE_A);
703 } else {
704 EXPECT_TRUE(localOption == option);
705 }
706 return checkDeviceResult;
707 });
708 adapter->ForkGetSecurityOption(
709 [&localOption, &remoteOption](const std::string &filePath, SecurityOption &option) {
710 if (filePath.empty()) {
711 option = remoteOption;
712 } else {
713 option = localOption;
714 }
715 return OK;
716 });
717 RuntimeConfig::SetProcessSystemAPIAdapter(adapter);
718 DBStatus resStatus = GetSecurityRes(localOption, remoteOption, checkDeviceResult);
719 if (remoteQuery) {
720 RemoteCondition condition;
721 condition.sql = "SELECT * FROM " + g_tableName;
722 std::shared_ptr<ResultSet> result = nullptr;
723 ASSERT_NE(g_rdbDelegatePtr, nullptr);
724 EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), resStatus);
725 } else {
726 BlockSync(SYNC_MODE_PUSH_ONLY, resStatus, {DEVICE_B});
727 }
728 RuntimeConfig::SetProcessSystemAPIAdapter(nullptr);
729 if (g_rdbDelegatePtr != nullptr) {
730 LOGD("CloseStore Start");
731 ASSERT_EQ(g_mgr.CloseStore(g_rdbDelegatePtr), OK);
732 g_rdbDelegatePtr = nullptr;
733 }
734 OpenStore();
735 }
736
TestWithSecurityCheck(bool remoteQuery)737 void TestWithSecurityCheck(bool remoteQuery)
738 {
739 /**
740 * @tc.steps: step1. create table and open store
741 * @tc.expected: step1. open store ok
742 */
743 std::map<std::string, DataValue> dataMap;
744 if (remoteQuery) {
745 PrepareEnvironment(dataMap, {g_deviceB});
746 } else {
747 PrepareVirtualEnvironment(dataMap, {g_deviceB});
748 }
749 ASSERT_NE(g_rdbDelegatePtr, nullptr);
750
751 /**
752 * @tc.steps: step2. generate test data
753 */
754 std::vector<SecurityLabel> labelList;
755 std::vector<SecurityFlag> flagList;
756 int localLabelIndex = 0;
757 int localFlagIndex = 0;
758 GenerateSecurityData(labelList, flagList);
759
760 // loop local
761 while (!SelectSecurityEnd(localFlagIndex, flagList)) {
762 SecurityOption localOption = SelectSecurityOption(localLabelIndex, localFlagIndex, labelList, flagList);
763 // loop remote
764 int remoteLabelIndex = 0;
765 int remoteFlagIndex = 0;
766 while (!SelectSecurityEnd(remoteFlagIndex, flagList)) {
767 SecurityOption remoteOption = SelectSecurityOption(remoteLabelIndex, remoteFlagIndex,
768 labelList, flagList);
769 /**
770 * @tc.steps: step3. call sync
771 * @tc.expected: step3. sync result is based on security option
772 */
773 SyncWithSecurityCheck(localOption, remoteOption, remoteQuery, true);
774 SyncWithSecurityCheck(localOption, remoteOption, remoteQuery, false);
775 }
776 }
777 }
778 }
779
780 class DistributedDBRelationalVerP2PSyncTest : public testing::Test {
781 public:
782 static void SetUpTestCase();
783 static void TearDownTestCase();
784 void SetUp();
785 void TearDown();
786 };
787
SetUpTestCase()788 void DistributedDBRelationalVerP2PSyncTest::SetUpTestCase()
789 {
790 /**
791 * @tc.setup: Init datadir and Virtual Communicator.
792 */
793 DistributedDBToolsUnitTest::TestDirInit(g_testDir);
794 g_dbDir = g_testDir + "/test.db";
795 sqlite3 *db = nullptr;
796 ASSERT_EQ(GetDB(db), SQLITE_OK);
797 sqlite3_close(db);
798
799 g_communicatorAggregator = new (std::nothrow) VirtualCommunicatorAggregator();
800 ASSERT_TRUE(g_communicatorAggregator != nullptr);
801 RuntimeContext::GetInstance()->SetCommunicatorAggregator(g_communicatorAggregator);
802
803 g_id = g_mgr.GetRelationalStoreIdentifier(USER_ID, APP_ID, STORE_ID_1);
804
805 #ifndef OMIT_ENCRYPT
806 g_correctPasswd.SetValue(reinterpret_cast<const uint8_t *>(CORRECT_KEY.data()), CORRECT_KEY.size());
807 g_rekeyPasswd.SetValue(reinterpret_cast<const uint8_t *>(REKEY_KEY.data()), REKEY_KEY.size());
808 g_incorrectPasswd.SetValue(reinterpret_cast<const uint8_t *>(INCORRECT_KEY.data()), INCORRECT_KEY.size());
809 #endif
810 }
811
TearDownTestCase()812 void DistributedDBRelationalVerP2PSyncTest::TearDownTestCase()
813 {
814 /**
815 * @tc.teardown: Release virtual Communicator and clear data dir.
816 */
817 if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) {
818 LOGE("rm test db files error!");
819 }
820 RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr);
821 LOGD("TearDownTestCase FINISH");
822 }
823
SetUp(void)824 void DistributedDBRelationalVerP2PSyncTest::SetUp(void)
825 {
826 DistributedDBToolsUnitTest::PrintTestCaseInfo();
827 g_fieldInfoList.clear();
828 /**
829 * @tc.setup: create virtual device B, and get a KvStoreNbDelegate as deviceA
830 */
831 sqlite3 *db = nullptr;
832 ASSERT_EQ(GetDB(db), SQLITE_OK);
833 sqlite3_close(db);
834 OpenStore();
835 g_deviceB = new (std::nothrow) RelationalVirtualDevice(DEVICE_B);
836 ASSERT_TRUE(g_deviceB != nullptr);
837 g_deviceC = new (std::nothrow) RelationalVirtualDevice(DEVICE_C);
838 ASSERT_TRUE(g_deviceC != nullptr);
839 g_deviceD = new (std::nothrow) KvVirtualDevice(DEVICE_D);
840 ASSERT_TRUE(g_deviceD != nullptr);
841 auto *syncInterfaceB = new (std::nothrow) VirtualRelationalVerSyncDBInterface();
842 auto *syncInterfaceC = new (std::nothrow) VirtualRelationalVerSyncDBInterface();
843 auto *syncInterfaceD = new (std::nothrow) VirtualSingleVerSyncDBInterface();
844 ASSERT_TRUE(syncInterfaceB != nullptr);
845 ASSERT_TRUE(syncInterfaceC != nullptr);
846 ASSERT_TRUE(syncInterfaceD != nullptr);
847 ASSERT_EQ(g_deviceB->Initialize(g_communicatorAggregator, syncInterfaceB), E_OK);
848 ASSERT_EQ(g_deviceC->Initialize(g_communicatorAggregator, syncInterfaceC), E_OK);
849 ASSERT_EQ(g_deviceD->Initialize(g_communicatorAggregator, syncInterfaceD), E_OK);
850
851 auto permissionCheckCallback = [] (const std::string &userId, const std::string &appId, const std::string &storeId,
852 const std::string &deviceId, uint8_t flag) -> bool {
853 return true;
854 };
855 EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(permissionCheckCallback), OK);
856 }
857
TearDown(void)858 void DistributedDBRelationalVerP2PSyncTest::TearDown(void)
859 {
860 /**
861 * @tc.teardown: Release device A, B, C
862 */
863 if (g_rdbDelegatePtr != nullptr) {
864 LOGD("CloseStore Start");
865 ASSERT_EQ(g_mgr.CloseStore(g_rdbDelegatePtr), OK);
866 g_rdbDelegatePtr = nullptr;
867 }
868 if (g_deviceB != nullptr) {
869 delete g_deviceB;
870 g_deviceB = nullptr;
871 }
872 if (g_deviceC != nullptr) {
873 delete g_deviceC;
874 g_deviceC = nullptr;
875 }
876 if (g_deviceD != nullptr) {
877 delete g_deviceD;
878 g_deviceD = nullptr;
879 }
880 if (g_observer != nullptr) {
881 delete g_observer;
882 g_observer = nullptr;
883 }
884 PermissionCheckCallbackV2 nullCallback;
885 EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(nullCallback), OK);
886 EXPECT_EQ(DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir), OK);
887 if (g_communicatorAggregator != nullptr) {
888 g_communicatorAggregator->RegOnDispatch(nullptr);
889 }
890 g_isAfterRekey = false;
891 LOGD("TearDown FINISH");
892 }
893
894 /**
895 * @tc.name: Normal Sync 001
896 * @tc.desc: Test normal push sync for add data.
897 * @tc.type: FUNC
898 * @tc.require: AR000GK58N
899 * @tc.author: zhangqiquan
900 */
901 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync001, TestSize.Level0)
902 {
903 std::map<std::string, DataValue> dataMap;
904 PrepareEnvironment(dataMap, {g_deviceB});
905 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
906
907 CheckVirtualData(dataMap);
908 }
909
910 /**
911 * @tc.name: Normal Sync 002
912 * @tc.desc: Test normal pull sync for add data.
913 * @tc.type: FUNC
914 * @tc.require: AR000GK58N
915 * @tc.author: zhangqiquan
916 */
917 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync002, TestSize.Level0)
918 {
919 std::map<std::string, DataValue> dataMap;
920 PrepareEnvironment(dataMap, {g_deviceB});
921
922 Query query = Query::Select(g_tableName);
923 g_deviceB->GenericVirtualDevice::Sync(DistributedDB::SYNC_MODE_PULL_ONLY, query, true);
924
925 CheckVirtualData(dataMap);
926 }
927
928 /**
929 * @tc.name: Normal Sync 003
930 * @tc.desc: Test normal push sync for update data.
931 * @tc.type: FUNC
932 * @tc.require: AR000GK58N
933 * @tc.author: zhangqiquan
934 */
935 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync003, TestSize.Level1)
936 {
937 std::map<std::string, DataValue> dataMap;
938 PrepareEnvironment(dataMap, {g_deviceB});
939
940 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
941
942 CheckVirtualData(dataMap);
943
944 GenerateValue(dataMap, g_fieldInfoList);
945 dataMap["AGE"] = static_cast<int64_t>(1);
946 InsertValueToDB(dataMap);
947 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
948
949 CheckVirtualData(dataMap);
950 }
951
952 /**
953 * @tc.name: Normal Sync 004
954 * @tc.desc: Test normal push sync for delete data.
955 * @tc.type: FUNC
956 * @tc.require: AR000GK58N
957 * @tc.author: zhangqiquan
958 */
959 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync004, TestSize.Level1)
960 {
961 std::map<std::string, DataValue> dataMap;
962 PrepareEnvironment(dataMap, {g_deviceB});
963
964 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
965
966 CheckVirtualData(dataMap);
967
968 sqlite3 *db = nullptr;
969 EXPECT_EQ(GetDB(db), SQLITE_OK);
970 std::string sql = "DELETE FROM TEST_TABLE WHERE 1 = 1";
971 EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, sql), E_OK);
972 sqlite3_close(db);
973
974 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
975
976 std::vector<VirtualRowData> dataList;
977 EXPECT_EQ(g_deviceB->GetAllSyncData(g_tableName, dataList), E_OK);
978 EXPECT_EQ(static_cast<int>(dataList.size()), 1);
979 for (const auto &item : dataList) {
980 EXPECT_EQ(item.logInfo.flag, DataItem::DELETE_FLAG);
981 }
982 }
983
984 /**
985 * @tc.name: Normal Sync 005
986 * @tc.desc: Test normal push sync for add data.
987 * @tc.type: FUNC
988 * @tc.require: AR000GK58N
989 * @tc.author: zhangqiquan
990 */
991 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync005, TestSize.Level0)
992 {
993 std::map<std::string, DataValue> dataMap;
994 PrepareVirtualEnvironment(dataMap, {g_deviceB});
995
996 Query query = Query::Select(g_tableName);
997 g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true);
998
999 CheckData(dataMap);
1000
1001 g_rdbDelegatePtr->RemoveDeviceData(DEVICE_B);
1002
1003 g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true);
1004
1005 CheckData(dataMap);
1006 }
1007
1008 /**
1009 * @tc.name: Normal Sync 007
1010 * @tc.desc: Test normal sync for miss query data.
1011 * @tc.type: FUNC
1012 * @tc.require: AR000GK58N
1013 * @tc.author: zhangqiquan
1014 */
1015 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync007, TestSize.Level1)
1016 {
1017 std::map<std::string, DataValue> dataMap;
1018 PrepareEnvironment(dataMap, {g_deviceB});
1019
1020 Query query = Query::Select(g_tableName).EqualTo("NAME", DEFAULT_TEXT);
1021 BlockSync(query, SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1022
1023 CheckVirtualData(dataMap);
1024
1025 sqlite3 *db = nullptr;
1026 EXPECT_EQ(GetDB(db), SQLITE_OK);
1027 std::string sql = "UPDATE TEST_TABLE SET NAME = '' WHERE 1 = 1";
1028 EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, sql), E_OK);
1029 sqlite3_close(db);
1030
1031 BlockSync(query, SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1032
1033 std::vector<VirtualRowData> dataList;
1034 EXPECT_EQ(g_deviceB->GetAllSyncData(g_tableName, dataList), E_OK);
1035 EXPECT_EQ(static_cast<int>(dataList.size()), 1);
1036 for (const auto &item : dataList) {
1037 EXPECT_EQ(item.logInfo.flag, DataItem::REMOTE_DEVICE_DATA_MISS_QUERY);
1038 }
1039 }
1040
1041 /**
1042 * @tc.name: Normal Sync 006
1043 * @tc.desc: Test normal pull sync for add data.
1044 * @tc.type: FUNC
1045 * @tc.require: AR000GK58N
1046 * @tc.author: zhangqiquan
1047 */
1048 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, NormalSync006, TestSize.Level1)
1049 {
1050 std::map<std::string, DataValue> dataMap;
1051 PrepareVirtualEnvironment(dataMap, {g_deviceB});
1052
1053 BlockSync(SYNC_MODE_PULL_ONLY, OK, {DEVICE_B});
1054
1055 CheckData(dataMap);
1056 }
1057
1058 /**
1059 * @tc.name: AutoLaunchSync 001
1060 * @tc.desc: Test rdb autoLaunch success when callback return true.
1061 * @tc.type: FUNC
1062 * @tc.require: AR000GK58N
1063 * @tc.author: zhangqiquan
1064 */
1065 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AutoLaunchSync001, TestSize.Level3)
1066 {
1067 /**
1068 * @tc.steps: step1. open rdb store, create distribute table and insert data
1069 */
1070 std::map<std::string, DataValue> dataMap;
1071 PrepareVirtualEnvironment(dataMap, {g_deviceB});
1072
1073 /**
1074 * @tc.steps: step2. set auto launch callBack
1075 */
1076 int currentStatus = 0;
1077 const AutoLaunchNotifier notifier = [¤tStatus](const std::string &userId,
__anonc2e146140602(const std::string &userId, const std::string &appId, const std::string &storeId, AutoLaunchStatus status) 1078 const std::string &appId, const std::string &storeId, AutoLaunchStatus status) {
1079 currentStatus = static_cast<int>(status);
1080 };
__anonc2e146140702(const std::string &identifier, AutoLaunchParam ¶m) 1081 const AutoLaunchRequestCallback callback = [¬ifier](const std::string &identifier, AutoLaunchParam ¶m) {
1082 if (g_id != identifier) {
1083 return false;
1084 }
1085 param.path = g_dbDir;
1086 param.appId = APP_ID;
1087 param.userId = USER_ID;
1088 param.storeId = STORE_ID_1;
1089 param.notifier = notifier;
1090 #ifndef OMIT_ENCRYPT
1091 param.option.isEncryptedDb = true;
1092 param.option.cipher = CipherType::DEFAULT;
1093 param.option.passwd = g_correctPasswd;
1094 param.option.iterateTimes = DEFAULT_ITER;
1095 #endif
1096 return true;
1097 };
1098 g_mgr.SetAutoLaunchRequestCallback(callback);
1099 /**
1100 * @tc.steps: step3. close store ensure communicator has closed
1101 */
1102 g_mgr.CloseStore(g_rdbDelegatePtr);
1103 g_rdbDelegatePtr = nullptr;
1104 /**
1105 * @tc.steps: step4. RunCommunicatorLackCallback to autolaunch store
1106 */
1107 LabelType labelType(g_id.begin(), g_id.end());
1108 g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1109 std::this_thread::sleep_for(std::chrono::seconds(1));
1110 EXPECT_EQ(currentStatus, 0);
1111 /**
1112 * @tc.steps: step5. Call sync expect sync successful
1113 */
1114 Query query = Query::Select(g_tableName);
1115 EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK);
1116 EXPECT_EQ(currentStatus, AutoLaunchStatus::WRITE_OPENED);
1117 /**
1118 * @tc.steps: step6. check sync data ensure sync successful
1119 */
1120 CheckData(dataMap);
1121
1122 OpenStore();
1123 std::this_thread::sleep_for(std::chrono::seconds(61)); // sleep 61s
1124 EXPECT_EQ(currentStatus, AutoLaunchStatus::WRITE_CLOSED);
1125 }
1126
1127 /**
1128 * @tc.name: AutoLaunchSyncAfterRekey_001
1129 * @tc.desc: Test auto launch sync ok after rekey.
1130 * @tc.type: FUNC
1131 * @tc.require: AR000H68LL
1132 * @tc.author: lidongwei
1133 */
1134 #ifndef OMIT_ENCRYPT
1135 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AutoLaunchSyncAfterRekey_001, TestSize.Level3)
1136 {
1137 /**
1138 * @tc.steps: step1. open rdb store, create distribute table and insert data
1139 */
1140 std::map<std::string, DataValue> dataMap;
1141 PrepareVirtualEnvironment(dataMap, {g_deviceB});
1142
1143 /**
1144 * @tc.steps: step2. set auto launch callBack
1145 */
1146 AutoLaunchParam encryptedParam { USER_ID, APP_ID, STORE_ID_1, AutoLaunchOption {}, nullptr, g_dbDir };
1147 encryptedParam.option.isEncryptedDb = true;
1148 encryptedParam.option.cipher = CipherType::DEFAULT;
1149 encryptedParam.option.passwd = g_correctPasswd;
1150 encryptedParam.option.iterateTimes = DEFAULT_ITER;
__anonc2e146140802(const std::string &identifier, AutoLaunchParam ¶m) 1151 AutoLaunchRequestCallback callback = [&encryptedParam](const std::string &identifier, AutoLaunchParam ¶m) {
1152 if (g_id != identifier) {
1153 return false;
1154 }
1155 param = encryptedParam;
1156 return true;
1157 };
1158 g_mgr.SetAutoLaunchRequestCallback(callback);
1159 /**
1160 * @tc.steps: step3. close store ensure communicator has closed
1161 */
1162 g_mgr.CloseStore(g_rdbDelegatePtr);
1163 g_rdbDelegatePtr = nullptr;
1164 /**
1165 * @tc.steps: step4. RunCommunicatorLackCallback to autolaunch store
1166 */
1167 LabelType labelType(g_id.begin(), g_id.end());
1168 g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1169 std::this_thread::sleep_for(std::chrono::seconds(1));
1170
1171 /**
1172 * @tc.steps: step5. Rekey
1173 */
1174 sqlite3 *db = nullptr;
1175 EXPECT_EQ(GetDB(db), SQLITE_OK);
__anonc2e146140902null1176 std::thread t1([&db] {
1177 std::string sql = "PARGMA rekey=" + REKEY_KEY;
1178 EXPECT_EQ(sqlite3_rekey(db, REKEY_KEY.data(), REKEY_KEY.size()), SQLITE_OK);
1179 });
1180 t1.join();
1181 g_isAfterRekey = true;
1182
1183 /**
1184 * @tc.steps: step5. Call sync expect sync failed
1185 */
1186 Query query = Query::Select(g_tableName);
1187 EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK);
1188 size_t count = 0;
1189 GetCount(db, "SELECT count(*) FROM sqlite_master WHERE name='" + GetDeviceTableName(g_tableName) + "';", count);
1190 EXPECT_EQ(count, 0u);
1191
1192 /**
1193 * @tc.steps: step6. Set callback.
1194 */
1195 encryptedParam.option.passwd = g_rekeyPasswd;
1196 g_mgr.SetAutoLaunchRequestCallback(callback);
1197 g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1198 std::this_thread::sleep_for(std::chrono::seconds(2));
1199
1200 /**
1201 * @tc.steps: step5. Call sync expect sync success
1202 */
1203 EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK);
1204 GetCount(db, "SELECT count(*) FROM sqlite_master WHERE name='" + GetDeviceTableName(g_tableName) + "';", count);
1205 EXPECT_EQ(count, 1u);
1206 GetSyncData(db, dataMap, g_tableName, g_fieldInfoList);
1207 EXPECT_EQ(dataMap.size(), 3u);
1208 OpenStore();
1209 std::this_thread::sleep_for(std::chrono::minutes(1));
1210 sqlite3_close(db);
1211 db = nullptr;
1212 }
1213 #endif
1214
1215 /**
1216 * @tc.name: AutoLaunchSync 002
1217 * @tc.desc: Test rdb autoLaunch failed when callback return false.
1218 * @tc.type: FUNC
1219 * @tc.require: AR000GK58N
1220 * @tc.author: zhangqiquan
1221 */
1222 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AutoLaunchSync002, TestSize.Level3)
1223 {
1224 /**
1225 * @tc.steps: step1. open rdb store, create distribute table and insert data
1226 */
1227 std::map<std::string, DataValue> dataMap;
1228 PrepareVirtualEnvironment(dataMap, {g_deviceB});
1229
1230 /**
1231 * @tc.steps: step2. set auto launch callBack
1232 */
__anonc2e146140a02(const std::string &identifier, AutoLaunchParam ¶m) 1233 const AutoLaunchRequestCallback callback = [](const std::string &identifier, AutoLaunchParam ¶m) {
1234 return false;
1235 };
1236 g_mgr.SetAutoLaunchRequestCallback(callback);
1237 /**
1238 * @tc.steps: step2. close store ensure communicator has closed
1239 */
1240 g_mgr.CloseStore(g_rdbDelegatePtr);
1241 g_rdbDelegatePtr = nullptr;
1242 /**
1243 * @tc.steps: step3. store can't autoLaunch because callback return false
1244 */
1245 LabelType labelType(g_id.begin(), g_id.end());
1246 g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1247 std::this_thread::sleep_for(std::chrono::seconds(1));
1248 /**
1249 * @tc.steps: step4. Call sync expect sync fail
1250 */
1251 Query query = Query::Select(g_tableName);
__anonc2e146140b02(const std::map<std::string, int> &statusMap) 1252 SyncOperation::UserCallback callBack = [](const std::map<std::string, int> &statusMap) {
1253 for (const auto &entry : statusMap) {
1254 EXPECT_EQ(entry.second, static_cast<int>(SyncOperation::OP_COMM_ABNORMAL));
1255 }
1256 };
1257 EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, callBack, true), E_OK);
1258
1259 OpenStore();
1260 std::this_thread::sleep_for(std::chrono::minutes(1));
1261 }
1262
1263 /**
1264 * @tc.name: AutoLaunchSync 003
1265 * @tc.desc: Test rdb autoLaunch failed when callback is nullptr.
1266 * @tc.type: FUNC
1267 * @tc.require: AR000GK58N
1268 * @tc.author: zhangqiquan
1269 */
1270 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AutoLaunchSync003, TestSize.Level3)
1271 {
1272 /**
1273 * @tc.steps: step1. open rdb store, create distribute table and insert data
1274 */
1275 std::map<std::string, DataValue> dataMap;
1276 PrepareVirtualEnvironment(dataMap, {g_deviceB});
1277
1278 g_mgr.SetAutoLaunchRequestCallback(nullptr);
1279 /**
1280 * @tc.steps: step2. close store ensure communicator has closed
1281 */
1282 g_mgr.CloseStore(g_rdbDelegatePtr);
1283 g_rdbDelegatePtr = nullptr;
1284 /**
1285 * @tc.steps: step3. store can't autoLaunch because callback is nullptr
1286 */
1287 LabelType labelType(g_id.begin(), g_id.end());
1288 g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1289 std::this_thread::sleep_for(std::chrono::seconds(1));
1290 /**
1291 * @tc.steps: step4. Call sync expect sync fail
1292 */
1293 Query query = Query::Select(g_tableName);
__anonc2e146140c02(const std::map<std::string, int> &statusMap) 1294 SyncOperation::UserCallback callBack = [](const std::map<std::string, int> &statusMap) {
1295 for (const auto &entry : statusMap) {
1296 EXPECT_EQ(entry.second, static_cast<int>(SyncOperation::OP_COMM_ABNORMAL));
1297 }
1298 };
1299 EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, callBack, true), E_OK);
1300
1301 OpenStore();
1302 std::this_thread::sleep_for(std::chrono::minutes(1));
1303 }
1304
1305 /**
1306 * @tc.name: Ability Sync 001
1307 * @tc.desc: Test ability sync success when has same schema.
1308 * @tc.type: FUNC
1309 * @tc.require: AR000GK58N
1310 * @tc.author: zhangqiquan
1311 */
1312 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync001, TestSize.Level1)
1313 {
1314 std::map<std::string, DataValue> dataMap;
1315 std::vector<FieldInfo> localFieldInfo;
1316 GetFieldInfo(localFieldInfo, g_storageType);
1317
1318 PrepareEnvironment(dataMap, localFieldInfo, localFieldInfo, {g_deviceB});
1319 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1320
1321 CheckVirtualData(dataMap);
1322 }
1323
1324 /**
1325 * @tc.name: Ability Sync 002
1326 * @tc.desc: Test ability sync failed when has different schema.
1327 * @tc.type: FUNC
1328 * @tc.require: AR000GK58N
1329 * @tc.author: zhangqiquan
1330 */
1331 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync002, TestSize.Level1)
1332 {
1333 /**
1334 * @tc.steps: step1. set local schema is (BOOL, INTEGER, REAL, TEXT, BLOB, INTEGER)
1335 */
1336 std::map<std::string, DataValue> dataMap;
1337 std::vector<FieldInfo> localFieldInfo;
1338 std::vector<StorageType> localStorageType = g_storageType;
1339 localStorageType.push_back(StorageType::STORAGE_TYPE_INTEGER);
1340 GetFieldInfo(localFieldInfo, localStorageType);
1341
1342 /**
1343 * @tc.steps: step2. set remote schema is (BOOL, INTEGER, REAL, TEXT, BLOB, TEXT)
1344 */
1345 std::vector<FieldInfo> remoteFieldInfo;
1346 std::vector<StorageType> remoteStorageType = g_storageType;
1347 remoteStorageType.push_back(StorageType::STORAGE_TYPE_TEXT);
1348 GetFieldInfo(remoteFieldInfo, remoteStorageType);
1349
1350 /**
1351 * @tc.steps: step3. call sync
1352 * @tc.expected: sync fail when abilitySync
1353 */
1354 PrepareEnvironment(dataMap, localFieldInfo, remoteFieldInfo, {g_deviceB});
1355 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, SCHEMA_MISMATCH, {DEVICE_B});
1356 }
1357
1358 /**
1359 * @tc.name: Ability Sync 003
1360 * @tc.desc: Test ability sync failed when has different schema.
1361 * @tc.type: FUNC
1362 * @tc.require: AR000GK58N
1363 * @tc.author: zhangqiquan
1364 */
1365 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync003, TestSize.Level1)
1366 {
1367 /**
1368 * @tc.steps: step1. set local and remote schema is (BOOL, INTEGER, REAL, TEXT, BLOB)
1369 */
1370 std::map<std::string, DataValue> dataMap;
1371 std::vector<FieldInfo> schema;
1372 std::vector<StorageType> localStorageType = g_storageType;
1373 GetFieldInfo(schema, localStorageType);
1374
1375 /**
1376 * @tc.steps: step2. create table and insert data
1377 */
1378 PrepareEnvironment(dataMap, schema, schema, {g_deviceB});
1379
1380 /**
1381 * @tc.steps: step3. change local table to (BOOL, INTEGER, REAL, TEXT, BLOB)
1382 * @tc.expected: sync fail
1383 */
__anonc2e146140d02(const std::string &target, Message *inMsg) 1384 g_communicatorAggregator->RegOnDispatch([](const std::string &target, Message *inMsg) {
1385 if (target != "real_device") {
1386 return;
1387 }
1388 if (inMsg->GetMessageType() != TYPE_NOTIFY || inMsg->GetMessageId() != ABILITY_SYNC_MESSAGE) {
1389 return;
1390 }
1391 sqlite3 *db = nullptr;
1392 EXPECT_EQ(GetDB(db), SQLITE_OK);
1393 ASSERT_NE(db, nullptr);
1394 std::string alterSql = "ALTER TABLE " + g_tableName + " ADD COLUMN NEW_COLUMN TEXT DEFAULT 'DEFAULT_TEXT'";
1395 EXPECT_EQ(sqlite3_exec(db, alterSql.c_str(), nullptr, nullptr, nullptr), SQLITE_OK);
1396 EXPECT_EQ(sqlite3_close(db), SQLITE_OK);
1397 EXPECT_EQ(g_rdbDelegatePtr->CreateDistributedTable(g_tableName), OK);
1398 });
1399
1400 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1401
1402 g_communicatorAggregator->RegOnDispatch(nullptr);
1403 }
1404
1405 /**
1406 * @tc.name: Ability Sync 004
1407 * @tc.desc: Test ability sync failed when one device hasn't distributed table.
1408 * @tc.type: FUNC
1409 * @tc.require: AR000GK58N
1410 * @tc.author: zhangqiquan
1411 */
1412 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, AbilitySync004, TestSize.Level1)
1413 {
1414 std::map<std::string, DataValue> dataMap;
1415 PrepareVirtualEnvironment(dataMap, {g_deviceB}, false);
1416
1417 Query query = Query::Select(g_tableName);
1418 int res = DB_ERROR;
__anonc2e146140e02(std::map<std::string, int> resMap) 1419 auto callBack = [&res](std::map<std::string, int> resMap) {
1420 if (resMap.find("real_device") != resMap.end()) {
1421 res = resMap["real_device"];
1422 }
1423 };
1424 EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(DistributedDB::SYNC_MODE_PULL_ONLY, query, callBack, true), E_OK);
1425 EXPECT_EQ(res, static_cast<int>(SyncOperation::Status::OP_SCHEMA_INCOMPATIBLE));
1426 }
1427
1428 /**
1429 * @tc.name: WaterMark 001
1430 * @tc.desc: Test sync success after erase waterMark.
1431 * @tc.type: FUNC
1432 * @tc.require: AR000GK58N
1433 * @tc.author: zhangqiquan
1434 */
1435 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, WaterMark001, TestSize.Level1)
1436 {
1437 std::map<std::string, DataValue> dataMap;
1438 PrepareEnvironment(dataMap, {g_deviceB});
1439 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1440
1441 CheckVirtualData(dataMap);
1442
1443 EXPECT_EQ(g_rdbDelegatePtr->RemoveDeviceData(g_deviceB->GetDeviceId(), g_tableName), OK);
1444 g_deviceB->EraseSyncData(g_tableName);
1445
1446 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1447
1448 CheckVirtualData(dataMap);
1449 }
1450
1451 /*
1452 * @tc.name: pressure sync 001
1453 * @tc.desc: Test rdb sync different table at same time
1454 * @tc.type: FUNC
1455 * @tc.require: AR000GK58N
1456 * @tc.author: zhangqiquan
1457 */
1458 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, PressureSync001, TestSize.Level1)
1459 {
1460 /**
1461 * @tc.steps: step1. create table A and device A push data to device B
1462 * @tc.expected: step1. all is ok
1463 */
1464 std::map<std::string, DataValue> tableADataMap;
1465 std::vector<FieldInfo> tableAFieldInfo;
1466 std::vector<StorageType> localStorageType = g_storageType;
1467 localStorageType.push_back(StorageType::STORAGE_TYPE_INTEGER);
1468 GetFieldInfo(tableAFieldInfo, localStorageType);
1469 const std::string tableNameA = "TABLE_A";
1470 PrepareEnvironment(tableADataMap, tableNameA, tableAFieldInfo, tableAFieldInfo, {g_deviceB});
1471
1472 /**
1473 * @tc.steps: step2. create table B and device B push data to device A
1474 * @tc.expected: step2. all is ok
1475 */
1476 std::map<std::string, DataValue> tableBDataMap;
1477 std::vector<FieldInfo> tableBFieldInfo;
1478 localStorageType = g_storageType;
1479 localStorageType.push_back(StorageType::STORAGE_TYPE_REAL);
1480 GetFieldInfo(tableBFieldInfo, localStorageType);
1481 const std::string tableNameB = "TABLE_B";
1482 PrepareVirtualEnvironment(tableBDataMap, tableNameB, tableBFieldInfo, {g_deviceB});
1483
1484 std::condition_variable cv;
1485 bool subFinish = false;
__anonc2e146140f02() 1486 std::thread subThread = std::thread([&subFinish, &cv, &tableNameA, &tableADataMap]() {
1487 BlockSync(tableNameA, SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
1488
1489 CheckVirtualData(tableNameA, tableADataMap);
1490 subFinish = true;
1491 cv.notify_all();
1492 });
1493 subThread.detach();
1494
1495 Query query = Query::Select(tableNameB);
1496 g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true);
1497 CheckData(tableBDataMap, tableNameB, tableBFieldInfo);
1498
1499 std::mutex mutex;
1500 std::unique_lock<std::mutex> lock(mutex);
__anonc2e146141002null1501 cv.wait(lock, [&subFinish] { return subFinish; });
1502 }
1503
1504 /*
1505 * @tc.name: relation observer 001
1506 * @tc.desc: Test relation observer while normal pull sync
1507 * @tc.type: FUNC
1508 * @tc.require:
1509 * @tc.author: zhuwentao
1510 */
1511 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, Observer001, TestSize.Level0)
1512 {
1513 /**
1514 * @tc.steps: step1. device A create table and device B insert data and device C don't insert data
1515 * @tc.expected: step1. create and insert ok
1516 */
1517 g_observer->ResetToZero();
1518 std::map<std::string, DataValue> dataMap;
1519 PrepareVirtualEnvironment(dataMap, {g_deviceB, g_deviceC});
1520 /**
1521 * @tc.steps: step2. device A pull sync mode
1522 * @tc.expected: step2. sync ok
1523 */
1524 BlockSync(SyncMode::SYNC_MODE_PULL_ONLY, OK, {DEVICE_B, DEVICE_C});
1525 /**
1526 * @tc.steps: step3. device A check observer
1527 * @tc.expected: step2. data change device is deviceB
1528 */
1529 EXPECT_EQ(g_observer->GetCallCount(), 1u);
1530 EXPECT_EQ(g_observer->GetDataChangeDevice(), DEVICE_B);
1531 CheckIdentify(g_observer);
1532 }
1533
1534 /**
1535 * @tc.name: relation observer 002
1536 * @tc.desc: Test rdb observer ok in autolauchCallback scene
1537 * @tc.type: FUNC
1538 * @tc.require: AR000GK58N
1539 * @tc.author: zhuwentao
1540 */
1541 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, observer002, TestSize.Level3)
1542 {
1543 /**
1544 * @tc.steps: step1. open rdb store, create distribute table and insert data
1545 */
1546 g_observer->ResetToZero();
1547 std::map<std::string, DataValue> dataMap;
1548 PrepareVirtualEnvironment(dataMap, {g_deviceB});
1549
1550 /**
1551 * @tc.steps: step2. set auto launch callBack
1552 */
1553 RelationalStoreObserverUnitTest *observer = new (std::nothrow) RelationalStoreObserverUnitTest();
__anonc2e146141102(const std::string &identifier, AutoLaunchParam ¶m) 1554 const AutoLaunchRequestCallback callback = [observer](const std::string &identifier, AutoLaunchParam ¶m) {
1555 if (g_id != identifier) {
1556 return false;
1557 }
1558 param.path = g_dbDir;
1559 param.appId = APP_ID;
1560 param.userId = USER_ID;
1561 param.storeId = STORE_ID_1;
1562 param.option.storeObserver = observer;
1563 #ifndef OMIT_ENCRYPT
1564 param.option.isEncryptedDb = true;
1565 param.option.cipher = CipherType::DEFAULT;
1566 param.option.passwd = g_correctPasswd;
1567 param.option.iterateTimes = DEFAULT_ITER;
1568 #endif
1569 return true;
1570 };
1571 g_mgr.SetAutoLaunchRequestCallback(callback);
1572 /**
1573 * @tc.steps: step3. close store ensure communicator has closed
1574 */
1575 g_mgr.CloseStore(g_rdbDelegatePtr);
1576 g_rdbDelegatePtr = nullptr;
1577 /**
1578 * @tc.steps: step4. RunCommunicatorLackCallback to autolaunch store
1579 */
1580 LabelType labelType(g_id.begin(), g_id.end());
1581 g_communicatorAggregator->RunCommunicatorLackCallback(labelType);
1582 std::this_thread::sleep_for(std::chrono::seconds(1));
1583 /**
1584 * @tc.steps: step5. Call sync expect sync successful and device A check observer
1585 */
1586 Query query = Query::Select(g_tableName);
1587 EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK);
1588 EXPECT_EQ(observer->GetCallCount(), 1u);
1589 EXPECT_EQ(observer->GetDataChangeDevice(), DEVICE_B);
1590 CheckIdentify(observer);
1591 std::this_thread::sleep_for(std::chrono::minutes(1));
1592 delete observer;
1593 }
1594
1595 /**
1596 * @tc.name: remote query 001
1597 * @tc.desc: Test rdb remote query
1598 * @tc.type: FUNC
1599 * @tc.require: AR000GK58G
1600 * @tc.author: zhangqiquan
1601 */
1602 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery001, TestSize.Level1)
1603 {
1604 std::map<std::string, DataValue> dataMap;
1605 PrepareEnvironment(dataMap, {g_deviceB});
1606 ASSERT_NE(g_rdbDelegatePtr, nullptr);
1607 RemoteCondition condition;
1608 condition.sql = "SELECT * FROM " + g_tableName;
1609 std::shared_ptr<ResultSet> result = nullptr;
1610 EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), OK);
1611
1612 EXPECT_NE(result, nullptr);
1613 }
1614
1615 /**
1616 * @tc.name: remote query 002
1617 * @tc.desc: Test rdb remote query
1618 * @tc.type: FUNC
1619 * @tc.require: AR000GK58G
1620 * @tc.author: zhangqiquan
1621 */
1622 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery002, TestSize.Level1)
1623 {
1624 std::map<std::string, DataValue> dataMap;
1625 PrepareEnvironment(dataMap, {g_deviceB});
1626 ASSERT_NE(g_deviceB, nullptr);
1627 ASSERT_NE(g_rdbDelegatePtr, nullptr);
1628 RemoteCondition condition;
1629 condition.sql = "SELECT * FROM " + g_tableName;
1630 std::shared_ptr<ResultSet> result = nullptr;
1631 EXPECT_EQ(g_deviceB->RemoteQuery(DEVICE_A, condition, DBConstant::MIN_TIMEOUT, result), OK);
1632 CheckSearchData(result, dataMap);
1633 }
1634
1635 /**
1636 * @tc.name: remote query 003
1637 * @tc.desc: Test rdb remote query but query not data
1638 * @tc.type: FUNC
1639 * @tc.require: AR000GK58G
1640 * @tc.author: zhangqiquan
1641 */
1642 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery003, TestSize.Level1)
1643 {
1644 std::map<std::string, DataValue> dataMap;
1645 PrepareEnvironment(dataMap, {g_deviceB});
1646 ASSERT_NE(g_deviceB, nullptr);
1647 ASSERT_NE(g_rdbDelegatePtr, nullptr);
1648 RemoteCondition condition;
1649 condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
1650 std::shared_ptr<ResultSet> result = nullptr;
1651 EXPECT_EQ(g_deviceB->RemoteQuery(DEVICE_A, condition, DBConstant::MIN_TIMEOUT, result), OK);
1652 ASSERT_NE(result, nullptr);
1653 EXPECT_EQ(result->GetCount(), 0);
1654 }
1655
1656 /**
1657 * @tc.name: remote query 004
1658 * @tc.desc: Test rdb queue size
1659 * @tc.type: FUNC
1660 * @tc.require: AR000GK58G
1661 * @tc.author: zhangqiquan
1662 */
1663 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery004, TestSize.Level3)
1664 {
1665 std::map<std::string, DataValue> dataMap;
1666 PrepareEnvironment(dataMap, {g_deviceB});
1667 ASSERT_NE(g_rdbDelegatePtr, nullptr);
1668 RemoteCondition condition;
1669 condition.sql = "SELECT * FROM " + g_tableName;
1670 std::vector<std::string> deviceMap = {DEVICE_B, DEVICE_C};
__anonc2e146141202(const std::string &device, Message *inMsg) 1671 g_communicatorAggregator->RegOnDispatch([](const std::string &device, Message *inMsg) {
1672 ASSERT_NE(inMsg, nullptr);
1673 inMsg->SetMessageId(INVALID_MESSAGE_ID);
1674 });
1675 const size_t MAX_SIZE = 7;
1676 std::vector<std::thread *> threadList;
1677 for (size_t j = 0; j < deviceMap.size(); j++) {
1678 for (size_t i = 0; i < MAX_SIZE; i++) {
1679 std::string device = deviceMap[j];
__anonc2e146141302() 1680 threadList.push_back(new std::thread([&, device]() {
1681 std::shared_ptr<ResultSet> result = nullptr;
1682 EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(device, condition,
1683 DBConstant::MIN_TIMEOUT, result), TIME_OUT);
1684 EXPECT_EQ(result, nullptr);
1685 }));
1686 }
1687 }
1688 for (size_t i = 0; i < threadList.size(); i++) {
1689 threadList[i]->join();
1690 delete threadList[i];
1691 threadList[i] = nullptr;
1692 }
1693 }
1694
1695 /**
1696 * @tc.name: remote query 005
1697 * @tc.desc: Test rdb remote query timeout by invalid message
1698 * @tc.type: FUNC
1699 * @tc.require: AR000GK58G
1700 * @tc.author: zhangqiquan
1701 */
1702 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery005, TestSize.Level1)
1703 {
1704 std::map<std::string, DataValue> dataMap;
1705 PrepareEnvironment(dataMap, {g_deviceB});
1706 ASSERT_NE(g_deviceB, nullptr);
1707 ASSERT_NE(g_rdbDelegatePtr, nullptr);
__anonc2e146141402(const std::string &device, Message *inMsg) 1708 g_communicatorAggregator->RegOnDispatch([](const std::string &device, Message *inMsg) {
1709 ASSERT_NE(inMsg, nullptr);
1710 inMsg->SetMessageId(INVALID_MESSAGE_ID);
1711 });
1712 RemoteCondition condition;
1713 condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
1714 std::shared_ptr<ResultSet> result = nullptr;
1715 EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), TIME_OUT);
1716 ASSERT_EQ(result, nullptr);
1717 }
1718
1719 /**
1720 * @tc.name: remote query 006
1721 * @tc.desc: Test rdb remote query commfailure by offline
1722 * @tc.type: FUNC
1723 * @tc.require: AR000GK58G
1724 * @tc.author: zhangqiquan
1725 */
1726 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery006, TestSize.Level1)
1727 {
1728 std::map<std::string, DataValue> dataMap;
1729 PrepareEnvironment(dataMap, {g_deviceB});
1730 ASSERT_NE(g_deviceB, nullptr);
1731 ASSERT_NE(g_rdbDelegatePtr, nullptr);
1732 std::thread *offlineThread = nullptr;
__anonc2e146141502(const std::string &device, Message *inMsg) 1733 g_communicatorAggregator->RegOnDispatch([&offlineThread](const std::string &device, Message *inMsg) {
1734 ASSERT_NE(inMsg, nullptr);
1735 inMsg->SetMessageId(INVALID_MESSAGE_ID);
1736 offlineThread = new std::thread([]() {
1737 g_deviceB->Offline();
1738 });
1739 });
1740 RemoteCondition condition;
1741 condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
1742 std::shared_ptr<ResultSet> result = nullptr;
1743 EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), COMM_FAILURE);
1744 ASSERT_EQ(result, nullptr);
1745 if (offlineThread != nullptr) {
1746 offlineThread->join();
1747 delete offlineThread;
1748 offlineThread = nullptr;
1749 }
1750 }
1751
1752 /**
1753 * @tc.name: remote query 007
1754 * @tc.desc: Test rdb remote query failed by permission check
1755 * @tc.type: FUNC
1756 * @tc.require: AR000GK58G
1757 * @tc.author: zhangqiquan
1758 */
1759 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery007, TestSize.Level1)
1760 {
1761 std::map<std::string, DataValue> dataMap;
1762 PrepareEnvironment(dataMap, {g_deviceB});
1763 ASSERT_NE(g_deviceB, nullptr);
1764 ASSERT_NE(g_rdbDelegatePtr, nullptr);
1765 PermissionCheckCallbackV2 callback = [](const std::string &userId, const std::string &appId,
__anonc2e146141702(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) 1766 const std::string &storeId, const std::string &deviceId, uint8_t flag) -> bool {
1767 return false;
1768 };
1769 EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(callback), OK);
1770 RemoteCondition condition;
1771 condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
1772 std::shared_ptr<ResultSet> result = nullptr;
1773 EXPECT_EQ(g_deviceB->RemoteQuery(DEVICE_A, condition, DBConstant::MIN_TIMEOUT, result),
1774 PERMISSION_CHECK_FORBID_SYNC);
1775 ASSERT_EQ(result, nullptr);
1776 callback = nullptr;
1777 EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(callback), OK);
1778 }
1779
1780 /**
1781 * @tc.name: remote query 008
1782 * @tc.desc: Test rdb remote query timeout but not effected by invalid message
1783 * @tc.type: FUNC
1784 * @tc.require: AR000GK58G
1785 * @tc.author: zhangqiquan
1786 */
1787 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery008, TestSize.Level1)
1788 {
1789 std::map<std::string, DataValue> dataMap;
1790 PrepareEnvironment(dataMap, {g_deviceB});
1791 ASSERT_NE(g_deviceB, nullptr);
1792 ASSERT_NE(g_rdbDelegatePtr, nullptr);
__anonc2e146141802(const std::string &device, Message *inMsg) 1793 g_communicatorAggregator->RegOnDispatch([](const std::string &device, Message *inMsg) {
1794 ASSERT_NE(inMsg, nullptr);
1795 if (device != DEVICE_B) {
1796 return;
1797 }
1798 inMsg->SetMessageId(INVALID_MESSAGE_ID);
1799 std::thread t([]() {
1800 auto *msg = new (std::nothrow) Message(REMOTE_EXECUTE_MESSAGE);
1801 ASSERT_NE(msg, nullptr);
1802 auto *packet = new (std::nothrow) RemoteExecutorAckPacket();
1803 if (packet != nullptr) {
1804 packet->SetAckCode(-E_FEEDBACK_COMMUNICATOR_NOT_FOUND);
1805 }
1806 if (msg->SetExternalObject(packet) != E_OK) {
1807 delete packet;
1808 packet = nullptr;
1809 }
1810 msg->SetMessageType(TYPE_RESPONSE);
1811 msg->SetErrorNo(E_FEEDBACK_COMMUNICATOR_NOT_FOUND);
1812 msg->SetSessionId(0u);
1813 msg->SetSequenceId(1u);
1814 g_communicatorAggregator->DispatchMessage(DEVICE_B, DEVICE_A, msg, nullptr);
1815 LOGD("DispatchMessage Finish");
1816 });
1817 t.detach();
1818 });
1819 RemoteCondition condition;
1820 condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
1821 std::shared_ptr<ResultSet> result = nullptr;
1822 EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), TIME_OUT);
1823 ASSERT_EQ(result, nullptr);
1824 }
1825
1826 /**
1827 * @tc.name: remote query 009
1828 * @tc.desc: Test rdb remote query busy before timeout
1829 * @tc.type: FUNC
1830 * @tc.require: AR000GK58G
1831 * @tc.author: zhangqiquan
1832 */
1833 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery009, TestSize.Level1)
1834 {
1835 std::map<std::string, DataValue> dataMap;
1836 PrepareEnvironment(dataMap, {g_deviceB});
1837 ASSERT_NE(g_deviceB, nullptr);
1838 ASSERT_NE(g_rdbDelegatePtr, nullptr);
__anonc2e146141a02(const std::string &device, Message *inMsg) 1839 g_communicatorAggregator->RegOnDispatch([](const std::string &device, Message *inMsg) {
1840 ASSERT_NE(inMsg, nullptr);
1841 inMsg->SetMessageId(INVALID_MESSAGE_ID);
1842 });
1843 RemoteCondition condition;
1844 condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
1845 std::shared_ptr<ResultSet> result = nullptr;
__anonc2e146141b02() 1846 std::thread t([]() {
1847 std::this_thread::sleep_for(std::chrono::seconds(1));
1848 if (g_rdbDelegatePtr != nullptr) {
1849 LOGD("CloseStore Start");
1850 ASSERT_EQ(g_mgr.CloseStore(g_rdbDelegatePtr), OK);
1851 g_rdbDelegatePtr = nullptr;
1852 }
1853 });
1854 EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_B, condition, DBConstant::MIN_TIMEOUT, result), BUSY);
1855 ASSERT_EQ(result, nullptr);
1856 t.join();
1857 }
1858
1859 /**
1860 * @tc.name: remote query 010
1861 * @tc.desc: Test rdb remote query with kv db
1862 * @tc.type: FUNC
1863 * @tc.require: AR000GK58G
1864 * @tc.author: zhangqiquan
1865 */
1866 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery010, TestSize.Level1)
1867 {
1868 std::map<std::string, DataValue> dataMap;
1869 PrepareEnvironment(dataMap, {g_deviceB});
1870 ASSERT_NE(g_rdbDelegatePtr, nullptr);
1871 RemoteCondition condition;
1872 condition.sql = "SELECT * FROM " + g_tableName;
1873 std::shared_ptr<ResultSet> result = nullptr;
1874 EXPECT_EQ(g_rdbDelegatePtr->RemoteQuery(DEVICE_D, condition, DBConstant::MIN_TIMEOUT, result), NOT_SUPPORT);
1875
1876 EXPECT_EQ(result, nullptr);
1877 }
1878
1879 /**
1880 * @tc.name: remote query 010
1881 * @tc.desc: Test rdb remote query with
1882 * @tc.type: FUNC
1883 * @tc.require: AR000GK58G
1884 * @tc.author: zhangqiquan
1885 */
1886 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RemoteQuery011, TestSize.Level1)
1887 {
1888 std::map<std::string, DataValue> dataMap;
1889 PrepareEnvironment(dataMap, {g_deviceB});
1890 ASSERT_NE(g_deviceB, nullptr);
1891 ASSERT_NE(g_rdbDelegatePtr, nullptr);
1892 RemoteCondition condition;
1893 condition.sql = "This is error sql";
1894 std::shared_ptr<ResultSet> result = nullptr;
1895 EXPECT_EQ(g_deviceB->RemoteQuery(DEVICE_A, condition, DBConstant::MIN_TIMEOUT, result), DB_ERROR);
1896 EXPECT_EQ(result, nullptr);
1897 }
1898
1899 /**
1900 * @tc.name: RelationalPemissionTest001
1901 * @tc.desc: deviceB PermissionCheck not pass test, SYNC_MODE_PUSH_ONLY
1902 * @tc.type: FUNC
1903 * @tc.require: AR000GK58N
1904 * @tc.author: zhangshijie
1905 */
1906 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RelationalPemissionTest001, TestSize.Level0)
1907 {
1908 /**
1909 * @tc.steps: step1. SetPermissionCheckCallback
1910 * @tc.expected: step1. return OK.
1911 */
1912 auto permissionCheckCallback = [] (const std::string &userId, const std::string &appId,
__anonc2e146141c02(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) 1913 const std::string &storeId, const std::string &deviceId, uint8_t flag) -> bool {
1914 LOGE("u: %s, a: %s, s: %s", userId.c_str(), appId.c_str(), storeId.c_str());
1915 bool empty = userId.empty() || appId.empty() || storeId.empty();
1916 EXPECT_TRUE(empty == false);
1917 if (flag & (CHECK_FLAG_SEND)) {
1918 LOGD("in RunPermissionCheck callback, check not pass, flag:%d", flag);
1919 return false;
1920 } else {
1921 LOGD("in RunPermissionCheck callback, check pass, flag:%d", flag);
1922 return true;
1923 }
1924 };
1925 EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(permissionCheckCallback), OK);
1926
1927 /**
1928 * @tc.steps: step2. sync with deviceB
1929 */
1930 std::map<std::string, DataValue> dataMap;
1931 PrepareEnvironment(dataMap, { g_deviceB });
1932 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, PERMISSION_CHECK_FORBID_SYNC, { DEVICE_B });
1933
1934 /**
1935 * @tc.steps: step3. check data in deviceB
1936 * @tc.expected: step3. deviceB has no data
1937 */
1938 std::vector<VirtualRowData> targetData;
1939 g_deviceB->GetAllSyncData(g_tableName, targetData);
1940
1941 ASSERT_EQ(targetData.size(), 0u);
1942 }
1943
1944 /**
1945 * @tc.name: RelationalPemissionTest002
1946 * @tc.desc: deviceB PermissionCheck not pass test, SYNC_MODE_PULL_ONLY
1947 * @tc.type: FUNC
1948 * @tc.require: AR000GK58N
1949 * @tc.author: zhangshijie
1950 */
1951 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RelationalPemissionTest002, TestSize.Level0)
1952 {
1953 /**
1954 * @tc.steps: step1. SetPermissionCheckCallback
1955 * @tc.expected: step1. return OK.
1956 */
1957 auto permissionCheckCallback = [] (const std::string &userId, const std::string &appId,
__anonc2e146141d02(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) 1958 const std::string &storeId, const std::string &deviceId, uint8_t flag) -> bool {
1959 LOGE("u: %s, a: %s, s: %s", userId.c_str(), appId.c_str(), storeId.c_str());
1960 bool empty = userId.empty() || appId.empty() || storeId.empty();
1961 EXPECT_TRUE(empty == false);
1962 if (flag & (CHECK_FLAG_RECEIVE)) {
1963 LOGD("in RunPermissionCheck callback, check not pass, flag:%d", flag);
1964 return false;
1965 } else {
1966 LOGD("in RunPermissionCheck callback, check pass, flag:%d", flag);
1967 return true;
1968 }
1969 };
1970 EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(permissionCheckCallback), OK);
1971
1972 /**
1973 * @tc.steps: step2. sync with deviceB
1974 */
1975 std::map<std::string, DataValue> dataMap;
1976 PrepareEnvironment(dataMap, { g_deviceB });
1977 BlockSync(SyncMode::SYNC_MODE_PULL_ONLY, PERMISSION_CHECK_FORBID_SYNC, { DEVICE_B });
1978
1979 /**
1980 * @tc.steps: step3. check data in deviceB
1981 * @tc.expected: step3. deviceB has no data
1982 */
1983 std::vector<VirtualRowData> targetData;
1984 g_deviceB->GetAllSyncData(g_tableName, targetData);
1985
1986 ASSERT_EQ(targetData.size(), 0u);
1987 }
1988
1989 /**
1990 * @tc.name: RelationalPemissionTest003
1991 * @tc.desc: deviceB PermissionCheck not pass test, flag CHECK_FLAG_SPONSOR
1992 * @tc.type: FUNC
1993 * @tc.require: AR000GK58N
1994 * @tc.author: zhangshijie
1995 */
1996 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RelationalPemissionTest003, TestSize.Level0)
1997 {
1998 /**
1999 * @tc.steps: step1. SetPermissionCheckCallback
2000 * @tc.expected: step1. return OK.
2001 */
2002 auto permissionCheckCallback = [] (const std::string &userId, const std::string &appId,
__anonc2e146141e02(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) 2003 const std::string &storeId, const std::string &deviceId, uint8_t flag) -> bool {
2004 LOGE("u: %s, a: %s, s: %s", userId.c_str(), appId.c_str(), storeId.c_str());
2005 bool empty = userId.empty() || appId.empty() || storeId.empty();
2006 EXPECT_TRUE(empty == false);
2007 if (flag & CHECK_FLAG_SPONSOR) {
2008 LOGD("in RunPermissionCheck callback, check not pass, flag:%d", flag);
2009 return false;
2010 } else {
2011 LOGD("in RunPermissionCheck callback, check pass, flag:%d", flag);
2012 return true;
2013 }
2014 };
2015 EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(permissionCheckCallback), OK);
2016
2017 /**
2018 * @tc.steps: step2. sync with deviceB
2019 */
2020 std::map<std::string, DataValue> dataMap;
2021 PrepareEnvironment(dataMap, { g_deviceB });
2022 BlockSync(SyncMode::SYNC_MODE_PULL_ONLY, PERMISSION_CHECK_FORBID_SYNC, { DEVICE_B });
2023
2024 /**
2025 * @tc.steps: step3. check data in deviceB
2026 * @tc.expected: step3. deviceB has no data
2027 */
2028 std::vector<VirtualRowData> targetData;
2029 g_deviceB->GetAllSyncData(g_tableName, targetData);
2030
2031 ASSERT_EQ(targetData.size(), 0u);
2032 }
2033
2034 /**
2035 * @tc.name: RelationalPemissionTest004
2036 * @tc.desc: deviceB PermissionCheck pass test. deviceC not pass, SYNC_MODE_PUSH_ONLY
2037 * @tc.type: FUNC
2038 * @tc.require: AR000GK58N
2039 * @tc.author: zhangshijie
2040 */
2041 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RelationalPemissionTest004, TestSize.Level0)
2042 {
2043 /**
2044 * @tc.steps: step1. SetPermissionCheckCallback
2045 * @tc.expected: step1. return OK.
2046 */
2047 auto permissionCheckCallback = [] (const std::string &userId, const std::string &appId,
__anonc2e146141f02(const std::string &userId, const std::string &appId, const std::string &storeId, const std::string &deviceId, uint8_t flag) 2048 const std::string &storeId, const std::string &deviceId, uint8_t flag) -> bool {
2049 LOGE("u: %s, a: %s, s: %s", userId.c_str(), appId.c_str(), storeId.c_str());
2050 if (deviceId == g_deviceC->GetDeviceId()) {
2051 LOGE("in RunPermissionCheck callback, check pass, device:%s", deviceId.c_str());
2052 return false;
2053 } else {
2054 LOGE("in RunPermissionCheck callback, check not pass, device:%s", deviceId.c_str());
2055 return true;
2056 }
2057 };
2058 EXPECT_EQ(RuntimeConfig::SetPermissionCheckCallback(permissionCheckCallback), OK);
2059
2060 std::map<std::string, DataValue> dataMap;
2061 PrepareEnvironment(dataMap, { g_deviceB, g_deviceC });
2062
2063 /**
2064 * @tc.steps: step2. sync with deviceB
2065 */
2066 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, { DEVICE_B });
2067
2068 /**
2069 * @tc.steps: step3. check data in deviceB
2070 * @tc.expected: step3. deviceB has data
2071 */
2072 std::vector<VirtualRowData> targetData;
2073 g_deviceB->GetAllSyncData(g_tableName, targetData);
2074 ASSERT_EQ(targetData.size(), 1u);
2075
2076 /**
2077 * @tc.steps: step4. sync with deviceC
2078 */
2079 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, PERMISSION_CHECK_FORBID_SYNC, { DEVICE_C });
2080
2081 /**
2082 * @tc.steps: step5. check data in deviceC
2083 * @tc.expected: step5. deviceC has no data
2084 */
2085 targetData.clear();
2086 g_deviceC->GetAllSyncData(g_tableName, targetData);
2087 ASSERT_EQ(targetData.size(), 0u);
2088 }
2089
2090 /**
2091 * @tc.name: SecurityOptionCheck001
2092 * @tc.desc: Test sync failed when getSecurityOption return error
2093 * @tc.type: FUNC
2094 * @tc.require: AR000GK58N
2095 * @tc.author: zhangqiquan
2096 */
2097 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, SecurityOptionCheck001, TestSize.Level1)
2098 {
2099 std::vector<std::string> devices;
2100 devices.push_back(g_deviceB->GetDeviceId());
2101
2102 /**
2103 * @tc.steps: step1. make getSecurityOption return -1
2104 */
2105 std::shared_ptr<ProcessSystemApiAdapterImpl> adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
2106 adapter->ForkGetSecurityOption(
__anonc2e146142002(const std::string &filePath, SecurityOption &option) 2107 [](const std::string &filePath, SecurityOption &option) {
2108 (void)filePath;
2109 (void)option;
2110 return DB_ERROR;
2111 });
2112 RuntimeConfig::SetProcessSystemAPIAdapter(adapter);
2113
2114 std::map<std::string, DataValue> dataMap;
2115 PrepareEnvironment(dataMap, { g_deviceB });
2116
2117 /**
2118 * @tc.steps: step2. sync with deviceB
2119 */
2120 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, SECURITY_OPTION_CHECK_ERROR, { DEVICE_B });
2121 RuntimeConfig::SetProcessSystemAPIAdapter(nullptr);
2122 }
2123
2124 /**
2125 * @tc.name: SecurityOptionCheck002
2126 * @tc.desc: Test remote query failed when getSecurityOption return error
2127 * @tc.type: FUNC
2128 * @tc.require: AR000GK58G
2129 * @tc.author: zhangqiquan
2130 */
2131 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, SecurityOptionCheck002, TestSize.Level1)
2132 {
2133 /**
2134 * @tc.steps: step1. make getSecurityOption return -1
2135 */
2136 std::shared_ptr<ProcessSystemApiAdapterImpl> adapter = std::make_shared<ProcessSystemApiAdapterImpl>();
2137 adapter->ForkGetSecurityOption(
__anonc2e146142102(const std::string &filePath, SecurityOption &option) 2138 [](const std::string &filePath, SecurityOption &option) {
2139 (void)filePath;
2140 (void)option;
2141 return DB_ERROR;
2142 });
2143 RuntimeConfig::SetProcessSystemAPIAdapter(adapter);
2144
2145 /**
2146 * @tc.steps: step2. remote query with deviceB
2147 */
2148 std::map<std::string, DataValue> dataMap;
2149 PrepareEnvironment(dataMap, {g_deviceB});
2150 ASSERT_NE(g_deviceB, nullptr);
2151 ASSERT_NE(g_rdbDelegatePtr, nullptr);
2152 RemoteCondition condition;
2153 condition.sql = "SELECT * FROM " + g_tableName + " WHERE 1=0";
2154 std::shared_ptr<ResultSet> result = nullptr;
2155 EXPECT_EQ(g_deviceB->RemoteQuery(DEVICE_A, condition, DBConstant::MIN_TIMEOUT, result),
2156 SECURITY_OPTION_CHECK_ERROR);
2157 EXPECT_EQ(result, nullptr);
2158 RuntimeConfig::SetProcessSystemAPIAdapter(nullptr);
2159 }
2160
2161 /**
2162 * @tc.name: OrderbyWriteTimeSync001
2163 * @tc.desc: sync query with order by writeTime
2164 * @tc.type: FUNC
2165 * @tc.require: AR000H5VLO
2166 * @tc.author: zhuwentao
2167 */
2168 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, OrderbyWriteTimeSync001, TestSize.Level0)
2169 {
2170 std::map<std::string, DataValue> dataMap;
2171 PrepareEnvironment(dataMap, {g_deviceB});
2172 Query query = Query::Select(g_tableName).OrderByWriteTime(true);;
2173 EXPECT_EQ(g_rdbDelegatePtr->Sync({DEVICE_B}, DistributedDB::SYNC_MODE_PUSH_ONLY, query, nullptr, false),
2174 NOT_SUPPORT);
2175 }
2176
2177 /**
2178 * @tc.name: RDBSecurityOptionCheck001
2179 * @tc.desc: Test sync with security option.
2180 * @tc.type: FUNC
2181 * @tc.require: AR000GK58N
2182 * @tc.author: zhangqiquan
2183 */
2184 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RDBSecurityOptionCheck001, TestSize.Level3)
2185 {
2186 TestWithSecurityCheck(false);
2187 }
2188
2189 /**
2190 * @tc.name: RDBSecurityOptionCheck002
2191 * @tc.desc: Test remote query with security option.
2192 * @tc.type: FUNC
2193 * @tc.require: AR000GK58N
2194 * @tc.author: zhangqiquan
2195 */
2196 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, RDBSecurityOptionCheck002, TestSize.Level1)
2197 {
2198 TestWithSecurityCheck(true);
2199 }
2200
2201 /**
2202 * @tc.name: EncryptedAlgoUpgrade001
2203 * @tc.desc: Test upgrade encrypted db can sync normally
2204 * @tc.type: FUNC
2205 * @tc.require: AR000HI2JS
2206 * @tc.author: zhuwentao
2207 */
2208 HWTEST_F(DistributedDBRelationalVerP2PSyncTest, EncryptedAlgoUpgrade001, TestSize.Level0)
2209 {
2210 if (g_rdbDelegatePtr != nullptr) {
2211 LOGD("CloseStore Start");
2212 ASSERT_EQ(g_mgr.CloseStore(g_rdbDelegatePtr), OK);
2213 g_rdbDelegatePtr = nullptr;
2214 }
2215 EXPECT_EQ(OS::RemoveFile(g_dbDir), E_OK);
2216 /**
2217 * @tc.steps: step1. open old db use sha1 algo and insert some data
2218 * @tc.expected: step1. interface return ok
2219 */
2220 sqlite3 *db = nullptr;
2221 EXPECT_EQ(GetDB(db, false), SQLITE_OK);
2222 const std::string user_version_sql = "PRAGMA user_version=101;";
2223 EXPECT_EQ(SQLiteUtils::ExecuteRawSQL(db, user_version_sql), E_OK);
2224 sqlite3_close(db);
2225
2226 /**
2227 * @tc.steps: step2. open db by OpenStore
2228 * @tc.expected: step2. interface return ok
2229 */
2230 OpenStore();
2231 /**
2232 * @tc.steps: step3. sync with push
2233 * @tc.expected: step3. interface return ok
2234 */
2235 std::map<std::string, DataValue> dataMap;
2236 PrepareEnvironment(dataMap, {g_deviceB});
2237 BlockSync(SyncMode::SYNC_MODE_PUSH_ONLY, OK, {DEVICE_B});
2238 CheckVirtualData(dataMap);
2239 dataMap.clear();
2240
2241 /**
2242 * @tc.steps: step4. sync with pull
2243 * @tc.expected: step4. interface return ok
2244 */
2245
2246 Query query = Query::Select(g_tableName);
2247 g_deviceB->GenericVirtualDevice::Sync(DistributedDB::SYNC_MODE_PULL_ONLY, query, true);
2248 CheckVirtualData(dataMap);
2249 }
2250 #endif